context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// 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.
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mike Gorse <mgorse@novell.com>
//
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
namespace Atspi
{
public class EventObject : EventBase
{
private IEventObject proxy;
public EventObject (Accessible accessible) : base (accessible)
{
proxy = Registry.Bus.GetObject<IEventObject> (accessible.Application.Name, new ObjectPath (accessible.path));
// Hack so that managed-dbus can get the alternate name
if (accessible.Application is Registry)
proxy.Introspect ();
}
public event EventSV PropertyChange {
add {
Registry.RegisterEventListener ("Object:PropertyChange");
proxy.PropertyChange += GetDelegate (value);
}
remove {
proxy.PropertyChange -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:PropertyChange");
}
}
public event EventR BoundsChanged {
add {
Registry.RegisterEventListener ("Object:BoundsChanged");
proxy.BoundsChanged += GetDelegate (value);
}
remove {
proxy.BoundsChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:BoundsChanged");
}
}
public event EventI LinkSelected {
add {
Registry.RegisterEventListener ("Object:LinkSelected");
proxy.LinkSelected += GetDelegate (value);
}
remove {
proxy.LinkSelected -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:LinkSelected");
}
}
public event EventSB StateChanged {
add {
Registry.RegisterEventListener ("Object:StateChanged");
proxy.StateChanged += GetDelegate (value);
}
remove {
proxy.StateChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:StateChanged");
}
}
public event EventSIO ChildrenChanged {
add {
Registry.RegisterEventListener ("Object:ChildrenChanged");
proxy.ChildrenChanged += GetChildrenChangedDelegate (value);
}
remove {
proxy.ChildrenChanged -= GetChildrenChangedDelegate (value);
Registry.DeregisterEventListener ("Object:ChildrenChanged");
}
}
public event EventSimple VisibleDataChanged {
add {
Registry.RegisterEventListener ("Object:VisibleDataChanged");
proxy.VisibleDataChanged += GetDelegate (value);
}
remove {
proxy.VisibleDataChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:VisibleDataChanged");
}
}
public event EventSimple SelectionChanged {
add {
Registry.RegisterEventListener ("Object:SelectionChanged");
proxy.SelectionChanged += GetDelegate (value);
}
remove {
proxy.SelectionChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:SelectionChanged");
}
}
public event EventSimple ModelChanged {
add {
Registry.RegisterEventListener ("Object:ModelChanged");
proxy.ModelChanged += GetDelegate (value);
}
remove {
proxy.ModelChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:ModelChanged");
}
}
public event EventO ActiveDescendantChanged {
add {
Registry.RegisterEventListener ("Object:ActiveDescendantChanged");
proxy.ActiveDescendantChanged += GetDelegate (value);
}
remove {
proxy.ActiveDescendantChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:ActiveDescendantChanged");
}
}
public event EventII RowInserted {
add {
Registry.RegisterEventListener ("Object:RowInserted");
proxy.RowInserted += GetDelegate (value);
}
remove {
proxy.RowInserted -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:RowInserted");
}
}
public event EventSimple RowReordered {
add {
Registry.RegisterEventListener ("Object:RowReordered");
proxy.RowReordered += GetDelegate (value);
}
remove {
proxy.RowReordered -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:RowReordered");
}
}
public event EventII RowDeleted {
add {
Registry.RegisterEventListener ("Object:RowDeleted");
proxy.RowDeleted += GetDelegate (value);
}
remove {
proxy.RowDeleted -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:RowDeleted");
}
}
public event EventII ColumnInserted {
add {
Registry.RegisterEventListener ("Object:ColumnInserted");
proxy.ColumnInserted += GetDelegate (value);
}
remove {
proxy.ColumnInserted -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:ColumnInserted");
}
}
public event EventSimple ColumnReordered {
add {
Registry.RegisterEventListener ("Object:ColumnReordered");
proxy.ColumnReordered += GetDelegate (value);
}
remove {
proxy.ColumnReordered -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:ColumnReordered");
}
}
public event EventII ColumnDeleted {
add {
Registry.RegisterEventListener ("Object:ColumnDeleted");
proxy.ColumnDeleted += GetDelegate (value);
}
remove {
proxy.ColumnDeleted -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:ColumnDeleted");
}
}
public event EventSimple TextBoundsChanged {
add {
Registry.RegisterEventListener ("Object:TextBoundsChanged");
proxy.TextBoundsChanged += GetDelegate (value);
}
remove {
proxy.TextBoundsChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:TextBoundsChanged");
}
}
public event EventSimple TextSelectionChanged {
add {
Registry.RegisterEventListener ("Object:TextSelectionChanged");
proxy.TextSelectionChanged += GetDelegate (value);
}
remove {
proxy.TextSelectionChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:TextSelectionChanged");
}
}
public event EventSIIS TextChanged {
add {
Registry.RegisterEventListener ("Object:TextChanged");
proxy.TextChanged += GetDelegate (value);
}
remove {
proxy.TextChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:TextChanged");
}
}
public event EventSimple TextAttributesChanged {
add {
Registry.RegisterEventListener ("Object:TextAttributesChanged");
proxy.TextAttributesChanged += GetDelegate (value);
}
remove {
proxy.TextAttributesChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:TextAttributesChanged");
}
}
public event EventI TextCaretMoved {
add {
Registry.RegisterEventListener ("Object:TextCaretMoved");
proxy.TextCaretMoved += GetDelegate (value);
}
remove {
proxy.TextCaretMoved -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:TextCaretMoved");
}
}
public event EventSimple AttributesChanged {
add {
Registry.RegisterEventListener ("Object:AttributesChanged");
proxy.AttributesChanged += GetDelegate (value);
}
remove {
proxy.AttributesChanged -= GetDelegate (value);
Registry.DeregisterEventListener ("Object:AttributesChanged");
}
}
}
[Interface ("org.a11y.atspi.Event.Object")]
internal interface IEventObject : Introspectable
{
event AtspiEventHandler PropertyChange;
event AtspiEventHandler BoundsChanged;
event AtspiEventHandler LinkSelected;
event AtspiEventHandler StateChanged;
event AtspiEventHandler ChildrenChanged;
event AtspiEventHandler VisibleDataChanged;
event AtspiEventHandler SelectionChanged;
event AtspiEventHandler ModelChanged;
event AtspiEventHandler ActiveDescendantChanged;
event AtspiEventHandler RowInserted;
event AtspiEventHandler RowReordered;
event AtspiEventHandler RowDeleted;
event AtspiEventHandler ColumnInserted;
event AtspiEventHandler ColumnReordered;
event AtspiEventHandler ColumnDeleted;
event AtspiEventHandler TextBoundsChanged;
event AtspiEventHandler TextSelectionChanged;
event AtspiEventHandler TextChanged;
event AtspiEventHandler TextAttributesChanged;
event AtspiEventHandler TextCaretMoved;
event AtspiEventHandler AttributesChanged;
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Sce.Atf;
using Sce.Atf.Applications;
using Sce.Atf.Controls.PropertyEditing;
using Sce.Sled.Resources;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Plugin;
using Sce.Sled.Shared.Scmp;
using Sce.Sled.Shared.Services;
using Sce.Sled.Shared.Utilities;
namespace Sce.Sled
{
[Export(typeof(IInitializable))]
[Export(typeof(ISledTtyService))]
[Export(typeof(SledTtyService))]
[PartCreationPolicy(CreationPolicy.Shared)]
class SledTtyService : IInitializable, ISledTtyService, IControlHostClient, ICommandClient, IInstancingContext
{
[ImportingConstructor]
public SledTtyService(
MainForm mainForm,
ICommandService commandService,
ISettingsService settingsService,
IControlHostService controlHostService)
{
m_mainForm = mainForm;
m_commandService = commandService;
m_lastFlush = DateTime.Now;
// Create GUI
m_control =
new SledTtyGui
{
Name = "TTY",
ColumnNames = new[] {"Time", "Data"}
};
m_control.SendClicked += ControlSendClicked;
// Register menu
commandService.RegisterMenu(
Menu.Tty,
Localization.SledTTY,
Localization.SledTTYOptions);
// Register command to bring up TTY filters
commandService.RegisterCommand(
Command.Filter,
Menu.Tty,
CommandGroup.Tty,
Localization.SledTTYFilterTTYOutput,
Localization.SledTTYFilterTTYOutputComment,
Keys.None,
null,
CommandVisibility.Menu,
this);
// Register clear TTY window command
commandService.RegisterCommand(
Command.Clear,
Menu.Tty,
CommandGroup.Tty,
Localization.SledTTYClearTTYWindow,
Localization.SledTTYClearTTYWindowComment,
Keys.None,
null,
CommandVisibility.Menu,
this);
// Save the TTY filter list
settingsService.RegisterSettings(
this,
new BoundPropertyDescriptor(
this,
() => TtyFilters,
Resources.Resource.TTYFilterListTitle,
Resources.Resource.TTY,
Resources.Resource.TTYFilterListComment));
// Save GUI settings
settingsService.RegisterSettings(
this,
new BoundPropertyDescriptor(
this,
() => GuiSettings,
"Tty GUI Settings",
Resources.Resource.TTY,
"Tty GUI settings"));
}
#region IInitializable Interface
void IInitializable.Initialize()
{
m_control.Initialize();
var controlHostService =
SledServiceInstance.Get<IControlHostService>();
// Grab image
var image =
ResourceUtil.GetImage(Atf.Resources.UnsortedImage);
// Rotate image
image.RotateFlip(RotateFlipType.Rotate90FlipX);
var controlInfo =
new ControlInfo(
m_control.Name,
m_control.Name,
StandardControlGroup.Bottom,
image);
// Show GUI
controlHostService.RegisterControl(
m_control,
controlInfo,
this);
// Subscribe to events
m_debugService = SledServiceInstance.Get<ISledDebugService>();
m_debugService.DataReady += DebugServiceDataReady;
m_debugService.BreakpointContinue += DebugServiceBreakpointContinue;
m_debugService.UpdateEnd += DebugServiceUpdateEnd;
m_debugService.Disconnected += DebugServiceDisconnected;
m_projectService.Get.Closed += ProjectServiceClosed;
}
#endregion
#region Commands
enum Command
{
Filter,
Clear,
}
enum Menu
{
Tty,
}
enum CommandGroup
{
Tty,
}
#endregion
#region ICommandClient Interface
public bool CanDoCommand(object commandTag)
{
var bEnabled = false;
if (commandTag is Command)
{
switch ((Command)commandTag)
{
case Command.Clear:
case Command.Filter:
bEnabled = true;
break;
}
}
return bEnabled;
}
public void DoCommand(object commandTag)
{
if (!(commandTag is Command))
return;
switch ((Command)commandTag)
{
case Command.Clear:
Clear();
break;
case Command.Filter:
ShowTtyFilterForm();
break;
}
}
public void UpdateCommand(object commandTag, CommandState state)
{
}
#endregion
#region ISledTtyService Interface
public void Write(SledTtyMessage message)
{
if (message == null)
return;
if (StringUtil.IsNullOrEmptyOrWhitespace(message.Message))
return;
m_lstMessages.Add(message);
var now = DateTime.Now;
if (now.Subtract(m_lastFlush).TotalSeconds >= 1)
{
Flush();
return;
}
if (m_bShouldFlush)
Flush();
}
public void Clear()
{
m_control.Clear();
}
public bool InputEnabled
{
get { return m_control.SendEnabled; }
set { m_control.SendEnabled = value; }
}
public void RegisterLanguage(ISledLanguagePlugin languagePlugin)
{
if (languagePlugin == null)
throw new ArgumentNullException("languagePlugin");
m_control.RegisterLanguage(languagePlugin);
}
#endregion
#region Persisted Settings
public string TtyFilters
{
get
{
// Generate Xml string to contain the TTY filter list
var xmlDoc = new XmlDocument();
xmlDoc.AppendChild(
xmlDoc.CreateXmlDeclaration(
Resources.Resource.OnePointZero,
Resources.Resource.UtfDashEight,
Resources.Resource.YesLower));
var root = xmlDoc.CreateElement(Resources.Resource.TTYFilters);
xmlDoc.AppendChild(root);
try
{
foreach (var filter in m_lstFilters)
{
var elem = xmlDoc.CreateElement(Resources.Resource.TTYFilter);
elem.SetAttribute("filter", filter.Filter);
elem.SetAttribute("txtColorR", filter.TextColor.R.ToString());
elem.SetAttribute("txtColorG", filter.TextColor.G.ToString());
elem.SetAttribute("txtColorB", filter.TextColor.B.ToString());
elem.SetAttribute("bgColorR", filter.BackgroundColor.R.ToString());
elem.SetAttribute("bgColorG", filter.BackgroundColor.G.ToString());
elem.SetAttribute("bgColorB", filter.BackgroundColor.B.ToString());
elem.SetAttribute("result", (filter.Result == SledTtyFilterResult.Show) ? Resources.Resource.One : Resources.Resource.Zero);
root.AppendChild(elem);
}
if (xmlDoc.DocumentElement == null)
xmlDoc.RemoveAll();
else if (xmlDoc.DocumentElement.ChildNodes.Count == 0)
xmlDoc.RemoveAll();
}
catch (Exception ex)
{
xmlDoc.RemoveAll();
var szSetting = Resources.Resource.TTYFilters;
SledOutDevice.OutLine(
SledMessageType.Info,
SledUtil.TransSub(Localization.SledSettingsErrorExceptionSavingSetting, szSetting, ex.Message));
}
return xmlDoc.InnerXml.Trim();
}
set
{
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(value);
if (xmlDoc.DocumentElement == null)
return;
var nodes = xmlDoc.DocumentElement.SelectNodes(Resources.Resource.TTYFilter);
if ((nodes == null) || (nodes.Count == 0))
return;
foreach (XmlElement elem in nodes)
{
var filter = new SledTtyFilter(
elem.GetAttribute("filter"),
((int.Parse(elem.GetAttribute("result")) == 1) ? SledTtyFilterResult.Show : SledTtyFilterResult.Ignore),
Color.FromArgb(
int.Parse(elem.GetAttribute("txtColorR")),
int.Parse(elem.GetAttribute("txtColorG")),
int.Parse(elem.GetAttribute("txtColorB"))
),
Color.FromArgb(
int.Parse(elem.GetAttribute("bgColorR")),
int.Parse(elem.GetAttribute("bgColorG")),
int.Parse(elem.GetAttribute("bgColorB"))
));
m_lstFilters.Add(filter);
}
}
catch (Exception ex)
{
var szSetting = Resources.Resource.TTYFilters;
SledOutDevice.OutLine(
SledMessageType.Info,
SledUtil.TransSub(Localization.SledSettingsErrorExceptionLoadingSetting, szSetting, ex.Message));
}
}
}
public string GuiSettings
{
get { return m_control.Settings; }
set { m_control.Settings = value; }
}
#endregion
#region IControlHostClient Members
/// <summary>
/// Activates the client control</summary>
/// <param name="control">Client control to be activated</param>
public void Activate(Control control)
{
if (control != m_control)
return;
// We need to do this so we can steal keystrokes
m_commandService.SetActiveClient(this);
if (m_contextRegistry.Get != null)
m_contextRegistry.Get.ActiveContext = this;
}
/// <summary>
/// Deactivates the client control</summary>
/// <param name="control">Client control to be deactivated</param>
public void Deactivate(Control control)
{
}
/// <summary>
/// Closes the client control</summary>
/// <param name="control">Client control to be closed</param>
public bool Close(Control control)
{
return true;
}
#endregion
#region ISledProjectService Events
private void ProjectServiceClosed(object sender, SledProjectServiceProjectEventArgs e)
{
// Clear TTY when project closes
Clear();
}
#endregion
#region ISledDebugService Events
private void DebugServiceDataReady(object sender, SledDebugServiceEventArgs e)
{
var typeCode = (TypeCodes)e.Scmp.TypeCode;
switch (typeCode)
{
case TypeCodes.TtyBegin:
HandleTtyBegin();
break;
case TypeCodes.Tty:
HandleTty();
break;
case TypeCodes.TtyEnd:
HandleTtyEnd();
break;
}
}
private void DebugServiceBreakpointContinue(object sender, SledDebugServiceBreakpointEventArgs e)
{
InputEnabled = false;
}
private void DebugServiceUpdateEnd(object sender, SledDebugServiceBreakpointEventArgs e)
{
InputEnabled = true;
Flush();
}
private void DebugServiceDisconnected(object sender, SledDebugServiceEventArgs e)
{
InputEnabled = false;
}
#endregion
#region IInstancingContext Interface
public bool CanInsert(object data)
{
return false;
}
public void Insert(object data)
{
}
public bool CanCopy()
{
return m_control.SelectionCount != 0;
}
public object Copy()
{
var sb = new StringBuilder();
foreach (var message in m_control.Selection)
sb.Append(message.Message);
return new DataObject(sb.ToString());
}
public bool CanDelete()
{
return false;
}
public void Delete()
{
}
#endregion
#region Member Methods
private void ShowTtyFilterForm()
{
using (var form = new SledTtyFilterForm())
{
form.TtyFilterList = m_lstFilters;
form.ShowDialog(m_mainForm);
}
}
private void HandleTtyBegin()
{
m_builder.Remove(0, m_builder.Length);
}
private void HandleTty()
{
var tty = m_debugService.GetScmpBlob<Tty>();
m_builder.Append(tty.Message);
}
private void HandleTtyEnd()
{
ProcessTtyMessage(m_builder.ToString());
}
private void ProcessTtyMessage(string message)
{
if (string.IsNullOrEmpty(message))
return;
// Scan for embedded color tags
if (CheckTtyEmbeddedColorCodes(message))
return;
// No color tags; check against filters
if (m_lstFilters.Count <= 0)
{
// Not filters so display normally
Write(new SledTtyMessage(SledMessageType.Info, message));
}
else
{
// Run message through TTY filters
foreach (var filter in m_lstFilters)
{
// If it passes the filter it means the message
// matched the filter pattern
if (PassesTtyFilter(message, filter))
{
// Check what to do with this message
if (filter.Result == SledTtyFilterResult.Show)
Write(new SledTtyMessage(message, filter.TextColor, filter.BackgroundColor));
return;
}
}
// Default display - didn't match any filters
Write(new SledTtyMessage(SledMessageType.Info, message));
}
}
private bool CheckTtyEmbeddedColorCodes(string message)
{
if (string.IsNullOrEmpty(message))
return false;
var colorCodes = message.Split(s_ttyColorCodes, StringSplitOptions.RemoveEmptyEntries);
if (colorCodes.Length <= 1)
return false;
var bRetval = false;
var colTxtColor = Color.Black;
var colBgColor = Color.White;
var strippedMsg = message;
foreach (var colorCode in colorCodes)
{
var color = colorCode.Split(s_ttyColorCodesSep, StringSplitOptions.RemoveEmptyEntries);
if (color.Length != 4)
continue;
int r, g, b;
if (!int.TryParse(color[1], out r))
continue;
if (!int.TryParse(color[2], out g))
continue;
if (!int.TryParse(color[3], out b))
continue;
if (color[0] == "txt")
colTxtColor = Color.FromArgb(255, r, g, b);
else if (color[0] == "bg")
colBgColor = Color.FromArgb(255, r, g, b);
else
continue;
// If we got here lets pull the color code completely out of the string
var iPos = strippedMsg.IndexOf(Resources.Resource.LeftSquiggly + colorCode + Resources.Resource.RightSquiggly);
if (iPos == -1)
continue;
bRetval = true;
strippedMsg = strippedMsg.Remove(iPos, colorCode.Length + 2);
}
if (bRetval)
Write(new SledTtyMessage(strippedMsg, colTxtColor, colBgColor));
return bRetval;
}
private static bool PassesTtyFilter(string message, SledTtyFilter filter)
{
if (filter.Asterisks.Length <= 0)
{
// Direct comparison with filter string
if (message == filter.Filter)
return true;
}
else
{
// Filter pattern
// If filter string - number of asterisks is greater than the messages length it can't match
if ((filter.Filter.Length - filter.Asterisks.Length) > message.Length)
return false;
var iPos = -1;
// Go through checking each part of the filter
for (var i = 0; i < filter.FilterList.Count; i++)
{
iPos = message.IndexOf(filter.FilterList[i], iPos + 1);
// Pattern wasn't found
if (iPos == -1)
return false;
// On first iteration check first-asterisk condition
if ((i == 0) && !filter.FirstAsterisk && (iPos != 0))
return false;
// On last iteration check last-asterisk condition
if ((i == (filter.FilterList.Count - 1)) && !filter.LastAsterisk && (iPos != (message.Length - filter.FilterList[filter.FilterList.Count - 1].Length)))
return false;
}
return true;
}
return false;
}
private void ControlSendClicked(object sender, SledTtyGui.SendClickedEventArgs e)
{
if (e.Plugin == null)
{
// Don't clear the user entered text
e.ClearText = false;
// Show error message
MessageBox.Show(
Localization.SledTTYErrorInvalidLanguage,
Localization.SledTTYErrorTitle,
MessageBoxButtons.OK);
return;
}
Write(new SledTtyMessage(SledMessageType.Info, e.Text));
m_bShouldFlush = true;
m_debugService.SendScmp(new DevCmd(e.Plugin.LanguageId, e.Text));
}
private void Flush()
{
try
{
m_control.AppendMessages(m_lstMessages);
m_lstMessages.Clear();
}
finally
{
m_lastFlush = DateTime.Now;
m_bShouldFlush = false;
}
}
#endregion
private bool m_bShouldFlush;
private DateTime m_lastFlush;
private ISledDebugService m_debugService;
private readonly MainForm m_mainForm;
private readonly SledTtyGui m_control;
private readonly ICommandService m_commandService;
private readonly StringBuilder m_builder =
new StringBuilder();
private readonly List<SledTtyFilter> m_lstFilters =
new List<SledTtyFilter>();
private readonly List<SledTtyMessage> m_lstMessages =
new List<SledTtyMessage>();
private readonly static char[] s_ttyColorCodes =
new[] { '{', '}' };
private readonly static char[] s_ttyColorCodesSep =
new[] { '|' };
private readonly SledServiceReference<ISledProjectService> m_projectService =
new SledServiceReference<ISledProjectService>();
private readonly SledServiceReference<IContextRegistry> m_contextRegistry =
new SledServiceReference<IContextRegistry>();
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Reflection;
namespace NUnit.Framework.Internal
{
#if NETSTANDARD1_6
internal class AssemblyLoader : System.Runtime.Loader.AssemblyLoadContext
{
protected override Assembly Load(AssemblyName assemblyName)
{
return Assembly.Load(assemblyName);
}
}
#endif
/// <summary>
/// AssemblyHelper provides static methods for working
/// with assemblies.
/// </summary>
public static class AssemblyHelper
{
#if PORTABLE || NETSTANDARD1_6
const string UriSchemeFile = "file";
const string SchemeDelimiter = "://";
#else
static readonly string UriSchemeFile = Uri.UriSchemeFile;
static readonly string SchemeDelimiter = Uri.SchemeDelimiter;
#endif
#region GetAssemblyPath
/// <summary>
/// Gets the path from which an assembly was loaded.
/// For builds where this is not possible, returns
/// the name of the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>The path.</returns>
public static string GetAssemblyPath(Assembly assembly)
{
#if PORTABLE
return assembly.ManifestModule.FullyQualifiedName;
#else
string codeBase = assembly.CodeBase;
if (IsFileUri(codeBase))
return GetAssemblyPathFromCodeBase(codeBase);
return assembly.Location;
#endif
}
#endregion
#region GetDirectoryName
#if !PORTABLE
/// <summary>
/// Gets the path to the directory from which an assembly was loaded.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>The path.</returns>
public static string GetDirectoryName(Assembly assembly)
{
return Path.GetDirectoryName(GetAssemblyPath(assembly));
}
#endif
#endregion
#region GetAssemblyName
/// <summary>
/// Gets the AssemblyName of an assembly.
/// </summary>
/// <param name="assembly">The assembly</param>
/// <returns>An AssemblyName</returns>
public static AssemblyName GetAssemblyName(Assembly assembly)
{
#if PORTABLE
return new AssemblyName(assembly.FullName);
#else
return assembly.GetName();
#endif
}
#endregion
#region Load
#if PORTABLE
/// <summary>
/// Loads an assembly given a string, which is the AssemblyName
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Assembly Load(string name)
{
var ext = Path.GetExtension(name);
if (ext == ".dll" || ext == ".exe")
name = Path.GetFileNameWithoutExtension(name);
return Assembly.Load(new AssemblyName { Name = name });
}
#elif NETSTANDARD1_6
/// <summary>
/// Loads an assembly given a string, which may be the
/// path to the assembly or the AssemblyName
/// </summary>
/// <param name="nameOrPath"></param>
/// <returns></returns>
public static Assembly Load(string nameOrPath)
{
var ext = Path.GetExtension(nameOrPath).ToLower();
// Handle case where this is the path to an assembly
if (ext == ".dll" || ext == ".exe")
{
var loader = new AssemblyLoader();
return loader.LoadFromAssemblyPath(Path.GetFullPath(nameOrPath));
}
// Assume it's the string representation of an AssemblyName
return Assembly.Load(new AssemblyName { Name = nameOrPath });
}
#else
/// <summary>
/// Loads an assembly given a string, which may be the
/// path to the assembly or the AssemblyName
/// </summary>
/// <param name="nameOrPath"></param>
/// <returns></returns>
public static Assembly Load(string nameOrPath)
{
var ext = Path.GetExtension(nameOrPath).ToLower();
// Handle case where this is the path to an assembly
if (ext == ".dll" || ext == ".exe")
{
return Assembly.Load(AssemblyName.GetAssemblyName(nameOrPath));
}
// Assume it's the string representation of an AssemblyName
return Assembly.Load(nameOrPath);
}
#endif
#endregion
#region Helper Methods
private static bool IsFileUri(string uri)
{
return uri.ToLower().StartsWith(UriSchemeFile);
}
/// <summary>
/// Gets the assembly path from code base.
/// </summary>
/// <remarks>Public for testing purposes</remarks>
/// <param name="codeBase">The code base.</param>
/// <returns></returns>
public static string GetAssemblyPathFromCodeBase(string codeBase)
{
// Skip over the file:// part
int start = UriSchemeFile.Length + SchemeDelimiter.Length;
if (codeBase[start] == '/') // third slash means a local path
{
// Handle Windows Drive specifications
if (codeBase[start + 2] == ':')
++start;
// else leave the last slash so path is absolute
}
else // It's either a Windows Drive spec or a share
{
if (codeBase[start + 1] != ':')
start -= 2; // Back up to include two slashes
}
return codeBase.Substring(start);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using TIKSN.Localization;
namespace TIKSN.Shell
{
public class ShellCommandEngine : IShellCommandEngine
{
private readonly IConsoleService _consoleService;
private readonly ILogger<ShellCommandEngine> _logger;
private readonly IServiceProvider _serviceProvider;
private readonly IStringLocalizer _stringLocalizer;
private readonly List<Tuple<Type, ShellCommandAttribute, ConstructorInfo,
IEnumerable<Tuple<ShellCommandParameterAttribute, PropertyInfo>>>> commands;
public ShellCommandEngine(IServiceProvider serviceProvider, ILogger<ShellCommandEngine> logger,
IStringLocalizer stringLocalizer, IConsoleService consoleService)
{
this.commands =
new List<Tuple<Type, ShellCommandAttribute, ConstructorInfo,
IEnumerable<Tuple<ShellCommandParameterAttribute, PropertyInfo>>>>();
this._logger = logger;
this._stringLocalizer = stringLocalizer;
this._consoleService = consoleService;
this._serviceProvider = serviceProvider;
}
public void AddAssembly(Assembly assembly)
{
foreach (var definedType in assembly.DefinedTypes)
{
_ = this.TryAddType(definedType.AsType());
}
}
public void AddType(Type type)
{
if (this.commands.Any(item => item.Item1 == type))
{
return;
}
if (!type.GetInterfaces().Contains(typeof(IShellCommand)))
{
throw new ArgumentException(
this._stringLocalizer.GetRequiredString(LocalizationKeys.Key588506767, type.FullName,
typeof(IShellCommand).FullName), nameof(type));
}
var commandAttribute = type.GetTypeInfo().GetCustomAttribute<ShellCommandAttribute>();
if (commandAttribute == null)
{
throw new ArgumentException(
this._stringLocalizer.GetRequiredString(LocalizationKeys.Key491461331, type.FullName,
typeof(ShellCommandAttribute).FullName), nameof(type));
}
this._logger.LogDebug(804856258, $"Checking command name localization for '{type.FullName}' command.");
_ = commandAttribute.GetName(this._stringLocalizer);
var constructors = type.GetConstructors();
if (constructors.Length != 1)
{
throw new ArgumentException(
this._stringLocalizer.GetRequiredString(LocalizationKeys.Key225262334, type.FullName),
nameof(type));
}
var properties = new List<Tuple<ShellCommandParameterAttribute, PropertyInfo>>();
foreach (var propertyInfo in type.GetProperties())
{
var commandParameterAttribute = propertyInfo.GetCustomAttribute<ShellCommandParameterAttribute>();
if (commandParameterAttribute != null)
{
this._logger.LogDebug(804856258,
$"Checking string localization for '{type.FullName}' command's '{propertyInfo.Name}' parameter.");
_ = commandParameterAttribute.GetName(this._stringLocalizer);
properties.Add(
new Tuple<ShellCommandParameterAttribute, PropertyInfo>(commandParameterAttribute,
propertyInfo));
}
}
this.commands.Add(
new Tuple<Type, ShellCommandAttribute, ConstructorInfo,
IEnumerable<Tuple<ShellCommandParameterAttribute, PropertyInfo>>>(
type, commandAttribute, constructors.Single(), properties));
}
public async Task RunAsync()
{
while (true)
{
var command = this._consoleService.ReadLine(
this._stringLocalizer.GetRequiredString(LocalizationKeys.Key671767216), ConsoleColor.Green);
if (string.IsNullOrWhiteSpace(command))
{
continue;
}
command = NormalizeCommandName(command);
if (string.Equals(command, this._stringLocalizer.GetRequiredString(LocalizationKeys.Key785393579),
StringComparison.OrdinalIgnoreCase))
{
break;
}
if (string.Equals(command, this._stringLocalizer.GetRequiredString(LocalizationKeys.Key427524976),
StringComparison.OrdinalIgnoreCase))
{
var helpItems = new List<ShellCommandHelpItem>
{
new ShellCommandHelpItem(
NormalizeCommandName(
this._stringLocalizer.GetRequiredString(LocalizationKeys.Key785393579)),
Enumerable.Empty<string>()),
new ShellCommandHelpItem(
NormalizeCommandName(
this._stringLocalizer.GetRequiredString(LocalizationKeys.Key427524976)),
Enumerable.Empty<string>())
};
foreach (var commandItem in this.commands)
{
helpItems.Add(new ShellCommandHelpItem(
NormalizeCommandName(commandItem.Item2.GetName(this._stringLocalizer)),
commandItem.Item4.Select(item => item.Item1.GetName(this._stringLocalizer))));
}
helpItems = helpItems.OrderBy(i => i.CommandName).ToList();
this._consoleService.WriteObjects(helpItems);
}
else
{
var matches = this.commands.Where(item => string.Equals(command,
NormalizeCommandName(item.Item2.GetName(this._stringLocalizer)),
StringComparison.OrdinalIgnoreCase));
switch (matches.Count())
{
case 0:
this._consoleService.WriteError(
this._stringLocalizer.GetRequiredString(LocalizationKeys.Key879318823));
break;
case 1:
await this.RunCommandAsync(command, matches.Single()).ConfigureAwait(false);
break;
default:
break;
}
}
}
}
private static void AppendExceptionMessage(StringBuilder messageBuilder, Exception exception)
{
_ = messageBuilder.Append(exception.Message);
if (exception.Message.EndsWith(".", StringComparison.OrdinalIgnoreCase))
{
_ = messageBuilder.Append(' ');
}
else
{
_ = messageBuilder.Append(". ");
}
}
private void AppendException(StringBuilder messageBuilder, Exception exception)
{
AppendExceptionMessage(messageBuilder, exception);
if (exception.InnerException != null)
{
this.AppendException(messageBuilder, exception.InnerException);
}
}
private static string NormalizeCommandName(string command)
{
if (command != null)
{
var additionalSeparators = new[] { "-", "_" };
var normalizedParts = command.Split(null)
.SelectMany(whitespaceSeparatedPart =>
whitespaceSeparatedPart.Split(additionalSeparators, StringSplitOptions.RemoveEmptyEntries));
return string.Join(" ", normalizedParts);
}
return command;
}
private void PrintError(EventId eventId, Exception exception)
{
var messageBuilder = new StringBuilder();
AppendExceptionMessage(messageBuilder, exception);
this.AppendException(messageBuilder, exception);
var builtMessage = messageBuilder.ToString();
this._consoleService.WriteError(builtMessage);
this._logger.LogError(eventId, exception, builtMessage);
}
private object ReadCommandParameter(Tuple<ShellCommandParameterAttribute, PropertyInfo> property)
{
if (property.Item2.PropertyType == typeof(SecureString))
{
var secureStringParameter =
this._consoleService.ReadPasswordLine(property.Item1.GetName(this._stringLocalizer),
ConsoleColor.Green);
if (property.Item1.Mandatory && secureStringParameter.Length == 0)
{
return this.ReadCommandParameter(property);
}
return secureStringParameter;
}
var stringParameter =
this._consoleService.ReadLine(property.Item1.GetName(this._stringLocalizer), ConsoleColor.Green);
if (string.IsNullOrEmpty(stringParameter))
{
if (property.Item1.Mandatory)
{
return this.ReadCommandParameter(property);
}
return null;
}
var typeToConvert = property.Item2.PropertyType;
if (typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(Nullable<>))
{
typeToConvert = Nullable.GetUnderlyingType(typeToConvert);
}
return Convert.ChangeType(stringParameter, typeToConvert);
}
private async Task RunCommandAsync(string commandName,
Tuple<Type, ShellCommandAttribute, ConstructorInfo,
IEnumerable<Tuple<ShellCommandParameterAttribute, PropertyInfo>>> commandInfo)
{
using var commandScope = this._serviceProvider.CreateScope();
try
{
var commandContextStore =
commandScope.ServiceProvider.GetRequiredService<IShellCommandContext>() as
IShellCommandContextStore;
commandContextStore.SetCommandName(commandName);
var args = new List<object>();
foreach (var parameterInfo in commandInfo.Item3.GetParameters())
{
args.Add(commandScope.ServiceProvider.GetRequiredService(parameterInfo.ParameterType));
}
var obj = Activator.CreateInstance(commandInfo.Item1, args.ToArray());
foreach (var property in commandInfo.Item4)
{
var parameter = this.ReadCommandParameter(property);
if (parameter != null)
{
property.Item2.SetValue(obj, parameter);
}
this._logger.LogTrace(
$"Parameter '{property.Item1.GetName(this._stringLocalizer)}' has value '{property.Item2.GetValue(obj)}'");
}
var command = obj as IShellCommand;
try
{
using (var cancellationTokenSource = new CancellationTokenSource())
using (this._consoleService.RegisterCancellation(cancellationTokenSource))
{
await command.ExecuteAsync(cancellationTokenSource.Token).ConfigureAwait(false);
}
}
#pragma warning disable CC0004 // Catch block cannot be empty
catch (ShellCommandSuspendedException) { }
#pragma warning restore CC0004 // Catch block cannot be empty
catch (Exception ex)
{
this.PrintError(1815744366, ex);
}
}
catch (Exception ex)
{
this.PrintError(1999436483, ex);
}
}
private bool TryAddType(Type type)
{
try
{
this.AddType(type);
return true;
}
catch (Exception)
{
//_logger.LogError(1955486110, ex, "Failed to add type {0} as command.", type.FullName);
//_logger.LogDebug(650126203, ex, string.Empty);
return false;
}
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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.Text;
using System.Collections;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Caching.Topologies.Local;
using Alachisoft.NCache.Common.Util;
using Runtime = Alachisoft.NCache.Runtime;
namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
#region / --- BucketLockResult --- /
#endregion
#region / --- StateTxfrCorresponder --- /
class StateTxfrCorresponder : IDisposable
{
/// <summary>
/// 200K is the threshold data size.
/// Above this threshold value, data will be
/// transfered in chunks.
/// </summary>
protected long _threshold = 50 * 1024;//200 * 1000;
internal ClusterCacheBase _parent;
protected int _currentBucket = -1;
protected ArrayList _keyList;
protected Hashtable _keyUpdateLogTbl = new Hashtable();
protected int _keyCount;
protected bool _sendLogData = false;
int _lastTxfrId = 0;
private DistributionManager _distMgr;
private Address _clientNode;
private ArrayList _logableBuckets = new ArrayList();
private byte _transferType;
private bool _isBalanceDataLoad = false;
/// <summary>
/// Gets or sets a value indicating whether this StateTransfer Corresponder is in Data balancing mode or not.
/// </summary>
public bool IsBalanceDataLoad
{
get { return _isBalanceDataLoad; }
set { _isBalanceDataLoad = value; }
}
internal StateTxfrCorresponder(ClusterCacheBase parent, DistributionManager distMgr, Address requestingNode, byte transferType)
{
_parent = parent;
_distMgr = distMgr;
_clientNode = requestingNode;
_transferType = transferType;
}
public StateTxfrInfo TransferBucket(ArrayList bucketIds, bool sparsedBuckets, int expectedTxfrId)
{
if (bucketIds != null)
{
for (int i = bucketIds.Count - 1; i >= 0; i--)
{
int bkId = (int)bucketIds[i];
if (_transferType == StateTransferType.MOVE_DATA && !_distMgr.VerifyTemporaryOwnership(bkId, _clientNode))
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.TransferBucket", bkId + " ownership changed");
}
}
}
if (sparsedBuckets)
{
return GetData(bucketIds);
}
else
{
if (bucketIds != null && bucketIds.Count > 0)
{
foreach (int bucketId in bucketIds)
{
lock (_parent._bucketStateTxfrStatus.SyncRoot)
{
_parent._bucketStateTxfrStatus[bucketId] = true;
}
}
if (_currentBucket != (int)bucketIds[0])
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.TxfrBucket", "bucketid : " + bucketIds[0] + " exptxfrId : " + expectedTxfrId);
_lastTxfrId = expectedTxfrId;
//request for a new bucket.
//get its key list from parent.
_currentBucket = (int)bucketIds[0];
bool enableLogs = _transferType == StateTransferType.MOVE_DATA ? true : false;
ArrayList keyList = _parent.InternalCache.GetKeyList(_currentBucket, enableLogs);
_logableBuckets.Add(_currentBucket);
if (keyList != null)
_keyList = keyList.Clone() as ArrayList;
//muds:
//reset the _lastLogTblCount
_sendLogData = false;
}
else
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.TxfrBucket", "bucketid : " + bucketIds[0] + " exptxfrId : " + expectedTxfrId);
//remove all the last sent keys from keylist that has not been
//modified during this time.
if (_keyList != null && expectedTxfrId > _lastTxfrId)
{
lock (_keyList.SyncRoot)
{
_keyList.RemoveRange(0, _keyCount);
_keyCount = 0;
}
_lastTxfrId = expectedTxfrId;
}
}
}
else
{
return new StateTxfrInfo(new Hashtable(),null,null, true);
}
//take care that we need to send data in chunks if
//bucket is too large.
return GetData(_currentBucket);
}
}
protected StateTxfrInfo GetData(ArrayList bucketIds)
{
try
{
object[] keys = null;
Hashtable data = null;
Hashtable result = new Hashtable();
ArrayList payLoad = new ArrayList();
ArrayList payLoadCompilationInfo = new ArrayList();
if (!_sendLogData)
{
IEnumerator ie = bucketIds.GetEnumerator();
while (ie.MoveNext())
{
int bucketId = (int)ie.Current;
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(1)", "transfering data for bucket : " + bucketId);
bool enableLogs = _transferType == StateTransferType.MOVE_DATA ? true : false;
ArrayList keyList = _parent.InternalCache.GetKeyList(bucketId, enableLogs);
_logableBuckets.Add(bucketId);
data = null;
if (keyList != null)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(1)", "bucket : " + bucketId + " [" + keyList.Count + " ]");
keys = keyList.ToArray();
OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
data = _parent.InternalCache.Get(keys,operationContext);
}
if (data != null && data.Count > 0)
{
if (result.Count == 0)
{
result = data.Clone() as Hashtable;
}
else
{
IDictionaryEnumerator ide = data.GetEnumerator();
while (ide.MoveNext())
{
CacheEntry entry = ide.Value as CacheEntry;
UserBinaryObject ubObject = null;
if (entry.Value is CallbackEntry)
{
ubObject = ((CallbackEntry)entry.Value).Value as UserBinaryObject;
}
else
ubObject = entry.Value as UserBinaryObject;
payLoad.AddRange(ubObject.Data);
long size = entry.DataSize;
int index = payLoadCompilationInfo.Add(size);
PayloadInfo payLoadInfo = new PayloadInfo(entry.CloneWithoutValue(), index);
result[ide.Key] = payLoadInfo;
}
}
}
}
_sendLogData = true;
if (_parent.Context.NCacheLog.IsInfoEnabled)
_parent.Context.NCacheLog.Info("State Transfer Corresponder", "BalanceDataLoad = " + _isBalanceDataLoad.ToString());
if (_isBalanceDataLoad)
{
_parent.Context.PerfStatsColl.IncrementDataBalPerSecStatsBy(result.Count);
}
else
{
_parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(result.Count);
}
return new StateTxfrInfo(result,payLoad,payLoadCompilationInfo, false);
}
else
return GetLoggedData(bucketIds);
}
catch (Exception ex)
{
_parent.Context.NCacheLog.Error("StateTxfrCorresponder.GetData(1)", ex.ToString());
return null;
}
}
protected StateTxfrInfo GetData(int bucketId)
{
Hashtable result = new Hashtable();
ArrayList payLoad = new ArrayList();
ArrayList payLoadCompilationInfo = new ArrayList();
long sizeToSend = 0;
lock (_parent._bucketStateTxfrStatus.SyncRoot)
{
_parent._bucketStateTxfrStatus[bucketId] = true;
}
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "state txfr request for :" + bucketId + " txfrid :" + _lastTxfrId);
if (_keyList != null && _keyList.Count > 0)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "bucket size :" + _keyList.Count);
for (_keyCount = 0; _keyCount < _keyList.Count; _keyCount++)
{
string key = _keyList[_keyCount] as string;
OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
CacheEntry entry = _parent.InternalCache.InternalCache.Get(key, false,operationContext);
if (entry != null)
{
long size = (entry.InMemorySize + Common.MemoryUtil.GetStringSize(key));//.DataSize;
if (sizeToSend > _threshold) break;
UserBinaryObject ubObject = null;
if (entry.Value is CallbackEntry)
{
ubObject = ((CallbackEntry)entry.Value).Value as UserBinaryObject;
}
else
ubObject = entry.Value as UserBinaryObject;
payLoad.AddRange(ubObject.Data);
long entrySize = entry.DataSize;
int index = payLoadCompilationInfo.Add(entrySize);
PayloadInfo payLoadInfo = new PayloadInfo(entry.CloneWithoutValue(), index);
result[key] = payLoadInfo;
sizeToSend += size;
}
}
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "items sent :" + _keyCount);
if (_parent.Context.NCacheLog.IsInfoEnabled)
_parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "BalanceDataLoad = " + _isBalanceDataLoad.ToString());
if (_isBalanceDataLoad)
_parent.Context.PerfStatsColl.IncrementDataBalPerSecStatsBy(result.Count);
else
_parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(result.Count);
return new StateTxfrInfo(result,payLoad,payLoadCompilationInfo, false,sizeToSend);
}
else if (_transferType == StateTransferType.MOVE_DATA)
{
//We need to transfer the logs.
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "sending log data for bucket: " + bucketId);
ArrayList list = new ArrayList(1);
list.Add(bucketId);
return GetLoggedData(list);
}
else
{
//As transfer mode is not MOVE_DATA, therefore no logs are maintained
//and hence are not transferred.
return new StateTxfrInfo(null,null,null, true);
}
}
protected virtual StateTxfrInfo GetLoggedData(ArrayList bucketIds)
{
ArrayList updatedKeys = null;
ArrayList removedKeys = null;
Hashtable logTbl = null;
StateTxfrInfo info = null;
Hashtable result = new Hashtable();
ArrayList payLoad = new ArrayList();
ArrayList payLoadCompilationInfo = new ArrayList();
bool isLoggingStopped = false;
try
{
logTbl = _parent.InternalCache.GetLogTable(bucketIds, ref isLoggingStopped);
if (logTbl != null)
{
updatedKeys = logTbl["updated"] as ArrayList;
removedKeys = logTbl["removed"] as ArrayList;
if (updatedKeys != null && updatedKeys.Count > 0)
{
for (int i = 0; i < updatedKeys.Count; i++)
{
string key = updatedKeys[i] as string;
OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
CacheEntry entry = _parent.InternalCache.Get(key, false, operationContext);
UserBinaryObject ubObject = null;
if (entry.Value is CallbackEntry)
{
ubObject = ((CallbackEntry)entry.Value).Value as UserBinaryObject;
}
else
ubObject = entry.Value as UserBinaryObject;
payLoad.AddRange(ubObject.Data);
long size = entry.DataSize;
int index = payLoadCompilationInfo.Add(size);
PayloadInfo payLoadInfo = new PayloadInfo(entry.CloneWithoutValue(), index);
result[key] = payLoadInfo;
}
}
if (removedKeys != null && removedKeys.Count > 0)
{
for (int i = 0; i < removedKeys.Count; i++)
{
string key = removedKeys[i] as string;
result[key] = null;
}
}
if (!isLoggingStopped)
info = new StateTxfrInfo(result,payLoad,payLoadCompilationInfo, false);
else
info = new StateTxfrInfo(result, payLoad, payLoadCompilationInfo, true);
_parent.Context.NCacheLog.Debug("StateTxfrCorresponder.GetLoggedData()", info == null ? "returning null state-txfr-info" : "returning " + info.data.Count.ToString() + " items in state-txfr-info");
return info;
}
else
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresoponder.GetLoggedData", "no logged data found");
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error("StateTxfrCorresoponder.GetLoggedData", e.ToString());
throw;
}
finally
{
}
//no operation has been logged during state transfer.
//so announce completion of state transfer for this bucket.
return new StateTxfrInfo(result, payLoad, payLoadCompilationInfo, true);
}
#region IDisposable Members
/// <summary>
/// Disposes the state txfr corresponder. On dispose corresponder should
/// stop logger in the hashed cache if it has turned on any one.
/// </summary>
public void Dispose()
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.Dispose", _clientNode.ToString() + " corresponder disposed");
if(_keyList != null) _keyList.Clear();
if(_keyUpdateLogTbl != null) _keyUpdateLogTbl.Clear();
if (_transferType == StateTransferType.MOVE_DATA)
{
if (_parent != null && _logableBuckets != null)
{
for (int i = 0; i < _logableBuckets.Count; i++)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.Dispose", " removing logs for bucketid " + _logableBuckets[i]);
_parent.RemoveFromLogTbl((int)_logableBuckets[i]);
}
}
}
}
#endregion
}
#endregion
#region / --- BucketTxfrInfo --- /
#endregion
#region / --- BucketTxfrInfo --- /
#endregion
#region / --- StateTxfrInfo --- /
#endregion
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Map : MonoBehaviour {
public static Map instance = null;
public int m_xCell = 4; //casillas en X
public int m_zCell = 4; // casillas en Z
public float m_xSize = 1.0f; //tamano de las celdas en X
public float m_zSize = 1.0f; //tamano de las celdas en Z
public List<GameObject>[][] m_ObjectsMap;
public Renderer[][] m_Quads;
public bool[][] m_visited;
public bool[][] m_visiting;
public int m_xFogCell; //casillas en X
public int m_zFogCell; // casillas en Z
private bool execution = false;
public bool draw = true;
public GameObject fogQuad;
public float fogQuadScale;
void Awake()
{
//if (instance == null)
{
instance = this;
// DontDestroyOnLoad(instance);
execution = true;
m_ObjectsMap = new List<GameObject>[m_xCell][];
for (int x = 0; x < m_xCell; ++x)
{
m_ObjectsMap[x] = new List<GameObject>[m_zCell];
for (int z = 0; z < m_zCell; ++z)
{
m_ObjectsMap[x][z] = new List<GameObject>(2);
}
}
GameObject quadsMap = new GameObject("FogMap");
quadsMap = (GameObject)Instantiate(quadsMap);
float maxX = m_xCell * m_xSize;
float maxZ = m_zCell * m_zSize;
m_xFogCell = (int)(maxX / fogQuadScale);
m_zFogCell = (int)(maxZ / fogQuadScale);
Vector3 position = transform.position;
position.y = 5;
position.x += fogQuadScale * 0.5f;
m_visited = new bool[m_xFogCell][];
m_visiting = new bool[m_xFogCell][];
m_Quads = new Renderer[m_xFogCell][];
for (int i = 0; i < m_xFogCell; ++i)
{
m_visited[i] = new bool[m_zFogCell];
m_visiting[i] = new bool[m_zFogCell];
m_Quads[i] = new Renderer[m_zFogCell];
position.z = transform.position.z + fogQuadScale * 0.5f;
for (int j = 0; j < m_zFogCell; ++j)
{
m_visited[i][j] = false;
m_visiting[i][j] = false;
m_Quads[i][j] = ((GameObject)Instantiate(fogQuad, position, fogQuad.transform.rotation)).GetComponent < Renderer>();
m_Quads[i][j].gameObject.transform.localScale = new Vector3(fogQuadScale, fogQuadScale, 1);
m_Quads[i][j].material = new Material(m_Quads[i][j].material);
m_Quads[i][j].transform.parent = quadsMap.transform;
position.z += fogQuadScale;
}
position.x += fogQuadScale;
}
}
/*else if (instance != this)
{
Destroy(this.gameObject);
}*/
}
// Use this for initialization
void Start () {
init();
}
void init()
{
}
void OnDrawGizmos()
{
if (!draw) return;
// Display the explosion radius when selected
if (execution)
{
for (uint x = 0; x < m_xCell; ++x)
{
for (uint z = 0; z < m_zCell; ++z)
{
if (m_ObjectsMap[x][z].Count > 0)
{
Gizmos.color = Color.green;
}
else
{
Gizmos.color = Color.blue;
}
Gizmos.DrawCube(new Vector3(x * m_xSize + m_xSize * 0.5f, -0.1f, z * m_zSize + m_zSize * 0.5f), new Vector3(m_xSize, 0.2f, m_zSize));
}
}
}
Gizmos.color = Color.white;
for (uint z = 0; z <= m_zCell; ++z) {
Gizmos.DrawLine(new Vector3(0, 0.1f, z * m_zSize), new Vector3(m_xCell * m_xSize, 0.1f, z * m_zSize));
}
for (uint x = 0; x <= m_xCell; ++x)
{
Gizmos.DrawLine(new Vector3(x * m_xSize, 0.11f, 0), new Vector3(x * m_xSize, 0.1f, m_zCell * m_zSize));
}
}
public void addObjectToMap(Vector3 position, GameObject go)
{
int x = (int)(position.x / m_xSize);
int z = (int)(position.z / m_zSize);
if (x < m_xCell && z < m_zCell)
{
m_ObjectsMap[x][z].Add(go);
Unit unitAux = go.GetComponent<Unit>();
if (unitAux != null)
{
unitAux.setMapXZ(x, z);
}
else
{
Buildng buildAux = go.GetComponent<Buildng>();
if (buildAux != null)
{
buildAux.setMapXZ(x, z);
}
}
}
}
public void remObjectToMap(int x, int z, GameObject go)
{
m_ObjectsMap[x][z].Remove(go);
}
public void moveObjectToMap(int x, int z, Vector3 position, GameObject go)
{
int newX = (int)(position.x / m_xSize);
int newZ = (int)(position.z / m_zSize);
if (newX == x && newZ == z) return;
remObjectToMap(x, z, go);
addObjectToMap(position, go);
}
public GameObject anyEnemyInRadious(Vector3 position, float radious, int team)
{
GameObject goAux = null;
int nearestX = int.MaxValue;
int nearestZ = int.MaxValue;
int xMin = (int)((position.x - radious) / m_xSize);
int zMin = (int)((position.z - radious) / m_zSize);
int xMax = (int)((position.x + radious) / m_xSize);
int zMax = (int)((position.z + radious) / m_zSize);
for (int x = xMin; x <= xMax; ++x)
{
for (int z = zMin; z <= zMax; ++z)
{
if (x < m_xCell && z < m_zCell)
{
for (int i = 0; i < m_ObjectsMap[x][z].Count; ++i)
{
//mejorable, mucho...
Unit unitAux = m_ObjectsMap[x][z][i].GetComponent<Unit>();
if ( unitAux !=null)
{
if ((unitAux.getTeam() != team) /*&& (nearestX > x || nearestZ > z )*/)
{
goAux = m_ObjectsMap[x][z][i];
nearestX = x;
nearestZ = z;
}
}
else
{
Buildng buildingAux = m_ObjectsMap[x][z][i].GetComponent<Buildng>();
if (buildingAux != null)
{
if (buildingAux.getTeam() != team && (nearestX > x || nearestZ > z))
{
goAux = m_ObjectsMap[x][z][i];
nearestX = x;
nearestZ = z;
}
}
}
}
}
}
}
return goAux;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine
{
public class DiagnosticAnalyzerDriverTests
{
[Fact]
public async Task DiagnosticAnalyzerDriverAllInOne()
{
var source = TestResource.AllInOneCSharpCode;
// AllInOneCSharpCode has no properties with initializers or named types with primary constructors.
var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>();
symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property);
symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType);
// AllInOneCSharpCode has no pattern matching.
var syntaxKindsPatterns = new HashSet<SyntaxKind>();
syntaxKindsPatterns.Add(SyntaxKind.IsPatternExpression);
syntaxKindsPatterns.Add(SyntaxKind.DeclarationPattern);
syntaxKindsPatterns.Add(SyntaxKind.ConstantPattern);
syntaxKindsPatterns.Add(SyntaxKind.WhenClause);
syntaxKindsPatterns.Add(SyntaxKind.CasePatternSwitchLabel);
var analyzer = new CSharpTrackingDiagnosticAnalyzer();
using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular))
{
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
AccessSupportedDiagnostics(analyzer);
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length));
analyzer.VerifyAllAnalyzerMembersWereCalled();
analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds();
analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(syntaxKindsPatterns);
analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true);
}
}
[Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")]
public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock()
{
var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" };
var source = @"
[System.Obsolete]
class C
{
int P { get; set; }
delegate void A();
delegate string F();
}
";
var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer();
using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source))
{
var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single();
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length));
foreach (var method in methodNames)
{
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid));
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid));
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType));
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property));
}
}
var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer();
using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source))
{
var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer });
foreach (var method in methodNames)
{
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid));
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid));
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType));
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property));
}
}
}
[Fact]
[WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")]
public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions()
{
var source = TestResource.AllInOneCSharpCode;
using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular))
{
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer =>
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true));
}
}
[WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")]
[Fact]
public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1()
{
var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>();
analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name);
AccessSupportedDiagnostics(analyzer);
}
[WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")]
[Fact]
public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2()
{
var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>();
analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name);
var exceptions = new List<Exception>();
try
{
AccessSupportedDiagnostics(analyzer);
}
catch (Exception e)
{
exceptions.Add(e);
}
Assert.True(exceptions.Count == 0);
}
[Fact]
public async Task AnalyzerOptionsArePassedToAllAnalyzers()
{
using (var workspace = await TestWorkspace.CreateCSharpAsync(TestResource.AllInOneCSharpCode, TestOptions.Regular))
{
var currentProject = workspace.CurrentSolution.Projects.Single();
var additionalDocId = DocumentId.CreateNewId(currentProject.Id);
var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text"));
currentProject = newSln.Projects.Single();
var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId);
AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.GetDocumentState());
AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream));
var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options);
var sourceDocument = currentProject.Documents.Single();
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length));
analyzer.VerifyAnalyzerOptions();
}
}
private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer)
{
var diagnosticService = new TestDiagnosticAnalyzerService(LanguageNames.CSharp, analyzer);
diagnosticService.GetDiagnosticDescriptors(projectOpt: null);
}
private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct
{
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SyntaxAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis;
}
}
[Fact]
public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer()
{
var source = @"x";
var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer();
using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source))
{
var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single();
var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length));
var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic");
Assert.Equal(1, diagnosticsFromAnalyzer.Count());
}
}
private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer
{
private const string ID = "SyntaxDiagnostic";
private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor =
new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(s_syntaxDiagnosticDescriptor);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
}
public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
{
context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree);
}
private class SyntaxTreeAnalyzer
{
public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation()));
}
}
}
[Fact]
public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode()
{
var source = @"
using System;
class C
{
void F(int x = 0)
{
Console.WriteLine(0);
}
}
";
var analyzer = new CodeBlockAnalyzerFactory();
using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source))
{
var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single();
var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length));
var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id);
Assert.Equal(2, diagnosticsFromAnalyzer.Count());
}
source = @"
using System;
class C
{
void F(int x = 0, int y = 1, int z = 2)
{
Console.WriteLine(0);
}
}
";
using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source))
{
var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer });
var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id);
Assert.Equal(4, diagnosticsFromAnalyzer.Count());
}
}
private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer
{
public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Descriptor);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock);
}
public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context)
{
var blockAnalyzer = new CodeBlockAnalyzer();
context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock);
context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray());
}
private class CodeBlockAnalyzer
{
public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest
{
get
{
return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause);
}
}
public void AnalyzeCodeBlock(CodeBlockAnalysisContext context)
{
}
public void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
// Ensure only executable nodes are analyzed.
Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind());
context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation()));
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="LandingPageViewServiceClient"/> instances.</summary>
public sealed partial class LandingPageViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="LandingPageViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="LandingPageViewServiceSettings"/>.</returns>
public static LandingPageViewServiceSettings GetDefault() => new LandingPageViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="LandingPageViewServiceSettings"/> object with default settings.
/// </summary>
public LandingPageViewServiceSettings()
{
}
private LandingPageViewServiceSettings(LandingPageViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetLandingPageViewSettings = existing.GetLandingPageViewSettings;
OnCopy(existing);
}
partial void OnCopy(LandingPageViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>LandingPageViewServiceClient.GetLandingPageView</c> and
/// <c>LandingPageViewServiceClient.GetLandingPageViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetLandingPageViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="LandingPageViewServiceSettings"/> object.</returns>
public LandingPageViewServiceSettings Clone() => new LandingPageViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="LandingPageViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class LandingPageViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<LandingPageViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public LandingPageViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public LandingPageViewServiceClientBuilder()
{
UseJwtAccessWithScopes = LandingPageViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref LandingPageViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<LandingPageViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override LandingPageViewServiceClient Build()
{
LandingPageViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<LandingPageViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<LandingPageViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private LandingPageViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return LandingPageViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<LandingPageViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return LandingPageViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => LandingPageViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => LandingPageViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => LandingPageViewServiceClient.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>LandingPageViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch landing page views.
/// </remarks>
public abstract partial class LandingPageViewServiceClient
{
/// <summary>
/// The default endpoint for the LandingPageViewService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default LandingPageViewService scopes.</summary>
/// <remarks>
/// The default LandingPageViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="LandingPageViewServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="LandingPageViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="LandingPageViewServiceClient"/>.</returns>
public static stt::Task<LandingPageViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new LandingPageViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="LandingPageViewServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="LandingPageViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="LandingPageViewServiceClient"/>.</returns>
public static LandingPageViewServiceClient Create() => new LandingPageViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="LandingPageViewServiceClient"/> 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="LandingPageViewServiceSettings"/>.</param>
/// <returns>The created <see cref="LandingPageViewServiceClient"/>.</returns>
internal static LandingPageViewServiceClient Create(grpccore::CallInvoker callInvoker, LandingPageViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
LandingPageViewService.LandingPageViewServiceClient grpcClient = new LandingPageViewService.LandingPageViewServiceClient(callInvoker);
return new LandingPageViewServiceClientImpl(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 LandingPageViewService client</summary>
public virtual LandingPageViewService.LandingPageViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::LandingPageView GetLandingPageView(GetLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::LandingPageView> GetLandingPageViewAsync(GetLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::LandingPageView> GetLandingPageViewAsync(GetLandingPageViewRequest request, st::CancellationToken cancellationToken) =>
GetLandingPageViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the landing page view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::LandingPageView GetLandingPageView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetLandingPageView(new GetLandingPageViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the landing page view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::LandingPageView> GetLandingPageViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetLandingPageViewAsync(new GetLandingPageViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the landing page view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::LandingPageView> GetLandingPageViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetLandingPageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the landing page view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::LandingPageView GetLandingPageView(gagvr::LandingPageViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetLandingPageView(new GetLandingPageViewRequest
{
ResourceNameAsLandingPageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the landing page view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::LandingPageView> GetLandingPageViewAsync(gagvr::LandingPageViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetLandingPageViewAsync(new GetLandingPageViewRequest
{
ResourceNameAsLandingPageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the landing page view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::LandingPageView> GetLandingPageViewAsync(gagvr::LandingPageViewName resourceName, st::CancellationToken cancellationToken) =>
GetLandingPageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>LandingPageViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch landing page views.
/// </remarks>
public sealed partial class LandingPageViewServiceClientImpl : LandingPageViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetLandingPageViewRequest, gagvr::LandingPageView> _callGetLandingPageView;
/// <summary>
/// Constructs a client wrapper for the LandingPageViewService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="LandingPageViewServiceSettings"/> used within this client.
/// </param>
public LandingPageViewServiceClientImpl(LandingPageViewService.LandingPageViewServiceClient grpcClient, LandingPageViewServiceSettings settings)
{
GrpcClient = grpcClient;
LandingPageViewServiceSettings effectiveSettings = settings ?? LandingPageViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetLandingPageView = clientHelper.BuildApiCall<GetLandingPageViewRequest, gagvr::LandingPageView>(grpcClient.GetLandingPageViewAsync, grpcClient.GetLandingPageView, effectiveSettings.GetLandingPageViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetLandingPageView);
Modify_GetLandingPageViewApiCall(ref _callGetLandingPageView);
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_GetLandingPageViewApiCall(ref gaxgrpc::ApiCall<GetLandingPageViewRequest, gagvr::LandingPageView> call);
partial void OnConstruction(LandingPageViewService.LandingPageViewServiceClient grpcClient, LandingPageViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC LandingPageViewService client</summary>
public override LandingPageViewService.LandingPageViewServiceClient GrpcClient { get; }
partial void Modify_GetLandingPageViewRequest(ref GetLandingPageViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::LandingPageView GetLandingPageView(GetLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetLandingPageViewRequest(ref request, ref callSettings);
return _callGetLandingPageView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested landing page view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::LandingPageView> GetLandingPageViewAsync(GetLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetLandingPageViewRequest(ref request, ref callSettings);
return _callGetLandingPageView.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace CloudStack.Net
{
public class HostForMigrationResponse
{
/// <summary>
/// the ID of the host
/// </summary>
public string Id { get; set; }
/// <summary>
/// the cpu average load on the host
/// </summary>
public long AverageLoad { get; set; }
/// <summary>
/// capabilities of the host
/// </summary>
public string Capabilities { get; set; }
/// <summary>
/// the cluster ID of the host
/// </summary>
public string ClusterId { get; set; }
/// <summary>
/// the cluster name of the host
/// </summary>
public string ClusterName { get; set; }
/// <summary>
/// the cluster type of the cluster that host belongs to
/// </summary>
public string ClusterType { get; set; }
/// <summary>
/// the amount of the host's CPU currently allocated
/// </summary>
public string CpuAllocated { get; set; }
/// <summary>
/// the CPU number of the host
/// </summary>
public int? CpuNumber { get; set; }
/// <summary>
/// the CPU speed of the host
/// </summary>
public long CpuSpeed { get; set; }
/// <summary>
/// the amount of the host's CPU currently used
/// </summary>
public string CpuUsed { get; set; }
/// <summary>
/// the amount of the host's CPU after applying the cpu.overprovisioning.factor
/// </summary>
public string CpuWithOverprovisioning { get; set; }
/// <summary>
/// the date and time the host was created
/// </summary>
public DateTime Created { get; set; }
/// <summary>
/// true if the host is disconnected. False otherwise.
/// </summary>
public DateTime Disconnected { get; set; }
/// <summary>
/// the host's currently allocated disk size
/// </summary>
public long DiskSizeAllocated { get; set; }
/// <summary>
/// the total disk size of the host
/// </summary>
public long DiskSizeTotal { get; set; }
/// <summary>
/// events available for the host
/// </summary>
public string Events { get; set; }
/// <summary>
/// true if the host is Ha host (dedicated to vms started by HA process; false otherwise
/// </summary>
public bool HaHost { get; set; }
/// <summary>
/// true if this host has enough CPU and RAM capacity to migrate a VM to it, false otherwise
/// </summary>
public bool HasEnoughCapacity { get; set; }
/// <summary>
/// comma-separated list of tags for the host
/// </summary>
public string HostTags { get; set; }
/// <summary>
/// the host hypervisor
/// </summary>
public HypervisorType Hypervisor { get; set; }
/// <summary>
/// the hypervisor version
/// </summary>
public string HypervisorVersion { get; set; }
/// <summary>
/// the IP address of the host
/// </summary>
public string IpAddress { get; set; }
/// <summary>
/// true if local storage is active, false otherwise
/// </summary>
public bool Islocalstorageactive { get; set; }
/// <summary>
/// the date and time the host was last pinged
/// </summary>
public DateTime LastPinged { get; set; }
/// <summary>
/// the management server ID of the host
/// </summary>
public long ManagementServerId { get; set; }
/// <summary>
/// the amount of the host's memory currently allocated
/// </summary>
public long MemoryAllocated { get; set; }
/// <summary>
/// the memory total of the host
/// </summary>
public long MemoryTotal { get; set; }
/// <summary>
/// the amount of the host's memory currently used
/// </summary>
public long MemoryUsed { get; set; }
/// <summary>
/// the name of the host
/// </summary>
public string Name { get; set; }
/// <summary>
/// the incoming network traffic on the host
/// </summary>
public long NetworkKbsRead { get; set; }
/// <summary>
/// the outgoing network traffic on the host
/// </summary>
public long NetworkKbsWrite { get; set; }
/// <summary>
/// the OS category ID of the host
/// </summary>
public string OsCategoryId { get; set; }
/// <summary>
/// the OS category name of the host
/// </summary>
public string OsCategoryName { get; set; }
/// <summary>
/// the Pod ID of the host
/// </summary>
public string PodId { get; set; }
/// <summary>
/// the Pod name of the host
/// </summary>
public string PodName { get; set; }
/// <summary>
/// the date and time the host was removed
/// </summary>
public DateTime Removed { get; set; }
/// <summary>
/// true if migrating a vm to this host requires storage motion, false otherwise
/// </summary>
public bool RequiresStorageMotion { get; set; }
/// <summary>
/// the resource state of the host
/// </summary>
public string ResourceState { get; set; }
/// <summary>
/// the state of the host
/// </summary>
public Status State { get; set; }
/// <summary>
/// true if this host is suitable(has enough capacity and satisfies all conditions like hosttags, max guests vm limit etc) to migrate a VM to it , false otherwise
/// </summary>
public bool SuitableForMigration { get; set; }
/// <summary>
/// the host type
/// </summary>
public HostType Type { get; set; }
/// <summary>
/// the host version
/// </summary>
public string Version { get; set; }
/// <summary>
/// the Zone ID of the host
/// </summary>
public string ZoneId { get; set; }
/// <summary>
/// the Zone name of the host
/// </summary>
public string ZoneName { get; set; }
public override string ToString() => JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace Aurora.Framework
{
/// <summary>
/// Synchronized Cenome cache wrapper.
/// </summary>
/// <typeparam name = "TKey">
/// The type of keys in the cache.
/// </typeparam>
/// <typeparam name = "TValue">
/// The type of values in the cache.
/// </typeparam>
/// <remarks>
/// <para>
/// Enumerator will block other threads, until enumerator's <see cref = "IDisposable.Dispose" /> method is called.
/// "foreach" statement is automatically calling it.
/// </para>
/// </remarks>
public class CnmSynchronizedCache<TKey, TValue> : ICnmCache<TKey, TValue>
{
/// <summary>
/// The cache object.
/// </summary>
private readonly ICnmCache<TKey, TValue> m_cache;
/// <summary>
/// Synchronization root.
/// </summary>
private readonly object m_syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref = "CnmSynchronizedCache{TKey,TValue}" /> class.
/// Initializes a new instance of the <see cref = "CnmSynchronizedCache{TKey,TValue}" /> class.
/// </summary>
/// <param name = "cache">
/// The cache.
/// </param>
private CnmSynchronizedCache(ICnmCache<TKey, TValue> cache)
{
m_cache = cache;
m_syncRoot = m_cache.SyncRoot;
}
#region ICnmCache<TKey,TValue> Members
/// <summary>
/// Gets current count of elements stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <remarks>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting element count,
/// <see cref = "ICnmCache{TKey,TValue}" /> will remove less recently used elements until it can fit an new element.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxCount" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsCountLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsTimeLimited" />
public int Count
{
get
{
lock (m_syncRoot)
{
return m_cache.Count;
}
}
}
/// <summary>
/// Gets or sets elements expiration time.
/// </summary>
/// <value>
/// Elements expiration time.
/// </value>
/// <remarks>
/// <para>
/// When element has been stored in <see cref = "ICnmCache{TKey,TValue}" /> longer than <see
/// cref = "ICnmCache{TKey,TValue}.ExpirationTime" />
/// and it is not accessed through <see cref = "ICnmCache{TKey,TValue}.TryGetValue" /> method or element's value is
/// not replaced by <see cref = "ICnmCache{TKey,TValue}.Set" /> method, then it is automatically removed from the
/// <see cref = "ICnmCache{TKey,TValue}" />.
/// </para>
/// <para>
/// It is possible that <see cref = "ICnmCache{TKey,TValue}" /> implementation removes element before it's expiration time,
/// because total size or count of elements stored to cache is larger than <see cref = "ICnmCache{TKey,TValue}.MaxSize" /> or <see
/// cref = "ICnmCache{TKey,TValue}.MaxCount" />.
/// </para>
/// <para>
/// It is also possible that element stays in cache longer than <see cref = "ICnmCache{TKey,TValue}.ExpirationTime" />.
/// </para>
/// <para>
/// Calling <see cref = "ICnmCache{TKey,TValue}.PurgeExpired" /> try to remove all elements that are expired.
/// </para>
/// <para>
/// To disable time limit in cache, set <see cref = "ICnmCache{TKey,TValue}.ExpirationTime" /> to <see
/// cref = "DateTime.MaxValue" />.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.IsTimeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsCountLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.PurgeExpired" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Count" />
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxCount" />
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxSize" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Size" />
public TimeSpan ExpirationTime
{
get
{
lock (m_syncRoot)
{
return m_cache.ExpirationTime;
}
}
set
{
lock (m_syncRoot)
{
m_cache.ExpirationTime = value;
}
}
}
/// <summary>
/// Gets a value indicating whether <see cref = "ICnmCache{TKey,TValue}" /> is limiting count of elements.
/// </summary>
/// <value>
/// <see langword = "true" /> if the <see cref = "ICnmCache{TKey,TValue}" /> count of elements is limited;
/// otherwise, <see langword = "false" />.
/// </value>
/// <remarks>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting element count,
/// <see cref = "ICnmCache{TKey,TValue}" /> will remove less recently used elements until it can fit an new element.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.Count" />
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxCount" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsTimeLimited" />
public bool IsCountLimited
{
get
{
lock (m_syncRoot)
{
return m_cache.IsCountLimited;
}
}
}
/// <summary>
/// Gets a value indicating whether <see cref = "ICnmCache{TKey,TValue}" /> is limiting size of elements.
/// </summary>
/// <value>
/// <see langword = "true" /> if the <see cref = "ICnmCache{TKey,TValue}" /> total size of elements is limited;
/// otherwise, <see langword = "false" />.
/// </value>
/// <remarks>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting total size of elements,
/// <see cref = "ICnmCache{TKey,TValue}" /> will remove less recently used elements until it can fit an new element.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxElementSize" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Size" />
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxSize" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsCountLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsTimeLimited" />
public bool IsSizeLimited
{
get
{
lock (m_syncRoot)
{
return m_cache.IsSizeLimited;
}
}
}
/// <summary>
/// Gets a value indicating whether or not access to the <see cref = "ICnmCache{TKey,TValue}" /> is synchronized (thread safe).
/// </summary>
/// <value>
/// <see langword = "true" /> if access to the <see cref = "ICnmCache{TKey,TValue}" /> is synchronized (thread safe);
/// otherwise, <see langword = "false" />.
/// </value>
/// <remarks>
/// <para>
/// To get synchronized (thread safe) access to <see cref = "ICnmCache{TKey,TValue}" /> object, use
/// <see cref = "CnmSynchronizedCache{TKey,TValue}.Synchronized" /> in <see cref = "CnmSynchronizedCache{TKey,TValue}" /> class
/// to retrieve synchronized wrapper for <see cref = "ICnmCache{TKey,TValue}" /> object.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.SyncRoot" />
/// <seealso cref = "CnmSynchronizedCache{TKey,TValue}" />
public bool IsSynchronized
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether elements stored to <see cref = "ICnmCache{TKey,TValue}" /> have limited inactivity time.
/// </summary>
/// <value>
/// <see langword = "true" /> if the <see cref = "ICnmCache{TKey,TValue}" /> has a fixed total size of elements;
/// otherwise, <see langword = "false" />.
/// </value>
/// <remarks>
/// If <see cref = "ICnmCache{TKey,TValue}" /> have limited inactivity time and element is not accessed through <see
/// cref = "ICnmCache{TKey,TValue}.Set" />
/// or <see cref = "ICnmCache{TKey,TValue}.TryGetValue" /> methods in <see cref = "ICnmCache{TKey,TValue}.ExpirationTime" /> , then element is automatically removed from
/// the cache. Depending on implementation of the <see cref = "ICnmCache{TKey,TValue}" />, some of the elements may
/// stay longer in cache.
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.ExpirationTime" />
/// <seealso cref = "ICnmCache{TKey,TValue}.PurgeExpired" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsCountLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
public bool IsTimeLimited
{
get
{
lock (m_syncRoot)
{
return m_cache.IsTimeLimited;
}
}
}
/// <summary>
/// Gets or sets maximal allowed count of elements that can be stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <value>
/// <see cref = "int.MaxValue" />, if <see cref = "ICnmCache{TKey,TValue}" /> is not limited by count of elements;
/// otherwise maximal allowed count of elements.
/// </value>
/// <remarks>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting element count,
/// <see cref = "ICnmCache{TKey,TValue}" /> will remove less recently used elements until it can fit an new element.
/// </para>
/// </remarks>
public int MaxCount
{
get
{
lock (m_syncRoot)
{
return m_cache.MaxCount;
}
}
set
{
lock (m_syncRoot)
{
m_cache.MaxCount = value;
}
}
}
/// <summary>
/// <para>Gets maximal allowed element size.</para>
/// </summary>
/// <value>
/// Maximal allowed element size.
/// </value>
/// <remarks>
/// <para>
/// If element's size is larger than <see cref = "ICnmCache{TKey,TValue}.MaxElementSize" />, then element is
/// not added to the <see cref = "ICnmCache{TKey,TValue}" />.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.Set" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Size" />
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxSize" />
public long MaxElementSize
{
get
{
lock (m_syncRoot)
{
return m_cache.MaxElementSize;
}
}
}
/// <summary>
/// Gets or sets maximal allowed total size for elements stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <value>
/// Maximal allowed total size for elements stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </value>
/// <remarks>
/// <para>
/// Normally size is total bytes used by elements in the cache. But it can be any other suitable unit of measure.
/// </para>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting total size of elements,
/// <see cref = "ICnmCache{TKey,TValue}" /> will remove less recently used elements until it can fit an new element.
/// </para>
/// </remarks>
/// <exception cref = "ArgumentOutOfRangeException">value is less than 0.</exception>
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxElementSize" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Size" />
public long MaxSize
{
get
{
lock (m_syncRoot)
{
return m_cache.MaxSize;
}
}
set
{
lock (m_syncRoot)
{
m_cache.MaxSize = value;
}
}
}
/// <summary>
/// Gets total size of elements stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <value>
/// Total size of elements stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </value>
/// <remarks>
/// <para>
/// Normally bytes, but can be any suitable unit of measure.
/// </para>
/// <para>
/// Element's size is given when element is added or replaced by <see cref = "ICnmCache{TKey,TValue}.Set" /> method.
/// </para>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting total size of elements,
/// <see cref = "ICnmCache{TKey,TValue}" /> will remove less recently used elements until it can fit an new element.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxElementSize" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.MaxSize" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsCountLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.ExpirationTime" />
public long Size
{
get
{
lock (m_syncRoot)
{
return m_cache.Size;
}
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the <see cref = "ICnmCache{TKey,TValue}" />.
/// </value>
/// <remarks>
/// <para>
/// To get synchronized (thread safe) access to <see cref = "ICnmCache{TKey,TValue}" />, use <see
/// cref = "CnmSynchronizedCache{TKey,TValue}" />
/// method <see cref = "CnmSynchronizedCache{TKey,TValue}.Synchronized" /> to retrieve synchronized wrapper interface to
/// <see cref = "ICnmCache{TKey,TValue}" />.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSynchronized" />
/// <seealso cref = "CnmSynchronizedCache{TKey,TValue}" />
public object SyncRoot
{
get { return m_syncRoot; }
}
/// <summary>
/// Removes all elements from the <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <seealso cref = "ICnmCache{TKey,TValue}.Set" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Remove" />
/// <seealso cref = "ICnmCache{TKey,TValue}.RemoveRange" />
/// <seealso cref = "ICnmCache{TKey,TValue}.TryGetValue" />
/// <seealso cref = "ICnmCache{TKey,TValue}.PurgeExpired" />
public void Clear()
{
lock (m_syncRoot)
{
m_cache.Clear();
}
}
/// <summary>
/// Returns an enumerator that iterates through the elements stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <returns>
/// A <see cref = "IEnumerator{T}" /> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
lock (m_syncRoot)
{
return new SynchronizedEnumerator(m_cache.GetEnumerator(), m_syncRoot);
}
}
/// <summary>
/// Purge expired elements from the <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <remarks>
/// <para>
/// Element becomes expired when last access time to it has been longer time than <see
/// cref = "ICnmCache{TKey,TValue}.ExpirationTime" />.
/// </para>
/// <para>
/// Depending on <see cref = "ICnmCache{TKey,TValue}" /> implementation, some of expired elements
/// may stay longer than <see cref = "ICnmCache{TKey,TValue}.ExpirationTime" /> in the cache.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.IsTimeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.ExpirationTime" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Set" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Remove" />
/// <seealso cref = "ICnmCache{TKey,TValue}.RemoveRange" />
/// <seealso cref = "ICnmCache{TKey,TValue}.TryGetValue" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Clear" />
public void PurgeExpired()
{
lock (m_syncRoot)
{
m_cache.PurgeExpired();
}
}
/// <summary>
/// Removes element associated with <paramref name = "key" /> from the <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <param name = "key">
/// The key that is associated with element to remove from the <see cref = "ICnmCache{TKey,TValue}" />.
/// </param>
/// <exception cref = "ArgumentNullException">
/// <paramref name = "key" />is <see langword = "null" />.
/// </exception>
/// <seealso cref = "ICnmCache{TKey,TValue}.Set" />
/// <seealso cref = "ICnmCache{TKey,TValue}.RemoveRange" />
/// <seealso cref = "ICnmCache{TKey,TValue}.TryGetValue" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Clear" />
/// <seealso cref = "ICnmCache{TKey,TValue}.PurgeExpired" />
public void Remove(TKey key)
{
lock (m_syncRoot)
{
m_cache.Remove(key);
}
}
/// <summary>
/// Removes elements that are associated with one of <paramref name = "keys" /> from the <see
/// cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <param name = "keys">
/// The keys that are associated with elements to remove from the <see cref = "ICnmCache{TKey,TValue}" />.
/// </param>
/// <exception cref = "ArgumentNullException">
/// <paramref name = "keys" />is <see langword = "null" />.
/// </exception>
/// <seealso cref = "ICnmCache{TKey,TValue}.Set" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Remove" />
/// <seealso cref = "ICnmCache{TKey,TValue}.TryGetValue" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Clear" />
/// <seealso cref = "ICnmCache{TKey,TValue}.PurgeExpired" />
public void RemoveRange(IEnumerable<TKey> keys)
{
lock (m_syncRoot)
{
m_cache.RemoveRange(keys);
}
}
/// <summary>
/// Add or replace an element with the provided <paramref name = "key" />, <paramref name = "value" /> and <paramref
/// name = "size" /> to
/// <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <param name = "key">
/// The object used as the key of the element. Can't be <see langword = "null" /> reference.
/// </param>
/// <param name = "value">
/// The object used as the value of the element to add or replace. <see langword = "null" /> is allowed.
/// </param>
/// <param name = "size">
/// The element's size. Normally bytes, but can be any suitable unit of measure.
/// </param>
/// <returns>
/// <see langword = "true" />if element has been added successfully to the <see cref = "ICnmCache{TKey,TValue}" />;
/// otherwise <see langword = "false" />.
/// </returns>
/// <exception cref = "ArgumentNullException">
/// <paramref name = "key" />is <see langword = "null" />.
/// </exception>
/// <exception cref = "ArgumentOutOfRangeException">
/// The element's <paramref name = "size" /> is less than 0.
/// </exception>
/// <remarks>
/// <para>
/// If element's <paramref name = "size" /> is larger than <see cref = "ICnmCache{TKey,TValue}.MaxElementSize" />, then element is
/// not added to the <see cref = "ICnmCache{TKey,TValue}" />, however - possible older element is
/// removed from the <see cref = "ICnmCache{TKey,TValue}" />.
/// </para>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting total size of elements,
/// <see cref = "ICnmCache{TKey,TValue}" />will remove less recently used elements until it can fit an new element.
/// </para>
/// <para>
/// When adding an new element to <see cref = "ICnmCache{TKey,TValue}" /> that is limiting element count,
/// <see cref = "ICnmCache{TKey,TValue}" />will remove less recently used elements until it can fit an new element.
/// </para>
/// </remarks>
/// <seealso cref = "ICnmCache{TKey,TValue}.IsSizeLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.IsCountLimited" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Remove" />
/// <seealso cref = "ICnmCache{TKey,TValue}.RemoveRange" />
/// <seealso cref = "ICnmCache{TKey,TValue}.TryGetValue" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Clear" />
/// <seealso cref = "ICnmCache{TKey,TValue}.PurgeExpired" />
public bool Set(TKey key, TValue value, long size)
{
lock (m_syncRoot)
{
return m_cache.Set(key, value, size);
}
}
/// <summary>
/// Gets the <paramref name = "value" /> associated with the specified <paramref name = "key" />.
/// </summary>
/// <returns>
/// <see langword = "true" />if the <see cref = "ICnmCache{TKey,TValue}" /> contains an element with
/// the specified key; otherwise, <see langword = "false" />.
/// </returns>
/// <param name = "key">
/// The key whose <paramref name = "value" /> to get.
/// </param>
/// <param name = "value">
/// When this method returns, the value associated with the specified <paramref name = "key" />,
/// if the <paramref name = "key" /> is found; otherwise, the
/// default value for the type of the <paramref name = "value" /> parameter. This parameter is passed uninitialized.
/// </param>
/// <exception cref = "ArgumentNullException">
/// <paramref name = "key" />is <see langword = "null" />.
/// </exception>
/// <seealso cref = "ICnmCache{TKey,TValue}.Set" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Remove" />
/// <seealso cref = "ICnmCache{TKey,TValue}.RemoveRange" />
/// <seealso cref = "ICnmCache{TKey,TValue}.Clear" />
/// <seealso cref = "ICnmCache{TKey,TValue}.PurgeExpired" />
public bool TryGetValue(TKey key, out TValue value)
{
lock (m_syncRoot)
{
return m_cache.TryGetValue(key, out value);
}
}
public bool Contains(TKey key)
{
return m_cache.Contains(key);
}
/// <summary>
/// Returns an enumerator that iterates through the elements stored to <see cref = "ICnmCache{TKey,TValue}" />.
/// </summary>
/// <returns>
/// A <see cref = "IEnumerator" /> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// Returns a <see cref = "ICnmCache{TKey,TValue}" /> wrapper that is synchronized (thread safe).
/// </summary>
/// <param name = "cache">
/// The <see cref = "ICnmCache{TKey,TValue}" /> to synchronize.
/// </param>
/// <returns>
/// A <see cref = "ICnmCache{TKey,TValue}" /> wrapper that is synchronized (thread safe).
/// </returns>
/// <exception cref = "ArgumentNullException">
/// <paramref name = "cache" />is null.
/// </exception>
public static ICnmCache<TKey, TValue> Synchronized(ICnmCache<TKey, TValue> cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
return cache.IsSynchronized ? cache : new CnmSynchronizedCache<TKey, TValue>(cache);
}
#region Nested type: SynchronizedEnumerator
/// <summary>
/// Synchronized enumerator.
/// </summary>
private class SynchronizedEnumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
/// <summary>
/// Enumerator that is being synchronized.
/// </summary>
private readonly IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator;
/// <summary>
/// Synchronization root.
/// </summary>
private object m_syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref = "SynchronizedEnumerator" /> class.
/// </summary>
/// <param name = "enumerator">
/// The enumerator that is being synchronized.
/// </param>
/// <param name = "syncRoot">
/// The sync root.
/// </param>
public SynchronizedEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> enumerator, object syncRoot)
{
m_syncRoot = syncRoot;
m_enumerator = enumerator;
Monitor.Enter(m_syncRoot);
}
#region IEnumerator<KeyValuePair<TKey,TValue>> Members
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
/// <exception cref = "InvalidOperationException">
/// The enumerator has reach end of collection or <see cref = "MoveNext" /> is not called.
/// </exception>
public KeyValuePair<TKey, TValue> Current
{
get { return m_enumerator.Current; }
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>
/// The current element in the collection.
/// </returns>
/// <exception cref = "InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
/// <filterpriority>2</filterpriority>
object IEnumerator.Current
{
get { return Current; }
}
/// <summary>
/// Releases synchronization lock.
/// </summary>
public void Dispose()
{
if (m_syncRoot != null)
{
Monitor.Exit(m_syncRoot);
m_syncRoot = null;
}
m_enumerator.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref = "InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
return m_enumerator.MoveNext();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref = "InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public void Reset()
{
m_enumerator.Reset();
}
#endregion
/// <summary>
/// Finalizes an instance of the <see cref = "SynchronizedEnumerator" /> class.
/// </summary>
~SynchronizedEnumerator()
{
Dispose();
}
}
#endregion
}
}
| |
using Newtonsoft.Json.Linq;
using DotVVM.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.Compilation.Javascript;
namespace DotVVM.Framework.ResourceManagement.ClientGlobalize
{
public static class JQueryGlobalizeScriptCreator
{
private static readonly string[] numberPatternStrings =
{ "(n)", "-n", "- n", "n-", "n -" };
private static readonly string[] percentPositivePatternStrings =
{ "n %", "n%", "%n", "% n" };
private static readonly string[] percentNegativePatternStrings =
{ "-n %", "-n%", "-%n", "%-n", "%n", "n-%", "n%-", "-% n", "n %-", "% n-", "% -n", "n- %"};
private static readonly string[] currencyNegativePatternStrings =
{ "($n)", "-$n", "$-n", "$n-", "(n$)", "-n$", "n-$", "n$-", "-n $", "-$ n", "n $-", "$ n-", "$ -n", "n- $", "($ n)", "(n $)" };
private static readonly string[] currencyPositivePatternStrings =
{ "$n", "n$", "$ n", "n $" };
private static readonly JObject defaultJson = JObject.Parse(@"{
name: 'en',
englishName: 'English',
nativeName: 'English',
isRTL: false,
language: 'en',
numberFormat: {
pattern: ['-n'],
decimals: 2,
',': ',',
'.': '.',
groupSizes: [3],
'+': '+',
'-': '-',
NaN: 'NaN',
negativeInfinity: '-Infinity',
positiveInfinity: 'Infinity',
percent: {
pattern: ['-n %', 'n %'],
decimals: 2,
groupSizes: [3],
',': ',',
'.': '.',
symbol: '%'
},
currency: {
pattern: [ '($n)', '$n' ],
decimals: 2,
groupSizes: [ 3 ],
',': ',',
'.': '.',
symbol: '$'
}
},
calendars: {
standard: {
name: 'Gregorian_USEnglish',
'/': '/',
':': ':',
firstDay: 0,
days: {
names: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
namesAbbr: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
namesShort: [ 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa' ]
},
months: {
names: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', '' ],
namesAbbr: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '' ]
},
AM: [ 'AM', 'am', 'AM' ],
PM: [ 'PM', 'pm', 'PM' ],
eras: [
{
'name': 'A.D.',
'start': null,
'offset': 0
}
],
twoDigitYearMax: 2029,
'patterns': {
'd': 'M/d/yyyy',
'D': 'dddd, MMMM dd, yyyy',
't': 'h:mm tt',
'T': 'h:mm:ss tt',
'f': 'dddd, MMMM dd, yyyy h:mm tt',
'F': 'dddd, MMMM dd, yyyy h:mm:ss tt',
'M': 'MMMM dd',
'Y': 'yyyy MMMM',
'S': 'yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss'
}
}
},
'messages': {}
}
");
private static JObject CreateNumberInfoJson(NumberFormatInfo ni)
{
var numberFormat = new
{
pattern = new[] { numberPatternStrings[ni.NumberNegativePattern] },
decimals = ni.NumberDecimalDigits,
groupSizes = ni.NumberGroupSizes,
NaN = ni.NaNSymbol,
negativeInfinity = ni.NegativeInfinitySymbol,
positiveInfinity = ni.PositiveInfinitySymbol,
percent = new
{
pattern = new[] {
percentNegativePatternStrings[ni.PercentNegativePattern],
percentPositivePatternStrings[ni.PercentPositivePattern]
},
decimals = ni.PercentDecimalDigits,
groupSizes = ni.PercentGroupSizes,
symbol = ni.PercentSymbol
},
currency = new
{
pattern = new[]
{
currencyNegativePatternStrings[ni.CurrencyNegativePattern],
currencyPositivePatternStrings[ni.CurrencyPositivePattern]
},
decimals = ni.CurrencyDecimalDigits,
groupSizes = ni.CurrencyGroupSizes,
symbol = ni.CurrencySymbol
}
};
var jobj = JObject.FromObject(numberFormat);
jobj[","] = ni.NumberGroupSeparator;
jobj["."] = ni.NumberDecimalSeparator;
jobj["percent"][","] = ni.PercentGroupSeparator;
jobj["percent"]["."] = ni.PercentDecimalSeparator;
jobj["currency"][","] = ni.CurrencyGroupSeparator;
jobj["currency"]["."] = ni.CurrencyDecimalSeparator;
return jobj;
}
private static JObject CreateDateInfoJson(DateTimeFormatInfo di)
{
var obj = new
{
firstDay = di.FirstDayOfWeek,
days = new
{
names = di.DayNames,
namesAbbr = di.AbbreviatedDayNames,
namesShort = di.ShortestDayNames
},
months = new
{
names = di.MonthNames,
namesAbbr = di.AbbreviatedMonthNames
},
AM = new[] { di.AMDesignator, di.AMDesignator.ToLowerInvariant(), di.AMDesignator.ToUpperInvariant() },
PM = new[] { di.PMDesignator, di.PMDesignator.ToLowerInvariant(), di.PMDesignator.ToUpperInvariant() },
eras = di.Calendar.Eras.Select(era => new { offset = 0, start = (string?)null, name = di.GetEraName(era) }).ToArray(),
twoDigitYearMax = di.Calendar.TwoDigitYearMax,
patterns = new
{
d = di.ShortDatePattern,
D = di.LongDatePattern,
t = di.ShortTimePattern,
T = di.LongTimePattern,
f = di.LongDatePattern + " " + di.ShortTimePattern,
F = di.LongDatePattern + " " + di.LongTimePattern,
M = di.MonthDayPattern,
Y = di.YearMonthPattern,
g = di.ShortDatePattern + " " + di.ShortTimePattern,
G = di.ShortDatePattern + " " + di.LongTimePattern
}
};
var jobj = JObject.FromObject(obj);
if (!di.MonthNames.SequenceEqual(di.MonthGenitiveNames))
{
var monthsGenitive = jobj["monthsGenitive"] = new JObject();
monthsGenitive["names"] = JArray.FromObject(di.MonthGenitiveNames);
monthsGenitive["namesAbbr"] = JArray.FromObject(di.AbbreviatedMonthGenitiveNames);
}
return new JObject()
{
{"standard", jobj }
};
}
public static JObject BuildCultureInfoJson(CultureInfo ci)
{
var cultureInfoClientObj = new
{
name = ci.Name,
nativeName = ci.NativeName,
englishName = ci.EnglishName,
isRTL = ci.TextInfo.IsRightToLeft,
language = ci.TwoLetterISOLanguageName
};
var jobj = JObject.FromObject(cultureInfoClientObj);
jobj["numberFormat"] = CreateNumberInfoJson(ci.NumberFormat);
jobj["calendars"] = CreateDateInfoJson(ci.DateTimeFormat);
return JsonUtils.Diff(defaultJson, jobj);
}
public static string BuildCultureInfoScript(CultureInfo ci)
{
var cultureJson = BuildCultureInfoJson(ci).ToString();
return $@"
(function(window, undefined) {{
var Globalize;
if ( typeof require !== 'undefined'
&& typeof exports !== 'undefined'
&& typeof module !== 'undefined' ) {{
// Assume CommonJS
Globalize = require('globalize');
}} else {{
// Global variable
Globalize = window.dotvvm_Globalize;
}}
Globalize.addCultureInfo({JavascriptCompilationHelper.CompileConstant(ci.Name)}, 'default', {cultureJson});
}}(this));
";
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.WebsiteBuilder.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.WebsiteBuilder.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Email Subscriptions.
/// </summary>
[RoutePrefix("api/v1.0/website/email-subscription")]
public class EmailSubscriptionController : FrapidApiController
{
/// <summary>
/// The EmailSubscription repository.
/// </summary>
private readonly IEmailSubscriptionRepository EmailSubscriptionRepository;
public EmailSubscriptionController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.EmailSubscriptionRepository = new Frapid.WebsiteBuilder.DataAccess.EmailSubscription
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public EmailSubscriptionController(IEmailSubscriptionRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.EmailSubscriptionRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "email subscription" entity.
/// </summary>
/// <returns>Returns the "email subscription" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/website/email-subscription/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "email_subscription_id",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "email_subscription_id", PropertyName = "EmailSubscriptionId", DataType = "System.Guid", DbDataType = "uuid", IsNullable = false, IsPrimaryKey = true, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "email", PropertyName = "Email", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "unsubscribed", PropertyName = "Unsubscribed", DataType = "bool", DbDataType = "bool", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "subscribed_on", PropertyName = "SubscribedOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "unsubscribed_on", PropertyName = "UnsubscribedOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of email subscriptions.
/// </summary>
/// <returns>Returns the count of the email subscriptions.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/website/email-subscription/count")]
[Authorize]
public long Count()
{
try
{
return this.EmailSubscriptionRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of email subscription.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/website/email-subscription/all")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> GetAll()
{
try
{
return this.EmailSubscriptionRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of email subscription for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/website/email-subscription/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.EmailSubscriptionRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of email subscription.
/// </summary>
/// <param name="emailSubscriptionId">Enter EmailSubscriptionId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{emailSubscriptionId}")]
[Route("~/api/website/email-subscription/{emailSubscriptionId}")]
[Authorize]
public Frapid.WebsiteBuilder.Entities.EmailSubscription Get(System.Guid emailSubscriptionId)
{
try
{
return this.EmailSubscriptionRepository.Get(emailSubscriptionId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/website/email-subscription/get")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> Get([FromUri] System.Guid[] emailSubscriptionIds)
{
try
{
return this.EmailSubscriptionRepository.Get(emailSubscriptionIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of email subscription.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/website/email-subscription/first")]
[Authorize]
public Frapid.WebsiteBuilder.Entities.EmailSubscription GetFirst()
{
try
{
return this.EmailSubscriptionRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of email subscription.
/// </summary>
/// <param name="emailSubscriptionId">Enter EmailSubscriptionId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{emailSubscriptionId}")]
[Route("~/api/website/email-subscription/previous/{emailSubscriptionId}")]
[Authorize]
public Frapid.WebsiteBuilder.Entities.EmailSubscription GetPrevious(System.Guid emailSubscriptionId)
{
try
{
return this.EmailSubscriptionRepository.GetPrevious(emailSubscriptionId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of email subscription.
/// </summary>
/// <param name="emailSubscriptionId">Enter EmailSubscriptionId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{emailSubscriptionId}")]
[Route("~/api/website/email-subscription/next/{emailSubscriptionId}")]
[Authorize]
public Frapid.WebsiteBuilder.Entities.EmailSubscription GetNext(System.Guid emailSubscriptionId)
{
try
{
return this.EmailSubscriptionRepository.GetNext(emailSubscriptionId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of email subscription.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/website/email-subscription/last")]
[Authorize]
public Frapid.WebsiteBuilder.Entities.EmailSubscription GetLast()
{
try
{
return this.EmailSubscriptionRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 email subscriptions on each page, sorted by the property EmailSubscriptionId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/website/email-subscription")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> GetPaginatedResult()
{
try
{
return this.EmailSubscriptionRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 email subscriptions on each page, sorted by the property EmailSubscriptionId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/website/email-subscription/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> GetPaginatedResult(long pageNumber)
{
try
{
return this.EmailSubscriptionRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of email subscriptions using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered email subscriptions.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/website/email-subscription/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.EmailSubscriptionRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 email subscriptions on each page, sorted by the property EmailSubscriptionId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/website/email-subscription/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.EmailSubscriptionRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of email subscriptions using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered email subscriptions.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/website/email-subscription/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.EmailSubscriptionRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 email subscriptions on each page, sorted by the property EmailSubscriptionId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/website/email-subscription/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.EmailSubscriptionRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of email subscriptions.
/// </summary>
/// <returns>Returns an enumerable key/value collection of email subscriptions.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/website/email-subscription/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.EmailSubscriptionRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for email subscriptions.
/// </summary>
/// <returns>Returns an enumerable custom field collection of email subscriptions.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/website/email-subscription/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.EmailSubscriptionRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for email subscriptions.
/// </summary>
/// <returns>Returns an enumerable custom field collection of email subscriptions.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/website/email-subscription/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.EmailSubscriptionRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of EmailSubscription class.
/// </summary>
/// <param name="emailSubscription">Your instance of email subscriptions class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/website/email-subscription/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic emailSubscription = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (emailSubscription == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.EmailSubscriptionRepository.AddOrEdit(emailSubscription, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of EmailSubscription class.
/// </summary>
/// <param name="emailSubscription">Your instance of email subscriptions class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{emailSubscription}")]
[Route("~/api/website/email-subscription/add/{emailSubscription}")]
[Authorize]
public void Add(Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription)
{
if (emailSubscription == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.EmailSubscriptionRepository.Add(emailSubscription);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of EmailSubscription class.
/// </summary>
/// <param name="emailSubscription">Your instance of EmailSubscription class to edit.</param>
/// <param name="emailSubscriptionId">Enter the value for EmailSubscriptionId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{emailSubscriptionId}")]
[Route("~/api/website/email-subscription/edit/{emailSubscriptionId}")]
[Authorize]
public void Edit(System.Guid emailSubscriptionId, [FromBody] Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription)
{
if (emailSubscription == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.EmailSubscriptionRepository.Update(emailSubscription, emailSubscriptionId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of EmailSubscription class.
/// </summary>
/// <param name="collection">Your collection of EmailSubscription class to bulk import.</param>
/// <returns>Returns list of imported emailSubscriptionIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any EmailSubscription class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/website/email-subscription/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> emailSubscriptionCollection = this.ParseCollection(collection);
if (emailSubscriptionCollection == null || emailSubscriptionCollection.Count.Equals(0))
{
return null;
}
try
{
return this.EmailSubscriptionRepository.BulkImport(emailSubscriptionCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of EmailSubscription class via EmailSubscriptionId.
/// </summary>
/// <param name="emailSubscriptionId">Enter the value for EmailSubscriptionId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{emailSubscriptionId}")]
[Route("~/api/website/email-subscription/delete/{emailSubscriptionId}")]
[Authorize]
public void Delete(System.Guid emailSubscriptionId)
{
try
{
this.EmailSubscriptionRepository.Delete(emailSubscriptionId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReorderParameters
{
public partial class ReorderParametersTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToImplementedMethod()
{
var markup = @"
interface I
{
void M(int x, string y);
}
class C : I
{
$$public void M(int x, string y)
{ }
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
interface I
{
void M(string y, int x);
}
class C : I
{
public void M(string y, int x)
{ }
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToImplementingMethod()
{
var markup = @"
interface I
{
$$void M(int x, string y);
}
class C : I
{
public void M(int x, string y)
{ }
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
interface I
{
void M(string y, int x);
}
class C : I
{
public void M(string y, int x)
{ }
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToOverriddenMethod()
{
var markup = @"
class B
{
public virtual void M(int x, string y)
{ }
}
class D : B
{
$$public override void M(int x, string y)
{ }
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class B
{
public virtual void M(string y, int x)
{ }
}
class D : B
{
public override void M(string y, int x)
{ }
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToOverridingMethod()
{
var markup = @"
class B
{
$$public virtual void M(int x, string y)
{ }
}
class D : B
{
public override void M(int x, string y)
{ }
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class B
{
public virtual void M(string y, int x)
{ }
}
class D : B
{
public override void M(string y, int x)
{ }
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToOverriddenMethod_Transitive()
{
var markup = @"
class B
{
public virtual void M(int x, string y)
{ }
}
class D : B
{
public override void M(int x, string y)
{ }
}
class D2 : D
{
$$public override void M(int x, string y)
{ }
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class B
{
public virtual void M(string y, int x)
{ }
}
class D : B
{
public override void M(string y, int x)
{ }
}
class D2 : D
{
public override void M(string y, int x)
{ }
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToOverridingMethod_Transitive()
{
var markup = @"
class B
{
$$public virtual void M(int x, string y)
{ }
}
class D : B
{
public override void M(int x, string y)
{ }
}
class D2 : D
{
public override void M(int x, string y)
{ }
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class B
{
public virtual void M(string y, int x)
{ }
}
class D : B
{
public override void M(string y, int x)
{ }
}
class D2 : D
{
public override void M(string y, int x)
{ }
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToMethods_Complex()
{
//// B I I2
//// \ / \ /
//// D (I3)
//// / \ \
//// $$D2 D3 C
var markup = @"
class B { public virtual void M(int x, string y) { } }
class D : B, I { public override void M(int x, string y) { } }
class D2 : D { public override void $$M(int x, string y) { } }
class D3 : D { public override void M(int x, string y) { } }
interface I { void M(int x, string y); }
interface I2 { void M(int x, string y); }
interface I3 : I, I2 { }
class C : I3 { public void M(int x, string y) { } }";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class B { public virtual void M(string y, int x) { } }
class D : B, I { public override void M(string y, int x) { } }
class D2 : D { public override void M(string y, int x) { } }
class D3 : D { public override void M(string y, int x) { } }
interface I { void M(string y, int x); }
interface I2 { void M(string y, int x); }
interface I3 : I, I2 { }
class C : I3 { public void M(string y, int x) { } }";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderParameters_Cascade_ToMethods_WithDifferentParameterNames()
{
var markup = @"
public class B
{
/// <param name=""x""></param>
/// <param name=""y""></param>
public virtual int M(int x, string y)
{
return 1;
}
}
public class D : B
{
/// <param name=""a""></param>
/// <param name=""b""></param>
public override int M(int a, string b)
{
return 1;
}
}
public class D2 : D
{
/// <param name=""y""></param>
/// <param name=""x""></param>
public override int $$M(int y, string x)
{
M(1, ""Two"");
((D)this).M(1, ""Two"");
((B)this).M(1, ""Two"");
M(1, x: ""Two"");
((D)this).M(1, b: ""Two"");
((B)this).M(1, y: ""Two"");
return 1;
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
public class B
{
/// <param name=""y""></param>
/// <param name=""x""></param>
public virtual int M(string y, int x)
{
return 1;
}
}
public class D : B
{
/// <param name=""b""></param>
/// <param name=""a""></param>
public override int M(string b, int a)
{
return 1;
}
}
public class D2 : D
{
/// <param name=""x""></param>
/// <param name=""y""></param>
public override int M(string x, int y)
{
M(""Two"", 1);
((D)this).M(""Two"", 1);
((B)this).M(""Two"", 1);
M(x: ""Two"", y: 1);
((D)this).M(b: ""Two"", a: 1);
((B)this).M(y: ""Two"", x: 1);
return 1;
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
}
}
| |
//
// LastfmSourceContents.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008-2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
using Lastfm;
using Lastfm.Data;
namespace Banshee.Lastfm
{
public class LastfmSourceContents : Hyena.Widgets.ScrolledWindow, ISourceContents
{
private VBox main_box;
private LastfmSource lastfm;
private NumberedList recently_loved;
private NumberedList recently_played;
private NumberedList top_artists;
private Viewport viewport;
// "Coming Soon: Profile, Friends, Events etc")
public LastfmSourceContents () : base ()
{
HscrollbarPolicy = PolicyType.Never;
VscrollbarPolicy = PolicyType.Automatic;
viewport = new Viewport ();
viewport.ShadowType = ShadowType.None;
main_box = new VBox ();
main_box.Spacing = 6;
main_box.BorderWidth = 5;
main_box.ReallocateRedraws = true;
// Clamp the width, preventing horizontal scrolling
SizeAllocated += delegate (object o, SizeAllocatedArgs args) {
// TODO '- 10' worked for Nereid, but not for Cubano; properly calculate the right width we should request
main_box.WidthRequest = args.Allocation.Width - 30;
};
viewport.Add (main_box);
StyleUpdated += delegate {
viewport.OverrideBackgroundColor (StateFlags.Normal, StyleContext.GetBackgroundColor (StateFlags.Normal));
viewport.OverrideColor (StateFlags.Normal, StyleContext.GetColor (StateFlags.Normal));
};
AddWithFrame (viewport);
ShowAll ();
}
public bool SetSource (ISource src)
{
lastfm = src as LastfmSource;
if (lastfm == null) {
return false;
}
if (lastfm.Connection.Connected) {
UpdateForUser (lastfm.Account.UserName);
} else {
lastfm.Connection.StateChanged += HandleConnectionStateChanged;
}
return true;
}
public ISource Source {
get { return lastfm; }
}
public void ResetSource ()
{
lastfm = null;
}
public Widget Widget {
get { return this; }
}
public void Refresh ()
{
if (user != null) {
user.RecentLovedTracks.Refresh ();
user.RecentTracks.Refresh ();
user.GetTopArtists (TopType.Overall).Refresh ();
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
}
}
private string last_user;
private LastfmUserData user;
private void UpdateForUser (string username)
{
if (username == last_user) {
return;
}
last_user = username;
while (main_box.Children.Length != 0) {
main_box.Remove (main_box.Children[0]);
}
recently_loved = new NumberedList (lastfm, Catalog.GetString ("Recently Loved Tracks"));
recently_played = new NumberedList (lastfm, Catalog.GetString ("Recently Played Tracks"));
top_artists = new NumberedList (lastfm, Catalog.GetString ("My Top Artists"));
//recommended_artists = new NumberedList (Catalog.GetString ("Recommended Artists"));
main_box.PackStart (recently_loved, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (recently_played, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (top_artists, false, false, 0);
//PackStart (recommended_artists, true, true, 0);
try {
user = new LastfmUserData (username);
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
} catch (Exception e) {
lastfm.SetStatus ("Failed to get information from your Last.fm profile", true, ConnectionState.InvalidAccount);
Log.Exception (String.Format ("LastfmUserData query failed for {0}", username), e);
}
ShowAll ();
}
private void HandleConnectionStateChanged (object sender, ConnectionStateChangedArgs args)
{
if (args.State == ConnectionState.Connected) {
ThreadAssist.ProxyToMain (delegate {
if (lastfm != null && lastfm.Account != null) {
UpdateForUser (lastfm.Account.UserName);
}
});
}
}
public class NumberedTileView : TileView
{
private int i = 1;
public NumberedTileView (int cols) : base (cols)
{
}
public new void ClearWidgets ()
{
i = 1;
base.ClearWidgets ();
}
public void AddNumberedWidget (Tile tile)
{
tile.PrimaryText = String.Format ("{0}. {1}", i++, tile.PrimaryText);
AddWidget (tile);
}
}
protected class NumberedList : TitledList
{
protected ArtworkManager artwork_manager = ServiceManager.Get<ArtworkManager> ();
protected LastfmSource lastfm;
protected NumberedTileView tile_view;
protected Dictionary<object, RecentTrack> widget_track_map = new Dictionary<object, RecentTrack> ();
public NumberedList (LastfmSource lastfm, string name) : base (name)
{
this.lastfm = lastfm;
artwork_manager.AddCachedSize(40);
tile_view = new NumberedTileView (1);
PackStart (tile_view, true, true, 0);
tile_view.Show ();
StyleUpdated += delegate {
tile_view.OverrideBackgroundColor (StateFlags.Normal, StyleContext.GetBackgroundColor (StateFlags.Normal));
tile_view.OverrideColor (StateFlags.Normal, StyleContext.GetColor (StateFlags.Normal));
};
}
// TODO generalize this
public void SetList (LastfmData<UserTopArtist> artists)
{
tile_view.ClearWidgets ();
foreach (UserTopArtist artist in artists) {
MenuTile tile = new MenuTile ();
tile.PrimaryText = artist.Name;
tile.SecondaryText = String.Format (Catalog.GetString ("{0} plays"), artist.PlayCount);
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
public void SetList (LastfmData<RecentTrack> tracks)
{
tile_view.ClearWidgets ();
foreach (RecentTrack track in tracks) {
MenuTile tile = new MenuTile ();
widget_track_map [tile] = track;
tile.PrimaryText = track.Name;
tile.SecondaryText = track.Artist;
tile.ButtonPressEvent += OnTileActivated;
// Unfortunately the recently loved list doesn't include what album the song is on
if (!String.IsNullOrEmpty (track.Album)) {
AlbumInfo album = new AlbumInfo (track.Album);
album.ArtistName = track.Artist;
Gdk.Pixbuf pb = artwork_manager == null ? null : artwork_manager.LookupScalePixbuf (album.ArtworkId, 40);
if (pb != null) {
tile.Pixbuf = pb;
}
}
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
private void OnTileActivated (object sender, EventArgs args)
{
(sender as Button).Relief = ReliefStyle.Normal;
RecentTrack track = widget_track_map [sender];
lastfm.Actions.CurrentArtist = track.Artist;
lastfm.Actions.CurrentAlbum = track.Album;
lastfm.Actions.CurrentTrack = track.Name;
Gtk.Menu menu = ServiceManager.Get<InterfaceActionService> ().UIManager.GetWidget ("/LastfmTrackPopup") as Menu;
// For an event
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Add to Google Calendar"));
// For a user
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Listen to Recommended Station"));
//menu.Append (new MenuItem ("Listen to Loved Station"));
//menu.Append (new MenuItem ("Listen to Neighbors Station"));
menu.ShowAll ();
menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime);
menu.Deactivated += delegate {
(sender as Button).Relief = ReliefStyle.None;
};
}
}
}
}
| |
// 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.IO;
using System.Xml;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class XmlSearcher_Tests
{
/// <summary>
/// Tests to make sure we can compute the correct element/attribute numbers
/// for given Xml nodes.
/// </summary>
/// <owner>RGoel</owner>
[Test]
public void GetElementAttributeNumberOfXmlNode()
{
string projectFileContents = @"
<Project xmlns=`msbuild`>
<PropertyGroup Condition=`false`>
<Optimize>true</Optimize>
<WarningLevel>
4
</WarningLevel>
<DebugType/>
goo
<OutputPath/>
</PropertyGroup>
<ItemGroup>
<Compile Include=`a.cs` Condition=`true`/>
<Reference Include=`msbuildengine`>
<HintPath>c:\\msbengine.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
";
projectFileContents = projectFileContents.Replace ("`", "\"");
XmlDocument doc = new XmlDocument();
doc.LoadXml(projectFileContents);
int elementNumber;
int attributeNumber;
// Find the element/attribute number of the <Optimize/> node.
Assertion.Assert(XmlSearcher.GetElementAndAttributeNumber(
// <Project> <PropertyGroup> <Optimize>
doc.FirstChild.ChildNodes[0]. ChildNodes[0],
out elementNumber,
out attributeNumber));
Assertion.AssertEquals(3, elementNumber);
Assertion.AssertEquals(0, attributeNumber);
// Find the element/attribute number of the "4" inside the <WarningLevel/> tag.
Assertion.Assert(XmlSearcher.GetElementAndAttributeNumber(
// <Project> <PropertyGroup> <WarningLevel> 4
doc.FirstChild.ChildNodes[0]. ChildNodes[1]. ChildNodes[0],
out elementNumber,
out attributeNumber));
Assertion.AssertEquals(6, elementNumber);
Assertion.AssertEquals(0, attributeNumber);
// Find the element/attribute number of the <DebugType/> node.
Assertion.Assert(XmlSearcher.GetElementAndAttributeNumber(
// <Project> <PropertyGroup> <DebugType>
doc.FirstChild.ChildNodes[0]. ChildNodes[2],
out elementNumber,
out attributeNumber));
Assertion.AssertEquals(7, elementNumber);
Assertion.AssertEquals(0, attributeNumber);
// Find the element/attribute number of the "goo" node.
Assertion.Assert(XmlSearcher.GetElementAndAttributeNumber(
// <Project> <PropertyGroup> goo
doc.FirstChild.ChildNodes[0]. ChildNodes[3],
out elementNumber,
out attributeNumber));
Assertion.AssertEquals(8, elementNumber);
Assertion.AssertEquals(0, attributeNumber);
// Find the element/attribute number of the <Reference> node.
Assertion.Assert(XmlSearcher.GetElementAndAttributeNumber(
// <Project> <ItemGroup> <Reference>
doc.FirstChild.ChildNodes[1].ChildNodes[1],
out elementNumber,
out attributeNumber));
Assertion.AssertEquals(12, elementNumber);
Assertion.AssertEquals(0, attributeNumber);
// Find the element/attribute number of the "Condition" attribute on the <Compile> node.
Assertion.Assert(XmlSearcher.GetElementAndAttributeNumber(
// <Project> <ItemGroup> <Compile> Condition
doc.FirstChild.ChildNodes[1].ChildNodes[0].Attributes[1],
out elementNumber,
out attributeNumber));
Assertion.AssertEquals(11, elementNumber);
Assertion.AssertEquals(2, attributeNumber);
// Try passing in an Xml element that doesn't even exist in the above document.
// This should fail.
Assertion.Assert(!XmlSearcher.GetElementAndAttributeNumber(
(new XmlDocument()).CreateElement("Project"),
out elementNumber,
out attributeNumber));
}
/// <summary>
/// Find the line/column number of a particular XML element.
/// </summary>
/// <owner>RGoel</owner>
[Test]
public void GetLineColumnOfXmlNode()
{
string projectFileContents =
"<Project xmlns=`msbuild`>" + "\r\n" +
"" + "\r\n" +
" <PropertyGroup Condition=`false`" + "\r\n" +
" BogusAttrib=`foo`>" + "\r\n" +
" <Optimize>true</Optimize>" + "\r\n" +
" <WarningLevel>" + "\r\n" +
" 4" + "\r\n" +
" </WarningLevel>" + "\r\n" +
" <DebugType/>" + "\r\n" +
" goo" + "\r\n" +
" <OutputPath/>" + "\r\n" +
" </PropertyGroup>" + "\r\n" +
"" + "\r\n" +
"</Project>" ;
int foundLineNumber;
int foundColumnNumber;
// Okay, we're going to try and find the line/column number for the <DebugType> node.
// This is the 7th element in the hierarchy.
// Correct answer is:
// Line Number 9
// Column Number 5
GetLineColumnFromProjectFileContentsHelper(projectFileContents,
7, 0, out foundLineNumber, out foundColumnNumber);
Assertion.AssertEquals(9, foundLineNumber);
Assertion.AssertEquals(5, foundColumnNumber);
// Okay, we're going to try and find the line/column number for the "4" in the <WarningLevel> property.
// This is the 6th element in the hierarchy.
// Correct answer is:
// Line Number 6
// Column Number 19
// This is because the text node actually begins immediately after the closing ">" in "<WarningLevel>".
GetLineColumnFromProjectFileContentsHelper(projectFileContents,
6, 0, out foundLineNumber, out foundColumnNumber);
Assertion.AssertEquals(6, foundLineNumber);
Assertion.AssertEquals(19, foundColumnNumber);
// Okay, we're going to try and find the line/column number for the BogusAttrib attribute.
// This is on the 2nd element in the hierarchy, and it is the 2nd attribute in that element.
// Correct answer is:
// Line Number 4
// Column Number 18
GetLineColumnFromProjectFileContentsHelper(projectFileContents,
2, 2, out foundLineNumber, out foundColumnNumber);
Assertion.AssertEquals(4, foundLineNumber);
Assertion.AssertEquals(18, foundColumnNumber);
// Okay, we're going to try and find the line/column number for the "goo" beneath <PropertyGroup>.
// This is the 8th element in the hierarchy.
// Correct answer is:
// Line Number 9
// Column Number 17
GetLineColumnFromProjectFileContentsHelper(projectFileContents,
8, 0, out foundLineNumber, out foundColumnNumber);
Assertion.AssertEquals(9, foundLineNumber);
Assertion.AssertEquals(17, foundColumnNumber);
// Let's try passing in a bogus element number.
GetLineColumnFromProjectFileContentsHelper(projectFileContents,
25, 0, out foundLineNumber, out foundColumnNumber);
Assertion.AssertEquals(0, foundLineNumber);
Assertion.AssertEquals(0, foundColumnNumber);
// And let's try passing in a bogus attribute number.
GetLineColumnFromProjectFileContentsHelper(projectFileContents,
7, 4, out foundLineNumber, out foundColumnNumber);
Assertion.AssertEquals(0, foundLineNumber);
Assertion.AssertEquals(0, foundColumnNumber);
}
/// <summary>
/// Given a string representing the contents of the project file, create a project file
/// on disk with those contents. Then call the method to find the line/column number of
/// a particular node in the project file, based on the element/attribute number of that node.
/// </summary>
/// <param name="projectFileContents"></param>
/// <returns>an instance of our special line-number-enabled reader</returns>
/// <owner>RGoel</owner>
private void GetLineColumnFromProjectFileContentsHelper
(
string projectFileContents,
int xmlElementNumberToSearchFor,
int xmlAttributeNumberToSearchFor,
out int foundLineNumber,
out int foundColumnNumber
)
{
string projectFile = ObjectModelHelpers.CreateTempFileOnDisk(projectFileContents);
XmlSearcher.GetLineColumnByNodeNumber(projectFile,
xmlElementNumberToSearchFor, xmlAttributeNumberToSearchFor,
out foundLineNumber, out foundColumnNumber);
// Delete the temp file.
File.Delete(projectFile);
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class FindTests
{
private const string LeftToRightMark = "\u200E";
private static void RunTest(Action<X509Certificate2Collection> test)
{
RunTest((msCer, pfxCer, col1) => test(col1));
}
private static void RunTest(Action<X509Certificate2, X509Certificate2, X509Certificate2Collection> test)
{
using (var msCer = new X509Certificate2(TestData.MsCertificate))
using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
{
X509Certificate2Collection col1 = new X509Certificate2Collection(new[] { msCer, pfxCer });
test(msCer, pfxCer, col1);
}
}
private static void RunExceptionTest<TException>(X509FindType findType, object findValue)
where TException : Exception
{
RunTest(
(msCer, pfxCer, col1) =>
{
Assert.Throws<TException>(() => col1.Find(findType, findValue, validOnly: false));
});
}
private static void RunZeroMatchTest(X509FindType findType, object findValue)
{
RunTest(
(msCer, pfxCer, col1) =>
{
X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(0, col2.Count);
}
});
}
private static void RunSingleMatchTest_MsCer(X509FindType findType, object findValue)
{
RunTest(
(msCer, pfxCer, col1) =>
{
EvaluateSingleMatch(msCer, col1, findType, findValue);
});
}
private static void RunSingleMatchTest_PfxCer(X509FindType findType, object findValue)
{
RunTest(
(msCer, pfxCer, col1) =>
{
EvaluateSingleMatch(pfxCer, col1, findType, findValue);
});
}
private static void EvaluateSingleMatch(
X509Certificate2 expected,
X509Certificate2Collection col1,
X509FindType findType,
object findValue)
{
X509Certificate2Collection col2 =
col1.Find(findType, findValue, validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(1, col2.Count);
byte[] serialNumber;
using (X509Certificate2 match = col2[0])
{
Assert.Equal(expected, match);
Assert.NotSame(expected, match);
// FriendlyName is Windows-only.
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Verify that the find result and original are linked, not just equal.
match.FriendlyName = "HAHA";
Assert.Equal("HAHA", expected.FriendlyName);
}
serialNumber = match.GetSerialNumber();
}
// Check that disposing match didn't dispose expected
Assert.Equal(serialNumber, expected.GetSerialNumber());
}
}
[Theory]
[MemberData(nameof(GenerateInvalidInputs))]
public static void FindWithWrongTypeValue(X509FindType findType, Type badValueType)
{
object badValue;
if (badValueType == typeof(object))
{
badValue = new object();
}
else if (badValueType == typeof(DateTime))
{
badValue = DateTime.Now;
}
else if (badValueType == typeof(byte[]))
{
badValue = Array.Empty<byte>();
}
else if (badValueType == typeof(string))
{
badValue = "Hello, world";
}
else
{
throw new InvalidOperationException("No creator exists for type " + badValueType);
}
RunExceptionTest<CryptographicException>(findType, badValue);
}
[Theory]
[MemberData(nameof(GenerateInvalidOidInputs))]
public static void FindWithBadOids(X509FindType findType, string badOid)
{
RunExceptionTest<ArgumentException>(findType, badOid);
}
[Fact]
public static void FindByNullName()
{
RunExceptionTest<ArgumentNullException>(X509FindType.FindBySubjectName, null);
}
[Fact]
public static void FindByInvalidThumbprint()
{
RunZeroMatchTest(X509FindType.FindByThumbprint, "Nothing");
}
[Fact]
public static void FindByInvalidThumbprint_RightLength()
{
RunZeroMatchTest(X509FindType.FindByThumbprint, "ffffffffffffffffffffffffffffffffffffffff");
}
[Fact]
public static void FindByValidThumbprint()
{
RunTest(
(msCer, pfxCer, col1) =>
{
EvaluateSingleMatch(
pfxCer,
col1,
X509FindType.FindByThumbprint,
pfxCer.Thumbprint);
});
}
[Fact]
public static void FindByThumbprint_WithLrm()
{
RunTest(
(msCer, pfxCer, col1) =>
{
EvaluateSingleMatch(
pfxCer,
col1,
X509FindType.FindByThumbprint,
LeftToRightMark + pfxCer.Thumbprint);
});
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void FindByValidThumbprint_ValidOnly(bool validOnly)
{
using (var msCer = new X509Certificate2(TestData.MsCertificate))
{
var col1 = new X509Certificate2Collection(msCer);
X509Certificate2Collection col2 =
col1.Find(X509FindType.FindByThumbprint, msCer.Thumbprint, validOnly);
using (new ImportedCollection(col2))
{
// The certificate is expired. Unless we invent time travel
// (or roll the computer clock back significantly), the validOnly
// criteria should filter it out.
//
// This test runs both ways to make sure that the precondition of
// "would match otherwise" is met (in the validOnly=false case it is
// effectively the same as FindByValidThumbprint, but does less inspection)
int expectedMatchCount = validOnly ? 0 : 1;
Assert.Equal(expectedMatchCount, col2.Count);
if (!validOnly)
{
// Double check that turning on validOnly doesn't prevent the cloning
// behavior of Find.
using (X509Certificate2 match = col2[0])
{
Assert.Equal(msCer, match);
Assert.NotSame(msCer, match);
}
}
}
}
}
[Fact]
public static void FindByValidThumbprint_RootCert()
{
using (X509Store machineRoot = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
machineRoot.Open(OpenFlags.ReadOnly);
using (var watchedStoreCerts = new ImportedCollection(machineRoot.Certificates))
{
X509Certificate2Collection storeCerts = watchedStoreCerts.Collection;
X509Certificate2 rootCert = null;
TimeSpan tolerance = TimeSpan.FromHours(12);
// These APIs use local time, so use DateTime.Now, not DateTime.UtcNow.
DateTime notBefore = DateTime.Now;
DateTime notAfter = DateTime.Now.Subtract(tolerance);
foreach (X509Certificate2 cert in storeCerts)
{
if (cert.NotBefore >= notBefore || cert.NotAfter <= notAfter)
{
// Not (safely) valid, skip.
continue;
}
X509KeyUsageExtension keyUsageExtension = null;
foreach (X509Extension extension in cert.Extensions)
{
keyUsageExtension = extension as X509KeyUsageExtension;
if (keyUsageExtension != null)
{
break;
}
}
// Some tool is putting the com.apple.systemdefault utility cert in the
// LM\Root store on OSX machines; but it gets rejected by OpenSSL as an
// invalid root for not having the Certificate Signing key usage value.
//
// While the real problem seems to be with whatever tool is putting it
// in the bundle; we can work around it here.
const X509KeyUsageFlags RequiredFlags = X509KeyUsageFlags.KeyCertSign;
// No key usage extension means "good for all usages"
if (keyUsageExtension != null &&
(keyUsageExtension.KeyUsages & RequiredFlags) != RequiredFlags)
{
// Not a valid KeyUsage, skip.
continue;
}
using (ChainHolder chainHolder = new ChainHolder())
{
chainHolder.Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
if (!chainHolder.Chain.Build(cert))
{
// Despite being not expired and having a valid KeyUsage, it's
// not considered a valid root/chain.
continue;
}
}
rootCert = cert;
break;
}
// Just in case someone has a system with no valid trusted root certs whatsoever.
if (rootCert != null)
{
X509Certificate2Collection matches =
storeCerts.Find(X509FindType.FindByThumbprint, rootCert.Thumbprint, true);
using (new ImportedCollection(matches))
{
// Improve the debuggability, since the root cert found on each
// machine might be different
if (matches.Count == 0)
{
Assert.True(
false,
$"Root certificate '{rootCert.Subject}' ({rootCert.NotBefore} - {rootCert.NotAfter}) is findable with thumbprint '{rootCert.Thumbprint}' and validOnly=true");
}
Assert.NotSame(rootCert, matches[0]);
Assert.Equal(rootCert, matches[0]);
}
}
}
}
}
[Theory]
[InlineData("Nothing")]
[InlineData("US, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")]
public static void TestSubjectName_NoMatch(string subjectQualifier)
{
RunZeroMatchTest(X509FindType.FindBySubjectName, subjectQualifier);
}
[Theory]
[InlineData("Microsoft Corporation")]
[InlineData("MOPR")]
[InlineData("Redmond")]
[InlineData("Washington")]
[InlineData("US")]
[InlineData("US, Washington")]
[InlineData("Washington, Redmond")]
[InlineData("US, Washington, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")]
[InlineData("us, washington, redmond, microsoft corporation, mopr, microsoft corporation")]
public static void TestSubjectName_Match(string subjectQualifier)
{
RunSingleMatchTest_MsCer(X509FindType.FindBySubjectName, subjectQualifier);
}
[Theory]
[InlineData("")]
[InlineData("Nothing")]
[InlineData("ou=mopr, o=microsoft corporation")]
[InlineData("CN=Microsoft Corporation")]
[InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
[InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")]
[InlineData(" CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
public static void TestDistinguishedSubjectName_NoMatch(string distinguishedSubjectName)
{
RunZeroMatchTest(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName);
}
[Theory]
[InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
[InlineData("CN=microsoft corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
[InlineData("cn=microsoft corporation, ou=mopr, o=microsoft corporation, l=redmond, s=washington, c=us")]
public static void TestDistinguishedSubjectName_Match(string distinguishedSubjectName)
{
RunSingleMatchTest_MsCer(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName);
}
[Fact]
public static void TestIssuerName_NoMatch()
{
RunZeroMatchTest(X509FindType.FindByIssuerName, "Nothing");
}
[Theory]
[InlineData("Microsoft Code Signing PCA")]
[InlineData("Microsoft Corporation")]
[InlineData("Redmond")]
[InlineData("Washington")]
[InlineData("US")]
[InlineData("US, Washington")]
[InlineData("Washington, Redmond")]
[InlineData("US, Washington, Redmond, Microsoft Corporation, Microsoft Code Signing PCA")]
[InlineData("us, washington, redmond, microsoft corporation, microsoft code signing pca")]
public static void TestIssuerName_Match(string issuerQualifier)
{
RunSingleMatchTest_MsCer(X509FindType.FindByIssuerName, issuerQualifier);
}
[Theory]
[InlineData("")]
[InlineData("Nothing")]
[InlineData("CN=Microsoft Code Signing PCA")]
[InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
[InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")]
[InlineData(" CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
public static void TestDistinguishedIssuerName_NoMatch(string issuerDistinguishedName)
{
RunZeroMatchTest(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName);
}
[Theory]
[InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
[InlineData("CN=microsoft Code signing pca, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")]
[InlineData("cn=microsoft code signing pca, o=microsoft corporation, l=redmond, s=washington, c=us")]
public static void TestDistinguishedIssuerName_Match(string issuerDistinguishedName)
{
RunSingleMatchTest_MsCer(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName);
}
[Fact]
public static void TestByTimeValid_Before()
{
RunTest(
(msCer, pfxCer, col1) =>
{
DateTime earliest = new[] { msCer.NotBefore, pfxCer.NotBefore }.Min();
X509Certificate2Collection col2 = col1.Find(
X509FindType.FindByTimeValid,
earliest - TimeSpan.FromSeconds(1),
validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(0, col2.Count);
}
});
}
[Fact]
public static void TestByTimeValid_After()
{
RunTest(
(msCer, pfxCer, col1) =>
{
DateTime latest = new[] { msCer.NotAfter, pfxCer.NotAfter }.Max();
X509Certificate2Collection col2 = col1.Find(
X509FindType.FindByTimeValid,
latest + TimeSpan.FromSeconds(1),
validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(0, col2.Count);
}
});
}
[Fact]
public static void TestByTimeValid_Between()
{
RunTest(
(msCer, pfxCer, col1) =>
{
DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min();
DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max();
TimeSpan gap = latestNotBefore - earliestNotAfter;
// If this assert fails it means our test data was rebuilt and the constraint
// can no longer be satisfied
Assert.True(gap > TimeSpan.FromSeconds(1));
DateTime noMatchTime = earliestNotAfter + TimeSpan.FromSeconds(1);
X509Certificate2Collection col2 = col1.Find(
X509FindType.FindByTimeValid,
noMatchTime,
validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(0, col2.Count);
}
});
}
[Fact]
public static void TestByTimeValid_Match()
{
RunTest(
(msCer, pfxCer, col1) =>
{
EvaluateSingleMatch(
msCer,
col1,
X509FindType.FindByTimeValid,
msCer.NotBefore + TimeSpan.FromSeconds(1));
});
}
[Fact]
public static void TestFindByTimeNotYetValid_Match()
{
RunTest(
(msCer, pfxCer, col1) =>
{
DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min();
DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max();
TimeSpan gap = latestNotBefore - earliestNotAfter;
// If this assert fails it means our test data was rebuilt and the constraint
// can no longer be satisfied
Assert.True(gap > TimeSpan.FromSeconds(1));
// One second before the latest NotBefore, so one is valid, the other is not yet valid.
DateTime matchTime = latestNotBefore - TimeSpan.FromSeconds(1);
X509Certificate2Collection col2 = col1.Find(
X509FindType.FindByTimeNotYetValid,
matchTime,
validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(1, col2.Count);
}
});
}
[Fact]
public static void TestFindByTimeNotYetValid_NoMatch()
{
RunTest(
(msCer, pfxCer, col1) =>
{
DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min();
DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max();
TimeSpan gap = latestNotBefore - earliestNotAfter;
// If this assert fails it means our test data was rebuilt and the constraint
// can no longer be satisfied
Assert.True(gap > TimeSpan.FromSeconds(1));
// One second after the latest NotBefore, both certificates are time-valid
DateTime noMatchTime = latestNotBefore + TimeSpan.FromSeconds(1);
X509Certificate2Collection col2 = col1.Find(
X509FindType.FindByTimeNotYetValid,
noMatchTime,
validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(0, col2.Count);
}
});
}
[Fact]
public static void TestFindByTimeExpired_Match()
{
RunTest(
(msCer, pfxCer, col1) =>
{
DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min();
DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max();
TimeSpan gap = latestNotBefore - earliestNotAfter;
// If this assert fails it means our test data was rebuilt and the constraint
// can no longer be satisfied
Assert.True(gap > TimeSpan.FromSeconds(1));
// One second after the earliest NotAfter, so one is valid, the other is no longer valid.
DateTime matchTime = earliestNotAfter + TimeSpan.FromSeconds(1);
X509Certificate2Collection col2 = col1.Find(
X509FindType.FindByTimeExpired,
matchTime,
validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(1, col2.Count);
}
});
}
[Fact]
public static void TestFindByTimeExpired_NoMatch()
{
RunTest(
(msCer, pfxCer, col1) =>
{
DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min();
DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max();
TimeSpan gap = latestNotBefore - earliestNotAfter;
// If this assert fails it means our test data was rebuilt and the constraint
// can no longer be satisfied
Assert.True(gap > TimeSpan.FromSeconds(1));
// One second before the earliest NotAfter, so both certificates are valid
DateTime noMatchTime = earliestNotAfter - TimeSpan.FromSeconds(1);
X509Certificate2Collection col2 = col1.Find(
X509FindType.FindByTimeExpired,
noMatchTime,
validOnly: false);
using (new ImportedCollection(col2))
{
Assert.Equal(0, col2.Count);
}
});
}
[Fact]
public static void TestBySerialNumber_Decimal()
{
// Decimal string is an allowed input format.
RunSingleMatchTest_PfxCer(
X509FindType.FindBySerialNumber,
"284069184166497622998429950103047369500");
}
[Fact]
public static void TestBySerialNumber_DecimalLeadingZeros()
{
// Checking that leading zeros are ignored.
RunSingleMatchTest_PfxCer(
X509FindType.FindBySerialNumber,
"000" + "284069184166497622998429950103047369500");
}
[Theory]
[InlineData("1137338006039264696476027508428304567989436592")]
// Leading zeroes are fine/ignored
[InlineData("0001137338006039264696476027508428304567989436592")]
// Compat: Minus signs are ignored
[InlineData("-1137338006039264696476027508428304567989436592")]
public static void TestBySerialNumber_Decimal_CertB(string serialNumber)
{
RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, serialNumber);
}
[Fact]
public static void TestBySerialNumber_Hex()
{
// Hex string is also an allowed input format.
RunSingleMatchTest_PfxCer(
X509FindType.FindBySerialNumber,
"D5B5BC1C458A558845BFF51CB4DFF31C");
}
[Fact]
public static void TestBySerialNumber_HexIgnoreCase()
{
// Hex string is also an allowed input format and case-blind
RunSingleMatchTest_PfxCer(
X509FindType.FindBySerialNumber,
"d5b5bc1c458a558845bff51cb4dff31c");
}
[Fact]
public static void TestBySerialNumber_HexLeadingZeros()
{
// Checking that leading zeros are ignored.
RunSingleMatchTest_PfxCer(
X509FindType.FindBySerialNumber,
"0000" + "D5B5BC1C458A558845BFF51CB4DFF31C");
}
[Fact]
public static void TestBySerialNumber_WithSpaces()
{
// Hex string is also an allowed input format and case-blind
RunSingleMatchTest_PfxCer(
X509FindType.FindBySerialNumber,
"d5 b5 bc 1c 45 8a 55 88 45 bf f5 1c b4 df f3 1c");
}
[Fact]
public static void TestBySerialNumber_WithLRM()
{
// Hex string is also an allowed input format and case-blind
RunSingleMatchTest_PfxCer(
X509FindType.FindBySerialNumber,
LeftToRightMark + "d5 b5 bc 1c 45 8a 55 88 45 bf f5 1c b4 df f3 1c");
}
[Fact]
public static void TestBySerialNumber_NoMatch()
{
RunZeroMatchTest(
X509FindType.FindBySerialNumber,
"23000000B011AF0A8BD03B9FDD0001000000B0");
}
[Theory]
[MemberData(nameof(GenerateWorkingFauxSerialNumbers))]
public static void TestBySerialNumber_Match_NonDecimalInput(string input)
{
RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, input);
}
[Fact]
public static void TestByExtension_FriendlyName()
{
// Cannot just say "Enhanced Key Usage" here because the extension name is localized.
// Instead, look it up via the OID.
RunSingleMatchTest_MsCer(X509FindType.FindByExtension, new Oid("2.5.29.37").FriendlyName);
}
[Fact]
public static void TestByExtension_OidValue()
{
RunSingleMatchTest_MsCer(X509FindType.FindByExtension, "2.5.29.37");
}
[Fact]
// Compat: Non-ASCII digits don't throw, but don't match.
public static void TestByExtension_OidValue_ArabicNumericChar()
{
// This uses the same OID as TestByExtension_OidValue, but uses "Arabic-Indic Digit Two" instead
// of "Digit Two" in the third segment. This value can't possibly ever match, but it doesn't throw
// as an illegal OID value.
RunZeroMatchTest(X509FindType.FindByExtension, "2.5.\u06629.37");
}
[Fact]
public static void TestByExtension_UnknownFriendlyName()
{
RunExceptionTest<ArgumentException>(X509FindType.FindByExtension, "BOGUS");
}
[Fact]
public static void TestByExtension_NoMatch()
{
RunZeroMatchTest(X509FindType.FindByExtension, "2.9");
}
[Fact]
public static void TestBySubjectKeyIdentifier_UsingFallback()
{
RunSingleMatchTest_PfxCer(
X509FindType.FindBySubjectKeyIdentifier,
"B4D738B2D4978AFF290A0B02987BABD114FEE9C7");
}
[Theory]
[InlineData("5971A65A334DDA980780FF841EBE87F9723241F2")]
// Whitespace is allowed
[InlineData("59 71\tA6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")]
// Lots of kinds of whitespace (does not include \u000b or \u000c, because those
// produce a build warning (which becomes an error):
// EXEC : warning : '(not included here)', hexadecimal value 0x0C, is an invalid character.
[InlineData(
"59\u000971\u000aA6\u30005A\u205f33\u000d4D\u0020DA\u008598\u00a007\u1680" +
"80\u2000FF\u200184\u20021E\u2003BE\u200487\u2005F9\u200672\u200732\u2008" +
"4\u20091\u200aF\u20282\u2029\u202f")]
// Non-byte-aligned whitespace is allowed
[InlineData("597 1A6 5A3 34D DA9 807 80F F84 1EB E87 F97 232 41F 2")]
// Non-symmetric whitespace is allowed
[InlineData(" 5971A65 A334DDA980780FF84 1EBE87F97 23241F 2")]
public static void TestBySubjectKeyIdentifier_ExtensionPresent(string subjectKeyIdentifier)
{
RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier);
}
// Should ignore Left-to-right mark \u200E
[Theory]
[InlineData(LeftToRightMark + "59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")]
// Compat: Lone trailing nybbles are ignored
[InlineData(LeftToRightMark + "59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")]
// Compat: Lone trailing nybbles are ignored, even if not hex
[InlineData(LeftToRightMark + "59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")]
public static void TestBySubjectKeyIdentifier_ExtensionPresentWithLTM(string subjectKeyIdentifier)
{
RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier);
}
[Theory]
// Compat: Lone trailing nybbles are ignored
[InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")]
// Compat: Lone trailing nybbles are ignored, even if not hex
[InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")]
// Compat: A non-hex character as the high nybble makes that nybble be F
[InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 p9 72 32 41 F2")]
// Compat: A non-hex character as the low nybble makes the whole byte FF.
[InlineData("59 71 A6 5A 33 4D DA 98 07 80 0p 84 1E BE 87 F9 72 32 41 F2")]
public static void TestBySubjectKeyIdentifier_Compat(string subjectKeyIdentifier)
{
RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier);
}
[Fact]
public static void TestBySubjectKeyIdentifier_NoMatch()
{
RunZeroMatchTest(X509FindType.FindBySubjectKeyIdentifier, "");
}
[Fact]
public static void TestBySubjectKeyIdentifier_NoMatch_RightLength()
{
RunZeroMatchTest(
X509FindType.FindBySubjectKeyIdentifier,
"5971A65A334DDA980780FF841EBE87F9723241F0");
}
[Fact]
public static void TestByApplicationPolicy_MatchAll()
{
RunTest(
(msCer, pfxCer, col1) =>
{
X509Certificate2Collection results =
col1.Find(X509FindType.FindByApplicationPolicy, "1.3.6.1.5.5.7.3.3", false);
using (new ImportedCollection(results))
{
Assert.Equal(2, results.Count);
Assert.True(results.Contains(msCer));
Assert.True(results.Contains(pfxCer));
}
});
}
[Fact]
public static void TestByApplicationPolicy_NoPolicyAlwaysMatches()
{
// PfxCer doesn't have any application policies which means it's good for all usages (even nonsensical ones.)
RunSingleMatchTest_PfxCer(X509FindType.FindByApplicationPolicy, "2.2");
}
[Fact]
public static void TestByApplicationPolicy_NoMatch()
{
RunTest(
(msCer, pfxCer, col1) =>
{
// Per TestByApplicationPolicy_NoPolicyAlwaysMatches we know that pfxCer will match, so remove it.
col1.Remove(pfxCer);
X509Certificate2Collection results =
col1.Find(X509FindType.FindByApplicationPolicy, "2.2", false);
using (new ImportedCollection(results))
{
Assert.Equal(0, results.Count);
}
});
}
[Fact]
public static void TestByCertificatePolicies_MatchA()
{
using (var policyCert = new X509Certificate2(TestData.CertWithPolicies))
{
EvaluateSingleMatch(
policyCert,
new X509Certificate2Collection(policyCert),
X509FindType.FindByCertificatePolicy,
"2.18.19");
}
}
[Fact]
public static void TestByCertificatePolicies_MatchB()
{
using (var policyCert = new X509Certificate2(TestData.CertWithPolicies))
{
EvaluateSingleMatch(
policyCert,
new X509Certificate2Collection(policyCert),
X509FindType.FindByCertificatePolicy,
"2.32.33");
}
}
[Fact]
public static void TestByCertificatePolicies_NoMatch()
{
using (var policyCert = new X509Certificate2(TestData.CertWithPolicies))
{
X509Certificate2Collection col1 = new X509Certificate2Collection(policyCert);
X509Certificate2Collection results = col1.Find(X509FindType.FindByCertificatePolicy, "2.999", false);
using (new ImportedCollection(results))
{
Assert.Equal(0, results.Count);
}
}
}
[Fact]
public static void TestByTemplate_MatchA()
{
using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData))
{
EvaluateSingleMatch(
templatedCert,
new X509Certificate2Collection(templatedCert),
X509FindType.FindByTemplateName,
"Hello");
}
}
[Fact]
public static void TestByTemplate_MatchB()
{
using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData))
{
EvaluateSingleMatch(
templatedCert,
new X509Certificate2Collection(templatedCert),
X509FindType.FindByTemplateName,
"2.7.8.9");
}
}
[Fact]
public static void TestByTemplate_NoMatch()
{
using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData))
{
X509Certificate2Collection col1 = new X509Certificate2Collection(templatedCert);
X509Certificate2Collection results = col1.Find(X509FindType.FindByTemplateName, "2.999", false);
using (new ImportedCollection(results))
{
Assert.Equal(0, results.Count);
}
}
}
[Theory]
[InlineData((int)0x80)]
[InlineData((uint)0x80)]
[InlineData(X509KeyUsageFlags.DigitalSignature)]
[InlineData("DigitalSignature")]
[InlineData("digitalSignature")]
public static void TestFindByKeyUsage_Match(object matchCriteria)
{
TestFindByKeyUsage(true, matchCriteria);
}
[Theory]
[InlineData((int)0x20)]
[InlineData((uint)0x20)]
[InlineData(X509KeyUsageFlags.KeyEncipherment)]
[InlineData("KeyEncipherment")]
[InlineData("KEYEncipherment")]
public static void TestFindByKeyUsage_NoMatch(object matchCriteria)
{
TestFindByKeyUsage(false, matchCriteria);
}
private static void TestFindByKeyUsage(bool shouldMatch, object matchCriteria)
{
using (var noKeyUsages = new X509Certificate2(TestData.MsCertificate))
using (var noKeyUsages2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
using (var keyUsages = new X509Certificate2(Path.Combine("TestData", "microsoft.cer")))
{
var coll = new X509Certificate2Collection { noKeyUsages, noKeyUsages2, keyUsages, };
X509Certificate2Collection results = coll.Find(X509FindType.FindByKeyUsage, matchCriteria, false);
using (new ImportedCollection(results))
{
// The two certificates with no KeyUsages extension will always match,
// the real question is about the third.
int matchCount = shouldMatch ? 3 : 2;
Assert.Equal(matchCount, results.Count);
if (shouldMatch)
{
bool found = false;
foreach (X509Certificate2 cert in results)
{
if (keyUsages.Equals(cert))
{
Assert.NotSame(cert, keyUsages);
found = true;
break;
}
}
Assert.True(found, "Certificate with key usages was found in the collection");
}
else
{
Assert.False(
results.Contains(keyUsages),
"KeyUsages certificate is not present in the collection");
}
}
}
}
public static IEnumerable<object[]> GenerateWorkingFauxSerialNumbers
{
get
{
const string seedDec = "1137338006039264696476027508428304567989436592";
string[] nonHexWords = { "wow", "its", "tough", "using", "only", "high", "lttr", "vlus" };
string gluedTogether = string.Join("", nonHexWords);
string withSpaces = string.Join(" ", nonHexWords);
yield return new object[] { gluedTogether + seedDec };
yield return new object[] { seedDec + gluedTogether };
yield return new object[] { withSpaces + seedDec };
yield return new object[] { seedDec + withSpaces };
StringBuilder builderDec = new StringBuilder(512);
int offsetDec = 0;
for (int i = 0; i < nonHexWords.Length; i++)
{
if (offsetDec < seedDec.Length)
{
int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length);
appendLen = Math.Min(appendLen, seedDec.Length - offsetDec);
builderDec.Append(seedDec, offsetDec, appendLen);
offsetDec += appendLen;
}
builderDec.Append(nonHexWords[i]);
}
builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec);
yield return new object[] { builderDec.ToString() };
builderDec.Length = 0;
offsetDec = 0;
for (int i = 0; i < nonHexWords.Length; i++)
{
if (offsetDec < seedDec.Length)
{
int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length);
appendLen = Math.Min(appendLen, seedDec.Length - offsetDec);
builderDec.Append(seedDec, offsetDec, appendLen);
offsetDec += appendLen;
builderDec.Append(' ');
}
builderDec.Append(nonHexWords[i]);
builderDec.Append(' ');
}
builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec);
yield return new object[] { builderDec.ToString() };
}
}
public static IEnumerable<object[]> GenerateInvalidOidInputs
{
get
{
X509FindType[] oidTypes =
{
X509FindType.FindByApplicationPolicy,
};
string[] invalidOids =
{
"",
"This Is Not An Oid",
"1",
"95.22",
".1",
"1..1",
"1.",
"1.2.",
};
List<object[]> combinations = new List<object[]>(oidTypes.Length * invalidOids.Length);
for (int findTypeIndex = 0; findTypeIndex < oidTypes.Length; findTypeIndex++)
{
for (int oidIndex = 0; oidIndex < invalidOids.Length; oidIndex++)
{
combinations.Add(new object[] { oidTypes[findTypeIndex], invalidOids[oidIndex] });
}
}
return combinations;
}
}
public static IEnumerable<object[]> GenerateInvalidInputs
{
get
{
Type[] allTypes =
{
typeof(object),
typeof(DateTime),
typeof(byte[]),
typeof(string),
};
Tuple<X509FindType, Type>[] legalInputs =
{
Tuple.Create(X509FindType.FindByThumbprint, typeof(string)),
Tuple.Create(X509FindType.FindBySubjectName, typeof(string)),
Tuple.Create(X509FindType.FindBySubjectDistinguishedName, typeof(string)),
Tuple.Create(X509FindType.FindByIssuerName, typeof(string)),
Tuple.Create(X509FindType.FindByIssuerDistinguishedName, typeof(string)),
Tuple.Create(X509FindType.FindBySerialNumber, typeof(string)),
Tuple.Create(X509FindType.FindByTimeValid, typeof(DateTime)),
Tuple.Create(X509FindType.FindByTimeNotYetValid, typeof(DateTime)),
Tuple.Create(X509FindType.FindByTimeExpired, typeof(DateTime)),
Tuple.Create(X509FindType.FindByTemplateName, typeof(string)),
Tuple.Create(X509FindType.FindByApplicationPolicy, typeof(string)),
Tuple.Create(X509FindType.FindByCertificatePolicy, typeof(string)),
Tuple.Create(X509FindType.FindByExtension, typeof(string)),
// KeyUsage supports int/uint/KeyUsage/string, but only one of those is in allTypes.
Tuple.Create(X509FindType.FindByKeyUsage, typeof(string)),
Tuple.Create(X509FindType.FindBySubjectKeyIdentifier, typeof(string)),
};
List<object[]> invalidCombinations = new List<object[]>();
for (int findTypesIndex = 0; findTypesIndex < legalInputs.Length; findTypesIndex++)
{
Tuple<X509FindType, Type> tuple = legalInputs[findTypesIndex];
for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++)
{
Type t = allTypes[typeIndex];
if (t != tuple.Item2)
{
invalidCombinations.Add(new object[] { tuple.Item1, t });
}
}
}
return invalidCombinations;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SiteMapPath.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.Util;
[
Designer("System.Web.UI.Design.WebControls.SiteMapPathDesigner, " + AssemblyRef.SystemDesign)
]
public class SiteMapPath : CompositeControl {
private const string _defaultSeparator = " > ";
private static readonly object _eventItemCreated = new object();
private static readonly object _eventItemDataBound = new object();
private SiteMapProvider _provider = null;
private Style _currentNodeStyle;
private Style _rootNodeStyle;
private Style _nodeStyle;
private Style _pathSeparatorStyle;
private Style _mergedCurrentNodeStyle;
private Style _mergedRootNodeStyle;
private ITemplate _currentNodeTemplate;
private ITemplate _rootNodeTemplate;
private ITemplate _nodeTemplate;
private ITemplate _pathSeparatorTemplate;
public SiteMapPath() {
}
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.SiteMapPath_CurrentNodeStyle)
]
public Style CurrentNodeStyle {
get {
if (_currentNodeStyle == null) {
_currentNodeStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_currentNodeStyle).TrackViewState();
}
}
return _currentNodeStyle;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how the current node is rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(SiteMapNodeItem)),
WebSysDescription(SR.SiteMapPath_CurrentNodeTemplate)
]
public virtual ITemplate CurrentNodeTemplate {
get {
return _currentNodeTemplate;
}
set {
_currentNodeTemplate = value;
}
}
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.SiteMapPath_NodeStyle)
]
public Style NodeStyle {
get {
if (_nodeStyle == null) {
_nodeStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_nodeStyle).TrackViewState();
}
}
return _nodeStyle;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how the parent node is rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(SiteMapNodeItem)),
WebSysDescription(SR.SiteMapPath_NodeTemplate)
]
public virtual ITemplate NodeTemplate {
get {
return _nodeTemplate;
}
set {
_nodeTemplate = value;
}
}
/// <devdoc>
/// <para>Indicates the number of parent nodes to display.</para>
/// </devdoc>
[
DefaultValue(-1),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.SiteMapPath_ParentLevelsDisplayed)
]
public virtual int ParentLevelsDisplayed {
get {
object o = ViewState["ParentLevelsDisplayed"];
if (o == null) {
return -1;
}
return (int)o;
}
set {
if (value < -1) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["ParentLevelsDisplayed"] = value;
}
}
[
DefaultValue(PathDirection.RootToCurrent),
WebCategory("Appearance"),
WebSysDescription(SR.SiteMapPath_PathDirection)
]
public virtual PathDirection PathDirection {
get {
object o = ViewState["PathDirection"];
if (o == null) {
return PathDirection.RootToCurrent;
}
return (PathDirection)o;
}
set {
if ((value < PathDirection.RootToCurrent) || (value > PathDirection.CurrentToRoot)) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["PathDirection"] = value;
}
}
[
DefaultValue(_defaultSeparator),
Localizable(true),
WebCategory("Appearance"),
WebSysDescription(SR.SiteMapPath_PathSeparator)
]
public virtual string PathSeparator {
get {
string s = (string)ViewState["PathSeparator"];
if (s == null) {
return _defaultSeparator;
}
return s;
}
set {
ViewState["PathSeparator"] = value;
}
}
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.SiteMapPath_PathSeparatorStyle)
]
public Style PathSeparatorStyle {
get {
if (_pathSeparatorStyle == null) {
_pathSeparatorStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_pathSeparatorStyle).TrackViewState();
}
}
return _pathSeparatorStyle;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how the path Separator is rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(SiteMapNodeItem)),
WebSysDescription(SR.SiteMapPath_PathSeparatorTemplate)
]
public virtual ITemplate PathSeparatorTemplate {
get {
return _pathSeparatorTemplate;
}
set {
_pathSeparatorTemplate = value;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
WebSysDescription(SR.SiteMapPath_Provider)
]
public SiteMapProvider Provider {
get {
// Designer must specify a provider, as code below access runtime config
if (_provider != null || DesignMode)
return _provider;
// If not specified, use the default provider.
if (String.IsNullOrEmpty(SiteMapProvider)) {
_provider = SiteMap.Provider;
if (_provider == null) {
throw new HttpException(SR.GetString(SR.SiteMapDataSource_DefaultProviderNotFound));
}
}
else {
_provider = SiteMap.Providers[SiteMapProvider];
if (_provider == null) {
throw new HttpException(SR.GetString(SR.SiteMapDataSource_ProviderNotFound, SiteMapProvider));
}
}
return _provider;
}
set {
_provider = value;
}
}
[
DefaultValue(false),
WebCategory("Appearance"),
WebSysDescription(SR.SiteMapPath_RenderCurrentNodeAsLink)
]
public virtual bool RenderCurrentNodeAsLink {
get {
object o = ViewState["RenderCurrentNodeAsLink"];
if (o == null) {
return false;
}
return (bool)o;
}
set {
ViewState["RenderCurrentNodeAsLink"] = value;
}
}
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.SiteMapPath_RootNodeStyle)
]
public Style RootNodeStyle {
get {
if (_rootNodeStyle == null) {
_rootNodeStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_rootNodeStyle).TrackViewState();
}
}
return _rootNodeStyle;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how the root node is rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(SiteMapNodeItem)),
WebSysDescription(SR.SiteMapPath_RootNodeTemplate)
]
public virtual ITemplate RootNodeTemplate {
get {
return _rootNodeTemplate;
}
set {
_rootNodeTemplate = value;
}
}
[
Localizable(true),
WebCategory("Accessibility"),
WebSysDefaultValue(SR.SiteMapPath_Default_SkipToContentText),
WebSysDescription(SR.SiteMapPath_SkipToContentText)
]
public virtual String SkipLinkText {
get {
string s = ViewState["SkipLinkText"] as String;
return s == null ? SR.GetString(SR.SiteMapPath_Default_SkipToContentText) : s;
}
set {
ViewState["SkipLinkText"] = value;
}
}
[
DefaultValue(true),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.SiteMapPath_ShowToolTips)
]
public virtual bool ShowToolTips {
get {
object o = ViewState["ShowToolTips"];
if (o == null) {
return true;
}
return (bool)o;
}
set {
ViewState["ShowToolTips"] = value;
}
}
[
DefaultValue(""),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.SiteMapPath_SiteMapProvider)
]
public virtual string SiteMapProvider {
get {
string provider = ViewState["SiteMapProvider"] as string;
return (provider == null) ? String.Empty : provider;
}
set {
ViewState["SiteMapProvider"] = value;
_provider = null;
}
}
[
WebCategory("Action"),
WebSysDescription(SR.DataControls_OnItemCreated)
]
public event SiteMapNodeItemEventHandler ItemCreated {
add {
Events.AddHandler(_eventItemCreated, value);
}
remove {
Events.RemoveHandler(_eventItemCreated, value);
}
}
/// <devdoc>
/// <para>Occurs when an item is databound within a <see cref='System.Web.UI.WebControls.SiteMapPath'/> control tree.</para>
/// </devdoc>
[
WebCategory("Action"),
WebSysDescription(SR.SiteMapPath_OnItemDataBound)
]
public event SiteMapNodeItemEventHandler ItemDataBound {
add {
Events.AddHandler(_eventItemDataBound, value);
}
remove {
Events.RemoveHandler(_eventItemDataBound, value);
}
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected internal override void CreateChildControls() {
Controls.Clear();
CreateControlHierarchy();
ClearChildState();
}
/// <devdoc>
/// A protected method. Creates a control hierarchy based on current sitemap OM.
/// </devdoc>
protected virtual void CreateControlHierarchy() {
if (Provider == null)
return;
int index = 0;
CreateMergedStyles();
SiteMapNode currentNode = Provider.GetCurrentNodeAndHintAncestorNodes(-1);
if (currentNode != null) {
SiteMapNode parentNode = currentNode.ParentNode;
if (parentNode != null) {
CreateControlHierarchyRecursive(ref index, parentNode, ParentLevelsDisplayed);
}
CreateItem(index++, SiteMapNodeItemType.Current, currentNode);
}
}
private void CreateControlHierarchyRecursive(ref int index, SiteMapNode node, int parentLevels) {
if (parentLevels == 0)
return;
SiteMapNode parentNode = node.ParentNode;
if (parentNode != null) {
CreateControlHierarchyRecursive(ref index, parentNode, parentLevels - 1);
CreateItem(index++, SiteMapNodeItemType.Parent, node);
}
else {
CreateItem(index++, SiteMapNodeItemType.Root, node);
}
CreateItem(index, SiteMapNodeItemType.PathSeparator, null);
}
private SiteMapNodeItem CreateItem(int itemIndex, SiteMapNodeItemType itemType, SiteMapNode node) {
SiteMapNodeItem item = new SiteMapNodeItem(itemIndex, itemType);
int index = (PathDirection == PathDirection.CurrentToRoot ? 0 : -1);
SiteMapNodeItemEventArgs e = new SiteMapNodeItemEventArgs(item);
//Add sitemap nodes so that they are accessible during events.
item.SiteMapNode = node;
InitializeItem(item);
// Notify items
OnItemCreated(e);
// Add items based on PathDirection.
Controls.AddAt(index, item);
// Databind.
item.DataBind();
// Notify items.
OnItemDataBound(e);
item.SiteMapNode = null;
// SiteMapNodeItem is dynamically created each time, don't track viewstate.
item.EnableViewState = false;
return item;
}
private void CopyStyle(Style toStyle, Style fromStyle) {
Debug.Assert(toStyle != null);
// Review: How to change the default value of Font.Underline?
if (fromStyle != null && fromStyle.IsSet(System.Web.UI.WebControls.Style.PROP_FONT_UNDERLINE))
toStyle.Font.Underline = fromStyle.Font.Underline;
toStyle.CopyFrom(fromStyle);
}
private void CreateMergedStyles() {
_mergedCurrentNodeStyle = new Style();
CopyStyle(_mergedCurrentNodeStyle, _nodeStyle);
CopyStyle(_mergedCurrentNodeStyle, _currentNodeStyle);
_mergedRootNodeStyle = new Style();
CopyStyle(_mergedRootNodeStyle, _nodeStyle);
CopyStyle(_mergedRootNodeStyle, _rootNodeStyle);
}
/// <internalonly/>
/// <devdoc>
/// <para>Overriden to handle our own databinding.</para>
/// </devdoc>
public override void DataBind() {
// do our own databinding
OnDataBinding(EventArgs.Empty);
// contained items will be databound after they have been created,
// so we don't want to walk the hierarchy here.
}
/// <devdoc>
/// <para>A protected method. Populates iteratively the specified <see cref='System.Web.UI.WebControls.SiteMapNodeItem'/> with a
/// sub-hierarchy of child controls.</para>
/// </devdoc>
protected virtual void InitializeItem(SiteMapNodeItem item) {
Debug.Assert(_mergedCurrentNodeStyle != null && _mergedRootNodeStyle != null);
ITemplate template = null;
Style style = null;
SiteMapNodeItemType itemType = item.ItemType;
SiteMapNode node = item.SiteMapNode;
switch (itemType) {
case SiteMapNodeItemType.Root:
template = RootNodeTemplate != null ? RootNodeTemplate : NodeTemplate;
style = _mergedRootNodeStyle;
break;
case SiteMapNodeItemType.Parent:
template = NodeTemplate;
style = _nodeStyle;
break;
case SiteMapNodeItemType.Current:
template = CurrentNodeTemplate != null ? CurrentNodeTemplate : NodeTemplate;
style = _mergedCurrentNodeStyle;
break;
case SiteMapNodeItemType.PathSeparator:
template = PathSeparatorTemplate;
style = _pathSeparatorStyle;
break;
}
if (template == null) {
if (itemType == SiteMapNodeItemType.PathSeparator) {
Literal separatorLiteral = new Literal();
separatorLiteral.Mode = LiteralMode.Encode;
separatorLiteral.Text = PathSeparator;
item.Controls.Add(separatorLiteral);
item.ApplyStyle(style);
}
else if (itemType == SiteMapNodeItemType.Current && !RenderCurrentNodeAsLink) {
Literal currentNodeLiteral = new Literal();
currentNodeLiteral.Mode = LiteralMode.Encode;
currentNodeLiteral.Text = node.Title;
item.Controls.Add(currentNodeLiteral);
item.ApplyStyle(style);
}
else {
HyperLink link = new HyperLink();
if (style != null && style.IsSet(System.Web.UI.WebControls.Style.PROP_FONT_UNDERLINE))
link.Font.Underline = style.Font.Underline;
link.EnableTheming = false;
link.Enabled = this.Enabled;
// VSWhidbey 281869 Don't modify input when url pointing to unc share
if (node.Url.StartsWith("\\\\", StringComparison.Ordinal)) {
link.NavigateUrl = ResolveClientUrl(HttpUtility.UrlPathEncode(node.Url));
}
else {
link.NavigateUrl = Context != null ?
Context.Response.ApplyAppPathModifier(ResolveClientUrl(HttpUtility.UrlPathEncode(node.Url))) : node.Url;
}
link.Text = HttpUtility.HtmlEncode(node.Title);
if (ShowToolTips)
link.ToolTip = node.Description;
item.Controls.Add(link);
link.ApplyStyle(style);
}
}
else {
template.InstantiateIn(item);
item.ApplyStyle(style);
}
}
/// <internalonly/>
/// <devdoc>
/// <para>Loads a saved state of the <see cref='System.Web.UI.WebControls.SiteMapPath'/>. </para>
/// </devdoc>
protected override void LoadViewState(object savedState) {
if (savedState != null) {
object[] myState = (object[])savedState;
Debug.Assert(myState.Length == 5);
base.LoadViewState(myState[0]);
if (myState[1] != null)
((IStateManager)CurrentNodeStyle).LoadViewState(myState[1]);
if (myState[2] != null)
((IStateManager)NodeStyle).LoadViewState(myState[2]);
if (myState[3] != null)
((IStateManager)RootNodeStyle).LoadViewState(myState[3]);
if (myState[4] != null)
((IStateManager)PathSeparatorStyle).LoadViewState(myState[4]);
}
else {
base.LoadViewState(null);
}
}
/// <internalonly/>
/// <devdoc>
/// <para>A protected method. Raises the <see langword='DataBinding'/> event.</para>
/// </devdoc>
protected override void OnDataBinding(EventArgs e) {
base.OnDataBinding(e);
// reset the control state
Controls.Clear();
ClearChildState();
CreateControlHierarchy();
ChildControlsCreated = true;
}
/// <devdoc>
/// <para>A protected method. Raises the <see langword='ItemCreated'/> event.</para>
/// </devdoc>
protected virtual void OnItemCreated(SiteMapNodeItemEventArgs e) {
SiteMapNodeItemEventHandler onItemCreatedHandler =
(SiteMapNodeItemEventHandler)Events[_eventItemCreated];
if (onItemCreatedHandler != null) {
onItemCreatedHandler(this, e);
}
}
/// <devdoc>
/// <para>A protected method. Raises the <see langword='ItemDataBound'/>
/// event.</para>
/// </devdoc>
protected virtual void OnItemDataBound(SiteMapNodeItemEventArgs e) {
SiteMapNodeItemEventHandler onItemDataBoundHandler =
(SiteMapNodeItemEventHandler)Events[_eventItemDataBound];
if (onItemDataBoundHandler != null) {
onItemDataBoundHandler(this, e);
}
}
/// <devdoc>
/// </devdoc>
protected internal override void Render(HtmlTextWriter writer) {
// Copied from CompositeControl.cs
if (DesignMode) {
ChildControlsCreated = false;
EnsureChildControls();
}
base.Render(writer);
}
/// <devdoc>
/// Adds the SkipToContextText.
/// </devdoc>
protected internal override void RenderContents(HtmlTextWriter writer) {
ControlRenderingHelper.WriteSkipLinkStart(writer, RenderingCompatibility, DesignMode, SkipLinkText, SpacerImageUrl, ClientID);
base.RenderContents(writer);
ControlRenderingHelper.WriteSkipLinkEnd(writer, DesignMode, SkipLinkText, ClientID);
}
/// <internalonly/>
/// <devdoc>
/// <para>Stores the state of the System.Web.UI.WebControls.SiteMapPath.</para>
/// </devdoc>
protected override object SaveViewState() {
object[] myState = new object[5];
myState[0] = base.SaveViewState();
myState[1] = (_currentNodeStyle != null) ? ((IStateManager)_currentNodeStyle).SaveViewState() : null;
myState[2] = (_nodeStyle != null) ? ((IStateManager)_nodeStyle).SaveViewState() : null;
myState[3] = (_rootNodeStyle != null) ? ((IStateManager)_rootNodeStyle).SaveViewState() : null;
myState[4] = (_pathSeparatorStyle != null) ? ((IStateManager)_pathSeparatorStyle).SaveViewState() : null;
for (int i = 0; i < myState.Length; i++) {
if (myState[i] != null)
return myState;
}
return null;
}
/// <internalonly/>
/// <devdoc>
/// <para>Marks the starting point to begin tracking and saving changes to the
/// control as part of the control viewstate.</para>
/// </devdoc>
protected override void TrackViewState() {
base.TrackViewState();
if (_currentNodeStyle != null)
((IStateManager)_currentNodeStyle).TrackViewState();
if (_nodeStyle != null)
((IStateManager)_nodeStyle).TrackViewState();
if (_rootNodeStyle != null)
((IStateManager)_rootNodeStyle).TrackViewState();
if (_pathSeparatorStyle != null)
((IStateManager)_pathSeparatorStyle).TrackViewState();
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using Reporting.Rdl;
namespace Reporting.Rdl
{
/// <summary>
/// The Financial class holds a number of static functions relating to financial
/// calculations.
///
/// Note: many of the financial functions use the following function as their basis
/// pv*(1+rate)^nper+pmt*(1+rate*type)*((1+rate)^nper-1)/rate)+fv=0
/// if rate = 0
/// (pmt*nper)+pv+fv=0
/// </summary>
sealed internal class Financial
{
/// <summary>
/// Double declining balance depreciation (when factor = 2). Other factors may be specified.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <param name="period">The period for which you want to know the depreciation amount.</param>
/// <returns></returns>
static public double DDB(double cost, double salvage, int life, int period)
{
return DDB(cost, salvage, life, period, 2);
}
/// <summary>
/// Double declining balance depreciation (when factor = 2). Other factors may be specified.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <param name="period">The period for which you want to know the depreciation amount.</param>
/// <param name="factor">The rate at which the balance declines. Defaults to 2 (double declining) when omitted.</param>
/// <returns></returns>
static public double DDB(double cost, double salvage, int life, int period, double factor)
{
if (period > life || period < 1 || life < 1) // invalid arguments
return double.NaN;
double depreciation=0;
for (int i=1; i < period; i++)
{
depreciation += (cost - depreciation)*factor/life;
}
if (period == life)
return cost - salvage - depreciation; // for last year we force the depreciation so that cost - total depreciation = salvage
else
return (cost - depreciation)*factor/life;
}
/// <summary>
/// Returns the future value of an investment when using periodic, constant payments and
/// constant interest rate.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double FV(double rate, int periods, double pmt, double presentValue, bool endOfPeriod)
{
int type = endOfPeriod? 0: 1;
double fv;
if (rate == 0)
fv = -(pmt*periods+presentValue);
else
{
double temp = Math.Pow(1+rate, periods);
fv = -(presentValue*temp + pmt*(1+rate*type)*((temp -1)/rate));
}
return fv;
}
/// <summary>
/// Returns the interest payment portion of a payment given a particular period.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="period">Period for which you want the interest payment.</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Cash balance you want to attain after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double IPmt(double rate, int period, int periods, double presentValue, double futureValue, bool endOfPeriod)
{
// TODO -- routine needs more work. off when endOfPeriod is false; must be more direct way to solve
if (!endOfPeriod)
throw new Exception("IPmt doesn't support payments due at beginning of period.");
if (period < 0 || period > periods)
return double.NaN;
if (!endOfPeriod)
period--;
double pmt = -Pmt(rate, periods, presentValue, futureValue, endOfPeriod);
double prin = presentValue;
double interest=0;
for (int i=0; i < period; i++)
{
interest = rate*prin;
prin = prin - pmt + interest;
}
return -interest;
}
/// <summary>
/// Returns the number of periods for an investment.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Future value or cash balance you want after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double NPer(double rate, double pmt, double presentValue, double futureValue, bool endOfPeriod)
{
if (Math.Abs(pmt) < double.Epsilon)
return double.NaN;
int type = endOfPeriod? 0: 1;
double nper;
if (rate == 0)
nper = -(presentValue + futureValue)/pmt;
else
{
double r1 = 1 + rate*type;
double pmtr1 = pmt * r1 / rate;
double y = (pmtr1 - futureValue) / (presentValue + pmtr1);
nper = Math.Log(y) / Math.Log(1 + rate);
}
return nper;
}
/// <summary>
/// Returns the periodic payment for an annuity using constant payments and
/// constant interest rate.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Cash balance you want to attain after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double Pmt(double rate, int periods, double presentValue, double futureValue, bool endOfPeriod)
{
if (periods < 1)
return double.NaN;
int type = endOfPeriod? 0: 1;
double pmt;
if (rate == 0)
pmt = -(presentValue + futureValue)/periods;
else
{
double temp = Math.Pow(1+rate, periods);
pmt = -(presentValue*temp + futureValue) / ((1+rate*type)*(temp-1)/rate);
}
return pmt;
}
/// <summary>
/// Returns the present value of an investment. The present value is the total
/// amount that a series of future payments is worth now.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="futureValue">Cash balance you want to attain after last payment is made</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double PV(double rate, int periods, double pmt, double futureValue, bool endOfPeriod)
{
int type = endOfPeriod? 0: 1;
double pv;
if (rate == 0)
pv = -(pmt*periods+futureValue);
else
{
double temp = Math.Pow(1+rate, periods);
pv = -(pmt*(1+rate*type)*((temp-1)/rate) + futureValue)/temp;
}
return pv;
}
/// <summary>
/// Returns the interest rate per period for an annuity. This routine uses an
/// iterative approach to solving for rate. If after 30 iterations the answer
/// doesn't converge to within 0.0000001 then double.NAN is returned.
/// </summary>
/// <param name="periods">Total number of payment periods</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Cash balance you want to attain after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <param name="guess">Your guess as to what the interest rate will be.</param>
/// <returns></returns>
static public double Rate(int periods, double pmt, double presentValue, double futureValue, bool endOfPeriod, double guess)
{
// TODO: should be better algorithm: linear interpolation, Newton-Raphson approximation???
int type = endOfPeriod? 0: 1;
// Set the lower bound
double gLower= guess > .1? guess-.1: 0;
double power2=.1;
while (RateGuess(periods, pmt, presentValue, futureValue, type, gLower) > 0)
{
gLower -= power2;
power2 *= 2;
}
// Set the upper bound
double gUpper= guess+.1;
power2=.1;
while (RateGuess(periods, pmt, presentValue, futureValue, type, gUpper) < 0)
{
gUpper += power2;
power2 *= 2;
}
double z;
double incr;
double newguess;
for (int i= 0; i<30; i++)
{
z = RateGuess(periods,pmt,presentValue,futureValue, type, guess);
if (z > 0)
{
gUpper = guess;
incr = (guess - gLower)/2;
newguess = guess - incr;
}
else
{
gLower = guess;
incr = (gUpper - guess)/2;
newguess = guess + incr;
}
if (incr < 0.0000001) // Is the difference within our margin of error?
return guess;
guess = newguess;
}
return double.NaN; // we didn't converge
}
static private double RateGuess(int periods, double pmt, double pv, double fv, int type, double rate)
{
// When the guess is close the result should almost be 0
if (rate == 0)
return pmt*periods + pv + fv;
double temp = Math.Pow(1+rate, periods);
return pv*temp + pmt*(1 + rate*type)*((temp - 1)/rate) + fv;
}
/// <summary>
/// SLN returns the straight line depreciation for an asset for a single period.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <returns></returns>
static public double SLN(double cost, double salvage, double life)
{
if (life == 0)
return double.NaN;
return (cost - salvage) / life;
}
/// <summary>
/// Sum of years digits depreciation. An asset often loses more of its value early in its lifetime.
/// SYD has this behavior.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <param name="period">The period for which you want to know the depreciation amount.</param>
/// <returns></returns>
static public double SYD(double cost, double salvage, int life, int period)
{
int sumOfPeriods;
if (life % 2 == 0) // sum = n/2 * (n+1) when even
sumOfPeriods = life/2 * (life + 1);
else // sum = (n+1)/2 * n when odd
sumOfPeriods = (life+1)/2 * life;
return ((life + 1 - period) * (cost - salvage)) / sumOfPeriods;
}
}
}
| |
/*
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 Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Runtime.Serialization;
using System.Windows;
using System.Security;
using System.Diagnostics;
using System.Threading.Tasks;
namespace WPCordovaClassLib.Cordova.Commands
{
public class FileTransfer : BaseCommand
{
public class DownloadRequestState
{
// This class stores the State of the request.
public HttpWebRequest request;
public TransferOptions options;
public bool isCancelled;
public DownloadRequestState()
{
request = null;
options = null;
isCancelled = false;
}
}
public class TransferOptions
{
/// File path to upload OR File path to download to
public string FilePath { get; set; }
public string Url { get; set; }
/// Flag to recognize if we should trust every host (only in debug environments)
public bool TrustAllHosts { get; set; }
public string Id { get; set; }
public string Headers { get; set; }
public string CallbackId { get; set; }
public bool ChunkedMode { get; set; }
/// Server address
public string Server { get; set; }
/// File key
public string FileKey { get; set; }
/// File name on the server
public string FileName { get; set; }
/// File Mime type
public string MimeType { get; set; }
/// Additional options
public string Params { get; set; }
public string Method { get; set; }
public TransferOptions()
{
FileKey = "file";
FileName = "image.jpg";
MimeType = "image/jpeg";
}
}
/// <summary>
/// Boundary symbol
/// </summary>
private string Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
// Error codes
public const int FileNotFoundError = 1;
public const int InvalidUrlError = 2;
public const int ConnectionError = 3;
public const int AbortError = 4; // not really an error, but whatevs
private static Dictionary<string, DownloadRequestState> InProcDownloads = new Dictionary<string,DownloadRequestState>();
// Private instance of the main WebBrowser instance
// NOTE: Any access to this object needs to occur on the UI thread via the Dispatcher
private WebBrowser browser;
/// <summary>
/// Uploading response info
/// </summary>
[DataContract]
public class FileUploadResult
{
/// <summary>
/// Amount of sent bytes
/// </summary>
[DataMember(Name = "bytesSent")]
public long BytesSent { get; set; }
/// <summary>
/// Server response code
/// </summary>
[DataMember(Name = "responseCode")]
public long ResponseCode { get; set; }
/// <summary>
/// Server response
/// </summary>
[DataMember(Name = "response", EmitDefaultValue = false)]
public string Response { get; set; }
/// <summary>
/// Creates FileUploadResult object with response values
/// </summary>
/// <param name="bytesSent">Amount of sent bytes</param>
/// <param name="responseCode">Server response code</param>
/// <param name="response">Server response</param>
public FileUploadResult(long bytesSent, long responseCode, string response)
{
this.BytesSent = bytesSent;
this.ResponseCode = responseCode;
this.Response = response;
}
}
/// <summary>
/// Represents transfer error codes for callback
/// </summary>
[DataContract]
public class FileTransferError
{
/// <summary>
/// Error code
/// </summary>
[DataMember(Name = "code", IsRequired = true)]
public int Code { get; set; }
/// <summary>
/// The source URI
/// </summary>
[DataMember(Name = "source", IsRequired = true)]
public string Source { get; set; }
/// <summary>
/// The target URI
/// </summary>
///
[DataMember(Name = "target", IsRequired = true)]
public string Target { get; set; }
[DataMember(Name = "body", IsRequired = true)]
public string Body { get; set; }
/// <summary>
/// The http status code response from the remote URI
/// </summary>
[DataMember(Name = "http_status", IsRequired = true)]
public int HttpStatus { get; set; }
/// <summary>
/// Creates FileTransferError object
/// </summary>
/// <param name="errorCode">Error code</param>
public FileTransferError(int errorCode)
{
this.Code = errorCode;
this.Source = null;
this.Target = null;
this.HttpStatus = 0;
this.Body = "";
}
public FileTransferError(int errorCode, string source, string target, int status, string body = "")
{
this.Code = errorCode;
this.Source = source;
this.Target = target;
this.HttpStatus = status;
this.Body = body;
}
}
/// <summary>
/// Represents a singular progress event to be passed back to javascript
/// </summary>
[DataContract]
public class FileTransferProgress
{
/// <summary>
/// Is the length of the response known?
/// </summary>
[DataMember(Name = "lengthComputable", IsRequired = true)]
public bool LengthComputable { get; set; }
/// <summary>
/// amount of bytes loaded
/// </summary>
[DataMember(Name = "loaded", IsRequired = true)]
public long BytesLoaded { get; set; }
/// <summary>
/// Total bytes
/// </summary>
[DataMember(Name = "total", IsRequired = false)]
public long BytesTotal { get; set; }
public FileTransferProgress(long bTotal = 0, long bLoaded = 0)
{
LengthComputable = bTotal > 0;
BytesLoaded = bLoaded;
BytesTotal = bTotal;
}
}
/// <summary>
/// Helper method to copy all relevant cookies from the WebBrowser control into a header on
/// the HttpWebRequest
/// </summary>
/// <param name="browser">The source browser to copy the cookies from</param>
/// <param name="webRequest">The destination HttpWebRequest to add the cookie header to</param>
/// <returns>Nothing</returns>
private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest)
{
var tcs = new TaskCompletionSource<object>();
// Accessing WebBrowser needs to happen on the UI thread
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Get the WebBrowser control
if (this.browser == null)
{
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
if (frame != null)
{
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
if (page != null)
{
CordovaView cView = page.FindName("CordovaView") as CordovaView;
if (cView != null)
{
this.browser = cView.Browser;
}
}
}
}
try
{
// Only copy the cookies if the scheme and host match (to avoid any issues with secure/insecure cookies)
// NOTE: since the returned CookieCollection appears to munge the original cookie's domain value in favor of the actual Source domain,
// we can't know for sure whether the cookies would be applicable to any other hosts, so best to play it safe and skip for now.
if (this.browser != null && this.browser.Source.IsAbsoluteUri == true &&
this.browser.Source.Scheme == webRequest.RequestUri.Scheme && this.browser.Source.Host == webRequest.RequestUri.Host)
{
string cookieHeader = "";
string requestPath = webRequest.RequestUri.PathAndQuery;
CookieCollection cookies = this.browser.GetCookies();
// Iterate over the cookies and add to the header
foreach (Cookie cookie in cookies)
{
// Check that the path is allowed, first
// NOTE: Path always seems to be empty for now, even if the cookie has a path set by the server.
if (cookie.Path.Length == 0 || requestPath.IndexOf(cookie.Path, StringComparison.InvariantCultureIgnoreCase) == 0)
{
cookieHeader += cookie.Name + "=" + cookie.Value + "; ";
}
}
// Finally, set the header if we found any cookies
if (cookieHeader.Length > 0)
{
webRequest.Headers["Cookie"] = cookieHeader;
}
}
}
catch (Exception)
{
// Swallow the exception
}
// Complete the task
tcs.SetResult(Type.Missing);
});
await tcs.Task;
}
/// <summary>
/// Upload options
/// </summary>
//private TransferOptions uploadOptions;
/// <summary>
/// Bytes sent
/// </summary>
private long bytesSent;
/// <summary>
/// sends a file to a server
/// </summary>
/// <param name="options">Upload options</param>
/// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
public async void upload(string options)
{
options = options.Replace("{}", ""); // empty objects screw up the Deserializer
string callbackId = "";
TransferOptions uploadOptions = null;
HttpWebRequest webRequest = null;
try
{
try
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
uploadOptions = new TransferOptions();
uploadOptions.FilePath = args[0];
uploadOptions.Server = args[1];
uploadOptions.FileKey = args[2];
uploadOptions.FileName = args[3];
uploadOptions.MimeType = args[4];
uploadOptions.Params = args[5];
bool trustAll = false;
bool.TryParse(args[6],out trustAll);
uploadOptions.TrustAllHosts = trustAll;
bool doChunked = false;
bool.TryParse(args[7], out doChunked);
uploadOptions.ChunkedMode = doChunked;
//8 : Headers
//9 : id
//10: method
uploadOptions.Headers = args[8];
uploadOptions.Id = args[9];
uploadOptions.Method = args[10];
uploadOptions.CallbackId = callbackId = args[11];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
Uri serverUri;
try
{
serverUri = new Uri(uploadOptions.Server);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
return;
}
webRequest = (HttpWebRequest)WebRequest.Create(serverUri);
webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
webRequest.Method = uploadOptions.Method;
// Associate cookies with the request
// This is an async call, so we need to await it in order to preserve proper control flow
await CopyCookiesFromWebBrowser(webRequest);
if (!string.IsNullOrEmpty(uploadOptions.Headers))
{
Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers);
foreach (string key in headers.Keys)
{
webRequest.Headers[key] = headers[key];
}
}
DownloadRequestState reqState = new DownloadRequestState();
reqState.options = uploadOptions;
reqState.request = webRequest;
InProcDownloads[uploadOptions.Id] = reqState;
webRequest.BeginGetRequestStream(uploadCallback, reqState);
}
catch (Exception /*ex*/)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId);
}
}
// example : "{\"Authorization\":\"Basic Y29yZG92YV91c2VyOmNvcmRvdmFfcGFzc3dvcmQ=\"}"
protected Dictionary<string,string> parseHeaders(string jsonHeaders)
{
try
{
Dictionary<string, string> result = JSON.JsonHelper.Deserialize<Dictionary<string, string>>(jsonHeaders);
return result;
}
catch (Exception)
{
Debug.WriteLine("Failed to parseHeaders from string :: " + jsonHeaders);
}
return null;
}
public async void download(string options)
{
TransferOptions downloadOptions = null;
HttpWebRequest webRequest = null;
string callbackId;
try
{
// source, target, trustAllHosts, this._id, headers
string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);
downloadOptions = new TransferOptions();
downloadOptions.Url = optionStrings[0];
downloadOptions.FilePath = optionStrings[1];
bool trustAll = false;
bool.TryParse(optionStrings[2],out trustAll);
downloadOptions.TrustAllHosts = trustAll;
downloadOptions.Id = optionStrings[3];
downloadOptions.Headers = optionStrings[4];
downloadOptions.CallbackId = callbackId = optionStrings[5];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
try
{
// is the URL a local app file?
if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//","");
// pre-emptively create any directories in the FilePath that do not exist
string directoryName = getDirectoryName(downloadOptions.FilePath);
if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
{
isoFile.CreateDirectory(directoryName);
}
// just copy from one area of iso-store to another ...
if (isoFile.FileExists(downloadOptions.Url))
{
isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
}
else
{
// need to unpack resource from the dll
Uri uri = new Uri(cleanUrl, UriKind.Relative);
var resource = Application.GetResourceStream(uri);
if (resource != null)
{
// create the file destination
if (!isoFile.FileExists(downloadOptions.FilePath))
{
var destFile = isoFile.CreateFile(downloadOptions.FilePath);
destFile.Close();
}
using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
{
long totalBytes = resource.Stream.Length;
int bytesRead = 0;
using (BinaryReader reader = new BinaryReader(resource.Stream))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
int BUFFER_SIZE = 1024;
byte[] buffer;
while (true)
{
buffer = reader.ReadBytes(BUFFER_SIZE);
// fire a progress event ?
bytesRead += buffer.Length;
if (buffer.Length > 0)
{
writer.Write(buffer);
DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
}
else
{
writer.Close();
reader.Close();
fileStream.Close();
break;
}
}
}
}
}
}
}
}
File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
}
return;
}
else
{
// otherwise it is web-bound, we will actually download it
//Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
}
}
catch (Exception /*ex*/)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
return;
}
if (downloadOptions != null && webRequest != null)
{
DownloadRequestState state = new DownloadRequestState();
state.options = downloadOptions;
state.request = webRequest;
InProcDownloads[downloadOptions.Id] = state;
// Associate cookies with the request
// This is an async call, so we need to await it in order to preserve proper control flow
await CopyCookiesFromWebBrowser(webRequest);
if (!string.IsNullOrEmpty(downloadOptions.Headers))
{
Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
foreach (string key in headers.Keys)
{
webRequest.Headers[key] = headers[key];
}
}
try
{
webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
}
catch (WebException)
{
// eat it
}
// dispatch an event for progress ( 0 )
lock (state)
{
if (!state.isCancelled)
{
var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
plugRes.KeepCallback = true;
plugRes.CallbackId = callbackId;
DispatchCommandResult(plugRes, callbackId);
}
}
}
}
public void abort(string options)
{
Debug.WriteLine("Abort :: " + options);
string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string id = optionStrings[0];
string callbackId = optionStrings[1];
if (id != null && InProcDownloads.ContainsKey(id))
{
DownloadRequestState state = InProcDownloads[id];
if (!state.isCancelled)
{ // prevent multiple callbacks for the same abort
state.isCancelled = true;
if (!state.request.HaveResponse)
{
state.request.Abort();
InProcDownloads.Remove(id);
//callbackId = state.options.CallbackId;
//state = null;
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(FileTransfer.AbortError)),
state.options.CallbackId);
}
}
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception?
}
}
private void DispatchFileTransferProgress(long bytesLoaded, long bytesTotal, string callbackId, bool keepCallback = true)
{
Debug.WriteLine("DispatchFileTransferProgress : " + callbackId);
// send a progress change event
FileTransferProgress progEvent = new FileTransferProgress(bytesTotal);
progEvent.BytesLoaded = bytesLoaded;
PluginResult plugRes = new PluginResult(PluginResult.Status.OK, progEvent);
plugRes.KeepCallback = keepCallback;
plugRes.CallbackId = callbackId;
DispatchCommandResult(plugRes, callbackId);
}
/// <summary>
///
/// </summary>
/// <param name="asynchronousResult"></param>
private void downloadCallback(IAsyncResult asynchronousResult)
{
DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
HttpWebRequest request = reqState.request;
string callbackId = reqState.options.CallbackId;
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
// send a progress change event
DispatchFileTransferProgress(0, response.ContentLength, callbackId);
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
// create any directories in the path that do not exist
string directoryName = getDirectoryName(reqState.options.FilePath);
if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
{
isoFile.CreateDirectory(directoryName);
}
// create the file if not exists
if (!isoFile.FileExists(reqState.options.FilePath))
{
var file = isoFile.CreateFile(reqState.options.FilePath);
file.Close();
}
using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile))
{
long totalBytes = response.ContentLength;
int bytesRead = 0;
using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
int BUFFER_SIZE = 1024;
byte[] buffer;
while (true)
{
buffer = reader.ReadBytes(BUFFER_SIZE);
// fire a progress event ?
bytesRead += buffer.Length;
if (buffer.Length > 0 && !reqState.isCancelled)
{
writer.Write(buffer);
DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
}
else
{
writer.Close();
reader.Close();
fileStream.Close();
break;
}
System.Threading.Thread.Sleep(1);
}
}
}
}
if (reqState.isCancelled)
{
isoFile.DeleteFile(reqState.options.FilePath);
}
}
if (reqState.isCancelled)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)),
callbackId);
}
else
{
File.FileEntry entry = new File.FileEntry(reqState.options.FilePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
}
}
catch (IsolatedStorageException)
{
// Trying to write the file somewhere within the IsoStorage.
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
callbackId);
}
catch (SecurityException)
{
// Trying to write the file somewhere not allowed.
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
callbackId);
}
catch (WebException webex)
{
// TODO: probably need better work here to properly respond with all http status codes back to JS
// Right now am jumping through hoops just to detect 404.
HttpWebResponse response = (HttpWebResponse)webex.Response;
if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound)
|| webex.Status == WebExceptionStatus.UnknownError)
{
// Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!!
// "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
// FACEPALM
// Or just cast it to an int, whiner ... -jm
int statusCode = (int)response.StatusCode;
string body = "";
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(streamResponse))
{
body = streamReader.ReadToEnd();
}
}
FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError),
callbackId);
}
else
{
lock (reqState)
{
if (!reqState.isCancelled)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(ConnectionError)),
callbackId);
}
else
{
Debug.WriteLine("It happened");
}
}
}
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(FileNotFoundError)),
callbackId);
}
//System.Threading.Thread.Sleep(1000);
if (InProcDownloads.ContainsKey(reqState.options.Id))
{
InProcDownloads.Remove(reqState.options.Id);
}
}
/// <summary>
/// Read file from Isolated Storage and sends it to server
/// </summary>
/// <param name="asynchronousResult"></param>
private void uploadCallback(IAsyncResult asynchronousResult)
{
DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
HttpWebRequest webRequest = reqState.request;
string callbackId = reqState.options.CallbackId;
try
{
using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult)))
{
string lineStart = "--";
string lineEnd = Environment.NewLine;
byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd);
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd;
if (!string.IsNullOrEmpty(reqState.options.Params))
{
Dictionary<string, string> paramMap = parseHeaders(reqState.options.Params);
foreach (string key in paramMap.Keys)
{
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
string formItem = string.Format(formdataTemplate, key, paramMap[key]);
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
requestStream.Write(formItemBytes, 0, formItemBytes.Length);
}
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(reqState.options.FilePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0)));
return;
}
byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd);
long totalBytesToSend = 0;
using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile))
{
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd;
string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType);
byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);
byte[] buffer = new byte[4096];
int bytesRead = 0;
//sent bytes needs to be reseted before new upload
bytesSent = 0;
totalBytesToSend = fileStream.Length;
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(headerBytes, 0, headerBytes.Length);
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
if (!reqState.isCancelled)
{
requestStream.Write(buffer, 0, bytesRead);
bytesSent += bytesRead;
DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId);
System.Threading.Thread.Sleep(1);
}
else
{
throw new Exception("UploadCancelledException");
}
}
}
requestStream.Write(endRequest, 0, endRequest.Length);
}
}
// webRequest
webRequest.BeginGetResponse(ReadCallback, reqState);
}
catch (Exception /*ex*/)
{
if (!reqState.isCancelled)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
}
}
}
/// <summary>
/// Reads response into FileUploadResult
/// </summary>
/// <param name="asynchronousResult"></param>
private void ReadCallback(IAsyncResult asynchronousResult)
{
DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
try
{
HttpWebRequest webRequest = reqState.request;
string callbackId = reqState.options.CallbackId;
if (InProcDownloads.ContainsKey(reqState.options.Id))
{
InProcDownloads.Remove(reqState.options.Id);
}
using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
{
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(streamResponse))
{
string responseString = streamReader.ReadToEnd();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileUploadResult(bytesSent, (long)response.StatusCode, responseString)));
});
}
}
}
}
catch (WebException webex)
{
// TODO: probably need better work here to properly respond with all http status codes back to JS
// Right now am jumping through hoops just to detect 404.
if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound)
|| webex.Status == WebExceptionStatus.UnknownError)
{
int statusCode = (int)((HttpWebResponse)webex.Response).StatusCode;
FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), reqState.options.CallbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(ConnectionError)),
reqState.options.CallbackId);
}
}
catch (Exception /*ex*/)
{
FileTransferError transferError = new FileTransferError(ConnectionError, reqState.options.Server, reqState.options.FilePath, 403);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, transferError), reqState.options.CallbackId);
}
}
// Gets the full path without the filename
private string getDirectoryName(String filePath)
{
string directoryName;
try
{
directoryName = filePath.Substring(0, filePath.LastIndexOf('/'));
}
catch
{
directoryName = "";
}
return directoryName;
}
}
}
| |
// 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 Internal.NativeCrypto;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography
{
public sealed class CspKeyContainerInfo
{
private readonly CspParameters _parameters;
private readonly bool _randomKeyContainer;
//Public Constructor will call internal constructor.
public CspKeyContainerInfo(CspParameters parameters)
: this(parameters, false)
{
}
/// <summary>
///Internal constructor for creating the CspKeyContainerInfo object
/// </summary>
/// <param name="parameters">CSP parameters</param>
/// <param name="randomKeyContainer">Is it random container</param>
internal CspKeyContainerInfo(CspParameters parameters, bool randomKeyContainer)
{
_parameters = new CspParameters(parameters);
if (_parameters.KeyNumber == -1)
{
if (_parameters.ProviderType == (int)CapiHelper.ProviderType.PROV_RSA_FULL ||
_parameters.ProviderType == (int)CapiHelper.ProviderType.PROV_RSA_AES)
{
_parameters.KeyNumber = (int)KeyNumber.Exchange;
}
else if (_parameters.ProviderType == (int)CapiHelper.ProviderType.PROV_DSS_DH)
{
_parameters.KeyNumber = (int)KeyNumber.Signature;
}
}
_randomKeyContainer = randomKeyContainer;
}
/// <summary>
/// Check the key is accessible
/// </summary>
public bool Accessible
{
get
{
object retVal = ReadKeyParameterSilent(Constants.CLR_ACCESSIBLE, throwOnNotFound: false);
if (retVal == null)
{
// The key wasn't found, so consider it to be not accessible.
return false;
}
return (bool)retVal;
}
}
/// <summary>
/// Check the key is exportable
/// </summary>
public bool Exportable
{
get
{
// Assume hardware keys are not exportable.
if (HardwareDevice)
{
return false;
}
return (bool)ReadKeyParameterSilent(Constants.CLR_EXPORTABLE);
}
}
/// <summary>
/// Check if device with key is HW device
/// </summary>
public bool HardwareDevice
{
get
{
return (bool)ReadDeviceParameterVerifyContext(Constants.CLR_HARDWARE);
}
}
/// <summary>
/// Get Key container Name
/// </summary>
public string KeyContainerName
{
get
{
return _parameters.KeyContainerName;
}
}
/// <summary>
/// Get the key number
/// </summary>
public KeyNumber KeyNumber
{
get
{
return (KeyNumber)_parameters.KeyNumber;
}
}
/// <summary>
/// Check if machine key store is in flag or not
/// </summary>
public bool MachineKeyStore
{
get
{
return CapiHelper.IsFlagBitSet((uint)_parameters.Flags, (uint)CspProviderFlags.UseMachineKeyStore);
}
}
/// <summary>
/// Check if key is protected
/// </summary>
public bool Protected
{
get
{
// Assume hardware keys are protected.
if (HardwareDevice)
{
return true;
}
return (bool)ReadKeyParameterSilent(Constants.CLR_PROTECTED);
}
}
/// <summary>
/// Gets the provider name
/// </summary>
public string ProviderName
{
get
{
return _parameters.ProviderName;
}
}
/// <summary>
/// Gets the provider type
/// </summary>
public int ProviderType
{
get
{
return _parameters.ProviderType;
}
}
/// <summary>
/// Check if key container is randomly generated
/// </summary>
public bool RandomlyGenerated
{
get
{
return _randomKeyContainer;
}
}
/// <summary>
/// Check if container is removable
/// </summary>
public bool Removable
{
get
{
return (bool)ReadDeviceParameterVerifyContext(Constants.CLR_REMOVABLE);
}
}
/// <summary>
/// Get the container name
/// </summary>
public string UniqueKeyContainerName
{
get
{
return (string)ReadKeyParameterSilent(Constants.CLR_UNIQUE_CONTAINER);
}
}
/// <summary>
/// Read a parameter from the current key using CRYPT_SILENT, to avoid any potential UI prompts.
/// </summary>
private object ReadKeyParameterSilent(int keyParam, bool throwOnNotFound = true)
{
const uint SilentFlags = (uint)Interop.Advapi32.CryptAcquireContextFlags.CRYPT_SILENT;
SafeProvHandle safeProvHandle;
int hr = CapiHelper.OpenCSP(_parameters, SilentFlags, out safeProvHandle);
using (safeProvHandle)
{
if (hr != CapiHelper.S_OK)
{
if (throwOnNotFound)
{
throw new CryptographicException(SR.Format(SR.Cryptography_CSP_NotFound, "Error"));
}
return null;
}
object retVal = CapiHelper.GetProviderParameter(safeProvHandle, _parameters.KeyNumber, keyParam);
return retVal;
}
}
/// <summary>
/// Read a parameter using VERIFY_CONTEXT to read from the device being targeted by _parameters
/// </summary>
private object ReadDeviceParameterVerifyContext(int keyParam)
{
CspParameters parameters = new CspParameters(_parameters);
// We're asking questions of the device container, the only flag that makes sense is Machine vs User.
parameters.Flags &= CspProviderFlags.UseMachineKeyStore;
// In order to ask about the device, instead of a key, we need to ensure that no key is named.
parameters.KeyContainerName = null;
const uint OpenDeviceFlags = (uint)Interop.Advapi32.CryptAcquireContextFlags.CRYPT_VERIFYCONTEXT;
SafeProvHandle safeProvHandle;
int hr = CapiHelper.OpenCSP(parameters, OpenDeviceFlags, out safeProvHandle);
using (safeProvHandle)
{
if (hr != CapiHelper.S_OK)
{
throw new CryptographicException(SR.Format(SR.Cryptography_CSP_NotFound, "Error"));
}
object retVal = CapiHelper.GetProviderParameter(safeProvHandle, parameters.KeyNumber, keyParam);
return retVal;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using Keen.Core;
using Keen.Query;
using Moq;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace Keen.Test
{
[TestFixture]
public class QueryTest : TestBase
{
private const string testCol = "QueryTestCol";
public QueryTest()
{
UseMocks = true;
}
[OneTimeSetUp]
public override void Setup()
{
base.Setup();
// If not using mocks, set up conditions on the server
if (!UseMocks)
{
var client = new KeenClient(SettingsEnv);
//client.DeleteCollection(testCol);
client.AddEvent(testCol, new { field1 = "99999999" });
}
}
[Test]
public void ReadKeyOnly_Success()
{
var settings = new ProjectSettingsProvider(SettingsEnv.ProjectId, readKey: SettingsEnv.ReadKey);
var client = new KeenClient(settings);
if (!UseMocks)
{
// Server is required for this test
// Also, test depends on existance of collection "AddEventTest"
Assert.DoesNotThrow(() => client.Query(QueryType.Count(), "AddEventTest", "", QueryRelativeTimeframe.ThisHour()));
}
}
[Test]
public async Task AvailableQueries_Success()
{
var client = new KeenClient(SettingsEnv);
Mock<IQueries> queryMock = null;
if (UseMocks)
{
// A few values that should be present and are unlikely to change
IEnumerable<KeyValuePair<string, string>> testResult = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("minimum", "url" ),
new KeyValuePair<string, string>("average", "url" ),
new KeyValuePair<string, string>("maximum", "url" ),
new KeyValuePair<string, string>("count_url", "url" ),
};
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.AvailableQueries())
.Returns(Task.FromResult(testResult));
client.Queries = queryMock.Object;
}
var response = await client.GetQueriesAsync();
Assert.True(response.Any(p => p.Key == "minimum"));
Assert.True(response.Any(p => p.Key == "average"));
Assert.True(response.Any(p => p.Key == "maximum"));
Assert.True(response.Any(p => p.Key == "count_url"));
if (null != queryMock)
queryMock.Verify(m => m.AvailableQueries());
}
[Test]
public void Query_InvalidCollection_Throws()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.PreviousHour();
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == null),
It.Is<string>(p => p == ""),
It.Is<QueryRelativeTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(z => z == "")
))
.Throws(new ArgumentNullException());
client.Queries = queryMock.Object;
}
Assert.ThrowsAsync<ArgumentNullException>(() => client.QueryAsync(QueryType.Count(), null, "", timeframe, null));
}
[Test]
public async Task Query_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == ""),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(z => z == "")))
.Returns(Task.FromResult("0"));
client.Queries = queryMock.Object;
}
var count = await client.QueryAsync(QueryType.Count(), testCol, "", timeframe, null);
Assert.IsNotNull(count, "expected valid count");
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Query_ValidRelativeGroup_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.PreviousNDays(2);
var groupby = "field1";
IEnumerable<QueryGroupValue<string>> reply = new List<QueryGroupValue<string>>()
{
new QueryGroupValue<string>( "0", "field1" ),
new QueryGroupValue<string>( "0", "field1" ),
};
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == ""),
It.Is<string>(g => g == groupby),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(z => z == "")))
.Returns(Task.FromResult(reply));
client.Queries = queryMock.Object;
}
var count = (await client.QueryGroupAsync(QueryType.Count(), testCol, "", groupby, timeframe)).ToList();
Assert.IsNotNull(count);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Query_ValidRelativeGroupInterval_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.PreviousNDays(2);
var interval = QueryInterval.EveryNHours(2);
var groupby = "field1";
IEnumerable<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>> reply = new List<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>>()
{
new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
new List<QueryGroupValue<string>>()
{
new QueryGroupValue<string>( "1", "field1" ),
new QueryGroupValue<string>( "1", "field1" ),
},
DateTime.Now, DateTime.Now.AddSeconds(2)
),
new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
new List<QueryGroupValue<string>>()
{
new QueryGroupValue<string>( "2", "field1" ),
new QueryGroupValue<string>( "2", "field1" ),
},
DateTime.Now, DateTime.Now.AddSeconds(2)
),
};
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == ""),
It.Is<string>(g => g == groupby),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(z => z == "")))
.Returns(Task.FromResult(reply));
client.Queries = queryMock.Object;
}
var count = (await client.QueryIntervalGroupAsync(QueryType.Count(), testCol, "", groupby, timeframe, interval)).ToList();
Assert.IsNotNull(count);
if (null != queryMock)
{
queryMock.VerifyAll();
}
}
[Test]
public async Task Query_ValidAbsoluteInterval_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var interval = QueryInterval.EveryNMinutes(5);
IEnumerable<QueryIntervalValue<string>> result =
new List<QueryIntervalValue<string>>() { new QueryIntervalValue<string>("0", timeframe.Start, timeframe.End) };
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == ""),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.IsAny<IEnumerable<QueryFilter>>(),
It.Is<string>(z => z == "")))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var counts = (await client.QueryIntervalAsync(QueryType.Count(), testCol, "", timeframe, interval)).ToList();
Assert.IsNotNull(counts);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Query_ValidRelative_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.ThisMinute();
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == ""),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(z => z == "")))
.Returns(Task.FromResult("0"));
client.Queries = queryMock.Object;
}
var count = await client.QueryAsync(QueryType.Count(), testCol, "", timeframe, null);
Assert.IsNotNull(count);
if (null != queryMock)
{
queryMock.VerifyAll();
}
}
[Test]
public async Task Query_ValidRelativeInterval_Success()
{
var client = new KeenClient(SettingsEnv);
var interval = QueryInterval.EveryNMinutes(5);
var timeframe = QueryRelativeTimeframe.ThisMinute();
IEnumerable<QueryIntervalValue<string>> result =
new List<QueryIntervalValue<string>>() { new QueryIntervalValue<string>("0", DateTime.Now.AddMinutes(-5), DateTime.Now) };
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == ""),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(z => z == "")))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var counts = (await client.QueryIntervalAsync(QueryType.Count(), testCol, "", timeframe, interval)).ToList();
Assert.IsNotNull(counts);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Query_ValidFilter_Success()
{
var client = new KeenClient(SettingsEnv);
var filters = new List<QueryFilter>() { new QueryFilter("field1", QueryFilter.FilterOperator.GreaterThan(), "1") };
var timeframe = QueryRelativeTimeframe.ThisHour();
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Count()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == ""),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == filters),
It.Is<string>(z => z == "")))
.Returns(Task.FromResult("1"));
client.Queries = queryMock.Object;
}
var count = await client.QueryAsync(QueryType.Count(), testCol, "", timeframe, filters);
Assert.IsNotNull(count);
if (null != queryMock)
{
queryMock.VerifyAll();
}
}
[Test]
public async Task CountUnique_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var prop = "field1";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.CountUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult("0"));
client.Queries = queryMock.Object;
}
var count = await client.QueryAsync(QueryType.CountUnique(), testCol, prop, timeframe);
Assert.IsNotNull(count);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Minimum_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var prop = "field1";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Minimum()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult("0"));
client.Queries = queryMock.Object;
}
var count = await client.QueryAsync(QueryType.Minimum(), testCol, prop, timeframe);
Assert.IsNotNull(count);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Maximum_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var prop = "field1";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Maximum()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult("0"));
client.Queries = queryMock.Object;
}
var count = await client.QueryAsync(QueryType.Maximum(), testCol, prop, timeframe);
Assert.IsNotNull(count);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Average_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var prop = "field1";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Average()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult("0.0"));
client.Queries = queryMock.Object;
}
await client.QueryAsync(QueryType.Average(), testCol, prop, timeframe);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task Sum_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var prop = "field1";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.Sum()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult("0.0"));
client.Queries = queryMock.Object;
}
await client.QueryAsync(QueryType.Sum(), testCol, prop, timeframe);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task SelectUnique_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var prop = "field1";
var result = "hello,goodbye,I'm late";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.SelectUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = await client.QueryAsync(QueryType.SelectUnique(), testCol, prop, timeframe);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task SelectUnique_ValidRelative_Success()
{
var client = new KeenClient(SettingsEnv);
var prop = "field1";
var timeframe = QueryRelativeTimeframe.ThisMinute();
var result = "hello,goodbye,I'm late";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.SelectUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryRelativeTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
await client.QueryAsync(QueryType.SelectUnique(), testCol, prop, timeframe);
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task SelectUnique_ValidRelativeGroup_Success()
{
var client = new KeenClient(SettingsEnv);
var prop = "field1";
var groupby = "field1";
var timeframe = QueryRelativeTimeframe.PreviousNDays(5);
IEnumerable<QueryGroupValue<string>> reply = new List<QueryGroupValue<string>>()
{
new QueryGroupValue<string>( "hello,goodbye,I'm late", "field1" ),
new QueryGroupValue<string>( "hello,goodbye,I'm late", "field1" ),
};
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.SelectUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<string>(g => g == groupby),
It.Is<QueryRelativeTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(reply));
client.Queries = queryMock.Object;
}
(await client.QueryGroupAsync(QueryType.SelectUnique(), testCol, prop, groupby, timeframe, null)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task SelectUnique_ValidFilter_Success()
{
var client = new KeenClient(SettingsEnv);
var prop = "field1";
var timeframe = QueryRelativeTimeframe.ThisHour();
var filters = new List<QueryFilter>() { new QueryFilter("field1", QueryFilter.FilterOperator.GreaterThan(), "1") };
var result = "hello,goodbye,I'm late";
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.SelectUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryRelativeTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == filters),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryAsync(QueryType.SelectUnique(), testCol, prop, timeframe, filters)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task SelectUnique_ValidAbsoluteInterval_Success()
{
var client = new KeenClient(SettingsEnv);
var prop = "field1";
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var interval = QueryInterval.EveryNMinutes(5);
var resultl = "hello,goodbye,I'm late";
IEnumerable<QueryIntervalValue<string>> result =
new List<QueryIntervalValue<string>>() { new QueryIntervalValue<string>(resultl, timeframe.Start, timeframe.End) };
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.SelectUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var counts = (await client.QueryIntervalAsync(QueryType.SelectUnique(), testCol, prop, timeframe, interval)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task SelectUnique_ValidAbsoluteIntervalGroup_Success()
{
var client = new KeenClient(SettingsEnv);
var prop = "field1";
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
var interval = QueryInterval.EveryNHours(4);
var groupby = "field1";
var resultl = "hello,goodbye,I'm late";
IEnumerable<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>> result =
new List<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>>()
{
new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
new List<QueryGroupValue<string>>(){
new QueryGroupValue<string>(resultl, "abc"),
new QueryGroupValue<string>(resultl, "def")
},
timeframe.Start, timeframe.End
),
new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
new List<QueryGroupValue<string>>(){
new QueryGroupValue<string>(resultl, "abc"),
new QueryGroupValue<string>(resultl, "def")
},
timeframe.Start, timeframe.End
),
};
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.SelectUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<string>(g => g == groupby),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var counts = (await client.QueryIntervalGroupAsync(QueryType.SelectUnique(), testCol, prop, groupby, timeframe, interval)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task SelectUnique_ValidRelativeInterval_Success()
{
var client = new KeenClient(SettingsEnv);
var prop = "field1";
var interval = QueryInterval.EveryNMinutes(5);
var timeframe = QueryRelativeTimeframe.ThisMinute();
var resultl = "hello,goodbye,I'm late";
IEnumerable<QueryIntervalValue<string>> result =
new List<QueryIntervalValue<string>>() { new QueryIntervalValue<string>(resultl, DateTime.Now.AddMinutes(-5), DateTime.Now) };
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Metric(
It.Is<QueryType>(q => q == QueryType.SelectUnique()),
It.Is<string>(c => c == testCol),
It.Is<string>(p => p == prop),
It.Is<QueryRelativeTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryIntervalAsync(QueryType.SelectUnique(), testCol, prop, timeframe, interval)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task ExtractResource_ValidAbsolute_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
dynamic eo = new ExpandoObject();
eo.field1 = "8888";
IEnumerable<dynamic> result = new List<dynamic>() { eo, eo };
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Extract(
It.Is<string>(c => c == testCol),
It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<int>(l => l == 0),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryExtractResourceAsync(testCol, timeframe)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task ExtractResource_ValidRelative_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.ThisMinute();
dynamic eo = new ExpandoObject();
eo.field1 = "8888";
IEnumerable<dynamic> result = new List<dynamic>() { eo, eo };
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Extract(
It.Is<string>(c => c == testCol),
It.Is<QueryRelativeTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<int>(l => l == 0),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryExtractResourceAsync(testCol, timeframe)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task ExtractResource_ValidFilter_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.ThisHour();
var filters = new List<QueryFilter>() { new QueryFilter("field1", QueryFilter.FilterOperator.GreaterThan(), "1") };
dynamic eo = new ExpandoObject();
eo.field1 = "8888";
IEnumerable<dynamic> result = new List<dynamic>() { eo, eo };
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.Extract(
It.Is<string>(c => c == testCol),
It.Is<QueryRelativeTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == filters),
It.Is<int>(l => l == 0),
It.Is<string>(t => t == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryExtractResourceAsync(testCol, timeframe, filters)).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task MultiAnalysis_Valid_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.ThisHour();
IEnumerable<MultiAnalysisParam> param = new List<MultiAnalysisParam>()
{
new MultiAnalysisParam("first", MultiAnalysisParam.Metric.Count()),
new MultiAnalysisParam("second", MultiAnalysisParam.Metric.Maximum("field1")),
new MultiAnalysisParam("third", MultiAnalysisParam.Metric.Minimum("field1")),
};
IDictionary<string, string> result = new Dictionary<string, string>();
result.Add("second", "fff");
result.Add("third", "aaa");
result.Add("first", "123");
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.MultiAnalysis(
It.Is<string>(c => c == testCol),
It.Is<IEnumerable<MultiAnalysisParam>>(p => p == param),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(tz => tz == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = await client.QueryMultiAnalysisAsync(testCol, param, timeframe, null, "");
if (null != queryMock)
{
Assert.AreEqual(reply.Count(), result.Count());
queryMock.VerifyAll();
}
}
[Test]
public async Task MultiAnalysis_ValidRelativeTimeFrame_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.PreviousNDays(2);
IEnumerable<MultiAnalysisParam> param = new List<MultiAnalysisParam>()
{
new MultiAnalysisParam("first", MultiAnalysisParam.Metric.Count()),
new MultiAnalysisParam("second", MultiAnalysisParam.Metric.Maximum("field1")),
new MultiAnalysisParam("third", MultiAnalysisParam.Metric.Minimum("field1")),
};
IDictionary<string, string> result = new Dictionary<string, string>();
result.Add("second", "fff");
result.Add("third", "aaa");
result.Add("first", "123");
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.MultiAnalysis(
It.Is<string>(c => c == testCol),
It.Is<IEnumerable<MultiAnalysisParam>>(p => p == param),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(tz => tz == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = await client.QueryMultiAnalysisAsync(testCol, param, timeframe, null, "");
if (null != queryMock)
{
Assert.AreEqual(reply.Count(), result.Count());
queryMock.VerifyAll();
}
}
[Test]
public async Task MultiAnalysis_ValidGroupBy_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.ThisHour();
var groupby = "field1";
IEnumerable<MultiAnalysisParam> param = new List<MultiAnalysisParam>()
{
new MultiAnalysisParam("first", MultiAnalysisParam.Metric.Count()),
new MultiAnalysisParam("second", MultiAnalysisParam.Metric.Maximum("field1")),
new MultiAnalysisParam("third", MultiAnalysisParam.Metric.Minimum("field1")),
};
var dict = new Dictionary<string, string>();
dict.Add("second", "fff");
dict.Add("third", "aaa");
dict.Add("first", "123");
dict.Add(groupby, "123");
IEnumerable<QueryGroupValue<IDictionary<string, string>>> result = new List<QueryGroupValue<IDictionary<string, string>>>()
{
new QueryGroupValue<IDictionary<string,string>>(dict, groupby),
new QueryGroupValue<IDictionary<string,string>>(dict, groupby),
};
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.MultiAnalysis(
It.Is<string>(c => c == testCol),
It.Is<IEnumerable<MultiAnalysisParam>>(p => p == param),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(g => g == groupby),
It.Is<string>(tz => tz == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryMultiAnalysisGroupAsync(testCol, param, timeframe, null, groupby, "")).ToList();
if (null != queryMock)
{
Assert.AreEqual(reply.Count(), result.Count());
queryMock.VerifyAll();
}
}
[Test]
public async Task MultiAnalysis_ValidIntervalGroupBy_Success()
{
var client = new KeenClient(SettingsEnv);
var timeframe = QueryRelativeTimeframe.PreviousNDays(3);
var interval = QueryInterval.Daily();
var groupby = "field1";
IEnumerable<MultiAnalysisParam> param = new List<MultiAnalysisParam>()
{
new MultiAnalysisParam("first", MultiAnalysisParam.Metric.Count()),
new MultiAnalysisParam("second", MultiAnalysisParam.Metric.Maximum("field1")),
new MultiAnalysisParam("third", MultiAnalysisParam.Metric.Minimum("field1")),
};
var dict = new Dictionary<string, string>();
dict.Add("second", "fff");
dict.Add("third", "aaa");
dict.Add("first", "123");
dict.Add(groupby, "123");
IEnumerable<QueryIntervalValue<IEnumerable<QueryGroupValue<IDictionary<string, string>>>>> result =
new List<QueryIntervalValue<IEnumerable<QueryGroupValue<IDictionary<string, string>>>>>()
{
new QueryIntervalValue<IEnumerable<QueryGroupValue<IDictionary<string, string>>>>(
new List<QueryGroupValue<IDictionary<string,string>>>(){
new QueryGroupValue<IDictionary<string,string>>(dict, groupby),
new QueryGroupValue<IDictionary<string,string>>(dict, groupby)
},
DateTime.Now, DateTime.Now.AddSeconds(2)
),
new QueryIntervalValue<IEnumerable<QueryGroupValue<IDictionary<string, string>>>>(
new List<QueryGroupValue<IDictionary<string,string>>>(){
new QueryGroupValue<IDictionary<string,string>>(dict, groupby),
new QueryGroupValue<IDictionary<string,string>>(dict, groupby)
},
DateTime.Now, DateTime.Now.AddSeconds(2)
),
};
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.MultiAnalysis(
It.Is<string>(c => c == testCol),
It.Is<IEnumerable<MultiAnalysisParam>>(p => p == param),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(g => g == groupby),
It.Is<string>(tz => tz == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryMultiAnalysisIntervalGroupAsync(testCol, param, timeframe, interval, null, groupby, "")).ToList();
if (null != queryMock)
queryMock.VerifyAll();
}
[Test]
public async Task MultiAnalysis_ValidInterval_Success()
{
var client = new KeenClient(SettingsEnv);
IEnumerable<MultiAnalysisParam> param = new List<MultiAnalysisParam>()
{
new MultiAnalysisParam("first", MultiAnalysisParam.Metric.Count()),
new MultiAnalysisParam("second", MultiAnalysisParam.Metric.Maximum("field1")),
new MultiAnalysisParam("third", MultiAnalysisParam.Metric.Minimum("field1")),
};
var timeframe = QueryRelativeTimeframe.PreviousNDays(3);
var interval = QueryInterval.Daily();
IEnumerable<QueryIntervalValue<IDictionary<string, string>>> result = new List<QueryIntervalValue<IDictionary<string, string>>>();
foreach (var i in Enumerable.Range(1, 3))
{
var dic = new Dictionary<string, string>();
dic.Add("second", "fff");
dic.Add("third", "aaa");
dic.Add("first", "123");
var qv = new QueryIntervalValue<IDictionary<string, string>>(dic, DateTime.Now, DateTime.Now.AddSeconds(2));
((List<QueryIntervalValue<IDictionary<string, string>>>)result).Add(qv);
}
Mock<IQueries> queryMock = null;
if (UseMocks)
{
queryMock = new Mock<IQueries>();
queryMock.Setup(m => m.MultiAnalysis(
It.Is<string>(c => c == testCol),
It.Is<IEnumerable<MultiAnalysisParam>>(p => p == param),
It.Is<IQueryTimeframe>(t => t == timeframe),
It.Is<QueryInterval>(i => i == interval),
It.Is<IEnumerable<QueryFilter>>(f => f == null),
It.Is<string>(tz => tz == "")
))
.Returns(Task.FromResult(result));
client.Queries = queryMock.Object;
}
var reply = (await client.QueryMultiAnalysisIntervalAsync(testCol, param, timeframe, interval)).ToList();
if (null != queryMock)
{
queryMock.VerifyAll();
Assert.AreEqual(reply.Count(), result.Count());
}
}
}
[TestFixture]
public class QueryFilterTest
{
[Test]
public void Constructor_InvalidProperty_Throws()
{
Assert.Throws<ArgumentNullException>(() => new QueryFilter(null, QueryFilter.FilterOperator.Equals(), "val"));
}
[Test]
public void Constructor_InvalidOp_Throws()
{
Assert.Throws<ArgumentNullException>(() => new QueryFilter("prop", null, "val"));
}
[Test]
public void Constructor_NullPropertyValue_Success()
{
Assert.DoesNotThrow(() => new QueryFilter("prop", QueryFilter.FilterOperator.Equals(), null));
}
[Test]
public void Constructor_ValidParams_Success()
{
Assert.DoesNotThrow(() => new QueryFilter("prop", QueryFilter.FilterOperator.Equals(), "val"));
}
[Test]
public void Serialize_SimpleValue_Success()
{
var filter = new QueryFilter("prop", QueryFilter.FilterOperator.Equals(), "val");
var json = JObject.FromObject(filter).ToString(Newtonsoft.Json.Formatting.None);
const string expectedJson = "{\"property_name\":\"prop\"," +
"\"operator\":\"eq\"," +
"\"property_value\":\"val\"}";
Assert.AreEqual(expectedJson, json);
}
[Test]
public void Serialize_NullValue_Success()
{
var filter = new QueryFilter("prop", QueryFilter.FilterOperator.Equals(), null);
var json = JObject.FromObject(filter).ToString(Newtonsoft.Json.Formatting.None);
const string expectedJson = "{\"property_name\":\"prop\"," +
"\"operator\":\"eq\"," +
"\"property_value\":null}";
Assert.AreEqual(expectedJson, json);
}
[Test]
public void Serialize_GeoValue_Success()
{
var filter = new QueryFilter("prop", QueryFilter.FilterOperator.Within(), new QueryFilter.GeoValue(10.0, 10.0, 5.0));
var json = JObject.FromObject(filter).ToString(Newtonsoft.Json.Formatting.None);
Trace.WriteLine(json);
const string expectedJson = "{" +
"\"property_name\":\"prop\"," +
"\"operator\":\"within\"," +
"\"property_value\":{" +
"\"coordinates\":[" +
"10.0," +
"10.0" +
"]," +
"\"max_distance_miles\":5.0" +
"}" +
"}";
Assert.AreEqual(expectedJson, json);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: folio/rpc/tax_fee_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Folio {
public static partial class TaxFeeSvc
{
static readonly string __ServiceName = "holms.types.folio.rpc.TaxFeeSvc";
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.TaxFeeSvcAllResponse> __Marshaller_TaxFeeSvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.TaxFeeSvcAllResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.TaxFeeIndicator> __Marshaller_TaxFeeIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.TaxFeeIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.TaxFee> __Marshaller_TaxFee = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.TaxFee.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Folio.TaxFeeSvcAllResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Folio.TaxFeeSvcAllResponse>(
grpc::MethodType.Unary,
__ServiceName,
"All",
__Marshaller_Empty,
__Marshaller_TaxFeeSvcAllResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.TaxFeeIndicator, global::HOLMS.Types.Folio.TaxFee> __Method_GetById = new grpc::Method<global::HOLMS.Types.Folio.TaxFeeIndicator, global::HOLMS.Types.Folio.TaxFee>(
grpc::MethodType.Unary,
__ServiceName,
"GetById",
__Marshaller_TaxFeeIndicator,
__Marshaller_TaxFee);
static readonly grpc::Method<global::HOLMS.Types.Folio.TaxFee, global::HOLMS.Types.Folio.TaxFee> __Method_Create = new grpc::Method<global::HOLMS.Types.Folio.TaxFee, global::HOLMS.Types.Folio.TaxFee>(
grpc::MethodType.Unary,
__ServiceName,
"Create",
__Marshaller_TaxFee,
__Marshaller_TaxFee);
static readonly grpc::Method<global::HOLMS.Types.Folio.TaxFee, global::HOLMS.Types.Folio.TaxFee> __Method_Update = new grpc::Method<global::HOLMS.Types.Folio.TaxFee, global::HOLMS.Types.Folio.TaxFee>(
grpc::MethodType.Unary,
__ServiceName,
"Update",
__Marshaller_TaxFee,
__Marshaller_TaxFee);
static readonly grpc::Method<global::HOLMS.Types.Folio.TaxFee, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.Folio.TaxFee, global::HOLMS.Types.Primitive.ServerActionConfirmation>(
grpc::MethodType.Unary,
__ServiceName,
"Delete",
__Marshaller_TaxFee,
__Marshaller_ServerActionConfirmation);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Folio.TaxFeeSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of TaxFeeSvc</summary>
public abstract partial class TaxFeeSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.TaxFeeSvcAllResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.TaxFee> GetById(global::HOLMS.Types.Folio.TaxFeeIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.TaxFee> Create(global::HOLMS.Types.Folio.TaxFee request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.TaxFee> Update(global::HOLMS.Types.Folio.TaxFee request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.Folio.TaxFee request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for TaxFeeSvc</summary>
public partial class TaxFeeSvcClient : grpc::ClientBase<TaxFeeSvcClient>
{
/// <summary>Creates a new client for TaxFeeSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public TaxFeeSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for TaxFeeSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public TaxFeeSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected TaxFeeSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected TaxFeeSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.Folio.TaxFeeSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return All(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.TaxFeeSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFeeSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFeeSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request);
}
public virtual global::HOLMS.Types.Folio.TaxFee GetById(global::HOLMS.Types.Folio.TaxFeeIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.TaxFee GetById(global::HOLMS.Types.Folio.TaxFeeIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFee> GetByIdAsync(global::HOLMS.Types.Folio.TaxFeeIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFee> GetByIdAsync(global::HOLMS.Types.Folio.TaxFeeIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request);
}
public virtual global::HOLMS.Types.Folio.TaxFee Create(global::HOLMS.Types.Folio.TaxFee request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.TaxFee Create(global::HOLMS.Types.Folio.TaxFee request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFee> CreateAsync(global::HOLMS.Types.Folio.TaxFee request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFee> CreateAsync(global::HOLMS.Types.Folio.TaxFee request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request);
}
public virtual global::HOLMS.Types.Folio.TaxFee Update(global::HOLMS.Types.Folio.TaxFee request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.TaxFee Update(global::HOLMS.Types.Folio.TaxFee request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFee> UpdateAsync(global::HOLMS.Types.Folio.TaxFee request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.TaxFee> UpdateAsync(global::HOLMS.Types.Folio.TaxFee request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request);
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Folio.TaxFee request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Folio.TaxFee request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Folio.TaxFee request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Folio.TaxFee request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override TaxFeeSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new TaxFeeSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(TaxFeeSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_All, serviceImpl.All)
.AddMethod(__Method_GetById, serviceImpl.GetById)
.AddMethod(__Method_Create, serviceImpl.Create)
.AddMethod(__Method_Update, serviceImpl.Update)
.AddMethod(__Method_Delete, serviceImpl.Delete).Build();
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using Signum.Engine.Basics;
using Signum.Engine.Maps;
using Signum.Utilities;
using Signum.Entities.Mailing;
using Signum.Entities.Processes;
using Signum.Entities;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Operations;
using Signum.Engine.Authorization;
using Signum.Utilities.Reflection;
using System.IO;
using Signum.Engine.Files;
using Microsoft.AspNetCore.StaticFiles;
using Signum.Entities.Basics;
using System.Text;
using System.Threading;
using Microsoft.Exchange.WebServices.Data;
namespace Signum.Engine.Mailing
{
public static class EmailLogic
{
[AutoExpressionField]
public static IQueryable<EmailMessageEntity> EmailMessages(this EmailPackageEntity e) =>
As.Expression(() => Database.Query<EmailMessageEntity>().Where(a => a.Package.Is(e)));
static Func<EmailConfigurationEmbedded> getConfiguration = null!;
public static EmailConfigurationEmbedded Configuration
{
get { return getConfiguration(); }
}
public static EmailSenderManager SenderManager = null!;
internal static void AssertStarted(SchemaBuilder sb)
{
sb.AssertDefined(ReflectionTools.GetMethodInfo(() => EmailLogic.Start(null!, null!, null!, null)));
}
public static void Start(
SchemaBuilder sb,
Func<EmailConfigurationEmbedded> getConfiguration,
Func<EmailTemplateEntity?, Lite<Entity>?, EmailMessageEntity?, EmailSenderConfigurationEntity> getEmailSenderConfiguration,
IFileTypeAlgorithm? attachment = null)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
FilePathEmbeddedLogic.AssertStarted(sb);
CultureInfoLogic.AssertStarted(sb);
EmailLogic.getConfiguration = getConfiguration;
EmailTemplateLogic.Start(sb, getEmailSenderConfiguration);
EmailSenderConfigurationLogic.Start(sb);
if (attachment != null)
FileTypeLogic.Register(EmailFileType.Attachment, attachment);
Schema.Current.WhenIncluded<ProcessEntity>(() => EmailPackageLogic.Start(sb));
sb.Include<EmailMessageEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.State,
e.Subject,
e.Template,
e.Sent,
e.Target,
e.Package,
e.Exception,
});
PermissionAuthLogic.RegisterPermissions(AsyncEmailSenderPermission.ViewAsyncEmailSenderPanel);
SenderManager = new EmailSenderManager(getEmailSenderConfiguration);
EmailGraph.Register();
QueryLogic.Expressions.Register((EmailPackageEntity a) => a.EmailMessages(), () => typeof(EmailMessageEntity).NicePluralName());
ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages;
}
}
public static void ExceptionLogic_DeletePackages(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token)
{
Database.Query<EmailPackageEntity>().Where(pack => !Database.Query<ProcessEntity>().Any(pr => pr.Data == pack) && !pack.EmailMessages().Any())
.UnsafeDeleteChunksLog(parameters, sb, token);
}
public static void ExceptionLogic_DeleteLogs(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token)
{
void Remove(DateTime? dateLimit, bool withExceptions)
{
if (dateLimit == null)
return;
var query = Database.Query<EmailMessageEntity>().Where(o => o.CreationDate < dateLimit.Value);
if (withExceptions)
query = query.Where(a => a.Exception != null);
query.UnsafeDeleteChunksLog(parameters, sb, token);
}
Remove(parameters.GetDateLimitDelete(typeof(EmailMessageEntity).ToTypeEntity()), withExceptions: false);
Remove(parameters.GetDateLimitDeleteWithExceptions(typeof(EmailMessageEntity).ToTypeEntity()), withExceptions: true);
}
public static HashSet<Type> GetAllTypes()
{
if (Schema.Current.IsAllowed(typeof(EmailMessageEntity), true) != null)
return new HashSet<Type>();
var field = Schema.Current.Field((EmailMessageEntity em) => em.Target);
if (field is FieldImplementedBy ib)
return ib.ImplementationColumns.Keys.ToHashSet();
//Hacky...
if (field is FieldImplementedByAll iba)
{
var types = Database.Query<EmailMessageEntity>().Where(a => a.Target != null).Select(a => a.Target!.Entity.GetType()).Distinct().ToHashSet();
return types;
}
return new HashSet<Type>();
}
public static void SendMail(this IEmailModel model)
{
foreach (var email in model.CreateEmailMessage())
SenderManager.Send(email);
}
public static void SendMail(this Lite<EmailTemplateEntity> template, ModifiableEntity entity)
{
foreach (var email in template.CreateEmailMessage(entity))
SenderManager.Send(email);
}
public static void SendMail(this EmailMessageEntity email)
{
SenderManager.Send(email);
}
public static void SendMailAsync(this IEmailModel model)
{
foreach (var email in model.CreateEmailMessage())
email.SendMailAsync();
}
public static void SendMailAsync(this Lite<EmailTemplateEntity> template, ModifiableEntity entity)
{
foreach (var email in template.CreateEmailMessage(entity))
email.SendMailAsync();
}
public static void SendMailAsync(this EmailMessageEntity email)
{
using (OperationLogic.AllowSave<EmailMessageEntity>())
{
email.State = EmailMessageState.ReadyToSend;
email.Save();
}
}
public static SmtpClient SafeSmtpClient()
{
if (!EmailLogic.Configuration.SendEmails)
throw new InvalidOperationException("EmailLogic.Configuration.SendEmails is set to false");
//http://weblogs.asp.net/stanleygu/archive/2010/03/31/tip-14-solve-smtpclient-issues-of-delayed-email-and-high-cpu-usage.aspx
return new SmtpClient()
{
ServicePoint = { MaxIdleTime = 2 }
};
}
internal static SmtpClient SafeSmtpClient(string host, int port)
{
if (!EmailLogic.Configuration.SendEmails)
throw new InvalidOperationException("EmailLogic.Configuration.SendEmails is set to false");
//http://weblogs.asp.net/stanleygu/archive/2010/03/31/tip-14-solve-smtpclient-issues-of-delayed-email-and-high-cpu-usage.aspx
return new SmtpClient(host, port)
{
ServicePoint = { MaxIdleTime = 2 }
};
}
public static MList<EmailTemplateMessageEmbedded> CreateMessages(Func<EmailTemplateMessageEmbedded> func)
{
var list = new MList<EmailTemplateMessageEmbedded>();
foreach (var ci in CultureInfoLogic.ApplicationCultures)
{
using (CultureInfoUtils.ChangeBothCultures(ci))
{
list.Add(func());
}
}
return list;
}
public static MailAddress ToMailAddress(this EmailAddressEmbedded address)
{
if (address.DisplayName.HasText())
return new MailAddress(address.EmailAddress, address.DisplayName);
return new MailAddress(address.EmailAddress);
}
public static MailAddress ToMailAddress(this EmailRecipientEmbedded recipient)
{
if (!Configuration.SendEmails)
throw new InvalidOperationException("EmailConfigurationEmbedded.SendEmails is set to false");
if (recipient.DisplayName.HasText())
return new MailAddress(Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress), recipient.DisplayName);
return new MailAddress(Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress));
}
public static EmailAddress ToEmailAddress(this EmailAddressEmbedded address)
{
if (address.DisplayName.HasText())
return new EmailAddress(address.DisplayName, address.EmailAddress);
return new EmailAddress(address.EmailAddress);
}
public static EmailAddress ToEmailAddress(this EmailRecipientEmbedded recipient)
{
if (!Configuration.SendEmails)
throw new InvalidOperationException("EmailConfigurationEmbedded.SendEmails is set to false");
if (recipient.DisplayName.HasText())
return new EmailAddress(recipient.DisplayName, Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress));
return new EmailAddress(Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress));
}
public static void SendAllAsync<T>(List<T> emails)
where T : IEmailModel
{
var list = emails.SelectMany(a => a.CreateEmailMessage()).ToList();
list.ForEach(a => a.State = EmailMessageState.ReadyToSend);
using (OperationLogic.AllowSave<EmailMessageEntity>())
{
list.SaveList();
}
}
class EmailGraph : Graph<EmailMessageEntity, EmailMessageState>
{
public static void Register()
{
GetState = m => m.State;
new Construct(EmailMessageOperation.CreateMail)
{
ToStates = { EmailMessageState.Created },
Construct = _ => new EmailMessageEntity
{
State = EmailMessageState.Created,
}
}.Register();
new ConstructFrom<EmailTemplateEntity>(EmailMessageOperation.CreateEmailFromTemplate)
{
ToStates = { EmailMessageState.Created },
CanConstruct = et =>
{
if (et.Model != null && EmailModelLogic.RequiresExtraParameters(et.Model))
return EmailMessageMessage._01requiresExtraParameters.NiceToString(typeof(EmailModelEntity).NiceName(), et.Model);
if (et.SendDifferentMessages)
return ValidationMessage._0IsSet.NiceToString(ReflectionTools.GetPropertyInfo(() => et.SendDifferentMessages).NiceName());
return null;
},
Construct = (et, args) =>
{
var entity = args.TryGetArgC<ModifiableEntity>() ?? args.GetArg<Lite<Entity>>().RetrieveAndRemember();
var emailMessageEntity = et.ToLite().CreateEmailMessage(entity).FirstOrDefault();
if (emailMessageEntity == null)
{
throw new InvalidOperationException("No suitable recipients were found");
}
return emailMessageEntity;
}
}.Register();
new Execute(EmailMessageOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
FromStates = { EmailMessageState.Created, EmailMessageState.Outdated },
ToStates = { EmailMessageState.Draft },
Execute = (m, _) => { m.State = EmailMessageState.Draft; }
}.Register();
new Execute(EmailMessageOperation.ReadyToSend)
{
CanBeNew = true,
CanBeModified = true,
FromStates = { EmailMessageState.Created, EmailMessageState.Draft, EmailMessageState.SentException, EmailMessageState.RecruitedForSending, EmailMessageState.Outdated },
ToStates = { EmailMessageState.ReadyToSend },
Execute = (m, _) =>
{
m.SendRetries = 0;
m.State = EmailMessageState.ReadyToSend;
}
}.Register();
new Execute(EmailMessageOperation.Send)
{
CanExecute = m => m.State == EmailMessageState.Created || m.State == EmailMessageState.Draft ||
m.State == EmailMessageState.ReadyToSend || m.State == EmailMessageState.RecruitedForSending ||
m.State == EmailMessageState.Outdated ? null : EmailMessageMessage.TheEmailMessageCannotBeSentFromState0.NiceToString().FormatWith(m.State.NiceToString()),
CanBeNew = true,
CanBeModified = true,
FromStates = { EmailMessageState.Created, EmailMessageState.Draft, EmailMessageState.ReadyToSend, EmailMessageState.Outdated },
ToStates = { EmailMessageState.Sent },
Execute = (m, _) => EmailLogic.SenderManager.Send(m)
}.Register();
new ConstructFrom<EmailMessageEntity>(EmailMessageOperation.ReSend)
{
ToStates = { EmailMessageState.Created },
Construct = (m, _) => new EmailMessageEntity
{
From = m.From!.Clone(),
Recipients = m.Recipients.Select(r => r.Clone()).ToMList(),
Target = m.Target,
Subject = m.Subject,
Body = new BigStringEmbedded(m.Body.Text),
IsBodyHtml = m.IsBodyHtml,
Template = m.Template,
EditableMessage = m.EditableMessage,
State = EmailMessageState.Created,
Attachments = m.Attachments.Select(a => a.Clone()).ToMList()
}
}.Register();
new Graph<EmailMessageEntity>.Delete(EmailMessageOperation.Delete)
{
Delete = (m, _) => m.Delete()
}.Register();
}
}
}
public class EmailSenderManager
{
private Func<EmailTemplateEntity?, Lite<Entity>?, EmailMessageEntity?, EmailSenderConfigurationEntity> getEmailSenderConfiguration;
public EmailSenderManager(Func<EmailTemplateEntity?, Lite<Entity>?,EmailMessageEntity?, EmailSenderConfigurationEntity> getEmailSenderConfiguration)
{
this.getEmailSenderConfiguration = getEmailSenderConfiguration;
}
public virtual void Send(EmailMessageEntity email)
{
using (OperationLogic.AllowSave<EmailMessageEntity>())
{
if (!EmailLogic.Configuration.SendEmails)
{
email.State = EmailMessageState.Sent;
email.Sent = TimeZoneManager.Now;
email.Save();
return;
}
try
{
SendInternal(email);
email.State = EmailMessageState.Sent;
email.Sent = TimeZoneManager.Now;
email.Save();
}
catch (Exception ex)
{
if (Transaction.InTestTransaction) //Transaction.IsTestTransaction
throw;
var exLog = ex.LogException().ToLite();
try
{
using (Transaction tr = Transaction.ForceNew())
{
email.Exception = exLog;
email.State = EmailMessageState.SentException;
email.Save();
tr.Commit();
}
}
catch { } //error updating state for email
throw;
}
}
}
protected virtual void SendInternal(EmailMessageEntity email)
{
var template = email.Template?.Try(t => EmailTemplateLogic.EmailTemplatesLazy.Value.GetOrThrow(t));
var config = getEmailSenderConfiguration(template, email.Target, email);
if (config.SMTP != null)
{
SentSMTP(email, config.SMTP);
}
else
{
SentExchangeWebService(email, config.Exchange!);
}
}
protected virtual void SentSMTP(EmailMessageEntity email, SmtpEmbedded smtp)
{
System.Net.Mail.MailMessage message = CreateMailMessage(email);
using (HeavyProfiler.Log("SMTP-Send"))
smtp.GenerateSmtpClient().Send(message);
}
protected virtual MailMessage CreateMailMessage(EmailMessageEntity email)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage()
{
From = email.From.ToMailAddress(),
Subject = email.Subject,
IsBodyHtml = email.IsBodyHtml,
};
System.Net.Mail.AlternateView view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(email.Body.Text, null, email.IsBodyHtml ? "text/html" : "text/plain");
view.LinkedResources.AddRange(email.Attachments
.Where(a => a.Type == EmailAttachmentType.LinkedResource)
.Select(a => new System.Net.Mail.LinkedResource(a.File.OpenRead(), MimeMapping.GetMimeType(a.File.FileName))
{
ContentId = a.ContentId,
}));
message.AlternateViews.Add(view);
message.Attachments.AddRange(email.Attachments
.Where(a => a.Type == EmailAttachmentType.Attachment)
.Select(a => new System.Net.Mail.Attachment(a.File.OpenRead(), MimeMapping.GetMimeType(a.File.FileName))
{
ContentId = a.ContentId,
Name = a.File.FileName,
}));
message.To.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.To).Select(r => r.ToMailAddress()).ToList());
message.CC.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Cc).Select(r => r.ToMailAddress()).ToList());
message.Bcc.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Bcc).Select(r => r.ToMailAddress()).ToList());
return message;
}
private void SentExchangeWebService(EmailMessageEntity email, ExchangeWebServiceEmbedded exchange)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.UseDefaultCredentials = exchange.UseDefaultCredentials;
service.Credentials = exchange.Username.HasText() ? new WebCredentials(exchange.Username, exchange.Password) : null;
//service.TraceEnabled = true;
//service.TraceFlags = TraceFlags.All;
if (exchange.Url.HasText())
service.Url = new Uri(exchange.Url);
else
service.AutodiscoverUrl(email.From.EmailAddress, RedirectionUrlValidationCallback);
EmailMessage message = new EmailMessage(service);
foreach (var a in email.Attachments.Where(a => a.Type == EmailAttachmentType.Attachment))
{
var fa = message.Attachments.AddFileAttachment(a.File.FileName, a.File.GetByteArray());
fa.ContentId = a.ContentId;
}
message.ToRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.To).Select(r => r.ToEmailAddress()).ToList());
message.CcRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Cc).Select(r => r.ToEmailAddress()).ToList());
message.BccRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Bcc).Select(r => r.ToEmailAddress()).ToList());
message.Subject = email.Subject;
message.Body = new MessageBody(email.IsBodyHtml ? BodyType.HTML : BodyType.Text, email.Body.Text);
message.Send();
}
protected virtual bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
return redirectionUri.Scheme == "https";
}
}
public static class MimeMapping
{
public static string GetMimeType(string fileName)
{
var extension = Path.GetExtension(fileName);
FileExtensionContentTypeProvider mimeConverter = new FileExtensionContentTypeProvider();
return mimeConverter.Mappings.TryGetValue(extension ?? "", out var result) ? result : "application/octet-stream";
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 SCG = System.Collections.Generic;
namespace RazorDBx.C5
{
/// <summary>
/// A set collection class based on linear hashing
/// </summary>
public class HashSet<T> : CollectionBase<T>, ICollection<T>
{
#region Feature
/// <summary>
/// Enum class to assist printing of compilation alternatives.
/// </summary>
[Flags]
public enum Feature : short
{
/// <summary>
/// Nothing
/// </summary>
Dummy = 0,
/// <summary>
/// Buckets are of reference type
/// </summary>
RefTypeBucket = 1,
/// <summary>
/// Primary buckets are of value type
/// </summary>
ValueTypeBucket = 2,
/// <summary>
/// Using linear probing to resolve index clashes
/// </summary>
LinearProbing = 4,
/// <summary>
/// Shrink table when very sparsely filled
/// </summary>
ShrinkTable = 8,
/// <summary>
/// Use chaining to resolve index clashes
/// </summary>
Chaining = 16,
/// <summary>
/// Use hash function on item hash code
/// </summary>
InterHashing = 32,
/// <summary>
/// Use a universal family of hash functions on item hash code
/// </summary>
RandomInterHashing = 64
}
private static Feature features = Feature.Dummy
| Feature.RefTypeBucket
| Feature.Chaining
| Feature.RandomInterHashing;
/// <summary>
/// Show which implementation features was chosen at compilation time
/// </summary>
public static Feature Features { get { return features; } }
#endregion
#region Fields
int indexmask, bits, bitsc, origbits, lastchosen; //bitsc==32-bits; indexmask==(1<<bits)-1;
Bucket[] table;
double fillfactor = 0.66;
int resizethreshhold;
private static readonly Random Random = new Random();
uint _randomhashfactor;
#endregion
#region Events
/// <summary>
///
/// </summary>
/// <value></value>
public override EventTypeEnum ListenableEvents { get { return EventTypeEnum.Basic; } }
#endregion
#region Bucket nested class(es)
class Bucket
{
internal T item;
internal int hashval; //Cache!
internal Bucket overflow;
internal Bucket(T item, int hashval, Bucket overflow)
{
this.item = item;
this.hashval = hashval;
this.overflow = overflow;
}
}
#endregion
#region Basic Util
bool equals(T i1, T i2) { return itemequalityComparer.Equals(i1, i2); }
int gethashcode(T item) { return itemequalityComparer.GetHashCode(item); }
int hv2i(int hashval)
{
return (int)(((uint)hashval * _randomhashfactor) >> bitsc);
}
void expand()
{
Logger.Log(string.Format(string.Format("Expand to {0} bits", bits + 1)));
resize(bits + 1);
}
void shrink()
{
if (bits > 3)
{
Logger.Log(string.Format(string.Format("Shrink to {0} bits", bits - 1)));
resize(bits - 1);
}
}
void resize(int bits)
{
Logger.Log(string.Format(string.Format("Resize to {0} bits", bits)));
this.bits = bits;
bitsc = 32 - bits;
indexmask = (1 << bits) - 1;
Bucket[] newtable = new Bucket[indexmask + 1];
for (int i = 0, s = table.Length; i < s; i++)
{
Bucket b = table[i];
while (b != null)
{
int j = hv2i(b.hashval);
newtable[j] = new Bucket(b.item, b.hashval, newtable[j]);
b = b.overflow;
}
}
table = newtable;
resizethreshhold = (int)(table.Length * fillfactor);
Logger.Log(string.Format(string.Format("Resize to {0} bits done", bits)));
}
/// <summary>
/// Search for an item equal (according to itemequalityComparer) to the supplied item.
/// </summary>
/// <param name="item"></param>
/// <param name="add">If true, add item to table if not found.</param>
/// <param name="update">If true, update table entry if item found.</param>
/// <param name="raise">If true raise events</param>
/// <returns>True if found</returns>
private bool searchoradd(ref T item, bool add, bool update, bool raise)
{
int hashval = gethashcode(item);
int i = hv2i(hashval);
Bucket b = table[i], bold = null;
if (b != null)
{
while (b != null)
{
T olditem = b.item;
if (equals(olditem, item))
{
if (update)
{
b.item = item;
}
if (raise && update)
raiseForUpdate(item, olditem);
// bug20071112:
item = olditem;
return true;
}
bold = b;
b = b.overflow;
}
if (!add) goto notfound;
bold.overflow = new Bucket(item, hashval, null);
}
else
{
if (!add) goto notfound;
table[i] = new Bucket(item, hashval, null);
}
size++;
if (size > resizethreshhold)
expand();
notfound:
if (raise && add)
raiseForAdd(item);
if (update)
item = default(T);
return false;
}
private bool remove(ref T item)
{
if (size == 0)
return false;
int hashval = gethashcode(item);
int index = hv2i(hashval);
Bucket b = table[index], bold;
if (b == null)
return false;
if (equals(item, b.item))
{
//ref
item = b.item;
table[index] = b.overflow;
}
else
{
bold = b;
b = b.overflow;
while (b != null && !equals(item, b.item))
{
bold = b;
b = b.overflow;
}
if (b == null)
return false;
//ref
item = b.item;
bold.overflow = b.overflow;
}
size--;
return true;
}
private void clear()
{
bits = origbits;
bitsc = 32 - bits;
indexmask = (1 << bits) - 1;
size = 0;
table = new Bucket[indexmask + 1];
resizethreshhold = (int)(table.Length * fillfactor);
}
#endregion
#region Constructors
/// <summary>
/// Create a hash set with natural item equalityComparer and default fill threshold (66%)
/// and initial table size (16).
/// </summary>
public HashSet()
: this(EqualityComparer<T>.Default) { }
/// <summary>
/// Create a hash set with external item equalityComparer and default fill threshold (66%)
/// and initial table size (16).
/// </summary>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashSet(SCG.IEqualityComparer<T> itemequalityComparer)
: this(16, itemequalityComparer) { }
/// <summary>
/// Create a hash set with external item equalityComparer and default fill threshold (66%)
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashSet(int capacity, SCG.IEqualityComparer<T> itemequalityComparer)
: this(capacity, 0.66, itemequalityComparer) { }
/// <summary>
/// Create a hash set with external item equalityComparer.
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="fill">Fill threshold (in range 10% to 90%)</param>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashSet(int capacity, double fill, SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
_randomhashfactor = (Debug.UseDeterministicHashing) ? 1529784659 : (2 * (uint)Random.Next() + 1) * 1529784659;
if (fill < 0.1 || fill > 0.9)
throw new ArgumentException("Fill outside valid range [0.1, 0.9]");
if (capacity <= 0)
throw new ArgumentException("Capacity must be non-negative");
//this.itemequalityComparer = itemequalityComparer;
origbits = 4;
while (capacity - 1 >> origbits > 0) origbits++;
clear();
}
#endregion
#region IEditableCollection<T> Members
/// <summary>
/// The complexity of the Contains operation
/// </summary>
/// <value>Always returns Speed.Constant</value>
public virtual Speed ContainsSpeed { get { return Speed.Constant; } }
/// <summary>
/// Check if an item is in the set
/// </summary>
/// <param name="item">The item to look for</param>
/// <returns>True if set contains item</returns>
public virtual bool Contains(T item) { return searchoradd(ref item, false, false, false); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set and
/// if so report the actual item object found.
/// </summary>
/// <param name="item">On entry, the item to look for.
/// On exit the item found, if any</param>
/// <returns>True if set contains item</returns>
public virtual bool Find(ref T item) { return searchoradd(ref item, false, false, false); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set and
/// if so replace the item object in the set with the supplied one.
/// </summary>
/// <param name="item">The item object to update with</param>
/// <returns>True if item was found (and updated)</returns>
public virtual bool Update(T item)
{ updatecheck(); return searchoradd(ref item, false, true, true); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set and
/// if so replace the item object in the set with the supplied one.
/// </summary>
/// <param name="item">The item object to update with</param>
/// <param name="olditem"></param>
/// <returns>True if item was found (and updated)</returns>
public virtual bool Update(T item, out T olditem)
{ updatecheck(); olditem = item; return searchoradd(ref olditem, false, true, true); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set.
/// If found, report the actual item object in the set,
/// else add the supplied one.
/// </summary>
/// <param name="item">On entry, the item to look for or add.
/// On exit the actual object found, if any.</param>
/// <returns>True if item was found</returns>
public virtual bool FindOrAdd(ref T item)
{ updatecheck(); return searchoradd(ref item, true, false, true); }
/// <summary>
/// Check if an item (collection equal to a supplied one) is in the set and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
/// </summary>
/// <param name="item">The item to look for and update or add</param>
/// <returns>True if item was updated</returns>
public virtual bool UpdateOrAdd(T item)
{ updatecheck(); return searchoradd(ref item, true, true, true); }
/// <summary>
/// Check if an item (collection equal to a supplied one) is in the set and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
/// </summary>
/// <param name="item">The item to look for and update or add</param>
/// <param name="olditem"></param>
/// <returns>True if item was updated</returns>
public virtual bool UpdateOrAdd(T item, out T olditem)
{ updatecheck(); olditem = item; return searchoradd(ref olditem, true, true, true); }
/// <summary>
/// Remove an item from the set
/// </summary>
/// <param name="item">The item to remove</param>
/// <returns>True if item was (found and) removed </returns>
public virtual bool Remove(T item)
{
updatecheck();
if (remove(ref item))
{
raiseForRemove(item);
return true;
}
else
return false;
}
/// <summary>
/// Remove an item from the set, reporting the actual matching item object.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <param name="removeditem">The removed value.</param>
/// <returns>True if item was found.</returns>
public virtual bool Remove(T item, out T removeditem)
{
updatecheck();
removeditem = item;
if (remove(ref removeditem))
{
raiseForRemove(removeditem);
return true;
}
else
return false;
}
/// <summary>
/// Remove all items in a supplied collection from this set.
/// </summary>
/// <param name="items">The items to remove.</param>
public virtual void RemoveAll(SCG.IEnumerable<T> items)
{
updatecheck();
RaiseForRemoveAllHandler raiseHandler = new RaiseForRemoveAllHandler(this);
bool raise = raiseHandler.MustFire;
T jtem;
foreach (var item in items)
{ jtem = item; if (remove(ref jtem) && raise) raiseHandler.Remove(jtem); }
if (raise) raiseHandler.Raise();
}
/// <summary>
/// Remove all items from the set, resetting internal table to initial size.
/// </summary>
public virtual void Clear()
{
updatecheck();
int oldsize = size;
clear();
if (ActiveEvents != 0 && oldsize > 0)
{
raiseCollectionCleared(true, oldsize);
raiseCollectionChanged();
}
}
/// <summary>
/// Remove all items *not* in a supplied collection from this set.
/// </summary>
/// <param name="items">The items to retain</param>
public virtual void RetainAll(SCG.IEnumerable<T> items)
{
updatecheck();
HashSet<T> aux = new HashSet<T>(EqualityComparer);
//This only works for sets:
foreach (var item in items)
if (Contains(item))
{
T jtem = item;
aux.searchoradd(ref jtem, true, false, false);
}
if (size == aux.size)
return;
CircularQueue<T> wasRemoved = null;
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
{
wasRemoved = new CircularQueue<T>();
foreach (T item in this)
if (!aux.Contains(item))
wasRemoved.Enqueue(item);
}
table = aux.table;
size = aux.size;
indexmask = aux.indexmask;
resizethreshhold = aux.resizethreshhold;
bits = aux.bits;
bitsc = aux.bitsc;
_randomhashfactor = aux._randomhashfactor;
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
raiseForRemoveAll(wasRemoved);
else if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
/// <summary>
/// Check if all items in a supplied collection is in this set
/// (ignoring multiplicities).
/// </summary>
/// <param name="items">The items to look for.</param>
/// <returns>True if all items are found.</returns>
public virtual bool ContainsAll(SCG.IEnumerable<T> items)
{
foreach (var item in items)
if (!Contains(item))
return false;
return true;
}
/// <summary>
/// Create an array containing all items in this set (in enumeration order).
/// </summary>
/// <returns>The array</returns>
public override T[] ToArray()
{
T[] res = new T[size];
int index = 0;
for (int i = 0; i < table.Length; i++)
{
Bucket b = table[i];
while (b != null)
{
res[index++] = b.item;
b = b.overflow;
}
}
System.Diagnostics.Debug.Assert(size == index);
return res;
}
/// <summary>
/// Count the number of times an item is in this set (either 0 or 1).
/// </summary>
/// <param name="item">The item to look for.</param>
/// <returns>1 if item is in set, 0 else</returns>
public virtual int ContainsCount(T item) { return Contains(item) ? 1 : 0; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<T> UniqueItems() { return this; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<KeyValuePair<T, int>> ItemMultiplicities()
{
return new MultiplicityOne<T>(this);
}
/// <summary>
/// Remove all (at most 1) copies of item from this set.
/// </summary>
/// <param name="item">The item to remove</param>
public virtual void RemoveAllCopies(T item) { Remove(item); }
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Choose some item of this collection.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override T Choose()
{
int len = table.Length;
if (size == 0)
throw new NoSuchItemException();
do { if (++lastchosen >= len) lastchosen = 0; } while (table[lastchosen] == null);
return table[lastchosen].item;
}
/// <summary>
/// Create an enumerator for this set.
/// </summary>
/// <returns>The enumerator</returns>
public override SCG.IEnumerator<T> GetEnumerator()
{
int index = -1;
int mystamp = stamp;
int len = table.Length;
Bucket b = null;
while (true)
{
if (mystamp != stamp)
throw new CollectionModifiedException();
if (b == null || b.overflow == null)
{
do
{
if (++index >= len) yield break;
} while (table[index] == null);
b = table[index];
yield return b.item;
}
else
{
b = b.overflow;
yield return b.item;
}
}
}
#endregion
#region ISink<T> Members
/// <summary>
/// Report if this is a set collection.
/// </summary>
/// <value>Always false</value>
public virtual bool AllowsDuplicates { get { return false; } }
/// <summary>
/// By convention this is true for any collection with set semantics.
/// </summary>
/// <value>True if only one representative of a group of equal items
/// is kept in the collection together with the total count.</value>
public virtual bool DuplicatesByCounting { get { return true; } }
/// <summary>
/// Add an item to this set.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>True if item was added (i.e. not found)</returns>
public virtual bool Add(T item)
{
updatecheck();
return !searchoradd(ref item, true, false, true);
}
/// <summary>
/// Add an item to this set.
/// </summary>
/// <param name="item">The item to add.</param>
void SCG.ICollection<T>.Add(T item)
{
Add(item);
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection. Since this
/// collection has set semantics, only items not already in the collection
/// will be added.
/// </summary>
/// <param name="items">The items to add</param>
public virtual void AddAll(SCG.IEnumerable<T> items)
{
updatecheck();
bool wasChanged = false;
bool raiseAdded = (ActiveEvents & EventTypeEnum.Added) != 0;
CircularQueue<T> wasAdded = raiseAdded ? new CircularQueue<T>() : null;
foreach (T item in items)
{
T jtem = item;
if (!searchoradd(ref jtem, true, false, false))
{
wasChanged = true;
if (raiseAdded)
wasAdded.Enqueue(item);
}
}
//TODO: implement a RaiseForAddAll() method
if (raiseAdded & wasChanged)
foreach (T item in wasAdded)
raiseItemsAdded(item, 1);
if (((ActiveEvents & EventTypeEnum.Changed) != 0 && wasChanged))
raiseCollectionChanged();
}
#endregion
#region Diagnostics
/// <summary>
/// Test internal structure of data (invariants)
/// </summary>
/// <returns>True if pass</returns>
public virtual bool Check()
{
int count = 0;
bool retval = true;
if (bitsc != 32 - bits)
{
Logger.Log(string.Format("bitsc != 32 - bits ({0}, {1})", bitsc, bits));
retval = false;
}
if (indexmask != (1 << bits) - 1)
{
Logger.Log(string.Format("indexmask != (1 << bits) - 1 ({0}, {1})", indexmask, bits));
retval = false;
}
if (table.Length != indexmask + 1)
{
Logger.Log(string.Format("table.Length != indexmask + 1 ({0}, {1})", table.Length, indexmask));
retval = false;
}
if (bitsc != 32 - bits)
{
Logger.Log(string.Format("resizethreshhold != (int)(table.Length * fillfactor) ({0}, {1}, {2})", resizethreshhold, table.Length, fillfactor));
retval = false;
}
for (int i = 0, s = table.Length; i < s; i++)
{
int level = 0;
Bucket b = table[i];
while (b != null)
{
if (i != hv2i(b.hashval))
{
Logger.Log(string.Format("Bad cell item={0}, hashval={1}, index={2}, level={3}", b.item, b.hashval, i, level));
retval = false;
}
count++;
level++;
b = b.overflow;
}
}
if (count != size)
{
Logger.Log(string.Format("size({0}) != count({1})", size, count));
retval = false;
}
return retval;
}
/// <summary>
/// Produce statistics on distribution of bucket sizes. Current implementation is incomplete.
/// </summary>
/// <returns>Histogram data.</returns>
public ISortedDictionary<int, int> BucketCostDistribution()
{
TreeDictionary<int, int> res = new TreeDictionary<int, int>();
for (int i = 0, s = table.Length; i < s; i++)
{
int count = 0;
Bucket b = table[i];
while (b != null)
{
count++;
b = b.overflow;
}
if (res.Contains(count))
res[count]++;
else
res[count] = 1;
}
return res;
}
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// A layer with drawing characteristics for images.
/// </summary>
public class ImageLayer : Layer, IImageLayer
{
#region Fields
private IImageSymbolizer _symbolizer;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ImageLayer"/> class that needs to be configured later.
/// </summary>
public ImageLayer()
{
Symbolizer = new ImageSymbolizer();
}
/// <summary>
/// Initializes a new instance of the <see cref="ImageLayer"/> class by opening the specified fileName.
/// </summary>
/// <param name="fileName">The fileName to open</param>
public ImageLayer(string fileName)
{
Symbolizer = new ImageSymbolizer();
DataSet = DataManager.DefaultDataManager.OpenImage(fileName);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImageLayer"/> class by opening the specified fileName, relaying progress to the
/// specified handler, and automatically adds the new layer to the specified container.
/// </summary>
/// <param name="fileName">The fileName to open</param>
/// <param name="progressHandler">A ProgressHandler that can receive progress updates</param>
/// <param name="container">The layer list that should contain this image layer</param>
public ImageLayer(string fileName, IProgressHandler progressHandler, ICollection<ILayer> container)
: base(container)
{
Symbolizer = new ImageSymbolizer();
DataSet = DataManager.DefaultDataManager.OpenImage(fileName, progressHandler);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImageLayer"/> class by opening the specified fileName and
/// relaying progress to the specified handler.
/// </summary>
/// <param name="fileName">The fileName to open</param>
/// <param name="progressHandler">The progressHandler</param>
public ImageLayer(string fileName, IProgressHandler progressHandler)
{
Symbolizer = new ImageSymbolizer();
DataSet = DataManager.DefaultDataManager.OpenImage(fileName, progressHandler);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImageLayer"/> class.
/// </summary>
/// <param name="baseImage">The image to draw as a layer</param>
public ImageLayer(IImageData baseImage)
{
Symbolizer = new ImageSymbolizer();
DataSet = baseImage;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImageLayer"/> class.
/// </summary>
/// <param name="baseImage">The image to draw as a layer</param>
/// <param name="container">The Layers collection that keeps track of the image layer</param>
public ImageLayer(IImageData baseImage, ICollection<ILayer> container)
: base(container)
{
Symbolizer = new ImageSymbolizer();
DataSet = baseImage;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the underlying data for this object.
/// </summary>
[Serialize("ImageData")]
public new IImageData DataSet
{
get
{
return base.DataSet as IImageData;
}
set
{
var current = DataSet;
if (current == value) return;
base.DataSet = value;
OnDataSetChanged(value);
}
}
/// <summary>
/// Gets the geographic bounding envelope for the image.
/// </summary>
public override Extent Extent => DataSet?.Extent;
/// <summary>
/// Gets or sets the image being drawn by this layer
/// </summary>
public IImageData Image
{
get
{
return DataSet;
}
set
{
DataSet = value;
}
}
/// <summary>
/// Gets or sets custom actions for ImageLayer
/// </summary>
[Browsable(false)]
public IImageLayerActions ImageLayerActions { get; set; }
/// <summary>
/// Gets or sets a class that has some basic parameters that control how the image layer
/// is drawn.
/// </summary>
[Browsable(false)]
[ShallowCopy]
[Serialize("Symbolizer")]
public IImageSymbolizer Symbolizer
{
get
{
return _symbolizer;
}
set
{
_symbolizer = value;
OnItemChanged();
}
}
#endregion
#region Methods
/// <summary>
/// Dispose memory objects.
/// </summary>
/// <param name="disposeManagedResources">True if managed memory objects should be set to null.</param>
protected override void Dispose(bool disposeManagedResources)
{
if (disposeManagedResources)
{
_symbolizer = null;
ImageLayerActions = null;
}
base.Dispose(disposeManagedResources);
}
/// <summary>
/// This updates the things that depend on the DataSet so that they fit to the changed DataSet.
/// </summary>
/// <param name="value">DataSet that was changed.</param>
protected virtual void OnDataSetChanged(IImageData value)
{
IsVisible = value != null;
// Change legendText only if image data refers to real file
if (value != null && File.Exists(value.Filename))
{
LegendText = Path.GetFileName(value.Filename);
}
}
/// <summary>
/// Handles export data from this layer.
/// </summary>
protected override void OnExportData()
{
ImageLayerActions?.ExportData(Image);
}
/// <summary>
/// Handles when this layer should show its properties by firing the event on the shared event sender
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnShowProperties(HandledEventArgs e)
{
ImageLayerActions?.ShowProperties(this);
}
#endregion
}
}
| |
using System;
using System.Linq;
using dotless.Core.Plugins;
namespace dotless.Core.Parser.Tree
{
using System.IO;
using Importers;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
using dotless.Core.Exceptions;
public class Import : Directive
{
private readonly ReferenceVisitor referenceVisitor = new ReferenceVisitor();
/// <summary>
/// The original path node
/// </summary>
protected Node OriginalPath { get; set; }
public string Path { get; set; }
/// <summary>
/// The inner root - if the action is ImportLess
/// </summary>
public Ruleset InnerRoot { get; set; }
/// <summary>
/// The inner content - if the action is ImportCss
/// </summary>
public string InnerContent { get; set; }
/// <summary>
/// The media features (if present)
/// </summary>
public Node Features { get; set; }
/// <summary>
/// The type of import: reference, inline, less, css, once, multiple or optional
/// </summary>
public ImportOptions ImportOptions { get; set; }
/// <summary>
/// The action to perform with this node
/// </summary>
private ImportAction? _importAction;
public Import(Quoted path, Value features, ImportOptions option)
: this((Node)path, features, option)
{
OriginalPath = path;
}
public Import(Url path, Value features, ImportOptions option)
: this((Node)path, features, option)
{
OriginalPath = path;
Path = path.GetUnadjustedUrl();
}
/// <summary>
/// Create a evaluated node that will render a @import
/// </summary>
/// <param name="originalPath"></param>
/// <param name="features"></param>
private Import(Node originalPath, Node features)
{
OriginalPath = originalPath;
Features = features;
_importAction = ImportAction.LeaveImport;
}
private Import(Node path, Value features, ImportOptions option)
{
if (path == null)
throw new ParserException("Imports do not allow expressions");
OriginalPath = path;
Features = features;
ImportOptions = option;
}
private ImportAction GetImportAction(IImporter importer)
{
if (!_importAction.HasValue)
{
_importAction = importer.Import(this);
}
return _importAction.Value;
}
public override void AppendCSS(Env env, Context context)
{
ImportAction action = GetImportAction(env.Parser.Importer);
if (action == ImportAction.ImportNothing)
{
return;
}
if (action == ImportAction.ImportCss)
{
env.Output.Append(InnerContent);
return;
}
env.Output.Append("@import ")
.Append(OriginalPath.ToCSS(env));
if (Features)
{
env.Output
.Append(" ")
.Append(Features);
}
env.Output.Append(";");
if (!env.Compress)
{
env.Output.Append("\n");
}
}
public override void Accept(Plugins.IVisitor visitor)
{
Features = VisitAndReplace(Features, visitor, true);
if (_importAction == ImportAction.ImportLess)
{
InnerRoot = VisitAndReplace(InnerRoot, visitor);
}
}
public override Node Evaluate(Env env)
{
OriginalPath = OriginalPath.Evaluate(env);
var quoted = OriginalPath as Quoted;
if (quoted != null)
{
Path = quoted.Value;
}
ImportAction action = GetImportAction(env.Parser.Importer);
if (action == Importers.ImportAction.ImportNothing)
{
return new NodeList().ReducedFrom<NodeList>(this);
}
Node features = null;
if (Features)
features = Features.Evaluate(env);
if (action == ImportAction.LeaveImport)
return new Import(OriginalPath, features);
if (action == ImportAction.ImportCss)
{
var importCss = new Import(OriginalPath, null) { _importAction = ImportAction.ImportCss, InnerContent = InnerContent };
if (features)
return new Media(features, new NodeList() { importCss });
return importCss;
}
using (env.Parser.Importer.BeginScope(this))
{
if (IsReference || IsOptionSet(ImportOptions, ImportOptions.Reference))
{
// Walk the parse tree and mark all nodes as references.
IsReference = true;
Accept(referenceVisitor);
}
NodeHelper.RecursiveExpandNodes<Import>(env, InnerRoot.Rules);
}
var rulesList = new NodeList(InnerRoot.Rules).ReducedFrom<NodeList>(this);
if (features)
{
return new Media(features, rulesList);
}
return rulesList;
}
private bool IsOptionSet(ImportOptions options, ImportOptions test)
{
return (options & test) == test;
}
}
public class ReferenceVisitor : IVisitor {
public Node Visit(Node node) {
var ruleset = node as Ruleset;
if (ruleset != null) {
if (ruleset.Selectors != null) {
ruleset.Selectors.Accept(this);
ruleset.Selectors.IsReference = true;
}
if (ruleset.Rules != null) {
ruleset.Rules.Accept(this);
ruleset.Rules.IsReference = true;
}
}
var media = node as Media;
if (media != null) {
media.Ruleset.Accept(this);
}
var nodeList = node as NodeList;
if (nodeList != null) {
nodeList.Accept(this);
}
node.IsReference = true;
return node;
}
}
[Flags]
public enum ImportOptions {
Once = 1,
Multiple = 2,
Optional = 4,
Css = 8,
Less = 16,
Inline = 32,
Reference = 64
}
}
| |
using System;
using System.Reflection;
using AutoPatterns.Extensions;
namespace AutoPatterns.Runtime
{
#pragma warning disable 659 // abstract TypeKey overrides Equals, but GetHashCode is overridden by TypeKey's descendands, which produces warning 659.
public abstract class TypeKey : IEquatable<TypeKey>
{
public override bool Equals(object obj)
{
var other = obj as TypeKey;
if (other != null)
{
return Equals(other);
}
return base.Equals(obj);
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
public abstract bool Equals(TypeKey other);
//-----------------------------------------------------------------------------------------------------------------------------------------------------
public abstract int Count { get; }
//-----------------------------------------------------------------------------------------------------------------------------------------------------
public abstract object this[int index] { get; }
//-----------------------------------------------------------------------------------------------------------------------------------------------------
protected bool FieldsEqual<T>(T field1, T field2, bool isValueType)
{
if (!isValueType && ReferenceEquals(field1, null))
{
return ReferenceEquals(field2, null);
}
return field1.Equals(field2);
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
private static readonly string _s_typeFriendlyNamePunctuation = new string(new[] { '_', '_', '_', '_', '_' });
//-----------------------------------------------------------------------------------------------------------------------------------------------------
protected static string Format<T>(T value)
{
if (typeof(T) == typeof(Type))
{
var typeInfo = ((Type)(object)value).GetTypeInfo();
var friendlyName = typeInfo.FriendlyName(punctuation: _s_typeFriendlyNamePunctuation).Replace("+", "_");
return typeInfo.Namespace.Replace(".", "_") + "_" + friendlyName;
}
return value.ToString();
}
}
#pragma warning restore 659
//---------------------------------------------------------------------------------------------------------------------------------------------------------
public class TypeKey<T0> : TypeKey
{
private readonly T0 _value0;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public TypeKey(T0 value0)
{
_value0 = value0;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of TypeKey
public override bool Equals(TypeKey other)
{
var typedOther = other as TypeKey<T0>;
if (typedOther != null)
{
if (!FieldsEqual(_value0, typedOther._value0, _s_isValueType0))
{
return false;
}
return true;
}
return false;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override int Count => 1;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override object this[int index]
{
get
{
switch (index)
{
case 0: return _value0;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of Object
public override int GetHashCode()
{
var hashCode = 0;
if (_s_isValueType0 || !ReferenceEquals(_value0, null))
{
hashCode ^= _value0.GetHashCode();
}
return hashCode;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override string ToString()
{
return $"{Format(_value0)}";
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
private static readonly bool _s_isValueType0 = typeof(T0).GetTypeInfo().IsValueType;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
public class TypeKey<T0, T1> : TypeKey
{
private readonly T0 _value0;
private readonly T1 _value1;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public TypeKey(T0 value0, T1 value1)
{
_value0 = value0;
_value1 = value1;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of TypeKey
public override bool Equals(TypeKey other)
{
var typedOther = other as TypeKey<T0, T1>;
if (typedOther != null)
{
if (!FieldsEqual(_value0, typedOther._value0, _s_isValueType0))
{
return false;
}
if (!FieldsEqual(_value1, typedOther._value1, _s_isValueType1))
{
return false;
}
return true;
}
return false;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override int Count => 2;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override object this[int index]
{
get
{
switch (index)
{
case 0: return _value0;
case 1: return _value1;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of Object
public override int GetHashCode()
{
var hashCode = 0;
if (_s_isValueType0 || !ReferenceEquals(_value0, null))
{
hashCode ^= _value0.GetHashCode();
}
if (_s_isValueType1 || !ReferenceEquals(_value1, null))
{
hashCode ^= _value1.GetHashCode();
}
return hashCode;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override string ToString()
{
return $"{Format(_value0)}_{Format(_value1)}";
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
private static readonly bool _s_isValueType0 = typeof(T0).GetTypeInfo().IsValueType;
private static readonly bool _s_isValueType1 = typeof(T1).GetTypeInfo().IsValueType;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
public class TypeKey<T0, T1, T2> : TypeKey
{
private readonly T0 _value0;
private readonly T1 _value1;
private readonly T2 _value2;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public TypeKey(T0 value0, T1 value1, T2 value2)
{
_value0 = value0;
_value1 = value1;
_value2 = value2;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of TypeKey
public override bool Equals(TypeKey other)
{
var typedOther = other as TypeKey<T0, T1, T2>;
if (typedOther != null)
{
if (!FieldsEqual(_value0, typedOther._value0, _s_isValueType0))
{
return false;
}
if (!FieldsEqual(_value1, typedOther._value1, _s_isValueType1))
{
return false;
}
if (!FieldsEqual(_value2, typedOther._value2, _s_isValueType2))
{
return false;
}
return true;
}
return false;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override int Count => 3;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override object this[int index]
{
get
{
switch (index)
{
case 0: return _value0;
case 1: return _value1;
case 2: return _value2;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of Object
public override int GetHashCode()
{
var hashCode = 0;
if (_s_isValueType0 || !ReferenceEquals(_value0, null))
{
hashCode ^= _value0.GetHashCode();
}
if (_s_isValueType1 || !ReferenceEquals(_value1, null))
{
hashCode ^= _value1.GetHashCode();
}
if (_s_isValueType2 || !ReferenceEquals(_value2, null))
{
hashCode ^= _value2.GetHashCode();
}
return hashCode;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override string ToString()
{
return $"{Format(_value0)}_{Format(_value1)}_{Format(_value2)}";
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
private static readonly bool _s_isValueType0 = typeof(T0).GetTypeInfo().IsValueType;
private static readonly bool _s_isValueType1 = typeof(T1).GetTypeInfo().IsValueType;
private static readonly bool _s_isValueType2 = typeof(T2).GetTypeInfo().IsValueType;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
public class TypeKey<T0, T1, T2, T3> : TypeKey
{
private readonly T0 _value0;
private readonly T1 _value1;
private readonly T2 _value2;
private readonly T3 _value3;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public TypeKey(T0 value0, T1 value1, T2 value2, T3 value3)
{
_value0 = value0;
_value1 = value1;
_value2 = value2;
_value3 = value3;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of TypeKey
public override bool Equals(TypeKey other)
{
var typedOther = other as TypeKey<T0, T1, T2, T3>;
if (typedOther != null)
{
if (!FieldsEqual(_value0, typedOther._value0, _s_isValueType0))
{
return false;
}
if (!FieldsEqual(_value1, typedOther._value1, _s_isValueType1))
{
return false;
}
if (!FieldsEqual(_value2, typedOther._value2, _s_isValueType2))
{
return false;
}
if (!FieldsEqual(_value3, typedOther._value3, _s_isValueType3))
{
return false;
}
return true;
}
return false;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override int Count => 4;
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override object this[int index]
{
get
{
switch (index)
{
case 0: return _value0;
case 1: return _value1;
case 2: return _value2;
case 3: return _value3;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
#region Overrides of Object
public override int GetHashCode()
{
var hashCode = 0;
if (_s_isValueType0 || !ReferenceEquals(_value0, null))
{
hashCode ^= _value0.GetHashCode();
}
if (_s_isValueType1 || !ReferenceEquals(_value1, null))
{
hashCode ^= _value1.GetHashCode();
}
if (_s_isValueType2 || !ReferenceEquals(_value2, null))
{
hashCode ^= _value2.GetHashCode();
}
if (_s_isValueType3 || !ReferenceEquals(_value3, null))
{
hashCode ^= _value3.GetHashCode();
}
return hashCode;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public override string ToString()
{
return $"{Format(_value0)}_{Format(_value1)}_{Format(_value2)}_{Format(_value3)}";
}
#endregion
//-------------------------------------------------------------------------------------------------------------------------------------------------
private static readonly bool _s_isValueType0 = typeof(T0).GetTypeInfo().IsValueType;
private static readonly bool _s_isValueType1 = typeof(T1).GetTypeInfo().IsValueType;
private static readonly bool _s_isValueType2 = typeof(T2).GetTypeInfo().IsValueType;
private static readonly bool _s_isValueType3 = typeof(T3).GetTypeInfo().IsValueType;
}
}
| |
//
// Mono.Data.Sqlite.SQLiteParameter.cs
//
// Author(s):
// Robert Simpson (robert@blackcastlesoft.com)
//
// Adapted and modified for the Mono Project by
// Marek Habersack (grendello@gmail.com)
//
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
// Copyright (C) 2007 Marek Habersack
//
// 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.
//
/********************************************************
* ADO.NET 2.0 Data Provider for Sqlite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
#if NET_2_0
namespace Mono.Data.Sqlite
{
using System;
using System.Data;
using System.Data.Common;
using System.ComponentModel;
/// <summary>
/// Sqlite implementation of DbParameter.
/// </summary>
public sealed class SqliteParameter : DbParameter, ICloneable
{
/// <summary>
/// The data type of the parameter
/// </summary>
internal int _dbType;
/// <summary>
/// The version information for mapping the parameter
/// </summary>
private DataRowVersion _rowVersion;
/// <summary>
/// The value of the data in the parameter
/// </summary>
private Object _objValue;
/// <summary>
/// The source column for the parameter
/// </summary>
private string _sourceColumn;
/// <summary>
/// The column name
/// </summary>
private string _parameterName;
/// <summary>
/// The data size, unused by Sqlite
/// </summary>
private int _dataSize;
private bool _nullable;
private bool _nullMapping;
/// <summary>
/// Default constructor
/// </summary>
public SqliteParameter()
: this(null, (DbType)(-1), 0, null, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs a named parameter given the specified parameter name
/// </summary>
/// <param name="parameterName">The parameter name</param>
public SqliteParameter(string parameterName)
: this(parameterName, (DbType)(-1), 0, null, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs a named parameter given the specified parameter name and initial value
/// </summary>
/// <param name="parameterName">The parameter name</param>
/// <param name="value">The initial value of the parameter</param>
public SqliteParameter(string parameterName, object value)
: this(parameterName, (DbType)(-1), 0, null, DataRowVersion.Current)
{
Value = value;
}
/// <summary>
/// Constructs a named parameter of the specified type
/// </summary>
/// <param name="parameterName">The parameter name</param>
/// <param name="dbType">The datatype of the parameter</param>
public SqliteParameter(string parameterName, DbType dbType)
: this(parameterName, dbType, 0, null, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs a named parameter of the specified type and source column reference
/// </summary>
/// <param name="parameterName">The parameter name</param>
/// <param name="dbType">The data type</param>
/// <param name="sourceColumn">The source column</param>
public SqliteParameter(string parameterName, DbType dbType, string sourceColumn)
: this(parameterName, dbType, 0, sourceColumn, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs a named parameter of the specified type, source column and row version
/// </summary>
/// <param name="parameterName">The parameter name</param>
/// <param name="dbType">The data type</param>
/// <param name="sourceColumn">The source column</param>
/// <param name="rowVersion">The row version information</param>
public SqliteParameter(string parameterName, DbType dbType, string sourceColumn, DataRowVersion rowVersion)
: this(parameterName, dbType, 0, sourceColumn, rowVersion)
{
}
/// <summary>
/// Constructs an unnamed parameter of the specified data type
/// </summary>
/// <param name="dbType">The datatype of the parameter</param>
public SqliteParameter(DbType dbType)
: this(null, dbType, 0, null, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs an unnamed parameter of the specified data type and sets the initial value
/// </summary>
/// <param name="dbType">The datatype of the parameter</param>
/// <param name="value">The initial value of the parameter</param>
public SqliteParameter(DbType dbType, object value)
: this(null, dbType, 0, null, DataRowVersion.Current)
{
Value = value;
}
/// <summary>
/// Constructs an unnamed parameter of the specified data type and source column
/// </summary>
/// <param name="dbType">The datatype of the parameter</param>
/// <param name="sourceColumn">The source column</param>
public SqliteParameter(DbType dbType, string sourceColumn)
: this(null, dbType, 0, sourceColumn, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs an unnamed parameter of the specified data type, source column and row version
/// </summary>
/// <param name="dbType">The data type</param>
/// <param name="sourceColumn">The source column</param>
/// <param name="rowVersion">The row version information</param>
public SqliteParameter(DbType dbType, string sourceColumn, DataRowVersion rowVersion)
: this(null, dbType, 0, sourceColumn, rowVersion)
{
}
/// <summary>
/// Constructs a named parameter of the specified type and size
/// </summary>
/// <param name="parameterName">The parameter name</param>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
public SqliteParameter(string parameterName, DbType parameterType, int parameterSize)
: this(parameterName, parameterType, parameterSize, null, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs a named parameter of the specified type, size and source column
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
/// <param name="sourceColumn">The source column</param>
public SqliteParameter(string parameterName, DbType parameterType, int parameterSize, string sourceColumn)
: this(parameterName, parameterType, parameterSize, sourceColumn, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs a named parameter of the specified type, size, source column and row version
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
/// <param name="sourceColumn">The source column</param>
/// <param name="rowVersion">The row version information</param>
public SqliteParameter(string parameterName, DbType parameterType, int parameterSize, string sourceColumn, DataRowVersion rowVersion)
{
_parameterName = parameterName;
_dbType = (int)parameterType;
_sourceColumn = sourceColumn;
_rowVersion = rowVersion;
_objValue = null;
_dataSize = parameterSize;
_nullMapping = false;
_nullable = true;
}
private SqliteParameter(SqliteParameter source)
: this(source.ParameterName, (DbType)source._dbType, 0, source.Direction, source.IsNullable, 0, 0, source.SourceColumn, source.SourceVersion, source.Value)
{
_nullMapping = source._nullMapping;
}
/// <summary>
/// Constructs a named parameter of the specified type, size, source column and row version
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
/// <param name="direction">Only input parameters are supported in Sqlite</param>
/// <param name="isNullable">Ignored</param>
/// <param name="precision">Ignored</param>
/// <param name="scale">Ignored</param>
/// <param name="sourceColumn">The source column</param>
/// <param name="rowVersion">The row version information</param>
/// <param name="value">The initial value to assign the parameter</param>
#if !PLATFORM_COMPACTFRAMEWORK
[EditorBrowsable(EditorBrowsableState.Advanced)]
#endif
public SqliteParameter(string parameterName, DbType parameterType, int parameterSize, ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, DataRowVersion rowVersion, object value)
: this(parameterName, parameterType, parameterSize, sourceColumn, rowVersion)
{
Direction = direction;
IsNullable = isNullable;
Value = value;
}
/// <summary>
/// Constructs a named parameter, yet another flavor
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
/// <param name="direction">Only input parameters are supported in Sqlite</param>
/// <param name="precision">Ignored</param>
/// <param name="scale">Ignored</param>
/// <param name="sourceColumn">The source column</param>
/// <param name="rowVersion">The row version information</param>
/// <param name="sourceColumnNullMapping">Whether or not this parameter is for comparing NULL's</param>
/// <param name="value">The intial value to assign the parameter</param>
#if !PLATFORM_COMPACTFRAMEWORK
[EditorBrowsable(EditorBrowsableState.Advanced)]
#endif
public SqliteParameter(string parameterName, DbType parameterType, int parameterSize, ParameterDirection direction, byte precision, byte scale, string sourceColumn, DataRowVersion rowVersion, bool sourceColumnNullMapping, object value)
: this(parameterName, parameterType, parameterSize, sourceColumn, rowVersion)
{
Direction = direction;
SourceColumnNullMapping = sourceColumnNullMapping;
Value = value;
}
/// <summary>
/// Constructs an unnamed parameter of the specified type and size
/// </summary>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
public SqliteParameter(DbType parameterType, int parameterSize)
: this(null, parameterType, parameterSize, null, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs an unnamed parameter of the specified type, size, and source column
/// </summary>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
/// <param name="sourceColumn">The source column</param>
public SqliteParameter(DbType parameterType, int parameterSize, string sourceColumn)
: this(null, parameterType, parameterSize, sourceColumn, DataRowVersion.Current)
{
}
/// <summary>
/// Constructs an unnamed parameter of the specified type, size, source column and row version
/// </summary>
/// <param name="parameterType">The data type</param>
/// <param name="parameterSize">The size of the parameter</param>
/// <param name="sourceColumn">The source column</param>
/// <param name="rowVersion">The row version information</param>
public SqliteParameter(DbType parameterType, int parameterSize, string sourceColumn, DataRowVersion rowVersion)
: this(null, parameterType, parameterSize, sourceColumn, rowVersion)
{
}
/// <summary>
/// Whether or not the parameter can contain a null value
/// </summary>
public override bool IsNullable
{
get
{
return _nullable;
}
set
{
_nullable = value;
}
}
/// <summary>
/// Returns the datatype of the parameter
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[DbProviderSpecificTypeProperty(true)]
[RefreshProperties(RefreshProperties.All)]
#endif
public override DbType DbType
{
get
{
if (_dbType == -1) return DbType.String; // Unassigned default value is String
return (DbType)_dbType;
}
set
{
_dbType = (int)value;
}
}
/// <summary>
/// Supports only input parameters
/// </summary>
public override ParameterDirection Direction
{
get
{
return ParameterDirection.Input;
}
set
{
if (value != ParameterDirection.Input)
throw new NotSupportedException();
}
}
/// <summary>
/// Returns the parameter name
/// </summary>
public override string ParameterName
{
get
{
return _parameterName;
}
set
{
_parameterName = value;
}
}
/// <summary>
/// Not implemented
/// </summary>
public override void ResetDbType()
{
}
/// <summary>
/// Returns the size of the parameter
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[DefaultValue((int)0)]
#endif
public override int Size
{
get
{
return _dataSize;
}
set
{
_dataSize = value;
}
}
/// <summary>
/// Gets/sets the source column
/// </summary>
public override string SourceColumn
{
get
{
return _sourceColumn;
}
set
{
_sourceColumn = value;
}
}
/// <summary>
/// Used by DbCommandBuilder to determine the mapping for nullable fields
/// </summary>
public override bool SourceColumnNullMapping
{
get
{
return _nullMapping;
}
set
{
_nullMapping = value;
}
}
/// <summary>
/// Gets and sets the row version
/// </summary>
public override DataRowVersion SourceVersion
{
get
{
return _rowVersion;
}
set
{
_rowVersion = value;
}
}
/// <summary>
/// Gets and sets the parameter value. If no datatype was specified, the datatype will assume the type from the value given.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[TypeConverter(typeof(StringConverter)), RefreshProperties(RefreshProperties.All)]
#endif
public override object Value
{
get
{
return _objValue;
}
set
{
_objValue = value;
if (_dbType == -1 && _objValue != null && _objValue != DBNull.Value) // If the DbType has never been assigned, try to glean one from the value's datatype
_dbType = (int)SqliteConvert.TypeToDbType(_objValue.GetType());
}
}
/// <summary>
/// Clones a parameter
/// </summary>
/// <returns>A new, unassociated SqliteParameter</returns>
public object Clone()
{
SqliteParameter newparam = new SqliteParameter(this);
return newparam;
}
}
}
#endif
| |
using System;
using System.IO;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Asn1
{
/**
* Class representing the DER-type External
*/
public class DerExternal
: Asn1Object
{
private DerObjectIdentifier directReference;
private DerInteger indirectReference;
private Asn1Object dataValueDescriptor;
private int encoding;
private Asn1Object externalContent;
public DerExternal(
Asn1EncodableVector vector)
{
int offset = 0;
Asn1Object enc = GetObjFromVector(vector, offset);
if (enc is DerObjectIdentifier)
{
directReference = (DerObjectIdentifier)enc;
offset++;
enc = GetObjFromVector(vector, offset);
}
if (enc is DerInteger)
{
indirectReference = (DerInteger) enc;
offset++;
enc = GetObjFromVector(vector, offset);
}
if (!(enc is DerTaggedObject))
{
dataValueDescriptor = (Asn1Object) enc;
offset++;
enc = GetObjFromVector(vector, offset);
}
if (!(enc is DerTaggedObject))
{
throw new InvalidOperationException(
"No tagged object found in vector. Structure doesn't seem to be of type External");
}
if (vector.Count != offset + 1)
throw new ArgumentException("input vector too large", "vector");
if (!(enc is DerTaggedObject))
throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector");
DerTaggedObject obj = (DerTaggedObject)enc;
// Use property accessor to include check on value
Encoding = obj.TagNo;
if (encoding < 0 || encoding > 2)
throw new InvalidOperationException("invalid encoding value");
externalContent = obj.GetObject();
}
/**
* Creates a new instance of DerExternal
* See X.690 for more informations about the meaning of these parameters
* @param directReference The direct reference or <code>null</code> if not set.
* @param indirectReference The indirect reference or <code>null</code> if not set.
* @param dataValueDescriptor The data value descriptor or <code>null</code> if not set.
* @param externalData The external data in its encoded form.
*/
public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData)
: this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object())
{
}
/**
* Creates a new instance of DerExternal.
* See X.690 for more informations about the meaning of these parameters
* @param directReference The direct reference or <code>null</code> if not set.
* @param indirectReference The indirect reference or <code>null</code> if not set.
* @param dataValueDescriptor The data value descriptor or <code>null</code> if not set.
* @param encoding The encoding to be used for the external data
* @param externalData The external data
*/
public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, int encoding, Asn1Object externalData)
{
DirectReference = directReference;
IndirectReference = indirectReference;
DataValueDescriptor = dataValueDescriptor;
Encoding = encoding;
ExternalContent = externalData.ToAsn1Object();
}
internal override void Encode(DerOutputStream derOut)
{
MemoryStream ms = new MemoryStream();
WriteEncodable(ms, directReference);
WriteEncodable(ms, indirectReference);
WriteEncodable(ms, dataValueDescriptor);
WriteEncodable(ms, new DerTaggedObject(Asn1Tags.External, externalContent));
derOut.WriteEncoded(Asn1Tags.Constructed, Asn1Tags.External, ms.ToArray());
}
protected override int Asn1GetHashCode()
{
int ret = externalContent.GetHashCode();
if (directReference != null)
{
ret ^= directReference.GetHashCode();
}
if (indirectReference != null)
{
ret ^= indirectReference.GetHashCode();
}
if (dataValueDescriptor != null)
{
ret ^= dataValueDescriptor.GetHashCode();
}
return ret;
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
if (this == asn1Object)
return true;
DerExternal other = asn1Object as DerExternal;
if (other == null)
return false;
return Platform.Equals(directReference, other.directReference)
&& Platform.Equals(indirectReference, other.indirectReference)
&& Platform.Equals(dataValueDescriptor, other.dataValueDescriptor)
&& externalContent.Equals(other.externalContent);
}
public Asn1Object DataValueDescriptor
{
get { return dataValueDescriptor; }
set { this.dataValueDescriptor = value; }
}
public DerObjectIdentifier DirectReference
{
get { return directReference; }
set { this.directReference = value; }
}
/**
* The encoding of the content. Valid values are
* <ul>
* <li><code>0</code> single-ASN1-type</li>
* <li><code>1</code> OCTET STRING</li>
* <li><code>2</code> BIT STRING</li>
* </ul>
*/
public int Encoding
{
get
{
return encoding;
}
set
{
if (encoding < 0 || encoding > 2)
throw new InvalidOperationException("invalid encoding value: " + encoding);
this.encoding = value;
}
}
public Asn1Object ExternalContent
{
get { return externalContent; }
set { this.externalContent = value; }
}
public DerInteger IndirectReference
{
get { return indirectReference; }
set { this.indirectReference = value; }
}
private static Asn1Object GetObjFromVector(Asn1EncodableVector v, int index)
{
if (v.Count <= index)
throw new ArgumentException("too few objects in input vector", "v");
return v[index].ToAsn1Object();
}
private static void WriteEncodable(MemoryStream ms, Asn1Encodable e)
{
if (e != null)
{
byte[] bs = e.GetDerEncoded();
ms.Write(bs, 0, bs.Length);
}
}
}
}
| |
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */
//2018-02-24: Added option to raise event on read/write instead of using registry.
//2010-10-31: Added option to skip registry writes (NoRegistryWrites).
//2010-10-17: Limited all loaded forms to screen's working area.
// Changed LoadNowAndSaveOnClose to use SetupOnLoadAndClose.
//2009-07-04: Compatibility with Mono 2.4.
//2008-12-27: Added LoadNowAndSaveOnClose method.
//2008-07-10: Fixed resize on load when window is maximized.
//2008-05-11: Windows with fixed borders are no longer resized.
//2008-04-11: Cleaned code to match FxCop 1.36 beta 2 (CompoundWordsShouldBeCasedCorrectly).
//2008-02-15: Fixed bug with positioning of centered forms.
//2008-01-31: Fixed bug that caused only first control to be loaded/saved.
//2008-01-10: Moved private methods to Helper class.
//2008-01-05: Removed obsoleted methods.
//2008-01-02: Calls to MoveSplitterTo method are now checked.
//2007-12-27: Added Load overloads for multiple controls.
// Obsoleted Subscribe method.
//2007-12-24: Changed SubKeyPath to include full path.
//2007-11-21: Initial version.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Medo.Windows.Forms {
/// <summary>
/// Enables storing and loading of windows control's state.
/// It is written in State key at HKEY_CURRENT_USER branch withing SubKeyPath of Settings class.
/// This class is not thread-safe since it should be called only from one thread - one that has interface.
/// </summary>
public static class State {
private static string _subkeyPath;
/// <summary>
/// Gets/sets subkey used for registry storage.
/// </summary>
public static string SubkeyPath {
get {
if (_subkeyPath == null) {
var assembly = Assembly.GetEntryAssembly();
string company = null;
var companyAttributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
if ((companyAttributes != null) && (companyAttributes.Length >= 1)) {
company = ((AssemblyCompanyAttribute)companyAttributes[companyAttributes.Length - 1]).Company;
}
string product = null;
var productAttributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
if ((productAttributes != null) && (productAttributes.Length >= 1)) {
product = ((AssemblyProductAttribute)productAttributes[productAttributes.Length - 1]).Product;
} else {
var titleAttributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), true);
if ((titleAttributes != null) && (titleAttributes.Length >= 1)) {
product = ((AssemblyTitleAttribute)titleAttributes[titleAttributes.Length - 1]).Title;
} else {
product = assembly.GetName().Name;
}
}
var path = "Software";
if (!string.IsNullOrEmpty(company)) { path += "\\" + company; }
if (!string.IsNullOrEmpty(product)) { path += "\\" + product; }
_subkeyPath = path + "\\State";
}
return _subkeyPath;
}
set { _subkeyPath = value; }
}
/// <summary>
/// Gets/sets whether settings should be written to registry.
/// </summary>
public static bool NoRegistryWrites { get; set; }
#region Load Save - All
/// <summary>
/// Loads previous state.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="form">Form on which's FormClosing handler this function will attach. State will not be altered for this parameter.</param>
/// <param name="controls">Controls to load and to save.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
/// <exception cref="ArgumentException">Form already used.</exception>
[Obsolete("Use SetupOnLoadAndClose instead.")]
public static void LoadNowAndSaveOnClose(Form form, params Control[] controls) {
SetupOnLoadAndClose(form, controls);
}
/// <summary>
/// Loads previous state.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="form">Form on which's FormClosing handler this function will attach. State will not be altered for this parameter.</param>
/// <param name="controls">Controls to load and to save.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
/// <exception cref="ArgumentException">Form setup already done.</exception>
public static void SetupOnLoadAndClose(Form form, params Control[] controls) {
if (form == null) { throw new ArgumentNullException("form", "Form is null."); }
if (formSetup.ContainsKey(form)) { throw new ArgumentException("Form setup already done.", "form"); }
Load(form);
if (controls != null) { Load(controls); }
formSetup.Add(form, controls);
form.Load += new EventHandler(form_Load);
form.FormClosed += new FormClosedEventHandler(form_FormClosed);
}
private static Dictionary<Form, Control[]> formSetup = new Dictionary<Form, Control[]>();
private static void form_Load(object sender, EventArgs e) {
var form = sender as Form;
if (formSetup.ContainsKey(form)) {
Load(form);
Load(formSetup[form]);
}
}
private static void form_FormClosed(object sender, FormClosedEventArgs e) {
var form = sender as Form;
if (formSetup.ContainsKey(form)) {
Save(form);
Save(formSetup[form]);
formSetup.Remove(form);
}
}
/// <summary>
/// Loads previous state.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="controls">Controls to load.</param>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Load(params Control[] controls) {
if (controls == null) { return; }
for (var i = 0; i < controls.Length; ++i) {
if (controls[i] is Form form) {
Load(form);
} else if (controls[i] is PropertyGrid propertyGrid) {
Load(propertyGrid);
} else if (controls[i] is ListView listView) {
Load(listView);
} else if (controls[i] is SplitContainer splitContainer) {
Load(splitContainer);
}
}
}
/// <summary>
/// Saves control's state.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="controls">Controls to save.</param>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Save(params Control[] controls) {
if (controls == null) { return; }
for (var i = 0; i < controls.Length; ++i) {
if (controls[i] is Form form) {
Save(form);
} else if (controls[i] is PropertyGrid propertyGrid) {
Save(propertyGrid);
} else if (controls[i] is ListView listView) {
Save(listView);
} else if (controls[i] is SplitContainer splitContainer) {
Save(splitContainer);
}
}
}
#endregion
#region Load Save - Form
/// <summary>
/// Saves Form state (Left,Top,Width,Height,WindowState).
/// </summary>
/// <param name="form">Form.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Save(Form form) {
if (form == null) { throw new ArgumentNullException("form", "Form is null."); }
var baseValueName = Helper.GetControlPath(form);
Write(baseValueName + ".WindowState", Convert.ToInt32(form.WindowState, CultureInfo.InvariantCulture));
if (form.WindowState == FormWindowState.Normal) {
Write(baseValueName + ".Left", form.Bounds.Left);
Write(baseValueName + ".Top", form.Bounds.Top);
Write(baseValueName + ".Width", form.Bounds.Width);
Write(baseValueName + ".Height", form.Bounds.Height);
} else {
Write(baseValueName + ".Left", form.RestoreBounds.Left);
Write(baseValueName + ".Top", form.RestoreBounds.Top);
Write(baseValueName + ".Width", form.RestoreBounds.Width);
Write(baseValueName + ".Height", form.RestoreBounds.Height);
}
}
/// <summary>
/// Loads previous Form state (Left,Top,Width,Height,WindowState).
/// If StartupPosition value is Manual, saved settings are used, for other types, it tryes to resemble original behaviour.
/// </summary>
/// <param name="form">Form.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Load(Form form) {
if (form == null) { throw new ArgumentNullException("form", "Form is null."); }
var baseValueName = Helper.GetControlPath(form);
var currWindowState = Convert.ToInt32(form.WindowState, CultureInfo.InvariantCulture);
int currLeft, currTop, currWidth, currHeight;
if (form.WindowState == FormWindowState.Normal) {
currLeft = form.Bounds.Left;
currTop = form.Bounds.Top;
currWidth = form.Bounds.Width;
currHeight = form.Bounds.Height;
} else {
currLeft = form.RestoreBounds.Left;
currTop = form.RestoreBounds.Top;
currWidth = form.RestoreBounds.Width;
currHeight = form.RestoreBounds.Height;
}
var newLeft = Read(baseValueName + ".Left", currLeft);
var newTop = Read(baseValueName + ".Top", currTop);
var newWidth = Read(baseValueName + ".Width", currWidth);
var newHeight = Read(baseValueName + ".Height", currHeight);
var newWindowState = Read(baseValueName + ".WindowState", currWindowState);
if ((form.FormBorderStyle == FormBorderStyle.Fixed3D) || (form.FormBorderStyle == FormBorderStyle.FixedDialog) || (form.FormBorderStyle == FormBorderStyle.FixedSingle) || (form.FormBorderStyle == FormBorderStyle.FixedToolWindow)) {
newWidth = currWidth;
newHeight = currHeight;
}
var screen = Screen.FromRectangle(new Rectangle(newLeft, newTop, newWidth, newHeight));
switch (form.StartPosition) {
case FormStartPosition.CenterParent: {
if (form.Parent != null) {
newLeft = form.Parent.Left + (form.Parent.Width - newWidth) / 2;
newTop = form.Parent.Top + (form.Parent.Height - newHeight) / 2;
} else if (form.Owner != null) {
newLeft = form.Owner.Left + (form.Owner.Width - newWidth) / 2;
newTop = form.Owner.Top + (form.Owner.Height - newHeight) / 2;
} else {
newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth) / 2;
newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight) / 2;
}
}
break;
case FormStartPosition.CenterScreen: {
newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth) / 2;
newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight) / 2;
}
break;
}
if (newWidth <= 0) { newWidth = currWidth; }
if (newHeight <= 0) { newHeight = currHeight; }
if (newWidth > screen.WorkingArea.Width) { newWidth = screen.WorkingArea.Width; }
if (newHeight > screen.WorkingArea.Height) { newHeight = screen.WorkingArea.Height; }
if (newLeft + newWidth > screen.WorkingArea.Right) { newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth); }
if (newTop + newHeight > screen.WorkingArea.Bottom) { newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight); }
if (newLeft < screen.WorkingArea.Left) { newLeft = screen.WorkingArea.Left; }
if (newTop < screen.WorkingArea.Top) { newTop = screen.WorkingArea.Top; }
form.Location = new Point(newLeft, newTop);
form.Size = new Size(newWidth, newHeight);
if (newWindowState == Convert.ToInt32(FormWindowState.Maximized, CultureInfo.InvariantCulture)) {
form.WindowState = FormWindowState.Maximized;
} //no need for any code - it is already either in normal state or minimized (will be restored to normal).
}
#endregion
#region Load Save - PropertyGrid
/// <summary>
/// Loads previous PropertyGrid state (LabelWidth, PropertySort).
/// </summary>
/// <param name="control">PropertyGrid.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "PropertyGrid is passed because of reflection upon its member.")]
public static void Load(PropertyGrid control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
try {
control.PropertySort = (PropertySort)(Read(baseValueName + ".PropertySort", Convert.ToInt32(control.PropertySort, CultureInfo.InvariantCulture)));
} catch (InvalidEnumArgumentException) { }
var fieldGridView = control.GetType().GetField("gridView", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
var gridViewObject = fieldGridView.GetValue(control);
if (gridViewObject != null) {
var currentlabelWidth = 0;
var propertyInternalLabelWidth = gridViewObject.GetType().GetProperty("InternalLabelWidth", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance);
if (propertyInternalLabelWidth != null) {
var val = propertyInternalLabelWidth.GetValue(gridViewObject, null);
if (val is int) {
currentlabelWidth = (int)val;
}
}
var labelWidth = Read(baseValueName + ".LabelWidth", currentlabelWidth);
if ((labelWidth > 0) && (labelWidth < control.Width)) {
var methodMoveSplitterToFlags = BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance;
var methodMoveSplitterTo = gridViewObject.GetType().GetMethod("MoveSplitterTo", methodMoveSplitterToFlags);
if (methodMoveSplitterTo != null) {
methodMoveSplitterTo.Invoke(gridViewObject, methodMoveSplitterToFlags, null, new object[] { labelWidth }, CultureInfo.CurrentCulture);
}
}
}
}
/// <summary>
/// Saves PropertyGrid state (LabelWidth).
/// </summary>
/// <param name="control">PropertyGrid.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "PropertyGrid is passed because of reflection upon its member.")]
public static void Save(PropertyGrid control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
Write(baseValueName + ".PropertySort", Convert.ToInt32(control.PropertySort, CultureInfo.InvariantCulture));
var fieldGridView = control.GetType().GetField("gridView", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
var gridViewObject = fieldGridView.GetValue(control);
if (gridViewObject != null) {
var propertyInternalLabelWidth = gridViewObject.GetType().GetProperty("InternalLabelWidth", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance);
if (propertyInternalLabelWidth != null) {
var val = propertyInternalLabelWidth.GetValue(gridViewObject, null);
if (val is int) {
Write(baseValueName + ".LabelWidth", (int)val);
}
}
}
}
#endregion
#region Load Save - ListView
/// <summary>
/// Loads previous ListView state (Column header width).
/// </summary>
/// <param name="control">ListView.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Load(ListView control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
for (var i = 0; i < control.Columns.Count; i++) {
var width = Read(baseValueName + ".ColumnHeaderWidth[" + i.ToString(CultureInfo.InvariantCulture) + "]", control.Columns[i].Width);
if (width > control.ClientRectangle.Width) { width = control.ClientRectangle.Width; }
control.Columns[i].Width = width;
}
}
/// <summary>
/// Saves ListView state (Column header width).
/// </summary>
/// <param name="control">ListView.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Save(ListView control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
for (var i = 0; i < control.Columns.Count; i++) {
Write(baseValueName + ".ColumnHeaderWidth[" + i.ToString(CultureInfo.InvariantCulture) + "]", control.Columns[i].Width);
}
}
#endregion
#region Load Save - SplitContainer
/// <summary>
/// Loads previous SplitContainer state.
/// </summary>
/// <param name="control">SplitContainer.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Load(SplitContainer control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
try {
control.Orientation = (Orientation)(Read(baseValueName + ".Orientation", Convert.ToInt32(control.Orientation, CultureInfo.InvariantCulture)));
} catch (InvalidEnumArgumentException) { }
try {
var distance = Read(baseValueName + ".SplitterDistance", control.SplitterDistance);
try {
control.SplitterDistance = distance;
} catch (ArgumentOutOfRangeException) { }
} catch (InvalidEnumArgumentException) { }
}
/// <summary>
/// Saves SplitContainer state.
/// </summary>
/// <param name="control">SplitContainer.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Save(SplitContainer control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
Write(baseValueName + ".Orientation", Convert.ToInt32(control.Orientation, CultureInfo.InvariantCulture));
Write(baseValueName + ".SplitterDistance", control.SplitterDistance);
}
#endregion
#region Store
/// <summary>
/// Event handler used to read state.
/// If used, registry is not read.
/// </summary>
public static event EventHandler<StateReadEventArgs> ReadState;
/// <summary>
/// Event handler used to write state.
/// If used, registry is not written to.
/// </summary>
public static event EventHandler<StateWriteEventArgs> WriteState;
private static void Write(string valueName, int value) {
var ev = WriteState;
if (ev != null) {
ev.Invoke(null, new StateWriteEventArgs(valueName, value));
} else {
Helper.RegistryWrite(valueName, value);
}
}
private static int Read(string valueName, int defaultValue) {
var ev = ReadState;
if (ev != null) {
var state = new StateReadEventArgs(valueName, defaultValue);
ev.Invoke(null, state);
return state.Value;
} else {
return Helper.RegistryRead(valueName, defaultValue);
}
}
#endregion Store
private static class Helper {
internal static void RegistryWrite(string valueName, int value) {
if (State.NoRegistryWrites == false) {
try {
if (State.SubkeyPath.Length == 0) { return; }
using (var rk = Registry.CurrentUser.CreateSubKey(State.SubkeyPath)) {
if (rk != null) {
rk.SetValue(valueName, value, RegistryValueKind.DWord);
}
}
} catch (IOException) { //key is deleted.
} catch (UnauthorizedAccessException) { } //key is write protected.
}
}
internal static int RegistryRead(string valueName, int defaultValue) {
try {
using (var rk = Registry.CurrentUser.OpenSubKey(State.SubkeyPath, false)) {
if (rk != null) {
var value = rk.GetValue(valueName, null);
if (value == null) { return defaultValue; }
var valueKind = RegistryValueKind.DWord;
if (!State.Helper.IsRunningOnMono) { valueKind = rk.GetValueKind(valueName); }
if ((value != null) && (valueKind == RegistryValueKind.DWord)) {
return (int)value;
}
}
}
} catch (SecurityException) { }
return defaultValue;
}
internal static string GetControlPath(Control control) {
var sbPath = new StringBuilder();
var currControl = control;
while (true) {
var parentControl = currControl.Parent;
if (parentControl == null) {
if (sbPath.Length > 0) { sbPath.Insert(0, "."); }
sbPath.Insert(0, currControl.GetType().FullName);
break;
} else {
if (string.IsNullOrEmpty(currControl.Name)) {
throw new NotSupportedException("This control's parents cannot be resolved using Name property.");
} else {
if (sbPath.Length > 0) { sbPath.Insert(0, "."); }
sbPath.Insert(0, currControl.Name);
}
}
currControl = parentControl;
}
return sbPath.ToString();
}
private static bool IsRunningOnMono {
get {
return (Type.GetType("Mono.Runtime") != null);
}
}
}
}
/// <summary>
/// State read event arguments.
/// </summary>
public class StateReadEventArgs : EventArgs {
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="name">Property name.</param>
/// <param name="defaultValue">Default property value.</param>
public StateReadEventArgs(string name, int defaultValue) {
if (name == null) { throw new ArgumentNullException(nameof(name), "Name cannot be null."); }
if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentOutOfRangeException(nameof(name), "Name cannot be empty."); }
Name = name;
DefaultValue = defaultValue;
Value = defaultValue;
}
/// <summary>
/// Gets property name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets default property value.
/// </summary>
public int DefaultValue { get; }
/// <summary>
/// Gets/sets property value.
/// </summary>
public int Value { get; set; }
}
/// <summary>
/// State write event arguments.
/// </summary>
public class StateWriteEventArgs : EventArgs {
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="name">Property name.</param>
/// <param name="value">Property value.</param>
public StateWriteEventArgs(string name, int value) {
if (name == null) { throw new ArgumentNullException(nameof(name), "Name cannot be null."); }
if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentOutOfRangeException(nameof(name), "Name cannot be empty."); }
Name = name;
Value = value;
}
/// <summary>
/// Gets property name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets property value.
/// </summary>
public int Value { get; }
}
}
| |
using System;
namespace DMatlab
{
public class SyntaxAnalyzer
{
public static Token CurrentToken;
private static System.Collections.IEnumerator TokenEnm;
private static void GetToken(){
if (TokenEnm.MoveNext())
CurrentToken = (Token)TokenEnm.Current;
else
CurrentToken = new Token(TokenType.END,"End");
}
private static void match(TokenType ExpectedTokenType,string ExpectedTokenValue){
if(CurrentToken.TType == ExpectedTokenType && CurrentToken.TokenValue == ExpectedTokenValue)
GetToken();
else
Error();
}
private static void Error(){
//System.Windows.Forms.MessageBox.Show("Error -- CurrentToken : " + CurrentToken.TType.ToString() + " : " + CurrentToken.TokenValue);
throw (new Exception(CurrentToken.TokenValue));
}
public static SyntaxTree GetTree(System.Collections.ArrayList Tokens){
TokenEnm = Tokens.GetEnumerator();
GetToken();
return StatementBlock();
}
private static SyntaxTree StatementBlock(){
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.BLOCK,"StatementBlock");
while(CurrentToken.TType != TokenType.END)
if(CurrentToken.TType == TokenType.DIRECTIVE){
temp.AddChild(Directive());
}else
temp.AddChild(Statement());
return temp;
}
private static SyntaxTree StatementBlock2(){
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.BLOCK,"StatementBlock");
match(TokenType.LCURBRACKET,"{");
while(CurrentToken.TType != TokenType.RCURBRACKET)
if(CurrentToken.TType == TokenType.DIRECTIVE)
{
temp.AddChild(Directive());
}
else
temp.AddChild(Statement());
match(TokenType.RCURBRACKET,"}");
return temp;
}
private static SyntaxTree Directive(){
match(TokenType.DIRECTIVE,"#PARALLEL");
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.BLOCK,"ParallelBlock");
temp.AddChild(Statement());
while(CurrentToken.TType != TokenType.DIRECTIVE)
temp.AddChild(Statement());
match(TokenType.DIRECTIVE,"#ENDPARALLEL");
return temp;
}
private static SyntaxTree ParallelBlock()
{
match(TokenType.KEYWORD ,"parallel");
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.BLOCK,"ParallelBlock");
match(TokenType.LCURBRACKET,"{");
while(CurrentToken.TType != TokenType.RCURBRACKET)
if(CurrentToken.TType == TokenType.DIRECTIVE)
{
temp.AddChild(Directive());
}
else
temp.AddChild(Statement());
match(TokenType.RCURBRACKET,"}");
return temp;
}
private static SyntaxTree Statement()
{
SyntaxTree temp;
switch(CurrentToken.TType)
{
case TokenType.IDENTIFIER:
temp= AssignmentExpression();
match(TokenType.SEMICOLON,";");
break;
case TokenType.FUNCTION:
temp= FunctionCall();
match(TokenType.SEMICOLON,";");
break;
case TokenType.PROCEDURE:
temp= Procedure();
match(TokenType.SEMICOLON,";");
break;
case TokenType.KEYWORD:
switch(CurrentToken.TokenValue){
case "if":
temp = IfKeyWord();
break;
case "for":
temp = ForKeyWord();
break;
case "while":
temp = WhileKeyWord();
break;
case "do":
temp = DoKeyWord();
break;
case "parallel":
temp = ParallelBlock();
break;
case "sequential":
match(TokenType.KEYWORD ,"sequential");
temp = StatementBlock2();
break;
default:
Error();
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OTHER,"ERROR");
break;
}
break;
default:
Error();
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OTHER,"ERROR");
break;
}
return temp;
}
private static SyntaxTree ForKeyWord()
{
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.STRUCTURE,"for");
match(TokenType.KEYWORD,"for");
match(TokenType.LPARAN,"(");
temp.AddChild(AssignmentExpression());
match(TokenType.SEMICOLON,";");
temp.AddChild(Conditions());
match(TokenType.SEMICOLON,";");
temp.AddChild(AssignmentExpression());
match(TokenType.RPARAN,")");
if(CurrentToken.TType == TokenType.LCURBRACKET)
temp.AddChild(StatementBlock2());
else
temp.AddChild(Statement());
return temp;
}
private static SyntaxTree WhileKeyWord()
{
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.STRUCTURE,"while");
match(TokenType.KEYWORD,"while");
match(TokenType.LPARAN,"(");
temp.AddChild(Conditions());
match(TokenType.RPARAN,")");
if(CurrentToken.TType == TokenType.LCURBRACKET)
temp.AddChild(StatementBlock2());
else
temp.AddChild(Statement());
return temp;
}
private static SyntaxTree DoKeyWord()
{
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.STRUCTURE,"do");
match(TokenType.KEYWORD,"do");
if(CurrentToken.TType == TokenType.LCURBRACKET)
temp.AddChild(StatementBlock2());
else
temp.AddChild(Statement());
match(TokenType.KEYWORD,"while");
match(TokenType.LPARAN,"(");
temp.AddChild(Conditions());
match(TokenType.RPARAN,")");
match(TokenType.SEMICOLON,";");
return temp;
}
private static SyntaxTree IfKeyWord(){
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.STRUCTURE,"if");
match(TokenType.KEYWORD,"if");
match(TokenType.LPARAN,"(");
temp.AddChild(Conditions());
match(TokenType.RPARAN,")");
if(CurrentToken.TType == TokenType.LCURBRACKET)
temp.AddChild(StatementBlock2());
else
temp.AddChild(Statement());
if(CurrentToken.TType == TokenType.KEYWORD && CurrentToken.TokenValue == "else")
{
match(TokenType.KEYWORD,"else");
if(CurrentToken.TType == TokenType.LCURBRACKET)
temp.AddChild(StatementBlock2());
else
temp.AddChild(Statement());
}
return temp;
}
private static SyntaxTree Conditions(){
SyntaxTree temp;
if(CurrentToken.TType == TokenType.LPARAN)
{
match(TokenType.LPARAN,"(");
temp = Conditions();
match(TokenType.RPARAN,")");
}else
temp = TestExpression();
while(CurrentToken.TType ==TokenType.LOGICAL_OPERATOR && CurrentToken.TokenValue !="!")
{
SyntaxTree newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,CurrentToken.TokenValue);
match(TokenType.LOGICAL_OPERATOR,CurrentToken.TokenValue);
newtemp.AddChild(temp);
if(CurrentToken.TType == TokenType.LPARAN)
{
temp = Conditions();
}
else
temp = TestExpression();
newtemp.AddChild(temp);
temp = newtemp;
}
return temp;
}
private static SyntaxTree TestExpression(){
SyntaxTree temp;
if(CurrentToken.TType == TokenType.LPARAN)
{
match(TokenType.LPARAN,"(");
temp = TestExpression();
match(TokenType.RPARAN,")");
}
else if(CurrentToken.TType == TokenType.LOGICAL_OPERATOR && CurrentToken.TokenValue == "!"){
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR ,"!");
match(TokenType.LOGICAL_OPERATOR,"!");
match(TokenType.LPARAN,"(");
temp.AddChild(Conditions());
match(TokenType.RPARAN,")");
}
else
{
SyntaxTree newtemp = Expression();
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,CurrentToken.TokenValue);
match(TokenType.REL_OPERATOR,CurrentToken.TokenValue);
temp.AddChild(newtemp);
newtemp = Expression();
temp.AddChild(newtemp);
}
return temp;
}
private static SyntaxTree AssignmentExpression()
{
SyntaxTree temp,newtemp;
temp = Identifier(); // SyntaxTree.MakeNode(SyntaxTreeNodeType.IDENTIFIER,CurrentToken.TokenValue);
//match(TokenType.IDENTIFIER,CurrentToken.TokenValue);
if(CurrentToken.TType == TokenType.INCREMENTDECREMENT)
{
newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,CurrentToken.TokenValue);
match(TokenType.INCREMENTDECREMENT,CurrentToken.TokenValue);
newtemp.AddChild(temp);
}
else
{
match(TokenType.OPERATOR ,"=");
newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,"=");
newtemp.AddChild(temp);
newtemp.AddChild(Expression());
}
return newtemp;
}
private static SyntaxTree Expression(){
SyntaxTree temp;
if(CurrentToken.TType == TokenType.OPERATOR && CurrentToken.TokenValue=="-")
{
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue );
temp.AddChild(Term());
}
else{
temp= Term();
}
while(CurrentToken.TType == TokenType.OPERATOR && (CurrentToken.TokenValue=="+" || CurrentToken.TokenValue=="-"))
{
SyntaxTree newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue );
newtemp.AddChild(temp);
newtemp.AddChild(Term());
temp = newtemp;
}
return temp;
}
private static SyntaxTree Term(){
SyntaxTree temp = Factor();
while(CurrentToken.TType == TokenType.OPERATOR && (CurrentToken.TokenValue=="*" || CurrentToken.TokenValue=="/")){
SyntaxTree newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue );
newtemp.AddChild(temp);
newtemp.AddChild(Factor());
temp = newtemp;
}
return temp;
}
private static SyntaxTree Factor(){
SyntaxTree temp;
switch (CurrentToken.TType){
case TokenType.LPARAN:
match(TokenType.LPARAN,"(");
temp = Expression();
match(TokenType.RPARAN,")");
break;
case TokenType.NUMBER:
temp = SyntaxTree.MakeNode (SyntaxTreeNodeType.NUMBER,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue );
break;
case TokenType.IDENTIFIER:
temp = Identifier(); //SyntaxTree.MakeNode (SyntaxTreeNodeType.IDENTIFIER,CurrentToken.TokenValue);
//match(CurrentToken.TType,CurrentToken.TokenValue );
break;
case TokenType.FUNCTION:
temp = FunctionCall();
break;
default:
Error();
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OTHER,"ERROR");
break;
}
while ((CurrentToken.TokenValue == "^" || CurrentToken.TokenValue == "%") && CurrentToken.TType == TokenType.OPERATOR){
SyntaxTree newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OPERATOR,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue );
newtemp.AddChild(temp);
if(CurrentToken.TType == TokenType.LPARAN)
{
match(TokenType.LPARAN,"(");
newtemp.AddChild(Expression());
match(TokenType.RPARAN,")");
}
else{
newtemp.AddChild(Factor());
}
temp = newtemp;
}
return temp;
}
private static SyntaxTree FunctionCall(){
if(CurrentToken.TokenValue == "DefineMatrix"){
return DefineMatrix();
}
SyntaxTree temp;
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.FUNCTION,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue);
match(TokenType.LPARAN,"(");
if(CurrentToken.TType == TokenType.RPARAN){
match(CurrentToken.TType,")");
return temp;
}
if(CurrentToken.TType == TokenType.LITERAL)
{
temp.AddChild(SyntaxTree.MakeNode(SyntaxTreeNodeType.LITERAL,CurrentToken.TokenValue));
match(CurrentToken.TType,CurrentToken.TokenValue);
}
else
temp.AddChild( Expression());
while(CurrentToken.TType == TokenType.COMMA){
match(CurrentToken.TType,CurrentToken.TokenValue);
if(CurrentToken.TType == TokenType.LITERAL)
{
temp.AddChild(SyntaxTree.MakeNode(SyntaxTreeNodeType.LITERAL,CurrentToken.TokenValue));
match(CurrentToken.TType,CurrentToken.TokenValue);
}
else
temp.AddChild( Expression());
}
match(TokenType.RPARAN,")");
return temp;
}
private static SyntaxTree Procedure()
{
SyntaxTree temp;
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.PROCEDURE,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue);
if(CurrentToken.TType == TokenType.LITERAL){
temp.AddChild(SyntaxTree.MakeNode(SyntaxTreeNodeType.LITERAL,CurrentToken.TokenValue));
match(CurrentToken.TType,CurrentToken.TokenValue);
}
else
temp.AddChild( Expression());
while(CurrentToken.TType == TokenType.COMMA)
{
match(CurrentToken.TType,CurrentToken.TokenValue);
if(CurrentToken.TType == TokenType.LITERAL){
temp.AddChild(SyntaxTree.MakeNode(SyntaxTreeNodeType.LITERAL,CurrentToken.TokenValue));
match(CurrentToken.TType,CurrentToken.TokenValue);
}
else
temp.AddChild( Expression());
}
return temp;
}
private static SyntaxTree DefineMatrix(){
SyntaxTree temp;
temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.FUNCTION,CurrentToken.TokenValue);
match(CurrentToken.TType,CurrentToken.TokenValue);
match(TokenType.LPARAN,"(");
int nrow=0;
temp.AddChild(MatrixRow(ref nrow));
while(CurrentToken.TType == TokenType.LSQUARE)
temp.AddChild(MatrixRow(ref nrow));
match(TokenType.RPARAN,")");
return temp;
}
private static SyntaxTree MatrixRow(ref int nrow){
match(TokenType.LSQUARE,"[");
int tnrow = 0;
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.OTHER,"ROW");
if(CurrentToken.TType != TokenType.NUMBER)Error();
SyntaxTree newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.NUMBER,CurrentToken.TokenValue);
match(TokenType.NUMBER,CurrentToken.TokenValue);
if(CurrentToken.TType == TokenType.COLON)
{
double st=0,inc=1,ed=0;
SyntaxTree newtemp2 = SyntaxTree.MakeNode(SyntaxTreeNodeType.OTHER,":");
newtemp2.AddChild(newtemp);
st = double.Parse(newtemp.NodeValue);
match(TokenType.COLON,":");
if(CurrentToken.TType != TokenType.NUMBER)Error();
newtemp = SyntaxTree.MakeNode(SyntaxTreeNodeType.NUMBER,CurrentToken.TokenValue);
match(TokenType.NUMBER,CurrentToken.TokenValue);
if(CurrentToken.TType == TokenType.COLON)
{
match(TokenType.COLON,":");
if(CurrentToken.TType != TokenType.NUMBER)Error();
newtemp2.AddChild(newtemp);
inc = double.Parse(newtemp.NodeValue);
newtemp2.AddChild(SyntaxTree.MakeNode(SyntaxTreeNodeType.NUMBER,CurrentToken.TokenValue));
ed = double.Parse(CurrentToken.TokenValue);
match(TokenType.NUMBER,CurrentToken.TokenValue);
}
else{
newtemp2.AddChild(SyntaxTree.MakeNode(SyntaxTreeNodeType.NUMBER,"1"));
ed = double.Parse(newtemp.NodeValue);
newtemp2.AddChild(newtemp);
}
temp.AddChild(newtemp2);
tnrow = (int)((ed-st)/inc)+1;
}
else
{
tnrow++;
temp.AddChild(newtemp);
while(CurrentToken.TType == TokenType.NUMBER)
{
temp.AddChild(SyntaxTree.MakeNode(SyntaxTreeNodeType.NUMBER,CurrentToken.TokenValue));
match(CurrentToken.TType,CurrentToken.TokenValue);
tnrow++;
}
}
if(tnrow==0)Error();
if(nrow>0 && tnrow!=nrow)
Error();
else
nrow = tnrow;
match(TokenType.RSQUARE,"]");
return temp;
}
private static SyntaxTree Identifier(){
SyntaxTree temp = SyntaxTree.MakeNode(SyntaxTreeNodeType.IDENTIFIER,CurrentToken.TokenValue);
match(TokenType.IDENTIFIER,CurrentToken.TokenValue);
if(CurrentToken.TType == TokenType.LSQUARE){
match(TokenType.LSQUARE,"[");
temp.AddChild(Expression());
match(TokenType.COMMA,",");
temp.AddChild(Expression());
match(TokenType.RSQUARE,"]");
}
return temp;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public partial class Scene
{
/// <summary>
/// Send chat to listeners.
/// </summary>
/// <param name='message'></param>
/// <param name='type'>/param>
/// <param name='channel'></param>
/// <param name='fromPos'></param>
/// <param name='fromName'></param>
/// <param name='fromID'></param>
/// <param name='targetID'></param>
/// <param name='fromAgent'></param>
/// <param name='broadcast'></param>
protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, UUID targetID, bool fromAgent, bool broadcast)
{
OSChatMessage args = new OSChatMessage();
args.Message = Utils.BytesToString(message);
args.Channel = channel;
args.Type = type;
args.Position = fromPos;
args.SenderUUID = fromID;
args.Scene = this;
if (fromAgent)
{
ScenePresence user = GetScenePresence(fromID);
if (user != null)
args.Sender = user.ControllingClient;
}
else
{
SceneObjectPart obj = GetSceneObjectPart(fromID);
args.SenderObject = obj;
}
args.From = fromName;
args.TargetUUID = targetID;
// m_log.DebugFormat(
// "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}",
// args.Message.Replace("\n", "\\n"), args.Channel, args.Type, fromName, broadcast);
if (broadcast)
EventManager.TriggerOnChatBroadcast(this, args);
else
EventManager.TriggerOnChatFromWorld(this, args);
}
protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent, bool broadcast)
{
SimChat(message, type, channel, fromPos, fromName, fromID, UUID.Zero, fromAgent, broadcast);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, false);
}
public void SimChat(string message, ChatTypeEnum type, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
{
SimChat(Utils.StringToBytes(message), type, 0, fromPos, fromName, fromID, fromAgent);
}
public void SimChat(string message, string fromName)
{
SimChat(message, ChatTypeEnum.Broadcast, Vector3.Zero, fromName, UUID.Zero, false);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
public void SimChatBroadcast(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
/// <param name="targetID"></param>
public void SimChatToAgent(UUID targetID, byte[] message, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
{
SimChat(message, ChatTypeEnum.Say, 0, fromPos, fromName, fromID, targetID, fromAgent, false);
}
/// <summary>
/// Invoked when the client requests a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void RequestPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectGroup sog = GetGroupByPrim(primLocalID);
if (sog != null)
sog.SendFullUpdateToClient(remoteClient);
}
/// <summary>
/// Invoked when the client selects a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (null == part)
return;
if (part.IsRoot)
{
SceneObjectGroup sog = part.ParentGroup;
sog.SendPropertiesToClient(remoteClient);
sog.IsSelected = true;
// A prim is only tainted if it's allowed to be edited by the person clicking it.
if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
|| Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
{
EventManager.TriggerParcelPrimCountTainted();
}
}
else
{
part.SendPropertiesToClient(remoteClient);
}
}
/// <summary>
/// Handle the update of an object's user group.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="groupID"></param>
/// <param name="objectLocalID"></param>
/// <param name="Garbage"></param>
private void HandleObjectGroupUpdate(
IClientAPI remoteClient, UUID groupID, uint objectLocalID, UUID Garbage)
{
if (m_groupsModule == null)
return;
// XXX: Might be better to get rid of this special casing and have GetMembershipData return something
// reasonable for a UUID.Zero group.
if (groupID != UUID.Zero)
{
GroupMembershipData gmd = m_groupsModule.GetMembershipData(groupID, remoteClient.AgentId);
if (gmd == null)
{
// m_log.WarnFormat(
// "[GROUPS]: User {0} is not a member of group {1} so they can't update {2} to this group",
// remoteClient.Name, GroupID, objectLocalID);
return;
}
}
SceneObjectGroup so = ((Scene)remoteClient.Scene).GetGroupByPrim(objectLocalID);
if (so != null)
{
if (so.OwnerID == remoteClient.AgentId)
{
so.SetGroup(groupID, remoteClient);
}
}
}
/// <summary>
/// Handle the deselection of a prim from the client.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void DeselectPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (part == null)
return;
// A deselect packet contains all the local prims being deselected. However, since selection is still
// group based we only want the root prim to trigger a full update - otherwise on objects with many prims
// we end up sending many duplicate ObjectUpdates
if (part.ParentGroup.RootPart.LocalId != part.LocalId)
return;
bool isAttachment = false;
// This is wrong, wrong, wrong. Selection should not be
// handled by group, but by prim. Legacy cruft.
// TODO: Make selection flagging per prim!
//
part.ParentGroup.IsSelected = false;
if (part.ParentGroup.IsAttachment)
isAttachment = true;
else
part.ParentGroup.ScheduleGroupForFullUpdate();
// If it's not an attachment, and we are allowed to move it,
// then we might have done so. If we moved across a parcel
// boundary, we will need to recount prims on the parcels.
// For attachments, that makes no sense.
//
if (!isAttachment)
{
if (Permissions.CanEditObject(
part.UUID, remoteClient.AgentId)
|| Permissions.CanMoveObject(
part.UUID, remoteClient.AgentId))
EventManager.TriggerParcelPrimCountTainted();
}
}
public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
int transactiontype, string description)
{
EventManager.MoneyTransferArgs args = new EventManager.MoneyTransferArgs(source, destination, amount,
transactiontype, description);
EventManager.TriggerMoneyTransfer(this, args);
}
public virtual void ProcessParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned,
bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated)
{
EventManager.LandBuyArgs args = new EventManager.LandBuyArgs(agentId, groupId, final, groupOwned,
removeContribution, parcelLocalID, parcelArea,
parcelPrice, authenticated);
// First, allow all validators a stab at it
m_eventManager.TriggerValidateLandBuy(this, args);
// Then, check validation and transfer
m_eventManager.TriggerLandBuy(this, args);
}
public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
return;
SceneObjectGroup obj = part.ParentGroup;
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
// Currently only grab/touch for the single prim
// the client handles rez correctly
obj.ObjectGrabHandler(localID, offsetPos, remoteClient);
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch_start) != 0)
EventManager.TriggerObjectGrab(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg);
// Deliver to the root prim if the touched prim doesn't handle touches
// or if we're meant to pass on touches anyway. Don't send to root prim
// if prim touched is the root prim as we just did it
if (((part.ScriptEvents & scriptEvents.touch_start) == 0) ||
(part.PassTouches && (part.LocalId != obj.RootPart.LocalId)))
{
EventManager.TriggerObjectGrab(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg);
}
}
public virtual void ProcessObjectGrabUpdate(
UUID objectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SceneObjectPart part = GetSceneObjectPart(objectID);
if (part == null)
return;
SceneObjectGroup obj = part.ParentGroup;
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch) != 0)
EventManager.TriggerObjectGrabbing(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg);
// Deliver to the root prim if the touched prim doesn't handle touches
// or if we're meant to pass on touches anyway. Don't send to root prim
// if prim touched is the root prim as we just did it
if (((part.ScriptEvents & scriptEvents.touch) == 0) ||
(part.PassTouches && (part.LocalId != obj.RootPart.LocalId)))
{
EventManager.TriggerObjectGrabbing(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg);
}
}
public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
return;
SceneObjectGroup obj = part.ParentGroup;
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch_end) != 0)
EventManager.TriggerObjectDeGrab(part.LocalId, 0, remoteClient, surfaceArg);
else
EventManager.TriggerObjectDeGrab(obj.RootPart.LocalId, part.LocalId, remoteClient, surfaceArg);
}
public void ProcessScriptReset(IClientAPI remoteClient, UUID objectID,
UUID itemID)
{
SceneObjectPart part=GetSceneObjectPart(objectID);
if (part == null)
return;
if (Permissions.CanResetScript(objectID, itemID, remoteClient.AgentId))
{
EventManager.TriggerScriptReset(part.LocalId, itemID);
}
}
void ProcessViewerEffect(IClientAPI remoteClient, List<ViewerEffectEventHandlerArg> args)
{
// TODO: don't create new blocks if recycling an old packet
bool discardableEffects = true;
ViewerEffectPacket.EffectBlock[] effectBlockArray = new ViewerEffectPacket.EffectBlock[args.Count];
for (int i = 0; i < args.Count; i++)
{
ViewerEffectPacket.EffectBlock effect = new ViewerEffectPacket.EffectBlock();
effect.AgentID = args[i].AgentID;
effect.Color = args[i].Color;
effect.Duration = args[i].Duration;
effect.ID = args[i].ID;
effect.Type = args[i].Type;
effect.TypeData = args[i].TypeData;
effectBlockArray[i] = effect;
if ((EffectType)effect.Type != EffectType.LookAt && (EffectType)effect.Type != EffectType.Beam)
discardableEffects = false;
//m_log.DebugFormat("[YYY]: VE {0} {1} {2}", effect.AgentID, effect.Duration, (EffectType)effect.Type);
}
ForEachScenePresence(sp =>
{
if (sp.ControllingClient.AgentId != remoteClient.AgentId)
{
if (!discardableEffects ||
(discardableEffects && ShouldSendDiscardableEffect(remoteClient, sp)))
{
//m_log.DebugFormat("[YYY]: Sending to {0}", sp.UUID);
sp.ControllingClient.SendViewerEffect(effectBlockArray);
}
//else
// m_log.DebugFormat("[YYY]: Not sending to {0}", sp.UUID);
}
});
}
private bool ShouldSendDiscardableEffect(IClientAPI thisClient, ScenePresence other)
{
return Vector3.Distance(other.CameraPosition, thisClient.SceneAgent.AbsolutePosition) < 10;
}
/// <summary>
/// Tell the client about the various child items and folders contained in the requested folder.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
public void HandleFetchInventoryDescendents(IClientAPI remoteClient, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder)
{
// m_log.DebugFormat(
// "[USER INVENTORY]: HandleFetchInventoryDescendents() for {0}, folder={1}, fetchFolders={2}, fetchItems={3}, sortOrder={4}",
// remoteClient.Name, folderID, fetchFolders, fetchItems, sortOrder);
if (folderID == UUID.Zero)
return;
// FIXME MAYBE: We're not handling sortOrder!
// TODO: This code for looking in the folder for the library should be folded somewhere else
// so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold = null;
if (LibraryService != null && LibraryService.LibraryRootFolder != null)
{
if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null)
{
remoteClient.SendInventoryFolderDetails(
fold.Owner, folderID, fold.RequestListOfItems(),
fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems);
return;
}
}
// We're going to send the reply async, because there may be
// an enormous quantity of packets -- basically the entire inventory!
// We don't want to block the client thread while all that is happening.
SendInventoryDelegate d = SendInventoryAsync;
d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d);
}
delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder);
void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder)
{
SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems);
}
void SendInventoryComplete(IAsyncResult iar)
{
SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
/// <summary>
/// Handle an inventory folder creation request from the client.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="folderType"></param>
/// <param name="folderName"></param>
/// <param name="parentID"></param>
public void HandleCreateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort folderType,
string folderName, UUID parentID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, remoteClient.AgentId, (short)folderType, parentID, 1);
if (!InventoryService.AddFolder(folder))
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Failed to create folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
}
/// <summary>
/// Handle a client request to update the inventory folder
/// </summary>
///
/// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE
/// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing,
/// and needs to be changed.
///
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="parentID"></param>
public void HandleUpdateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort type, string name,
UUID parentID)
{
// m_log.DebugFormat(
// "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId);
InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder);
if (folder != null)
{
folder.Name = name;
folder.Type = (short)type;
folder.ParentID = parentID;
if (!InventoryService.UpdateFolder(folder))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Failed to update folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
}
}
public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder);
if (folder != null)
{
folder.ParentID = parentID;
if (!InventoryService.MoveFolder(folder))
m_log.WarnFormat("[AGENT INVENTORY]: could not move folder {0}", folderID);
else
m_log.DebugFormat("[AGENT INVENTORY]: folder {0} moved to parent {1}", folderID, parentID);
}
else
{
m_log.WarnFormat("[AGENT INVENTORY]: request to move folder {0} but folder not found", folderID);
}
}
delegate void PurgeFolderDelegate(UUID userID, UUID folder);
/// <summary>
/// This should delete all the items and folders in the given directory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID)
{
PurgeFolderDelegate d = PurgeFolderAsync;
try
{
d.BeginInvoke(remoteClient.AgentId, folderID, PurgeFolderCompleted, d);
}
catch (Exception e)
{
m_log.WarnFormat("[AGENT INVENTORY]: Exception on purge folder for user {0}: {1}", remoteClient.AgentId, e.Message);
}
}
private void PurgeFolderAsync(UUID userID, UUID folderID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, userID);
if (InventoryService.PurgeFolder(folder))
m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID);
else
m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID);
}
private void PurgeFolderCompleted(IAsyncResult iar)
{
PurgeFolderDelegate d = (PurgeFolderDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
}
}
| |
// 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 gcsv = Google.Cloud.SecurityCenter.V1;
using sys = System;
namespace Google.Cloud.SecurityCenter.V1
{
/// <summary>Resource name for the <c>BigQueryExport</c> resource.</summary>
public sealed partial class BigQueryExportName : gax::IResourceName, sys::IEquatable<BigQueryExportName>
{
/// <summary>The possible contents of <see cref="BigQueryExportName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/bigQueryExports/{export}</c>.
/// </summary>
OrganizationExport = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/bigQueryExports/{export}</c>.</summary>
FolderExport = 2,
/// <summary>A resource name with pattern <c>projects/{project}/bigQueryExports/{export}</c>.</summary>
ProjectExport = 3,
}
private static gax::PathTemplate s_organizationExport = new gax::PathTemplate("organizations/{organization}/bigQueryExports/{export}");
private static gax::PathTemplate s_folderExport = new gax::PathTemplate("folders/{folder}/bigQueryExports/{export}");
private static gax::PathTemplate s_projectExport = new gax::PathTemplate("projects/{project}/bigQueryExports/{export}");
/// <summary>Creates a <see cref="BigQueryExportName"/> 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="BigQueryExportName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static BigQueryExportName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BigQueryExportName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BigQueryExportName"/> with the pattern
/// <c>organizations/{organization}/bigQueryExports/{export}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BigQueryExportName"/> constructed from the provided ids.</returns>
public static BigQueryExportName FromOrganizationExport(string organizationId, string exportId) =>
new BigQueryExportName(ResourceNameType.OrganizationExport, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), exportId: gax::GaxPreconditions.CheckNotNullOrEmpty(exportId, nameof(exportId)));
/// <summary>
/// Creates a <see cref="BigQueryExportName"/> with the pattern <c>folders/{folder}/bigQueryExports/{export}</c>
/// .
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BigQueryExportName"/> constructed from the provided ids.</returns>
public static BigQueryExportName FromFolderExport(string folderId, string exportId) =>
new BigQueryExportName(ResourceNameType.FolderExport, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), exportId: gax::GaxPreconditions.CheckNotNullOrEmpty(exportId, nameof(exportId)));
/// <summary>
/// Creates a <see cref="BigQueryExportName"/> with the pattern <c>projects/{project}/bigQueryExports/{export}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BigQueryExportName"/> constructed from the provided ids.</returns>
public static BigQueryExportName FromProjectExport(string projectId, string exportId) =>
new BigQueryExportName(ResourceNameType.ProjectExport, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), exportId: gax::GaxPreconditions.CheckNotNullOrEmpty(exportId, nameof(exportId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>organizations/{organization}/bigQueryExports/{export}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>organizations/{organization}/bigQueryExports/{export}</c>.
/// </returns>
public static string Format(string organizationId, string exportId) =>
FormatOrganizationExport(organizationId, exportId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>organizations/{organization}/bigQueryExports/{export}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>organizations/{organization}/bigQueryExports/{export}</c>.
/// </returns>
public static string FormatOrganizationExport(string organizationId, string exportId) =>
s_organizationExport.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(exportId, nameof(exportId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>folders/{folder}/bigQueryExports/{export}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>folders/{folder}/bigQueryExports/{export}</c>.
/// </returns>
public static string FormatFolderExport(string folderId, string exportId) =>
s_folderExport.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(exportId, nameof(exportId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>projects/{project}/bigQueryExports/{export}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BigQueryExportName"/> with pattern
/// <c>projects/{project}/bigQueryExports/{export}</c>.
/// </returns>
public static string FormatProjectExport(string projectId, string exportId) =>
s_projectExport.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(exportId, nameof(exportId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="BigQueryExportName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>folders/{folder}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>projects/{project}/bigQueryExports/{export}</c></description></item>
/// </list>
/// </remarks>
/// <param name="bigQueryExportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="BigQueryExportName"/> if successful.</returns>
public static BigQueryExportName Parse(string bigQueryExportName) => Parse(bigQueryExportName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BigQueryExportName"/> 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>organizations/{organization}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>folders/{folder}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>projects/{project}/bigQueryExports/{export}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="bigQueryExportName">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="BigQueryExportName"/> if successful.</returns>
public static BigQueryExportName Parse(string bigQueryExportName, bool allowUnparsed) =>
TryParse(bigQueryExportName, allowUnparsed, out BigQueryExportName 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="BigQueryExportName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>folders/{folder}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>projects/{project}/bigQueryExports/{export}</c></description></item>
/// </list>
/// </remarks>
/// <param name="bigQueryExportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BigQueryExportName"/>, 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 bigQueryExportName, out BigQueryExportName result) =>
TryParse(bigQueryExportName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BigQueryExportName"/> 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>organizations/{organization}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>folders/{folder}/bigQueryExports/{export}</c></description></item>
/// <item><description><c>projects/{project}/bigQueryExports/{export}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="bigQueryExportName">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="BigQueryExportName"/>, 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 bigQueryExportName, bool allowUnparsed, out BigQueryExportName result)
{
gax::GaxPreconditions.CheckNotNull(bigQueryExportName, nameof(bigQueryExportName));
gax::TemplatedResourceName resourceName;
if (s_organizationExport.TryParseName(bigQueryExportName, out resourceName))
{
result = FromOrganizationExport(resourceName[0], resourceName[1]);
return true;
}
if (s_folderExport.TryParseName(bigQueryExportName, out resourceName))
{
result = FromFolderExport(resourceName[0], resourceName[1]);
return true;
}
if (s_projectExport.TryParseName(bigQueryExportName, out resourceName))
{
result = FromProjectExport(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(bigQueryExportName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BigQueryExportName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string exportId = null, string folderId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ExportId = exportId;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BigQueryExportName"/> class from the component parts of pattern
/// <c>organizations/{organization}/bigQueryExports/{export}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="exportId">The <c>Export</c> ID. Must not be <c>null</c> or empty.</param>
public BigQueryExportName(string organizationId, string exportId) : this(ResourceNameType.OrganizationExport, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), exportId: gax::GaxPreconditions.CheckNotNullOrEmpty(exportId, nameof(exportId)))
{
}
/// <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>Export</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ExportId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>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.OrganizationExport: return s_organizationExport.Expand(OrganizationId, ExportId);
case ResourceNameType.FolderExport: return s_folderExport.Expand(FolderId, ExportId);
case ResourceNameType.ProjectExport: return s_projectExport.Expand(ProjectId, ExportId);
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 BigQueryExportName);
/// <inheritdoc/>
public bool Equals(BigQueryExportName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BigQueryExportName a, BigQueryExportName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BigQueryExportName a, BigQueryExportName b) => !(a == b);
}
public partial class BigQueryExport
{
/// <summary>
/// <see cref="gcsv::BigQueryExportName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::BigQueryExportName BigQueryExportName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::BigQueryExportName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
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 names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Text;
using System.IO;
using System.Collections;
using System.Globalization;
namespace MSNPSharp.Core
{
/// <summary>
/// MultiMime message for SDG/NFY/PUT/DEL commands.
/// </summary>
public class MultiMimeMessage : NetworkMessage
{
private MimeDictionary routingHeaders = new MimeDictionary();
private MimeDictionary reliabilityHeaders = new MimeDictionary();
private MimeDictionary contentHeaders = new MimeDictionary();
private string contentKey = MIMEContentHeaders.Messaging;
private string contentKeyVersion = "1.0";
public MimeDictionary RoutingHeaders
{
get
{
return routingHeaders;
}
}
public MimeDictionary ReliabilityHeaders
{
get
{
return reliabilityHeaders;
}
}
public MimeDictionary ContentHeaders
{
get
{
return contentHeaders;
}
}
public string ContentKey
{
get
{
return contentKey;
}
set
{
contentKey = value;
}
}
public string ContentKeyVersion
{
get
{
return contentKeyVersion;
}
set
{
contentKeyVersion = value;
}
}
public MultiMimeMessage()
{
}
public MultiMimeMessage(string to, string from)
{
To = to;
From = from;
contentHeaders[MIMEContentHeaders.ContentLength] = "0";
contentHeaders[MIMEContentHeaders.ContentType] = "Text/plain";
contentHeaders[MIMEContentHeaders.ContentType][MIMEContentHeaders.CharSet] = "UTF-8";
}
public MultiMimeMessage(byte[] data)
{
ParseBytes(data);
}
public MimeValue To
{
get
{
return routingHeaders[MIMERoutingHeaders.To];
}
set
{
routingHeaders[MIMERoutingHeaders.To] = value;
}
}
public MimeValue From
{
get
{
return routingHeaders[MIMERoutingHeaders.From];
}
set
{
routingHeaders[MIMERoutingHeaders.From] = value;
}
}
public long Stream
{
get
{
return reliabilityHeaders.ContainsKey(MIMEReliabilityHeaders.Stream) ?
long.Parse(reliabilityHeaders[MIMEReliabilityHeaders.Stream], System.Globalization.CultureInfo.InvariantCulture) : 0;
}
set
{
reliabilityHeaders[MIMEReliabilityHeaders.Stream] = value.ToString(CultureInfo.InvariantCulture);
}
}
public long Segment
{
get
{
return reliabilityHeaders.ContainsKey(MIMEReliabilityHeaders.Segment) ?
long.Parse(reliabilityHeaders[MIMEReliabilityHeaders.Segment], CultureInfo.InvariantCulture) : 0;
}
set
{
reliabilityHeaders[MIMEReliabilityHeaders.Segment] = value.ToString(CultureInfo.InvariantCulture);
}
}
public MimeValue ContentType
{
get
{
return contentHeaders[MIMEContentHeaders.ContentType];
}
set
{
contentHeaders[MIMEContentHeaders.ContentType] = value;
}
}
public override byte[] GetBytes()
{
if (InnerBody == null)
InnerBody = new byte[0];
contentHeaders[MIMEContentHeaders.ContentLength] = InnerBody.Length.ToString(CultureInfo.InvariantCulture);
StringBuilder sb = new StringBuilder(128);
//Do not use append line, because under *nix the line break is \n but MSN need \r\n
//sb.AppendLine(MIMERoutingHeaders.Routing + MIMEHeaderStrings.KeyValueSeparator + "1.0");
sb.Append(MIMERoutingHeaders.Routing + MIMEHeaderStrings.KeyValueSeparator + "1.0");
sb.Append("\r\n");
foreach (string key in routingHeaders.Keys)
{
if (key != MIMERoutingHeaders.Routing)
{
sb.Append(key + MIMEHeaderStrings.KeyValueSeparator + routingHeaders[key].ToString());
sb.Append("\r\n");
}
}
sb.Append("\r\n");
sb.Append(MIMEReliabilityHeaders.Reliability + MIMEHeaderStrings.KeyValueSeparator + "1.0");
sb.Append("\r\n");
foreach (string key in reliabilityHeaders.Keys)
{
if (key != MIMEReliabilityHeaders.Reliability)
{
sb.Append(key + MIMEHeaderStrings.KeyValueSeparator + reliabilityHeaders[key].ToString());
sb.Append("\r\n");
}
}
sb.Append("\r\n");
sb.Append(ContentKey + MIMEHeaderStrings.KeyValueSeparator + ContentKeyVersion);
sb.Append("\r\n");
foreach (string key in contentHeaders.Keys)
{
if (key != ContentKey)
{
sb.Append(key + MIMEHeaderStrings.KeyValueSeparator + contentHeaders[key].ToString());
sb.Append("\r\n");
}
}
sb.Append("\r\n");
return (InnerBody.Length > 0) ?
AppendArray(Encoding.UTF8.GetBytes(sb.ToString()), InnerBody)
:
Encoding.UTF8.GetBytes(sb.ToString());
}
public override void ParseBytes(byte[] data)
{
routingHeaders.Clear();
int routerHeaderEnd = routingHeaders.Parse(data);
byte[] reliabilityData = new byte[data.Length - routerHeaderEnd];
Buffer.BlockCopy(data, routerHeaderEnd, reliabilityData, 0, reliabilityData.Length);
reliabilityHeaders.Clear();
int reliabilityHeaderEnd = reliabilityHeaders.Parse(reliabilityData);
byte[] messagingData = new byte[data.Length - routerHeaderEnd - reliabilityHeaderEnd];
Buffer.BlockCopy(reliabilityData, reliabilityHeaderEnd, messagingData, 0, messagingData.Length);
contentHeaders.Clear();
int messagingHeaderEnd = contentHeaders.Parse(messagingData);
contentKey = contentHeaders.ContainsKey(MIMEContentHeaders.Publication)
? MIMEContentHeaders.Publication
: (contentHeaders.ContainsKey(MIMEContentHeaders.Notification) ? MIMEContentHeaders.Notification : MIMEContentHeaders.Messaging);
int bodyLen = data.Length - routerHeaderEnd - reliabilityHeaderEnd - messagingHeaderEnd;
int contentLen = bodyLen;
if ((bodyLen > 0)
||
(contentHeaders.ContainsKey(MIMEContentHeaders.ContentLength) &&
int.TryParse(contentHeaders[MIMEContentHeaders.ContentLength], NumberStyles.Integer, CultureInfo.InvariantCulture, out contentLen) && contentLen > 0 &&
contentLen <= bodyLen /*don't allow buffer overflow*/))
{
InnerBody = new byte[contentLen];
Buffer.BlockCopy(messagingData, messagingHeaderEnd, InnerBody, 0, InnerBody.Length);
}
else
{
InnerBody = new byte[0];
}
}
public override string ToString()
{
string contentEncoding = string.Empty;
string debugString = string.Empty;
if (ContentHeaders.ContainsKey(MIMEContentHeaders.ContentTransferEncoding) && InnerBody != null)
{
contentEncoding = ContentHeaders[MIMEContentHeaders.ContentTransferEncoding].Value;
}
byte[] readableBinaries = GetBytes();
switch (contentEncoding)
{
case MIMEContentTransferEncoding.Binary:
int payLoadLength = 0;
payLoadLength = InnerBody.Length;
byte[] headers = new byte[readableBinaries.Length - payLoadLength];
Buffer.BlockCopy(readableBinaries, 0, headers, 0, headers.Length);
if (InnerBody != null && InnerMessage == null)
{
if (ContentHeaders.ContainsKey(MIMEContentHeaders.BridgingOffsets))
{
debugString = Encoding.UTF8.GetString(headers) + "\r\nMulti-Package Binary Data: {Length: " + payLoadLength + "}";
}
else
{
debugString = Encoding.UTF8.GetString(headers) + "\r\nUnknown Binary Data: {Length: " + payLoadLength + "}";
}
}
if (InnerBody != null && InnerMessage != null)
{
debugString = Encoding.UTF8.GetString(headers) + "\r\n" + InnerMessage.ToString();
}
break;
default:
debugString = Encoding.UTF8.GetString(readableBinaries);
break;
}
return debugString;
}
}
};
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// Used by a project to query the environment for permission to add, remove, or rename a file or directory in a solution
/// </summary>
internal class TrackDocumentsHelper
{
#region fields
private ProjectNode projectMgr;
#endregion
#region properties
#endregion
#region ctors
internal TrackDocumentsHelper(ProjectNode project)
{
this.projectMgr = project;
}
#endregion
#region helper methods
/// <summary>
/// Gets the IVsTrackProjectDocuments2 object by asking the service provider for it.
/// </summary>
/// <returns>the IVsTrackProjectDocuments2 object</returns>
private IVsTrackProjectDocuments2 GetIVsTrackProjectDocuments2()
{
Debug.Assert(this.projectMgr != null && !this.projectMgr.IsClosed && this.projectMgr.Site != null);
IVsTrackProjectDocuments2 documentTracker = this.projectMgr.Site.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2;
if(documentTracker == null)
{
throw new InvalidOperationException();
}
return documentTracker;
}
/// <summary>
/// Asks the environment for permission to add files.
/// </summary>
/// <param name="files">The files to add.</param>
/// <param name="flags">The VSQUERYADDFILEFLAGS flags associated to the files added</param>
/// <returns>true if the file can be added, false if not.</returns>
internal bool CanAddItems(string[] files, VSQUERYADDFILEFLAGS[] flags)
{
// If we are silent then we assume that the file can be added, since we do not want to trigger this event.
if((this.projectMgr.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerTrackerEvents) != 0)
{
return true;
}
if(files == null || files.Length == 0)
{
return false;
}
int len = files.Length;
VSQUERYADDFILERESULTS[] summary = new VSQUERYADDFILERESULTS[1];
ErrorHandler.ThrowOnFailure(this.GetIVsTrackProjectDocuments2().OnQueryAddFiles(this.projectMgr.InteropSafeIVsProject3, len, files, flags, summary, null));
if(summary[0] == VSQUERYADDFILERESULTS.VSQUERYADDFILERESULTS_AddNotOK)
{
return false;
}
return true;
}
/// <summary>
/// Notify the environment about a file just added
/// </summary>
internal void OnItemAdded(string file, VSADDFILEFLAGS flag)
{
if((this.projectMgr.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerTrackerEvents) == 0)
{
ErrorHandler.ThrowOnFailure(this.GetIVsTrackProjectDocuments2().OnAfterAddFilesEx(this.projectMgr.InteropSafeIVsProject3, 1, new string[1] { file }, new VSADDFILEFLAGS[1] { flag }));
}
}
/// <summary>
/// Asks the environment for permission to remove files.
/// </summary>
/// <param name="files">an array of files to remove</param>
/// <param name="flags">The VSQUERYREMOVEFILEFLAGS associated to the files to be removed.</param>
/// <returns>true if the files can be removed, false if not.</returns>
internal bool CanRemoveItems(string[] files, VSQUERYREMOVEFILEFLAGS[] flags)
{
// If we are silent then we assume that the file can be removed, since we do not want to trigger this event.
if((this.projectMgr.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerTrackerEvents) != 0)
{
return true;
}
if(files == null || files.Length == 0)
{
return false;
}
int length = files.Length;
VSQUERYREMOVEFILERESULTS[] summary = new VSQUERYREMOVEFILERESULTS[1];
ErrorHandler.ThrowOnFailure(this.GetIVsTrackProjectDocuments2().OnQueryRemoveFiles(this.projectMgr.InteropSafeIVsProject3, length, files, flags, summary, null));
if(summary[0] == VSQUERYREMOVEFILERESULTS.VSQUERYREMOVEFILERESULTS_RemoveNotOK)
{
return false;
}
return true;
}
/// <summary>
/// Notify the environment about a file just removed
/// </summary>
internal void OnItemRemoved(string file, VSREMOVEFILEFLAGS flag)
{
if((this.projectMgr.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerTrackerEvents) == 0)
{
ErrorHandler.ThrowOnFailure(this.GetIVsTrackProjectDocuments2().OnAfterRemoveFiles(this.projectMgr.InteropSafeIVsProject3, 1, new string[1] { file }, new VSREMOVEFILEFLAGS[1] { flag }));
}
}
/// <summary>
/// Asks the environment for permission to rename files.
/// </summary>
/// <param name="oldFileName">Path to the file to be renamed.</param>
/// <param name="newFileName">Path to the new file.</param>
/// <param name="flag">The VSRENAMEFILEFLAGS associated with the file to be renamed.</param>
/// <returns>true if the file can be renamed. Otherwise false.</returns>
internal bool CanRenameItem(string oldFileName, string newFileName, VSRENAMEFILEFLAGS flag)
{
// If we are silent then we assume that the file can be renamed, since we do not want to trigger this event.
if((this.projectMgr.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerTrackerEvents) != 0)
{
return true;
}
int iCanContinue = 0;
ErrorHandler.ThrowOnFailure(this.GetIVsTrackProjectDocuments2().OnQueryRenameFile(this.projectMgr.InteropSafeIVsProject3, oldFileName, newFileName, flag, out iCanContinue));
return (iCanContinue != 0);
}
/// <summary>
/// Get's called to tell the env that a file was renamed
/// </summary>
///
internal void OnItemRenamed(string strOldName, string strNewName, VSRENAMEFILEFLAGS flag)
{
if((this.projectMgr.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerTrackerEvents) == 0)
{
ErrorHandler.ThrowOnFailure(this.GetIVsTrackProjectDocuments2().OnAfterRenameFile(this.projectMgr.InteropSafeIVsProject3, strOldName, strNewName, flag));
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PolicyDefinitionsOperations operations.
/// </summary>
internal partial class PolicyDefinitionsOperations : Microsoft.Rest.IServiceOperations<PolicyClient>, IPolicyDefinitionsOperations
{
/// <summary>
/// Initializes a new instance of the PolicyDefinitionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolicyDefinitionsOperations(PolicyClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the PolicyClient
/// </summary>
public PolicyClient Client { get; private set; }
/// <summary>
/// Create or update a policy definition.
/// </summary>
/// <param name='policyDefinitionName'>
/// The policy definition name.
/// </param>
/// <param name='parameters'>
/// The policy definition properties.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PolicyDefinition>> CreateOrUpdateWithHttpMessagesAsync(string policyDefinitionName, PolicyDefinition parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (policyDefinitionName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyDefinitionName");
}
if (parameters == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("policyDefinitionName", policyDefinitionName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString();
_url = _url.Replace("{policyDefinitionName}", System.Uri.EscapeDataString(policyDefinitionName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<PolicyDefinition>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyDefinition>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the policy definition.
/// </summary>
/// <param name='policyDefinitionName'>
/// The policy definition name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string policyDefinitionName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (policyDefinitionName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyDefinitionName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("policyDefinitionName", policyDefinitionName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString();
_url = _url.Replace("{policyDefinitionName}", System.Uri.EscapeDataString(policyDefinitionName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the policy definition.
/// </summary>
/// <param name='policyDefinitionName'>
/// The policy definition name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PolicyDefinition>> GetWithHttpMessagesAsync(string policyDefinitionName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (policyDefinitionName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyDefinitionName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("policyDefinitionName", policyDefinitionName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString();
_url = _url.Replace("{policyDefinitionName}", System.Uri.EscapeDataString(policyDefinitionName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<PolicyDefinition>();
_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<PolicyDefinition>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the policy definitions of a subscription.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<PolicyDefinition>>> ListWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery<PolicyDefinition> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<PolicyDefinition>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<PolicyDefinition>>();
_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<PolicyDefinition>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the policy definitions of a subscription.
/// </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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<PolicyDefinition>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<PolicyDefinition>>();
_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<PolicyDefinition>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
namespace C5
{
/// <summary>
/// A read-only wrapper for a sorted collection
///
/// <i>This is mainly interesting as a base of other guard classes</i>
/// </summary>
[Serializable]
public class GuardedSorted<T> : GuardedSequenced<T>, ISorted<T>
{
#region Fields
private readonly ISorted<T> sorted;
#endregion
#region Constructor
/// <summary>
/// Wrap a sorted collection in a read-only wrapper
/// </summary>
/// <param name="sorted"></param>
public GuardedSorted(ISorted<T> sorted) : base(sorted) { this.sorted = sorted; }
#endregion
#region ISorted<T> Members
/// <summary>
/// Find the strict predecessor of item in the guarded sorted collection,
/// that is, the greatest item in the collection smaller than the item.
/// </summary>
/// <param name="item">The item to find the predecessor for.</param>
/// <param name="res">The predecessor, if any; otherwise the default value for T.</param>
/// <returns>True if item has a predecessor; otherwise false.</returns>
public bool TryPredecessor(T item, out T res) { return sorted.TryPredecessor(item, out res); }
/// <summary>
/// Find the strict successor of item in the guarded sorted collection,
/// that is, the least item in the collection greater than the supplied value.
/// </summary>
/// <param name="item">The item to find the successor for.</param>
/// <param name="res">The successor, if any; otherwise the default value for T.</param>
/// <returns>True if item has a successor; otherwise false.</returns>
public bool TrySuccessor(T item, out T res) { return sorted.TrySuccessor(item, out res); }
/// <summary>
/// Find the weak predecessor of item in the guarded sorted collection,
/// that is, the greatest item in the collection smaller than or equal to the item.
/// </summary>
/// <param name="item">The item to find the weak predecessor for.</param>
/// <param name="res">The weak predecessor, if any; otherwise the default value for T.</param>
/// <returns>True if item has a weak predecessor; otherwise false.</returns>
public bool TryWeakPredecessor(T item, out T res) { return sorted.TryWeakPredecessor(item, out res); }
/// <summary>
/// Find the weak successor of item in the sorted collection,
/// that is, the least item in the collection greater than or equal to the supplied value.
/// </summary>
/// <param name="item">The item to find the weak successor for.</param>
/// <param name="res">The weak successor, if any; otherwise the default value for T.</param>
/// <returns>True if item has a weak successor; otherwise false.</returns>
public bool TryWeakSuccessor(T item, out T res) { return sorted.TryWeakSuccessor(item, out res); }
/// <summary>
/// Find the predecessor of the item in the wrapped sorted collection
/// </summary>
/// <exception cref="NoSuchItemException"> if no such element exists </exception>
/// <param name="item">The item</param>
/// <returns>The predecessor</returns>
public T Predecessor(T item) { return sorted.Predecessor(item); }
/// <summary>
/// Find the Successor of the item in the wrapped sorted collection
/// </summary>
/// <exception cref="NoSuchItemException"> if no such element exists </exception>
/// <param name="item">The item</param>
/// <returns>The Successor</returns>
public T Successor(T item) { return sorted.Successor(item); }
/// <summary>
/// Find the weak predecessor of the item in the wrapped sorted collection
/// </summary>
/// <exception cref="NoSuchItemException"> if no such element exists </exception>
/// <param name="item">The item</param>
/// <returns>The weak predecessor</returns>
public T WeakPredecessor(T item) { return sorted.WeakPredecessor(item); }
/// <summary>
/// Find the weak Successor of the item in the wrapped sorted collection
/// </summary>
/// <exception cref="NoSuchItemException"> if no such element exists </exception>
/// <param name="item">The item</param>
/// <returns>The weak Successor</returns>
public T WeakSuccessor(T item) { return sorted.WeakSuccessor(item); }
/// <summary>
/// Run Cut on the wrapped sorted collection
/// </summary>
/// <param name="c"></param>
/// <param name="low"></param>
/// <param name="lval"></param>
/// <param name="high"></param>
/// <param name="hval"></param>
/// <returns></returns>
public bool Cut(IComparable<T> c, out T low, out bool lval, out T high, out bool hval)
{ return sorted.Cut(c, out low, out lval, out high, out hval); }
/// <summary>
/// Get the specified range from the wrapped collection.
/// (The current implementation erroneously does not wrap the result.)
/// </summary>
/// <param name="bot"></param>
/// <returns></returns>
public IDirectedEnumerable<T> RangeFrom(T bot) { return sorted.RangeFrom(bot); }
/// <summary>
/// Get the specified range from the wrapped collection.
/// (The current implementation erroneously does not wrap the result.)
/// </summary>
/// <param name="bot"></param>
/// <param name="top"></param>
/// <returns></returns>
public IDirectedEnumerable<T> RangeFromTo(T bot, T top)
{ return sorted.RangeFromTo(bot, top); }
/// <summary>
/// Get the specified range from the wrapped collection.
/// (The current implementation erroneously does not wrap the result.)
/// </summary>
/// <param name="top"></param>
/// <returns></returns>
public IDirectedEnumerable<T> RangeTo(T top) { return sorted.RangeTo(top); }
/// <summary>
/// Get the specified range from the wrapped collection.
/// (The current implementation erroneously does not wrap the result.)
/// </summary>
/// <returns></returns>
public IDirectedCollectionValue<T> RangeAll() { return sorted.RangeAll(); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="items"></param>
public void AddSorted(System.Collections.Generic.IEnumerable<T> items)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="low"></param>
public void RemoveRangeFrom(T low)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="low"></param>
/// <param name="hi"></param>
public void RemoveRangeFromTo(T low, T hi)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="hi"></param>
public void RemoveRangeTo(T hi)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
#endregion
#region IPriorityQueue<T> Members
/// <summary>
/// Find the minimum of the wrapped collection
/// </summary>
/// <returns>The minimum</returns>
public T FindMin() { return sorted.FindMin(); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns></returns>
public T DeleteMin()
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// Find the maximum of the wrapped collection
/// </summary>
/// <returns>The maximum</returns>
public T FindMax() { return sorted.FindMax(); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns></returns>
public T DeleteMax()
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
//TODO: we should guard the comparer!
/// <summary>
/// The comparer object supplied at creation time for the underlying collection
/// </summary>
/// <value>The comparer</value>
public System.Collections.Generic.IComparer<T> Comparer => sorted.Comparer;
#endregion
#region IDirectedEnumerable<T> Members
IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards()
{ return Backwards(); }
#endregion
}
}
| |
using Microsoft.Practices.ServiceLocation;
using Prism.Common;
using Prism.Events;
using Prism.Properties;
using Prism.Regions.Behaviors;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
namespace Prism.Regions
{
/// <summary>
/// This class is responsible for maintaining a collection of regions and attaching regions to controls.
/// </summary>
/// <remarks>
/// This class supplies the attached properties that can be used for simple region creation from XAML.
/// </remarks>
public class RegionManager : IRegionManager
{
#region Static members (for XAML support)
private static readonly WeakDelegatesManager updatingRegionsListeners = new WeakDelegatesManager();
/// <summary>
/// Identifies the RegionName attached property.
/// </summary>
/// <remarks>
/// When a control has both the <see cref="RegionNameProperty"/> and
/// <see cref="RegionManagerProperty"/> attached properties set to
/// a value different than <see langword="null" /> and there is a
/// <see cref="IRegionAdapter"/> mapping registered for the control, it
/// will create and adapt a new region for that control, and register it
/// in the <see cref="IRegionManager"/> with the specified region name.
/// </remarks>
public static readonly DependencyProperty RegionNameProperty = DependencyProperty.RegisterAttached(
"RegionName",
typeof(string),
typeof(RegionManager),
new PropertyMetadata(OnSetRegionNameCallback));
/// <summary>
/// Sets the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="regionTarget">The object to adapt. This is typically a container (i.e a control).</param>
/// <param name="regionName">The name of the region to register.</param>
public static void SetRegionName(DependencyObject regionTarget, string regionName)
{
if (regionTarget == null)
throw new ArgumentNullException(nameof(regionTarget));
regionTarget.SetValue(RegionNameProperty, regionName);
}
/// <summary>
/// Gets the value for the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="regionTarget">The object to adapt. This is typically a container (i.e a control).</param>
/// <returns>The name of the region that should be created when
/// <see cref="RegionManagerProperty"/> is also set in this element.</returns>
public static string GetRegionName(DependencyObject regionTarget)
{
if (regionTarget == null)
throw new ArgumentNullException(nameof(regionTarget));
return regionTarget.GetValue(RegionNameProperty) as string;
}
private static readonly DependencyProperty ObservableRegionProperty =
DependencyProperty.RegisterAttached("ObservableRegion", typeof(ObservableObject<IRegion>), typeof(RegionManager), null);
/// <summary>
/// Returns an <see cref="ObservableObject{T}"/> wrapper that can hold an <see cref="IRegion"/>. Using this wrapper
/// you can detect when an <see cref="IRegion"/> has been created by the <see cref="RegionAdapterBase{T}"/>.
///
/// If the <see cref="ObservableObject{T}"/> wrapper does not yet exist, a new wrapper will be created. When the region
/// gets created and assigned to the wrapper, you can use the <see cref="ObservableObject{T}.PropertyChanged"/> event
/// to get notified of that change.
/// </summary>
/// <param name="view">The view that will host the region. </param>
/// <returns>Wrapper that can hold an <see cref="IRegion"/> value and can notify when the <see cref="IRegion"/> value changes. </returns>
public static ObservableObject<IRegion> GetObservableRegion(DependencyObject view)
{
if (view == null) throw new ArgumentNullException(nameof(view));
ObservableObject<IRegion> regionWrapper = view.GetValue(ObservableRegionProperty) as ObservableObject<IRegion>;
if (regionWrapper == null)
{
regionWrapper = new ObservableObject<IRegion>();
view.SetValue(ObservableRegionProperty, regionWrapper);
}
return regionWrapper;
}
private static void OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)
{
if (!IsInDesignMode(element))
{
CreateRegion(element);
}
}
private static void CreateRegion(DependencyObject element)
{
IServiceLocator locator = ServiceLocator.Current;
DelayedRegionCreationBehavior regionCreationBehavior = locator.GetInstance<DelayedRegionCreationBehavior>();
regionCreationBehavior.TargetElement = element;
regionCreationBehavior.Attach();
}
/// <summary>
/// Identifies the RegionManager attached property.
/// </summary>
/// <remarks>
/// When a control has both the <see cref="RegionNameProperty"/> and
/// <see cref="RegionManagerProperty"/> attached properties set to
/// a value different than <see langword="null" /> and there is a
/// <see cref="IRegionAdapter"/> mapping registered for the control, it
/// will create and adapt a new region for that control, and register it
/// in the <see cref="IRegionManager"/> with the specified region name.
/// </remarks>
public static readonly DependencyProperty RegionManagerProperty =
DependencyProperty.RegisterAttached("RegionManager", typeof(IRegionManager), typeof(RegionManager), null);
/// <summary>
/// Gets the value of the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <returns>The <see cref="IRegionManager"/> attached to the <paramref name="target"/> element.</returns>
public static IRegionManager GetRegionManager(DependencyObject target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return (IRegionManager)target.GetValue(RegionManagerProperty);
}
/// <summary>
/// Sets the <see cref="RegionManagerProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <param name="value">The value.</param>
public static void SetRegionManager(DependencyObject target, IRegionManager value)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
target.SetValue(RegionManagerProperty, value);
}
/// <summary>
/// Identifies the RegionContext attached property.
/// </summary>
public static readonly DependencyProperty RegionContextProperty =
DependencyProperty.RegisterAttached("RegionContext", typeof(object), typeof(RegionManager), new PropertyMetadata(OnRegionContextChanged));
private static void OnRegionContextChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
if (RegionContext.GetObservableContext(depObj).Value != e.NewValue)
{
RegionContext.GetObservableContext(depObj).Value = e.NewValue;
}
}
/// <summary>
/// Gets the value of the <see cref="RegionContextProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <returns>The region context to pass to the contained views.</returns>
public static object GetRegionContext(DependencyObject target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return target.GetValue(RegionContextProperty);
}
/// <summary>
/// Sets the <see cref="RegionContextProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <param name="value">The value.</param>
public static void SetRegionContext(DependencyObject target, object value)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
target.SetValue(RegionContextProperty, value);
}
/// <summary>
/// Notification used by attached behaviors to update the region managers appropriatelly if needed to.
/// </summary>
/// <remarks>This event uses weak references to the event handler to prevent this static event of keeping the
/// target element longer than expected.</remarks>
public static event EventHandler UpdatingRegions
{
add { updatingRegionsListeners.AddListener(value); }
remove { updatingRegionsListeners.RemoveListener(value); }
}
/// <summary>
/// Notifies attached behaviors to update the region managers appropriatelly if needed to.
/// </summary>
/// <remarks>
/// This method is normally called internally, and there is usually no need to call this from user code.
/// </remarks>
public static void UpdateRegions()
{
try
{
updatingRegionsListeners.Raise(null, EventArgs.Empty);
}
catch (TargetInvocationException ex)
{
Exception rootException = ex.GetRootException();
throw new UpdateRegionsException(string.Format(CultureInfo.CurrentCulture,
Resources.UpdateRegionException, rootException), ex.InnerException);
}
}
private static bool IsInDesignMode(DependencyObject element)
{
return DesignerProperties.GetIsInDesignMode(element);
}
#endregion
private readonly RegionCollection regionCollection;
/// <summary>
/// Initializes a new instance of <see cref="RegionManager"/>.
/// </summary>
public RegionManager()
{
regionCollection = new RegionCollection(this);
}
/// <summary>
/// Gets a collection of <see cref="IRegion"/> that identify each region by name. You can use this collection to add or remove regions to the current region manager.
/// </summary>
/// <value>A <see cref="IRegionCollection"/> with all the registered regions.</value>
public IRegionCollection Regions
{
get { return regionCollection; }
}
/// <summary>
/// Creates a new region manager.
/// </summary>
/// <returns>A new region manager that can be used as a different scope from the current region manager.</returns>
public IRegionManager CreateRegionManager()
{
return new RegionManager();
}
/// <summary>
/// Add a view to the Views collection of a Region. Note that the region must already exist in this regionmanager.
/// </summary>
/// <param name="regionName">The name of the region to add a view to</param>
/// <param name="view">The view to add to the views collection</param>
/// <returns>The RegionManager, to easily add several views. </returns>
public IRegionManager AddToRegion(string regionName, object view)
{
if (!Regions.ContainsRegionWithName(regionName))
throw new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, Resources.RegionNotFound, regionName), nameof(regionName));
return Regions[regionName].Add(view);
}
/// <summary>
/// Associate a view with a region, by registering a type. When the region get's displayed
/// this type will be resolved using the ServiceLocator into a concrete instance. The instance
/// will be added to the Views collection of the region
/// </summary>
/// <param name="regionName">The name of the region to associate the view with.</param>
/// <param name="viewType">The type of the view to register with the </param>
/// <returns>The regionmanager, for adding several views easily</returns>
public IRegionManager RegisterViewWithRegion(string regionName, Type viewType)
{
var regionViewRegistry = ServiceLocator.Current.GetInstance<IRegionViewRegistry>();
regionViewRegistry.RegisterViewWithRegion(regionName, viewType);
return this;
}
/// <summary>
/// Associate a view with a region, using a delegate to resolve a concreate instance of the view.
/// When the region get's displayed, this delelgate will be called and the result will be added to the
/// views collection of the region.
/// </summary>
/// <param name="regionName">The name of the region to associate the view with.</param>
/// <param name="getContentDelegate">The delegate used to resolve a concreate instance of the view.</param>
/// <returns>The regionmanager, for adding several views easily</returns>
public IRegionManager RegisterViewWithRegion(string regionName, Func<object> getContentDelegate)
{
var regionViewRegistry = ServiceLocator.Current.GetInstance<IRegionViewRegistry>();
regionViewRegistry.RegisterViewWithRegion(regionName, getContentDelegate);
return this;
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
/// <param name="navigationCallback">The navigation callback.</param>
public void RequestNavigate(string regionName, Uri source, Action<NavigationResult> navigationCallback)
{
if (navigationCallback == null)
throw new ArgumentNullException(nameof(navigationCallback));
if (Regions.ContainsRegionWithName(regionName))
{
Regions[regionName].RequestNavigate(source, navigationCallback);
}
else
{
navigationCallback(new NavigationResult(new NavigationContext(null, source), false));
}
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
public void RequestNavigate(string regionName, Uri source)
{
RequestNavigate(regionName, source, nr => { });
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
/// <param name="navigationCallback">The navigation callback.</param>
public void RequestNavigate(string regionName, string source, Action<NavigationResult> navigationCallback)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
RequestNavigate(regionName, new Uri(source, UriKind.RelativeOrAbsolute), navigationCallback);
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
public void RequestNavigate(string regionName, string source)
{
RequestNavigate(regionName, source, nr => { });
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target Uri, passing a navigation callback and an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A Uri that represents the target where the region will navigate.</param>
/// <param name="navigationCallback">The navigation callback that will be executed after the navigation is completed.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
if (navigationCallback == null)
throw new ArgumentNullException(nameof(navigationCallback));
if (Regions.ContainsRegionWithName(regionName))
{
Regions[regionName].RequestNavigate(target, navigationCallback, navigationParameters);
}
else
{
navigationCallback(new NavigationResult(new NavigationContext(null, target, navigationParameters), false));
}
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target string, passing a navigation callback and an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A string that represents the target where the region will navigate.</param>
/// <param name="navigationCallback">The navigation callback that will be executed after the navigation is completed.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, string target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
RequestNavigate(regionName, new Uri(target, UriKind.RelativeOrAbsolute), navigationCallback, navigationParameters);
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target Uri, passing an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A Uri that represents the target where the region will navigate.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, Uri target, NavigationParameters navigationParameters)
{
RequestNavigate(regionName, target, nr => { }, navigationParameters);
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target string, passing an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A string that represents the target where the region will navigate.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, string target, NavigationParameters navigationParameters)
{
RequestNavigate(regionName, new Uri(target, UriKind.RelativeOrAbsolute), nr => { }, navigationParameters);
}
private class RegionCollection : IRegionCollection
{
private readonly IRegionManager regionManager;
private readonly List<IRegion> regions;
public RegionCollection(IRegionManager regionManager)
{
this.regionManager = regionManager;
this.regions = new List<IRegion>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public IEnumerator<IRegion> GetEnumerator()
{
UpdateRegions();
return this.regions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IRegion this[string regionName]
{
get
{
UpdateRegions();
IRegion region = GetRegionByName(regionName);
if (region == null)
{
throw new KeyNotFoundException(string.Format(CultureInfo.CurrentUICulture, Resources.RegionNotInRegionManagerException, regionName));
}
return region;
}
}
public void Add(IRegion region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
UpdateRegions();
if (region.Name == null)
{
throw new InvalidOperationException(Resources.RegionNameCannotBeEmptyException);
}
if (this.GetRegionByName(region.Name) != null)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.RegionNameExistsException, region.Name));
}
this.regions.Add(region);
region.RegionManager = this.regionManager;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, region, 0));
}
public bool Remove(string regionName)
{
UpdateRegions();
bool removed = false;
IRegion region = GetRegionByName(regionName);
if (region != null)
{
removed = true;
this.regions.Remove(region);
region.RegionManager = null;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, region, 0));
}
return removed;
}
public bool ContainsRegionWithName(string regionName)
{
UpdateRegions();
return GetRegionByName(regionName) != null;
}
/// <summary>
/// Adds a region to the regionmanager with the name received as argument.
/// </summary>
/// <param name="regionName">The name to be given to the region.</param>
/// <param name="region">The region to be added to the regionmanager.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="region"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="regionName"/> and <paramref name="region"/>'s name do not match and the <paramref name="region"/> <see cref="IRegion.Name"/> is not <see langword="null"/>.</exception>
public void Add(string regionName, IRegion region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
if (region.Name != null && region.Name != regionName)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.RegionManagerWithDifferentNameException, region.Name, regionName), nameof(regionName));
if (region.Name == null)
region.Name = regionName;
Add(region);
}
private IRegion GetRegionByName(string regionName)
{
return this.regions.FirstOrDefault(r => r.Name == regionName);
}
private void OnCollectionChanged(NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
var handler = this.CollectionChanged;
if (handler != null)
{
handler(this, notifyCollectionChangedEventArgs);
}
}
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2018 Leandro F. Vieira (leandromoh). 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.
#endregion
namespace MoreLinq.Test
{
using System;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class TransposeTest
{
[Test]
public void TransposeIsLazy()
{
new BreakingSequence<BreakingSequence<int>>().Transpose();
}
[Test]
public void TransposeWithOneNullRow()
{
using (var seq1 = TestingSequence.Of(10, 11))
using (var seq2 = TestingSequence.Of<int>())
using (var seq3 = TestingSequence.Of(30, 31, 32))
using (var matrix = TestingSequence.Of(seq1, seq2, seq3, null))
{
Assert.Throws<NullReferenceException>(() =>
matrix.Transpose().FirstOrDefault());
}
}
[Test]
public void TransposeWithRowsOfSameLength()
{
var expectations = new[]
{
new [] { 10, 20, 30 },
new [] { 11, 21, 31 },
new [] { 12, 22, 32 },
new [] { 13, 23, 33 },
};
using (var row1 = TestingSequence.Of(10, 11, 12, 13))
using (var row2 = TestingSequence.Of(20, 21, 22, 23))
using (var row3 = TestingSequence.Of(30, 31, 32, 33))
using (var matrix = TestingSequence.Of(row1, row2, row3))
{
AssertMatrix(expectations, matrix.Transpose());
}
}
[Test]
public void TransposeWithRowsOfDifferentLengths()
{
var expectations = new[]
{
new[] { 10, 20, 30 },
new[] { 11, 31 },
new[] { 32 }
};
using (var row1 = TestingSequence.Of(10, 11))
using (var row2 = TestingSequence.Of(20))
using (var row3 = TestingSequence.Of<int>())
using (var row4 = TestingSequence.Of(30, 31, 32))
using (var matrix = TestingSequence.Of(row1, row2, row3, row4))
{
AssertMatrix(expectations, matrix.Transpose());
}
}
[Test]
public void TransposeMaintainsCornerElements()
{
var matrix = new[]
{
new[] { 10, 11 },
new[] { 20 },
new int[0],
new[] { 30, 31, 32 }
};
var traspose = matrix.Transpose();
Assert.That(matrix.Last().Last(), Is.EqualTo(traspose.Last().Last()));
Assert.That(matrix.First().First(), Is.EqualTo(traspose.First().First()));
}
[Test]
public void TransposeWithAllRowsAsInfiniteSequences()
{
var matrix = MoreEnumerable.Generate(1, x => x + 1)
.Where(IsPrime)
.Take(3)
.Select(x => MoreEnumerable.Generate(x, n => n * x));
var result = matrix.Transpose().Take(5);
var expectations = new[]
{
new[] { 2, 3, 5 },
new[] { 4, 9, 25 },
new[] { 8, 27, 125 },
new[] { 16, 81, 625 },
new[] { 32, 243, 3125 }
};
AssertMatrix(expectations, result);
}
[Test]
public void TransposeWithSomeRowsAsInfiniteSequences()
{
var matrix = MoreEnumerable.Generate(1, x => x + 1)
.Where(IsPrime)
.Take(3)
.Select((x, i) => i == 1 ? MoreEnumerable.Generate(x, n => n * x).Take(2)
: MoreEnumerable.Generate(x, n => n * x));
var result = matrix.Transpose().Take(5);
var expectations = new[]
{
new[] { 2, 3, 5 },
new[] { 4, 9, 25 },
new[] { 8, 125 },
new[] { 16, 625 },
new[] { 32, 3125 }
};
AssertMatrix(expectations, result);
}
[Test]
public void TransposeColumnTraversalOrderIsIrrelevant()
{
var matrix = new[]
{
new[] { 10, 11 },
new[] { 20 },
new int[0],
new[] { 30, 31, 32 }
};
var transpose = matrix.Transpose().ToList();
transpose[1].AssertSequenceEqual(11, 31);
transpose[0].AssertSequenceEqual(10, 20, 30);
transpose[2].AssertSequenceEqual(32);
}
[Test]
public void TransposeConsumesRowsLazily()
{
var matrix = new[]
{
MoreEnumerable.From(() => 10, () => 11),
MoreEnumerable.From(() => 20, () => 22),
MoreEnumerable.From(() => 30, () => throw new TestException(), () => 31),
};
var result = matrix.Transpose();
result.ElementAt(0).AssertSequenceEqual(10, 20, 30);
Assert.Throws<TestException>(() =>
result.ElementAt(1));
}
[Test]
public void TransposeWithErroneousRowDisposesRowIterators()
{
using (var row1 = TestingSequence.Of(10, 11))
using (var row2 = MoreEnumerable.From(() => 20,
() => throw new TestException())
.AsTestingSequence())
using (var row3 = TestingSequence.Of(30, 32))
using (var matrix = TestingSequence.Of(row1, row2, row3))
{
Assert.Throws<TestException>(() =>
matrix.Transpose().Consume());
}
}
static bool IsPrime(int number)
{
if (number == 1) return false;
if (number == 2) return true;
var boundary = (int)Math.Floor(Math.Sqrt(number));
for (var i = 2; i <= boundary; ++i)
{
if (number % i == 0)
return false;
}
return true;
}
static void AssertMatrix<T>(IEnumerable<IEnumerable<T>> expectation, IEnumerable<IEnumerable<T>> result)
{
// necessary because NUnitLite 3.6.1 (.NET 4.5) for Mono don't assert nested enumerables
var resultList = result.ToList();
var expectationList = expectation.ToList();
Assert.AreEqual(expectationList.Count, resultList.Count);
expectationList.Zip(resultList, ValueTuple.Create)
.ForEach(t => t.Item1.AssertSequenceEqual(t.Item2));
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Avalonia.Utilities
{
/// <summary>
/// Provides utilities for working with types at runtime.
/// </summary>
public static class TypeUtilities
{
private static readonly int[] Conversions =
{
0b101111111111101, // Boolean
0b100001111111110, // Char
0b101111111111111, // SByte
0b101111111111111, // Byte
0b101111111111111, // Int16
0b101111111111111, // UInt16
0b101111111111111, // Int32
0b101111111111111, // UInt32
0b101111111111111, // Int64
0b101111111111111, // UInt64
0b101111111111101, // Single
0b101111111111101, // Double
0b101111111111101, // Decimal
0b110000000000000, // DateTime
0b111111111111111, // String
};
private static readonly int[] ImplicitConversions =
{
0b000000000000001, // Boolean
0b001110111100010, // Char
0b001110101010100, // SByte
0b001111111111000, // Byte
0b001110101010000, // Int16
0b001111111100000, // UInt16
0b001110101000000, // Int32
0b001111110000000, // UInt32
0b001110100000000, // Int64
0b001111000000000, // UInt64
0b000110000000000, // Single
0b000100000000000, // Double
0b001000000000000, // Decimal
0b010000000000000, // DateTime
0b100000000000000, // String
};
private static readonly Type[] InbuiltTypes =
{
typeof(Boolean),
typeof(Char),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(String),
};
private static readonly Type[] NumericTypes =
{
typeof(Byte),
typeof(Decimal),
typeof(Double),
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(SByte),
typeof(Single),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64),
};
/// <summary>
/// Returns a value indicating whether null can be assigned to the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if the type accepts null values; otherwise false.</returns>
public static bool AcceptsNull(Type type)
{
return !type.IsValueType || IsNullableType(type);
}
/// <summary>
/// Returns a value indicating whether null can be assigned to the specified type.
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <returns>True if the type accepts null values; otherwise false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool AcceptsNull<T>()
{
return default(T) is null;
}
/// <summary>
/// Returns a value indicating whether value can be casted to the specified type.
/// If value is null, checks if instances of that type can be null.
/// </summary>
/// <typeparam name="T">The type to cast to</typeparam>
/// <param name="value">The value to check if cast possible</param>
/// <returns>True if the cast is possible, otherwise false.</returns>
public static bool CanCast<T>(object value)
{
return value is T || (value is null && AcceptsNull<T>());
}
/// <summary>
/// Try to convert a value to a type by any means possible.
/// </summary>
/// <param name="to">The type to convert to.</param>
/// <param name="value">The value to convert.</param>
/// <param name="culture">The culture to use.</param>
/// <param name="result">If successful, contains the convert value.</param>
/// <returns>True if the cast was successful, otherwise false.</returns>
public static bool TryConvert(Type to, object value, CultureInfo culture, out object result)
{
if (value == null)
{
result = null;
return AcceptsNull(to);
}
if (value == AvaloniaProperty.UnsetValue)
{
result = value;
return true;
}
var toUnderl = Nullable.GetUnderlyingType(to) ?? to;
var from = value.GetType();
if (toUnderl.IsAssignableFrom(from))
{
result = value;
return true;
}
if (toUnderl == typeof(string))
{
result = Convert.ToString(value, culture);
return true;
}
if (toUnderl.IsEnum && from == typeof(string))
{
if (Enum.IsDefined(toUnderl, (string)value))
{
result = Enum.Parse(toUnderl, (string)value);
return true;
}
}
if (!from.IsEnum && toUnderl.IsEnum)
{
result = null;
if (TryConvert(Enum.GetUnderlyingType(toUnderl), value, culture, out object enumValue))
{
result = Enum.ToObject(toUnderl, enumValue);
return true;
}
}
if (from.IsEnum && IsNumeric(toUnderl))
{
try
{
result = Convert.ChangeType((int)value, toUnderl, culture);
return true;
}
catch
{
result = null;
return false;
}
}
var convertableFrom = Array.IndexOf(InbuiltTypes, from);
var convertableTo = Array.IndexOf(InbuiltTypes, toUnderl);
if (convertableFrom != -1 && convertableTo != -1)
{
if ((Conversions[convertableFrom] & 1 << convertableTo) != 0)
{
try
{
result = Convert.ChangeType(value, toUnderl, culture);
return true;
}
catch
{
result = null;
return false;
}
}
}
var toTypeConverter = TypeDescriptor.GetConverter(toUnderl);
if (toTypeConverter.CanConvertFrom(from) == true)
{
result = toTypeConverter.ConvertFrom(null, culture, value);
return true;
}
var fromTypeConverter = TypeDescriptor.GetConverter(from);
if (fromTypeConverter.CanConvertTo(toUnderl) == true)
{
result = fromTypeConverter.ConvertTo(null, culture, value, toUnderl);
return true;
}
var cast = FindTypeConversionOperatorMethod(from, toUnderl, OperatorType.Implicit | OperatorType.Explicit);
if (cast != null)
{
result = cast.Invoke(null, new[] { value });
return true;
}
result = null;
return false;
}
/// <summary>
/// Try to convert a value to a type using the implicit conversions allowed by the C#
/// language.
/// </summary>
/// <param name="to">The type to convert to.</param>
/// <param name="value">The value to convert.</param>
/// <param name="result">If successful, contains the converted value.</param>
/// <returns>True if the convert was successful, otherwise false.</returns>
public static bool TryConvertImplicit(Type to, object value, out object result)
{
if (value == null)
{
result = null;
return AcceptsNull(to);
}
if (value == AvaloniaProperty.UnsetValue)
{
result = value;
return true;
}
var from = value.GetType();
if (to.IsAssignableFrom(from))
{
result = value;
return true;
}
var convertableFrom = Array.IndexOf(InbuiltTypes, from);
var convertableTo = Array.IndexOf(InbuiltTypes, to);
if (convertableFrom != -1 && convertableTo != -1)
{
if ((ImplicitConversions[convertableFrom] & 1 << convertableTo) != 0)
{
try
{
result = Convert.ChangeType(value, to, CultureInfo.InvariantCulture);
return true;
}
catch
{
result = null;
return false;
}
}
}
var cast = FindTypeConversionOperatorMethod(from, to, OperatorType.Implicit);
if (cast != null)
{
result = cast.Invoke(null, new[] { value });
return true;
}
result = null;
return false;
}
/// <summary>
/// Convert a value to a type by any means possible, returning the default for that type
/// if the value could not be converted.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="type">The type to convert to..</param>
/// <param name="culture">The culture to use.</param>
/// <returns>A value of <paramref name="type"/>.</returns>
public static object ConvertOrDefault(object value, Type type, CultureInfo culture)
{
return TryConvert(type, value, culture, out object result) ? result : Default(type);
}
/// <summary>
/// Convert a value to a type using the implicit conversions allowed by the C# language or
/// return the default for the type if the value could not be converted.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="type">The type to convert to.</param>
/// <returns>A value of <paramref name="type"/>.</returns>
public static object ConvertImplicitOrDefault(object value, Type type)
{
return TryConvertImplicit(type, value, out object result) ? result : Default(type);
}
public static T ConvertImplicit<T>(object value)
{
if (TryConvertImplicit(typeof(T), value, out var result))
{
return (T)result;
}
throw new InvalidCastException(
$"Unable to convert object '{value ?? "(null)"}' of type '{value?.GetType()}' to type '{typeof(T)}'.");
}
/// <summary>
/// Gets the default value for the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The default value.</returns>
public static object Default(Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
else
{
return null;
}
}
/// <summary>
/// Determines if a type is numeric. Nullable numeric types are considered numeric.
/// </summary>
/// <returns>
/// True if the type is numeric; otherwise false.
/// </returns>
/// <remarks>
/// Boolean is not considered numeric.
/// </remarks>
public static bool IsNumeric(Type type)
{
if (type == null)
{
return false;
}
Type underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null)
{
return IsNumeric(underlyingType);
}
else
{
return NumericTypes.Contains(type);
}
}
[Flags]
private enum OperatorType
{
Implicit = 1,
Explicit = 2
}
private static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
private static MethodInfo FindTypeConversionOperatorMethod(Type fromType, Type toType, OperatorType operatorType)
{
const string implicitName = "op_Implicit";
const string explicitName = "op_Explicit";
bool allowImplicit = operatorType.HasAllFlags(OperatorType.Implicit);
bool allowExplicit = operatorType.HasAllFlags(OperatorType.Explicit);
foreach (MethodInfo method in fromType.GetMethods())
{
if (!method.IsSpecialName || method.ReturnType != toType)
{
continue;
}
if (allowImplicit && method.Name == implicitName)
{
return method;
}
if (allowExplicit && method.Name == explicitName)
{
return method;
}
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SelectTest
{
private readonly ITestOutputHelper _log;
public SelectTest(ITestOutputHelper output)
{
_log = output;
}
private const int SmallTimeoutMicroseconds = 10 * 1000;
private const int FailTimeoutMicroseconds = 30 * 1000 * 1000;
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
[Theory]
[InlineData(90, 0)]
[InlineData(0, 90)]
[InlineData(45, 45)]
public void Select_ReadWrite_AllReady_ManySockets(int reads, int writes)
{
Select_ReadWrite_AllReady(reads, writes);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadWrite_AllReady(int reads, int writes)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var writePairs = Enumerable.Range(0, writes).Select(_ => CreateConnectedSockets()).ToArray();
try
{
foreach (var pair in readPairs)
{
pair.Value.Send(new byte[1] { 42 });
}
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
var writeList = new List<Socket>(writePairs.Select(p => p.Key).ToArray());
Socket.Select(readList, writeList, null, -1); // using -1 to test wait code path, but should complete instantly
// Since no buffers are full, all writes should be available.
Assert.Equal(writePairs.Length, writeList.Count);
// We could wake up from Select for writes even if reads are about to become available,
// so there's very little we can assert if writes is non-zero.
if (writes == 0 && reads > 0)
{
Assert.InRange(readList.Count, 1, readPairs.Length);
}
// When we do the select again, the lists shouldn't change at all, as they've already
// been filtered to ones that were ready.
int readListCountBefore = readList.Count;
int writeListCountBefore = writeList.Count;
Socket.Select(readList, writeList, null, FailTimeoutMicroseconds);
Assert.Equal(readListCountBefore, readList.Count);
Assert.Equal(writeListCountBefore, writeList.Count);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(writePairs);
}
}
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
[Fact]
public void Select_ReadError_NoneReady_ManySockets()
{
Select_ReadError_NoneReady(45, 45);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadError_NoneReady(int reads, int errors)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var errorPairs = Enumerable.Range(0, errors).Select(_ => CreateConnectedSockets()).ToArray();
try
{
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, errorList, SmallTimeoutMicroseconds);
Assert.Empty(readList);
Assert.Empty(errorList);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(errorPairs);
}
}
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
public void Select_Read_OneReadyAtATime_ManySockets(int reads)
{
Select_Read_OneReadyAtATime(90); // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
}
[Theory]
[InlineData(2)]
public void Select_Read_OneReadyAtATime(int reads)
{
var rand = new Random(42);
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (readPairs.Count > 0)
{
int next = rand.Next(0, readPairs.Count);
readPairs[next].Value.Send(new byte[1] { 42 });
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, null, FailTimeoutMicroseconds);
Assert.Equal(1, readList.Count);
Assert.Same(readPairs[next].Key, readList[0]);
readPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(readPairs);
}
}
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/989
public void Select_Error_OneReadyAtATime()
{
const int Errors = 90; // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
var rand = new Random(42);
var errorPairs = Enumerable.Range(0, Errors).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (errorPairs.Count > 0)
{
int next = rand.Next(0, errorPairs.Count);
errorPairs[next].Value.Send(new byte[1] { 42 }, SocketFlags.OutOfBand);
var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(null, null, errorList, FailTimeoutMicroseconds);
Assert.Equal(1, errorList.Count);
Assert.Same(errorPairs[next].Key, errorList[0]);
errorPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(errorPairs);
}
}
[Theory]
[InlineData(SelectMode.SelectRead)]
[InlineData(SelectMode.SelectError)]
[ActiveIssue(21057, TargetFrameworkMonikers.Uap)]
public void Poll_NotReady(SelectMode mode)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Assert.False(pair.Key.Poll(SmallTimeoutMicroseconds, mode));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
[Theory]
[InlineData(-1)]
[InlineData(FailTimeoutMicroseconds)]
public void Poll_ReadReady_LongTimeouts(int microsecondsTimeout)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Task.Delay(1).ContinueWith(_ => pair.Value.Send(new byte[1] { 42 }),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Assert.True(pair.Key.Poll(microsecondsTimeout, SelectMode.SelectRead));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
private static KeyValuePair<Socket, Socket> CreateConnectedSockets()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.LingerState = new LingerOption(true, 0);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.LingerState = new LingerOption(true, 0);
Task<Socket> acceptTask = listener.AcceptAsync();
client.Connect(listener.LocalEndPoint);
Socket server = acceptTask.GetAwaiter().GetResult();
return new KeyValuePair<Socket, Socket>(client, server);
}
}
private static void DisposeSockets(IEnumerable<KeyValuePair<Socket, Socket>> sockets)
{
foreach (var pair in sockets)
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
[OuterLoop]
[Fact]
public static void Select_AcceptNonBlocking_Success()
{
using (Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listenSocket.BindToAnonymousPort(IPAddress.Loopback);
listenSocket.Blocking = false;
listenSocket.Listen(5);
Task t = Task.Run(() => { DoAccept(listenSocket, 5); });
// Loop, doing connections and pausing between
for (int i = 0; i < 5; i++)
{
Thread.Sleep(50);
using (Socket connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
connectSocket.Connect(listenSocket.LocalEndPoint);
}
}
// Give the task 5 seconds to complete; if not, assume it's hung.
bool completed = t.Wait(5000);
Assert.True(completed);
}
}
public static void DoAccept(Socket listenSocket, int connectionsToAccept)
{
int connectionCount = 0;
while (true)
{
var ls = new List<Socket> { listenSocket };
Socket.Select(ls, null, null, 1000000);
if (ls.Count > 0)
{
while (true)
{
try
{
Socket s = listenSocket.Accept();
s.Close();
connectionCount++;
}
catch (SocketException e)
{
Assert.Equal(e.SocketErrorCode, SocketError.WouldBlock);
//No more requests in queue
break;
}
if (connectionCount == connectionsToAccept)
{
return;
}
}
}
}
}
}
}
| |
// <copyright file="ContinuousUniformTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// 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.
// </copyright>
using System;
using System.Linq;
using MathNet.Numerics.Distributions;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous
{
using Random = System.Random;
/// <summary>
/// Continuous uniform tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class ContinuousUniformTests
{
/// <summary>
/// Can create continuous uniform.
/// </summary>
[Test]
public void CanCreateContinuousUniform()
{
var n = new ContinuousUniform();
Assert.AreEqual(0.0, n.LowerBound);
Assert.AreEqual(1.0, n.UpperBound);
}
/// <summary>
/// Can create continuous uniform.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(0.0, 0.0)]
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(10.0, 10.0)]
[TestCase(-5.0, 11.0)]
[TestCase(-5.0, 100.0)]
[TestCase(Double.NegativeInfinity, Double.PositiveInfinity)]
public void CanCreateContinuousUniform(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
Assert.AreEqual(lower, n.LowerBound);
Assert.AreEqual(upper, n.UpperBound);
}
/// <summary>
/// Continuous uniform create fails with bad parameters.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(Double.NaN, 1.0)]
[TestCase(1.0, Double.NaN)]
[TestCase(Double.NaN, Double.NaN)]
[TestCase(1.0, 0.0)]
public void ContinuousUniformCreateFailsWithBadParameters(double lower, double upper)
{
Assert.That(() => new ContinuousUniform(lower, upper), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
var n = new ContinuousUniform(1.0, 2.0);
Assert.AreEqual("ContinuousUniform(Lower = 1, Upper = 2)", n.ToString());
}
/// <summary>
/// Validate entropy.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateEntropy(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
Assert.AreEqual(Math.Log(upper - lower), n.Entropy);
}
/// <summary>
/// Validate skewness.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateSkewness(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
Assert.AreEqual(0.0, n.Skewness);
}
/// <summary>
/// Validate mode.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMode(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
Assert.AreEqual((lower + upper) / 2.0, n.Mode);
}
/// <summary>
/// Validate median.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMedian(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
Assert.AreEqual((lower + upper) / 2.0, n.Median);
}
/// <summary>
/// Validate minimum.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMinimum(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
Assert.AreEqual(lower, n.Minimum);
}
/// <summary>
/// Validate maximum.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMaximum(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
Assert.AreEqual(upper, n.Maximum);
}
/// <summary>
/// Validate density.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(0.0, 0.0)]
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateDensity(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
if (x >= lower && x <= upper)
{
Assert.AreEqual(1.0/(upper - lower), n.Density(x));
Assert.AreEqual(1.0/(upper - lower), ContinuousUniform.PDF(lower, upper, x));
}
else
{
Assert.AreEqual(0.0, n.Density(x));
Assert.AreEqual(0.0, ContinuousUniform.PDF(lower, upper, x));
}
}
}
/// <summary>
/// Validate density log.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(0.0, 0.0)]
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateDensityLn(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
if (x >= lower && x <= upper)
{
Assert.AreEqual(-Math.Log(upper - lower), n.DensityLn(x));
Assert.AreEqual(-Math.Log(upper - lower), ContinuousUniform.PDFLn(lower, upper, x));
}
else
{
Assert.AreEqual(double.NegativeInfinity, n.DensityLn(x));
Assert.AreEqual(double.NegativeInfinity, ContinuousUniform.PDFLn(lower, upper, x));
}
}
}
/// <summary>
/// Can sample static.
/// </summary>
[Test]
public void CanSampleStatic()
{
ContinuousUniform.Sample(new Random(0), 0.0, 1.0);
}
/// <summary>
/// Can sample sequence static.
/// </summary>
[Test]
public void CanSampleSequenceStatic()
{
var ied = ContinuousUniform.Samples(new Random(0), 0.0, 1.0);
GC.KeepAlive(ied.Take(5).ToArray());
}
/// <summary>
/// Fail sample static with bad parameters.
/// </summary>
[Test]
public void FailSampleStatic()
{
Assert.That(() => ContinuousUniform.Sample(new Random(0), 0.0, -1.0), Throws.ArgumentException);
}
/// <summary>
/// Fail sample sequence static with bad parameters.
/// </summary>
[Test]
public void FailSampleSequenceStatic()
{
Assert.That(() => ContinuousUniform.Samples(new Random(0), 0.0, -1.0).First(), Throws.ArgumentException);
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var n = new ContinuousUniform();
n.Sample();
}
/// <summary>
/// Can sample sequence.
/// </summary>
[Test]
public void CanSampleSequence()
{
var n = new ContinuousUniform();
var ied = n.Samples();
GC.KeepAlive(ied.Take(5).ToArray());
}
/// <summary>
/// Validate cumulative distribution.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(0.0, 0.0)]
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateCumulativeDistribution(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
if (x <= lower)
{
Assert.AreEqual(0.0, n.CumulativeDistribution(x));
Assert.AreEqual(0.0, ContinuousUniform.CDF(lower, upper, x));
}
else if (x >= upper)
{
Assert.AreEqual(1.0, n.CumulativeDistribution(x));
Assert.AreEqual(1.0, ContinuousUniform.CDF(lower, upper, x));
}
else
{
Assert.AreEqual((x - lower)/(upper - lower), n.CumulativeDistribution(x));
Assert.AreEqual((x - lower)/(upper - lower), ContinuousUniform.CDF(lower, upper, x));
}
}
}
/// <summary>
/// Validate inverse cumulative distribution.
/// </summary>
/// <param name="lower">Lower bound.</param>
/// <param name="upper">Upper bound.</param>
[TestCase(0.0, 0.0)]
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
public void ValidateInverseCumulativeDistribution(double lower, double upper)
{
var n = new ContinuousUniform(lower, upper);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
if (x <= lower)
{
Assert.AreEqual(lower, n.InverseCumulativeDistribution(0.0), 1e-12);
Assert.AreEqual(lower, ContinuousUniform.InvCDF(lower, upper, 0.0), 1e-12);
}
else if (x >= upper)
{
Assert.AreEqual(upper, n.InverseCumulativeDistribution(1.0), 1e-12);
Assert.AreEqual(upper, ContinuousUniform.InvCDF(lower, upper, 1.0), 1e-12);
}
else
{
Assert.AreEqual(x, n.InverseCumulativeDistribution((x - lower)/(upper - lower)), 1e-12);
Assert.AreEqual(x, ContinuousUniform.InvCDF(lower, upper, (x - lower)/(upper - lower)), 1e-12);
}
}
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using Fields = Lucene.Net.Index.Fields;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using IOContext = Lucene.Net.Store.IOContext;
using LogMergePolicy = Lucene.Net.Index.LogMergePolicy;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockTokenizer = Lucene.Net.Analysis.MockTokenizer;
using MultiFields = Lucene.Net.Index.MultiFields;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SegmentReader = Lucene.Net.Index.SegmentReader;
using Term = Lucene.Net.Index.Term;
using TermQuery = Lucene.Net.Search.TermQuery;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TestUtil = Lucene.Net.Util.TestUtil;
using TopDocs = Lucene.Net.Search.TopDocs;
#pragma warning disable 612, 618
[TestFixture]
public class TestTermInfosReaderIndex : LuceneTestCase
{
private static int NUMBER_OF_DOCUMENTS;
private static int NUMBER_OF_FIELDS;
private static TermInfosReaderIndex index;
private static Directory directory;
private static SegmentTermEnum termEnum;
private static int indexDivisor;
private static int termIndexInterval;
private static IndexReader reader;
private static IList<Term> sampleTerms;
/// <summary>
/// we will manually instantiate preflex-rw here
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
// NOTE: turn off compound file, this test will open some index files directly.
OldFormatImpersonationIsActive = true;
IndexWriterConfig config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.KEYWORD, false)).SetUseCompoundFile(false);
termIndexInterval = config.TermIndexInterval;
indexDivisor = TestUtil.NextInt32(Random, 1, 10);
NUMBER_OF_DOCUMENTS = AtLeast(100);
NUMBER_OF_FIELDS = AtLeast(Math.Max(10, 3 * termIndexInterval * indexDivisor / NUMBER_OF_DOCUMENTS));
directory = NewDirectory();
config.SetCodec(new PreFlexRWCodec());
LogMergePolicy mp = NewLogMergePolicy();
// NOTE: turn off compound file, this test will open some index files directly.
mp.NoCFSRatio = 0.0;
config.SetMergePolicy(mp);
Populate(directory, config);
DirectoryReader r0 = IndexReader.Open(directory);
SegmentReader r = LuceneTestCase.GetOnlySegmentReader(r0);
string segment = r.SegmentName;
r.Dispose();
FieldInfosReader infosReader = (new PreFlexRWCodec()).FieldInfosFormat.FieldInfosReader;
FieldInfos fieldInfos = infosReader.Read(directory, segment, "", IOContext.READ_ONCE);
string segmentFileName = IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
long tiiFileLength = directory.FileLength(segmentFileName);
IndexInput input = directory.OpenInput(segmentFileName, NewIOContext(Random));
termEnum = new SegmentTermEnum(directory.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), NewIOContext(Random)), fieldInfos, false);
int totalIndexInterval = termEnum.indexInterval * indexDivisor;
SegmentTermEnum indexEnum = new SegmentTermEnum(input, fieldInfos, true);
index = new TermInfosReaderIndex(indexEnum, indexDivisor, tiiFileLength, totalIndexInterval);
indexEnum.Dispose();
input.Dispose();
reader = IndexReader.Open(directory);
sampleTerms = Sample(Random, reader, 1000);
}
[OneTimeTearDown]
public override void AfterClass()
{
termEnum.Dispose();
reader.Dispose();
directory.Dispose();
termEnum = null;
reader = null;
directory = null;
index = null;
sampleTerms = null;
base.AfterClass();
}
[Test]
public virtual void TestSeekEnum()
{
int indexPosition = 3;
SegmentTermEnum clone = (SegmentTermEnum)termEnum.Clone();
Term term = FindTermThatWouldBeAtIndex(clone, indexPosition);
SegmentTermEnum enumerator = clone;
index.SeekEnum(enumerator, indexPosition);
Assert.AreEqual(term, enumerator.Term());
clone.Dispose();
}
[Test]
public virtual void TestCompareTo()
{
Term term = new Term("field" + Random.Next(NUMBER_OF_FIELDS), Text);
for (int i = 0; i < index.Length; i++)
{
Term t = index.GetTerm(i);
int compareTo = term.CompareTo(t);
Assert.AreEqual(compareTo, index.CompareTo(term, i));
}
}
[Test]
public virtual void TestRandomSearchPerformance()
{
IndexSearcher searcher = new IndexSearcher(reader);
foreach (Term t in sampleTerms)
{
TermQuery query = new TermQuery(t);
TopDocs topDocs = searcher.Search(query, 10);
Assert.IsTrue(topDocs.TotalHits > 0);
}
}
private static IList<Term> Sample(Random random, IndexReader reader, int size)
{
IList<Term> sample = new List<Term>();
Fields fields = MultiFields.GetFields(reader);
foreach (string field in fields)
{
Terms terms = fields.GetTerms(field);
Assert.IsNotNull(terms);
TermsEnum termsEnum = terms.GetEnumerator();
while (termsEnum.MoveNext())
{
if (sample.Count >= size)
{
int pos = random.Next(size);
sample[pos] = new Term(field, termsEnum.Term);
}
else
{
sample.Add(new Term(field, termsEnum.Term));
}
}
}
sample.Shuffle(Random);
return sample;
}
private Term FindTermThatWouldBeAtIndex(SegmentTermEnum termEnum, int index)
{
int termPosition = index * termIndexInterval * indexDivisor;
for (int i = 0; i < termPosition; i++)
{
// TODO: this test just uses random terms, so this is always possible
AssumeTrue("ran out of terms", termEnum.Next());
}
Term term = termEnum.Term();
// An indexed term is only written when the term after
// it exists, so, if the number of terms is 0 mod
// termIndexInterval, the last index term will not be
// written; so we require a term after this term
// as well:
AssumeTrue("ran out of terms", termEnum.Next());
return term;
}
private void Populate(Directory directory, IndexWriterConfig config)
{
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, config);
for (int i = 0; i < NUMBER_OF_DOCUMENTS; i++)
{
Document document = new Document();
for (int f = 0; f < NUMBER_OF_FIELDS; f++)
{
document.Add(NewStringField("field" + f, Text, Field.Store.NO));
}
writer.AddDocument(document);
}
writer.ForceMerge(1);
writer.Dispose();
}
private static string Text => Convert.ToString(Random.Next(), CultureInfo.InvariantCulture);
}
#pragma warning restore 612, 618
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// SecurityFlags
//
////////////////////////////////////////////////////////////////
public enum SecurityFlags
{
None = 0,
FullTrust = 1,
}
////////////////////////////////////////////////////////////////
// TestAttr (attribute)
//
////////////////////////////////////////////////////////////////
public class CAttrBase : Attribute
{
//Data
private string _name;
private string _desc;
private object[] _params;
private int _id;
private bool _inheritance = true;
private CAttrBase _parent = null;
private string _filter;
//Allows Inhertiance (ie: object to determine if ever been set)
private object _priority; //Allows Inhertiance
private object _implemented; //Allows Inhertiance
private object _skipped; //Allows Inhertiance
private object _error; //Allows Inhertiance
private object _security; //Allows Inhertiance
private object _filtercriteria;//Allows Inhertiance
private object[] _languages; //Allows Inhertiance
private object _xml; //Allows Inhertiance
//Constructors
public CAttrBase()
{
}
public CAttrBase(string desc)
{
Desc = desc;
}
//Accessors
public virtual string Name
{
get { return _name; }
set { _name = value; }
}
public virtual string Desc
{
get { return _desc; }
set { _desc = value; }
}
public virtual int id
{
get { return _id; }
set { _id = value; }
}
public virtual object Param
{
get
{
if (_params != null)
return _params[0];
return null;
}
set
{
if (_params == null)
_params = new object[1];
_params[0] = value;
}
}
public virtual object[] Params
{
get { return _params; }
set { _params = value; }
}
public virtual bool Inheritance
{
get { return _inheritance; }
set { _inheritance = value; }
}
public virtual CAttrBase Parent
{
get { return _parent; }
set { _parent = value; }
}
public virtual string Filter
{
get { return _filter; }
set { _filter = value; }
}
public virtual int Pri
{
get
{
if (_priority == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Pri;
//Default
return 2;
}
return (int)_priority;
}
set { _priority = value; }
}
public virtual int Priority //Alias for Pri
{
get { return this.Pri; }
set { this.Pri = value; }
}
public virtual bool Implemented
{
get
{
if (_implemented == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Implemented;
//Default
return true;
}
return (bool)_implemented;
}
set { _implemented = value; }
}
public virtual bool Skipped
{
get
{
if (_skipped == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Skipped;
//Default
return false;
}
return (bool)_skipped;
}
set { _skipped = value; }
}
public virtual bool Error
{
get
{
if (_error == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Error;
//Default
return false;
}
return (bool)_error;
}
set { _error = value; }
}
public virtual SecurityFlags Security
{
get
{
if (_security == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Security;
//Default
return SecurityFlags.None;
}
return (SecurityFlags)_security;
}
set { _security = value; }
}
public virtual string FilterCriteria
{
get
{
if (_filtercriteria == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.FilterCriteria;
//Default
return null;
}
return (string)_filtercriteria;
}
set { _filtercriteria = value; }
}
public virtual string Language
{
get
{
if (Languages != null)
return Languages[0];
return null;
}
set
{
if (Languages == null)
Languages = new string[1];
Languages[0] = value;
}
}
public virtual string[] Languages
{
get
{
if (_languages == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Languages;
//Default
return null;
}
return (string[])_languages;
}
set { _languages = value; }
}
public virtual string Xml
{
get
{
if (_xml == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Xml;
//Default
return null;
}
return (string)_xml;
}
set { _xml = value; }
}
}
////////////////////////////////////////////////////////////////
// TestModule (attribute)
//
////////////////////////////////////////////////////////////////
public class TestModule : CAttrBase
{
//Data
private string[] _owners;
private int _version;
private string _created;
private string _modified;
//Constructors
public TestModule()
: base()
{
}
public TestModule(string desc)
: base(desc)
{
//NOTE: For all other params, just simply use the named attributes:
//[TestModule(Desc="desc", Version=1)]
}
//Accessors (named attributes)
public virtual string Owner
{
get
{
if (_owners != null)
return _owners[0];
return null;
}
set
{
if (_owners == null)
_owners = new string[1];
_owners[0] = value;
}
}
public virtual string[] Owners
{
get { return _owners; }
set { _owners = value; }
}
public virtual int Version
{
get { return _version; }
set { _version = value; }
}
public virtual string Created
{
get { return _created; }
set { _created = value; }
}
public virtual string Modified
{
get { return _modified; }
set { _modified = value; }
}
}
////////////////////////////////////////////////////////////////
// TestCase (attribute)
//
////////////////////////////////////////////////////////////////
public class TestCase : CAttrBase
{
//Constructors
public TestCase()
: base()
{
}
public TestCase(string desc)
: base(desc)
{
//NOTE: For all other params, just simply use the named attributes:
//[TestCase(Desc="desc", Name="name")]
}
}
////////////////////////////////////////////////////////////////
// Variation (attribute)
//
////////////////////////////////////////////////////////////////
public class Variation : CAttrBase
{
//Data
//Constructors
public Variation()
: base()
{
}
public Variation(string desc)
: base(desc)
{
//NOTE: For all other params, just simply use the named attributes:
//[Variation(Desc="desc", id=1)]
}
}
////////////////////////////////////////////////////////////////
// TestInclude (attribute)
//
////////////////////////////////////////////////////////////////
public class TestInclude : Attribute
{
//Data
private string _name;
private string _file;
private string _files;
private string _filter;
//Constructors
public TestInclude()
{
}
public virtual string Name
{
//Prefix for testcase names
get { return _name; }
set { _name = value; }
}
public virtual string File
{
get { return _file; }
set { _file = value; }
}
public virtual string Files
{
//Search Pattern (ie: *.*)
get { return _files; }
set { _files = value; }
}
public virtual string Filter
{
get { return _filter; }
set { _filter = value; }
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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.Globalization;
using System.Linq;
using Newtonsoft.Json;
using NodaTime;
using NUnit.Framework;
using Python.Runtime;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Indicators;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.HistoricalData;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Packets;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Common.Util
{
[TestFixture]
public class ExtensionsTests
{
[TestCase("A", "a")]
[TestCase("", "")]
[TestCase(null, null)]
[TestCase("Buy", "buy")]
[TestCase("BuyTheDip", "buyTheDip")]
public void ToCamelCase(string toConvert, string expected)
{
Assert.AreEqual(expected, toConvert.ToCamelCase());
}
[Test]
public void BatchAlphaResultPacket()
{
var btcusd = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX);
var insights = new List<Insight>
{
new Insight(DateTime.UtcNow, btcusd, Time.OneMillisecond, InsightType.Price, InsightDirection.Up, 1, 2, "sourceModel1"),
new Insight(DateTime.UtcNow, btcusd, Time.OneSecond, InsightType.Price, InsightDirection.Down, 1, 2, "sourceModel1")
};
var orderEvents = new List<OrderEvent>
{
new OrderEvent(1, btcusd, DateTime.UtcNow, OrderStatus.Submitted, OrderDirection.Buy, 0, 0, OrderFee.Zero, message: "OrderEvent1"),
new OrderEvent(1, btcusd, DateTime.UtcNow, OrderStatus.Filled, OrderDirection.Buy, 1, 1000, OrderFee.Zero, message: "OrderEvent2")
};
var orders = new List<Order> { new MarketOrder(btcusd, 1000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 } };
var packet1 = new AlphaResultPacket("1", 1, insights: insights, portfolio: new AlphaStreamsPortfolioState { TotalPortfolioValue = 11 });
var packet2 = new AlphaResultPacket("1", 1, orders: orders);
var packet3 = new AlphaResultPacket("1", 1, orderEvents: orderEvents, portfolio: new AlphaStreamsPortfolioState { TotalPortfolioValue = 12 });
var result = new List<AlphaResultPacket> { packet1, packet2, packet3 }.Batch();
Assert.AreEqual(2, result.Insights.Count);
Assert.AreEqual(2, result.OrderEvents.Count);
Assert.AreEqual(1, result.Orders.Count);
Assert.AreEqual(12, result.Portfolio.TotalPortfolioValue);
Assert.IsTrue(result.Insights.SequenceEqual(insights));
Assert.IsTrue(result.OrderEvents.SequenceEqual(orderEvents));
Assert.IsTrue(result.Orders.SequenceEqual(orders));
Assert.IsNull(new List<AlphaResultPacket>().Batch());
}
[Test]
public void BatchAlphaResultPacketDuplicateOrder()
{
var btcusd = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX);
var orders = new List<Order>
{
new MarketOrder(btcusd, 1000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 },
new MarketOrder(btcusd, 100, DateTime.UtcNow, "ExpensiveOrder") { Id = 2 },
new MarketOrder(btcusd, 2000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 },
new MarketOrder(btcusd, 10, DateTime.UtcNow, "ExpensiveOrder") { Id = 3 },
new MarketOrder(btcusd, 3000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 }
};
var orders2 = new List<Order>
{
new MarketOrder(btcusd, 200, DateTime.UtcNow, "ExpensiveOrder") { Id = 2 },
new MarketOrder(btcusd, 20, DateTime.UtcNow, "ExpensiveOrder") { Id = 3 }
};
var packet1 = new AlphaResultPacket("1", 1, orders: orders);
var packet2 = new AlphaResultPacket("1", 1, orders: orders2);
var result = new List<AlphaResultPacket> { packet1, packet2 }.Batch();
// we expect just 1 order instance per order id
Assert.AreEqual(3, result.Orders.Count);
Assert.IsTrue(result.Orders.Any(order => order.Id == 1 && order.Quantity == 3000));
Assert.IsTrue(result.Orders.Any(order => order.Id == 2 && order.Quantity == 200));
Assert.IsTrue(result.Orders.Any(order => order.Id == 3 && order.Quantity == 20));
var expected = new List<Order> { orders[4], orders2[0], orders2[1] };
Assert.IsTrue(result.Orders.SequenceEqual(expected));
}
[Test]
public void SeriesIsNotEmpty()
{
var series = new Series("SadSeries")
{ Values = new List<ChartPoint> { new ChartPoint(1, 1) } };
Assert.IsFalse(series.IsEmpty());
}
[Test]
public void SeriesIsEmpty()
{
Assert.IsTrue((new Series("Cat")).IsEmpty());
}
[Test]
public void ChartIsEmpty()
{
Assert.IsTrue((new Chart("HappyChart")).IsEmpty());
}
[Test]
public void ChartIsEmptyWithEmptySeries()
{
Assert.IsTrue((new Chart("HappyChart")
{ Series = new Dictionary<string, Series> { { "SadSeries", new Series("SadSeries") } }}).IsEmpty());
}
[Test]
public void ChartIsNotEmptyWithNonEmptySeries()
{
var series = new Series("SadSeries")
{ Values = new List<ChartPoint> { new ChartPoint(1, 1) } };
Assert.IsFalse((new Chart("HappyChart")
{ Series = new Dictionary<string, Series> { { "SadSeries", series } } }).IsEmpty());
}
[Test]
public void IsSubclassOfGenericWorksWorksForNonGenericType()
{
Assert.IsTrue(typeof(Derived2).IsSubclassOfGeneric(typeof(Derived1)));
}
[Test]
public void IsSubclassOfGenericWorksForGenericTypeWithParameter()
{
Assert.IsTrue(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<int>)));
Assert.IsFalse(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<bool>)));
}
[Test]
public void IsSubclassOfGenericWorksForGenericTypeDefinitions()
{
Assert.IsTrue(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<>)));
Assert.IsTrue(typeof(Derived2).IsSubclassOfGeneric(typeof(Super<>)));
}
[Test]
public void DateTimeRoundDownFullDayDoesntRoundDownByDay()
{
var date = new DateTime(2000, 01, 01);
var rounded = date.RoundDown(TimeSpan.FromDays(1));
Assert.AreEqual(date, rounded);
}
[Test]
public void GetBetterTypeNameHandlesRecursiveGenericTypes()
{
var type = typeof (Dictionary<List<int>, Dictionary<int, string>>);
const string expected = "Dictionary<List<Int32>, Dictionary<Int32, String>>";
var actual = type.GetBetterTypeName();
Assert.AreEqual(expected, actual);
}
[Test]
public void ExchangeRoundDownSkipsWeekends()
{
var time = new DateTime(2015, 05, 02, 18, 01, 00);
var expected = new DateTime(2015, 05, 01);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.FXCM, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDown(Time.OneDay, hours, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownHandlesMarketOpenTime()
{
var time = new DateTime(2016, 1, 25, 9, 31, 0);
var expected = time.Date;
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity);
var exchangeRounded = time.ExchangeRoundDown(Time.OneDay, hours, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ConvertToSkipsDiscontinuitiesBecauseOfDaylightSavingsStart_AddingOneHour()
{
var expected = new DateTime(2014, 3, 9, 3, 0, 0);
var time = new DateTime(2014, 3, 9, 2, 0, 0).ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
var time2 = new DateTime(2014, 3, 9, 2, 0, 1).ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
Assert.AreEqual(expected, time);
Assert.AreEqual(expected, time2);
}
[Test]
public void ConvertToIgnoreDaylightSavingsEnd_SubtractingOneHour()
{
var time1Expected = new DateTime(2014, 11, 2, 1, 59, 59);
var time2Expected = new DateTime(2014, 11, 2, 2, 0, 0);
var time3Expected = new DateTime(2014, 11, 2, 2, 0, 1);
var time1 = time1Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
var time2 = time2Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
var time3 = time3Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
Assert.AreEqual(time1Expected, time1);
Assert.AreEqual(time2Expected, time2);
Assert.AreEqual(time3Expected, time3);
}
[Test]
public void ExchangeRoundDownInTimeZoneSkipsWeekends()
{
// moment before EST market open in UTC (time + one day)
var time = new DateTime(2017, 10, 01, 9, 29, 59).ConvertToUtc(TimeZones.NewYork);
var expected = new DateTime(2017, 09, 29).ConvertFromUtc(TimeZones.NewYork);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneDay, hours, TimeZones.Utc, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
// This unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, in ExchangeRoundDownInTimeZone, GH issue 2368.
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_UTC()
{
var time = new DateTime(2014, 3, 9, 16, 0, 1);
var expected = new DateTime(2014, 3, 7, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
// This unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, in ExchangeRoundDownInTimeZone, GH issue 2368.
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_UTC()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 10, 31, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_ExtendedHours_UTC()
{
var time = new DateTime(2014, 3, 9, 2, 0, 1);
var expected = new DateTime(2014, 3, 9, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_ExtendedHours_UTC()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 11, 2, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
// this unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, GH issue 3707.
public void RoundDownInTimeZoneAroundDaylightTimeChanges()
{
// sydney time advanced Sunday, 6 October 2019, 02:00:00 clocks were turned forward 1 hour to
// Sunday, 6 October 2019, 03:00:00 local daylight time instead.
var timeAt = new DateTime(2019, 10, 6, 10, 0, 0);
var expected = new DateTime(2019, 10, 5, 10, 0, 0);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneDay, TimeZones.Sydney, TimeZones.Utc);
// even though there is an entire 'roundingInterval' unit (1 day) between 'timeAt' and 'expected' round down
// is affected by daylight savings and rounds down the timeAt
Assert.AreEqual(expected, exchangeRoundedAt);
timeAt = new DateTime(2019, 10, 7, 10, 0, 0);
expected = new DateTime(2019, 10, 6, 11, 0, 0);
exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneDay, TimeZones.Sydney, TimeZones.Utc);
Assert.AreEqual(expected, exchangeRoundedAt);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_AddingOneHour_UTC()
{
var timeAt = new DateTime(2014, 3, 9, 2, 0, 0);
var timeAfter = new DateTime(2014, 3, 9, 2, 0, 1);
var timeBefore = new DateTime(2014, 3, 9, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 3, 9, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var expected = new DateTime(2014, 3, 9, 3, 0, 0);
Assert.AreEqual(expected, exchangeRoundedAt);
Assert.AreEqual(expected, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(expected, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_UTC()
{
var timeAt = new DateTime(2014, 11, 2, 2, 0, 0);
var timeAfter = new DateTime(2014, 11, 2, 2, 0, 1);
var timeBefore = new DateTime(2014, 11, 2, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 11, 2, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
Assert.AreEqual(timeAt, exchangeRoundedAt);
Assert.AreEqual(timeAfter, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(timeAfterDaylightTimeChanges, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_NewYork()
{
var time = new DateTime(2014, 3, 9, 16, 0, 1);
var expected = new DateTime(2014, 3, 7, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_NewYork()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 10, 31, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_ExtendedHours_NewYork()
{
var time = new DateTime(2014, 3, 9, 2, 0, 1);
var expected = new DateTime(2014, 3, 9, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_ExtendedHours_NewYork()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 11, 2, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_AddingOneHour_NewYork()
{
var timeAt = new DateTime(2014, 3, 9, 2, 0, 0);
var timeAfter = new DateTime(2014, 3, 9, 2, 0, 1);
var timeBefore = new DateTime(2014, 3, 9, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 3, 9, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var expected = new DateTime(2014, 3, 9, 3, 0, 0);
Assert.AreEqual(expected, exchangeRoundedAt);
Assert.AreEqual(expected, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(expected, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_NewYork()
{
var timeAt = new DateTime(2014, 11, 2, 2, 0, 0);
var timeAfter = new DateTime(2014, 11, 2, 2, 0, 1);
var timeBefore = new DateTime(2014, 11, 2, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 11, 2, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
Assert.AreEqual(timeAt, exchangeRoundedAt);
Assert.AreEqual(timeAfter, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(timeAfterDaylightTimeChanges, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void ConvertsInt32FromString()
{
const string input = "12345678";
var value = input.ToInt32();
Assert.AreEqual(12345678, value);
}
[Test]
public void ConvertsInt32FromStringWithDecimalTruncation()
{
const string input = "12345678.9";
var value = input.ToInt32();
Assert.AreEqual(12345678, value);
}
[Test]
public void ConvertsInt64FromString()
{
const string input = "12345678900";
var value = input.ToInt64();
Assert.AreEqual(12345678900, value);
}
[Test]
public void ConvertsInt64FromStringWithDecimalTruncation()
{
const string input = "12345678900.12";
var value = input.ToInt64();
Assert.AreEqual(12345678900, value);
}
[Test]
public void ToCsvDataParsesCorrectly()
{
var csv = "\"hello\",\"world\"".ToCsvData();
Assert.AreEqual(2, csv.Count);
Assert.AreEqual("\"hello\"", csv[0]);
Assert.AreEqual("\"world\"", csv[1]);
var csv2 = "1,2,3,4".ToCsvData();
Assert.AreEqual(4, csv2.Count);
Assert.AreEqual("1", csv2[0]);
Assert.AreEqual("2", csv2[1]);
Assert.AreEqual("3", csv2[2]);
Assert.AreEqual("4", csv2[3]);
}
[Test]
public void ToCsvDataParsesEmptyFinalValue()
{
var line = "\"hello\",world,";
var csv = line.ToCsvData();
Assert.AreEqual(3, csv.Count);
Assert.AreEqual("\"hello\"", csv[0]);
Assert.AreEqual("hello", csv[0].Trim('"'));
Assert.AreEqual("world", csv[1]);
Assert.AreEqual(string.Empty, csv[2]);
}
[Test]
public void ToCsvDataParsesEmptyValue()
{
Assert.AreEqual(string.Empty, string.Empty.ToCsvData()[0]);
}
[Test]
public void ConvertsDecimalFromString()
{
const string input = "123.45678";
var value = input.ToDecimal();
Assert.AreEqual(123.45678m, value);
}
[Test]
public void ConvertsDecimalFromStringWithExtraWhiteSpace()
{
const string input = " 123.45678 ";
var value = input.ToDecimal();
Assert.AreEqual(123.45678m, value);
}
[Test]
public void ConvertsDecimalFromIntStringWithExtraWhiteSpace()
{
const string input = " 12345678 ";
var value = input.ToDecimal();
Assert.AreEqual(12345678m, value);
}
[Test]
public void ConvertsZeroDecimalFromString()
{
const string input = "0.45678";
var value = input.ToDecimal();
Assert.AreEqual(0.45678m, value);
}
[Test]
public void ConvertsOneNumberDecimalFromString()
{
const string input = "1.45678";
var value = input.ToDecimal();
Assert.AreEqual(1.45678m, value);
}
[Test]
public void ConvertsZeroDecimalValueFromString()
{
const string input = "0";
var value = input.ToDecimal();
Assert.AreEqual(0m, value);
}
[Test]
public void ConvertsEmptyDecimalValueFromString()
{
const string input = "";
var value = input.ToDecimal();
Assert.AreEqual(0m, value);
}
[Test]
public void ConvertsNegativeDecimalFromString()
{
const string input = "-123.45678";
var value = input.ToDecimal();
Assert.AreEqual(-123.45678m, value);
}
[Test]
public void ConvertsNegativeDecimalFromStringWithExtraWhiteSpace()
{
const string input = " -123.45678 ";
var value = input.ToDecimal();
Assert.AreEqual(-123.45678m, value);
}
[Test]
public void ConvertsNegativeDecimalFromIntStringWithExtraWhiteSpace()
{
const string input = " -12345678 ";
var value = input.ToDecimal();
Assert.AreEqual(-12345678m, value);
}
[Test]
public void ConvertsNegativeZeroDecimalFromString()
{
const string input = "-0.45678";
var value = input.ToDecimal();
Assert.AreEqual(-0.45678m, value);
}
[Test]
public void ConvertsNegavtiveOneNumberDecimalFromString()
{
const string input = "-1.45678";
var value = input.ToDecimal();
Assert.AreEqual(-1.45678m, value);
}
[Test]
public void ConvertsNegativeZeroDecimalValueFromString()
{
const string input = "-0";
var value = input.ToDecimal();
Assert.AreEqual(-0m, value);
}
[TestCase("1.23%", 0.0123d)]
[TestCase("-1.23%", -0.0123d)]
[TestCase("31.2300%", 0.3123d)]
[TestCase("20%", 0.2d)]
[TestCase("-20%", -0.2d)]
[TestCase("220%", 2.2d)]
public void ConvertsPercent(string input, double expected)
{
Assert.AreEqual(new decimal(expected), input.ToNormalizedDecimal());
}
[Test]
public void ConvertsTimeSpanFromString()
{
const string input = "16:00";
var timespan = input.ConvertTo<TimeSpan>();
Assert.AreEqual(TimeSpan.FromHours(16), timespan);
}
[Test]
public void ConvertsDictionaryFromString()
{
var expected = new Dictionary<string, int> {{"a", 1}, {"b", 2}};
var input = JsonConvert.SerializeObject(expected);
var actual = input.ConvertTo<Dictionary<string, int>>();
CollectionAssert.AreEqual(expected, actual);
}
[Test]
public void DictionaryAddsItemToExistsList()
{
const int key = 0;
var list = new List<int> {1, 2};
var dictionary = new Dictionary<int, List<int>> {{key, list}};
Extensions.Add(dictionary, key, 3);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(3, list[2]);
}
[Test]
public void DictionaryAddCreatesNewList()
{
const int key = 0;
var dictionary = new Dictionary<int, List<int>>();
Extensions.Add(dictionary, key, 1);
Assert.IsTrue(dictionary.ContainsKey(key));
var list = dictionary[key];
Assert.AreEqual(1, list.Count);
Assert.AreEqual(1, list[0]);
}
[Test]
public void SafeDecimalCasts()
{
var input = 2d;
var output = input.SafeDecimalCast();
Assert.AreEqual(2m, output);
}
[Test]
public void SafeDecimalCastRespectsUpperBound()
{
var input = (double) decimal.MaxValue;
var output = input.SafeDecimalCast();
Assert.AreEqual(decimal.MaxValue, output);
}
[Test]
public void SafeDecimalCastRespectsLowerBound()
{
var input = (double) decimal.MinValue;
var output = input.SafeDecimalCast();
Assert.AreEqual(decimal.MinValue, output);
}
[TestCase(Language.CSharp, double.NaN)]
[TestCase(Language.Python, double.NaN)]
[TestCase(Language.CSharp, double.NegativeInfinity)]
[TestCase(Language.Python, double.NegativeInfinity)]
[TestCase(Language.CSharp, double.PositiveInfinity)]
[TestCase(Language.Python, double.PositiveInfinity)]
public void SafeDecimalCastThrowsArgumentException(Language language, double number)
{
if (language == Language.CSharp)
{
Assert.Throws<ArgumentException>(() => number.SafeDecimalCast());
return;
}
using (Py.GIL())
{
var pyNumber = number.ToPython();
var csNumber = pyNumber.As<double>();
Assert.Throws<ArgumentException>(() => csNumber.SafeDecimalCast());
}
}
[Test]
[TestCase(1.200, "1.2")]
[TestCase(1200, "1200")]
[TestCase(123.456, "123.456")]
public void NormalizeDecimalReturnsNoTrailingZeros(decimal input, string expectedOutput)
{
var output = input.Normalize();
Assert.AreEqual(expectedOutput, output.ToStringInvariant());
}
[Test]
[TestCase(0.072842, 3, "0.0728")]
[TestCase(0.0019999, 2, "0.0020")]
[TestCase(0.01234568423, 6, "0.0123457")]
public void RoundToSignificantDigits(decimal input, int digits, string expectedOutput)
{
var output = input.RoundToSignificantDigits(digits).ToStringInvariant();
Assert.AreEqual(expectedOutput, output);
}
[Test]
public void RoundsDownInTimeZone()
{
var dataTimeZone = TimeZones.Utc;
var exchangeTimeZone = TimeZones.EasternStandard;
var time = new DateTime(2000, 01, 01).ConvertTo(dataTimeZone, exchangeTimeZone);
var roundedTime = time.RoundDownInTimeZone(Time.OneDay, exchangeTimeZone, dataTimeZone);
Assert.AreEqual(time, roundedTime);
}
[Test]
public void GetStringBetweenCharsTests()
{
const string expected = "python3.6";
// Different characters cases
var input = "[ python3.6 ]";
var actual = input.GetStringBetweenChars('[', ']');
Assert.AreEqual(expected, actual);
input = "[ python3.6 ] [ python2.7 ]";
actual = input.GetStringBetweenChars('[', ']');
Assert.AreEqual(expected, actual);
input = "[ python2.7 [ python3.6 ] ]";
actual = input.GetStringBetweenChars('[', ']');
Assert.AreEqual(expected, actual);
// Same character cases
input = "\'python3.6\'";
actual = input.GetStringBetweenChars('\'', '\'');
Assert.AreEqual(expected, actual);
input = "\' python3.6 \' \' python2.7 \'";
actual = input.GetStringBetweenChars('\'', '\'');
Assert.AreEqual(expected, actual);
// In this case, it is not equal
input = "\' python2.7 \' python3.6 \' \'";
actual = input.GetStringBetweenChars('\'', '\'');
Assert.AreNotEqual(expected, actual);
}
[Test]
public void PyObjectTryConvertQuoteBar()
{
// Wrap a QuoteBar around a PyObject and convert it back
var value = ConvertToPyObject(new QuoteBar());
QuoteBar quoteBar;
var canConvert = value.TryConvert(out quoteBar);
Assert.IsTrue(canConvert);
Assert.IsNotNull(quoteBar);
Assert.IsAssignableFrom<QuoteBar>(quoteBar);
}
[Test]
public void PyObjectTryConvertSMA()
{
// Wrap a SimpleMovingAverage around a PyObject and convert it back
var value = ConvertToPyObject(new SimpleMovingAverage(14));
IndicatorBase<IndicatorDataPoint> indicatorBaseDataPoint;
var canConvert = value.TryConvert(out indicatorBaseDataPoint);
Assert.IsTrue(canConvert);
Assert.IsNotNull(indicatorBaseDataPoint);
Assert.IsAssignableFrom<SimpleMovingAverage>(indicatorBaseDataPoint);
}
[Test]
public void PyObjectTryConvertATR()
{
// Wrap a AverageTrueRange around a PyObject and convert it back
var value = ConvertToPyObject(new AverageTrueRange(14, MovingAverageType.Simple));
IndicatorBase<IBaseDataBar> indicatorBaseDataBar;
var canConvert = value.TryConvert(out indicatorBaseDataBar);
Assert.IsTrue(canConvert);
Assert.IsNotNull(indicatorBaseDataBar);
Assert.IsAssignableFrom<AverageTrueRange>(indicatorBaseDataBar);
}
[Test]
public void PyObjectTryConvertAD()
{
// Wrap a AccumulationDistribution around a PyObject and convert it back
var value = ConvertToPyObject(new AccumulationDistribution("AD"));
IndicatorBase<TradeBar> indicatorBaseTradeBar;
var canConvert = value.TryConvert(out indicatorBaseTradeBar);
Assert.IsTrue(canConvert);
Assert.IsNotNull(indicatorBaseTradeBar);
Assert.IsAssignableFrom<AccumulationDistribution>(indicatorBaseTradeBar);
}
[Test]
public void PyObjectTryConvertSymbolArray()
{
PyObject value;
using (Py.GIL())
{
// Wrap a Symbol Array around a PyObject and convert it back
value = new PyList(new[] { Symbols.SPY.ToPython(), Symbols.AAPL.ToPython() });
}
Symbol[] symbols;
var canConvert = value.TryConvert(out symbols);
Assert.IsTrue(canConvert);
Assert.IsNotNull(symbols);
Assert.IsAssignableFrom<Symbol[]>(symbols);
}
[Test]
public void PyObjectTryConvertFailCSharp()
{
// Try to convert a AccumulationDistribution as a QuoteBar
var value = ConvertToPyObject(new AccumulationDistribution("AD"));
QuoteBar quoteBar;
bool canConvert = value.TryConvert(out quoteBar);
Assert.IsFalse(canConvert);
Assert.IsNull(quoteBar);
}
[Test]
public void PyObjectTryConvertFailPython()
{
using (Py.GIL())
{
// Try to convert a python object as a IndicatorBase<TradeBar>
var locals = new PyDict();
PythonEngine.Exec("class A:\n pass", null, locals.Handle);
var value = locals.GetItem("A").Invoke();
IndicatorBase<TradeBar> indicatorBaseTradeBar;
bool canConvert = value.TryConvert(out indicatorBaseTradeBar);
Assert.IsFalse(canConvert);
Assert.IsNull(indicatorBaseTradeBar);
}
}
[Test]
[TestCase("coarseSelector = lambda coarse: [ x.Symbol for x in coarse if x.Price % 2 == 0 ]")]
[TestCase("def coarseSelector(coarse): return [ x.Symbol for x in coarse if x.Price % 2 == 0 ]")]
public void PyObjectTryConvertToFunc(string code)
{
Func<IEnumerable<CoarseFundamental>, Symbol[]> coarseSelector;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec(code, null, locals.Handle);
var pyObject = locals.GetItem("coarseSelector");
pyObject.TryConvertToDelegate(out coarseSelector);
}
var coarse = Enumerable
.Range(0, 9)
.Select(x => new CoarseFundamental { Symbol = Symbol.Create(x.ToStringInvariant(), SecurityType.Equity, Market.USA), Value = x });
var symbols = coarseSelector(coarse);
Assert.AreEqual(5, symbols.Length);
foreach (var symbol in symbols)
{
var price = symbol.Value.ConvertInvariant<int>();
Assert.AreEqual(0, price % 2);
}
}
[Test]
public void PyObjectTryConvertToAction1()
{
Action<int> action;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec("def raise_number(a): raise ValueError(a)", null, locals.Handle);
var pyObject = locals.GetItem("raise_number");
pyObject.TryConvertToDelegate(out action);
}
try
{
action(2);
Assert.Fail();
}
catch (PythonException e)
{
Assert.AreEqual($"ValueError : {2}", e.Message);
}
}
[Test]
public void PyObjectTryConvertToAction2()
{
Action<int, decimal> action;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec("def raise_number(a, b): raise ValueError(a * b)", null, locals.Handle);
var pyObject = locals.GetItem("raise_number");
pyObject.TryConvertToDelegate(out action);
}
try
{
action(2, 3m);
Assert.Fail();
}
catch (PythonException e)
{
Assert.AreEqual("ValueError : 6.0", e.Message);
}
}
[Test]
public void PyObjectTryConvertToNonDelegateFail()
{
int action;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec("def raise_number(a, b): raise ValueError(a * b)", null, locals.Handle);
var pyObject = locals.GetItem("raise_number");
Assert.Throws<ArgumentException>(() => pyObject.TryConvertToDelegate(out action));
}
}
[Test]
public void PyObjectStringConvertToSymbolEnumerable()
{
SymbolCache.Clear();
SymbolCache.Set("SPY", Symbols.SPY);
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = new PyString("SPY").ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectStringListConvertToSymbolEnumerable()
{
SymbolCache.Clear();
SymbolCache.Set("SPY", Symbols.SPY);
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = new PyList(new[] { "SPY".ToPython() }).ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectSymbolConvertToSymbolEnumerable()
{
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = Symbols.SPY.ToPython().ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectSymbolListConvertToSymbolEnumerable()
{
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = new PyList(new[] {Symbols.SPY.ToPython()}).ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectNonSymbolObjectConvertToSymbolEnumerable()
{
using (Py.GIL())
{
Assert.Throws<ArgumentException>(() => new PyInt(1).ConvertToSymbolEnumerable().ToList());
}
}
[Test]
public void PyObjectDictionaryConvertToDictionary_Success()
{
using (Py.GIL())
{
var actualDictionary = PythonEngine.ModuleFromString(
"PyObjectDictionaryConvertToDictionary_Success",
@"
from datetime import datetime as dt
actualDictionary = dict()
actualDictionary.update({'SPY': dt(2019,10,3)})
actualDictionary.update({'QQQ': dt(2019,10,4)})
actualDictionary.update({'IBM': dt(2019,10,5)})
"
).GetAttr("actualDictionary").ConvertToDictionary<string, DateTime>();
Assert.AreEqual(3, actualDictionary.Count);
var expectedDictionary = new Dictionary<string, DateTime>
{
{"SPY", new DateTime(2019,10,3) },
{"QQQ", new DateTime(2019,10,4) },
{"IBM", new DateTime(2019,10,5) },
};
foreach (var kvp in expectedDictionary)
{
Assert.IsTrue(actualDictionary.ContainsKey(kvp.Key));
var actual = actualDictionary[kvp.Key];
Assert.AreEqual(kvp.Value, actual);
}
}
}
[Test]
public void PyObjectDictionaryConvertToDictionary_FailNotDictionary()
{
using (Py.GIL())
{
var pyObject = PythonEngine.ModuleFromString(
"PyObjectDictionaryConvertToDictionary_FailNotDictionary",
"actualDictionary = list()"
).GetAttr("actualDictionary");
Assert.Throws<ArgumentException>(() => pyObject.ConvertToDictionary<string, DateTime>());
}
}
[Test]
public void PyObjectDictionaryConvertToDictionary_FailWrongItemType()
{
using (Py.GIL())
{
var pyObject = PythonEngine.ModuleFromString(
"PyObjectDictionaryConvertToDictionary_FailWrongItemType",
@"
actualDictionary = dict()
actualDictionary.update({'SPY': 3})
actualDictionary.update({'QQQ': 4})
actualDictionary.update({'IBM': 5})
"
).GetAttr("actualDictionary");
Assert.Throws<ArgumentException>(() => pyObject.ConvertToDictionary<string, DateTime>());
}
}
[Test]
public void BatchByDoesNotDropItems()
{
var list = new List<int> {1, 2, 3, 4, 5};
var by2 = list.BatchBy(2).ToList();
Assert.AreEqual(3, by2.Count);
Assert.AreEqual(2, by2[0].Count);
Assert.AreEqual(2, by2[1].Count);
Assert.AreEqual(1, by2[2].Count);
CollectionAssert.AreEqual(list, by2.SelectMany(x => x));
}
[Test]
public void ToOrderTicketCreatesCorrectTicket()
{
var orderRequest = new SubmitOrderRequest(OrderType.Limit, SecurityType.Equity, Symbols.USDJPY, 1000, 0, 1.11m, DateTime.Now, "Pepe");
var order = Order.CreateOrder(orderRequest);
order.Status = OrderStatus.Submitted;
order.Id = 11;
var orderTicket = order.ToOrderTicket(null);
Assert.AreEqual(order.Id, orderTicket.OrderId);
Assert.AreEqual(order.Quantity, orderTicket.Quantity);
Assert.AreEqual(order.Status, orderTicket.Status);
Assert.AreEqual(order.Type, orderTicket.OrderType);
Assert.AreEqual(order.Symbol, orderTicket.Symbol);
Assert.AreEqual(order.Tag, orderTicket.Tag);
Assert.AreEqual(order.Time, orderTicket.Time);
Assert.AreEqual(order.SecurityType, orderTicket.SecurityType);
}
[TestCase(4000, "4K")]
[TestCase(4103, "4.1K")]
[TestCase(40000, "40K")]
[TestCase(45321, "45.3K")]
[TestCase(654321, "654K")]
[TestCase(600031, "600K")]
[TestCase(1304303, "1.3M")]
[TestCase(2600000, "2.6M")]
[TestCase(26000000, "26M")]
[TestCase(260000000, "260M")]
[TestCase(2600000000, "2.6B")]
[TestCase(26000000000, "26B")]
public void ToFinancialFigures(double number, string expected)
{
var value = ((decimal)number).ToFinancialFigures();
Assert.AreEqual(expected, value);
}
[Test]
public void DecimalTruncateTo3DecimalPlaces()
{
var value = 10.999999m;
Assert.AreEqual(10.999m, value.TruncateTo3DecimalPlaces());
}
[Test]
public void DecimalTruncateTo3DecimalPlacesDoesNotThrowException()
{
var value = decimal.MaxValue;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
value = decimal.MinValue;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
value = decimal.MaxValue - 1;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
value = decimal.MinValue + 1;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
}
[Test]
public void DecimalAllowExponentTests()
{
const string strWithExponent = "5e-5";
Assert.AreEqual(strWithExponent.ToDecimalAllowExponent(), 0.00005);
Assert.AreNotEqual(strWithExponent.ToDecimal(), 0.00005);
Assert.AreEqual(strWithExponent.ToDecimal(), 10275);
}
[Test]
public void DateRulesToFunc()
{
var dateRules = new DateRules(new SecurityManager(
new TimeKeeper(new DateTime(2015, 1, 1), DateTimeZone.Utc)), DateTimeZone.Utc);
var first = new DateTime(2015, 1, 10);
var second = new DateTime(2015, 1, 30);
var dateRule = dateRules.On(first, second);
var func = dateRule.ToFunc();
Assert.AreEqual(first, func(new DateTime(2015, 1, 1)));
Assert.AreEqual(first, func(new DateTime(2015, 1, 5)));
Assert.AreEqual(second, func(first));
Assert.AreEqual(Time.EndOfTime, func(second));
Assert.AreEqual(Time.EndOfTime, func(second));
}
[Test]
[TestCase(OptionRight.Call, true, OrderDirection.Sell)]
[TestCase(OptionRight.Call, false, OrderDirection.Buy)]
[TestCase(OptionRight.Put, true, OrderDirection.Buy)]
[TestCase(OptionRight.Put, false, OrderDirection.Sell)]
public void GetsExerciseDirection(OptionRight right, bool isShort, OrderDirection expected)
{
var actual = right.GetExerciseDirection(isShort);
Assert.AreEqual(expected, actual);
}
[Test]
public void AppliesScalingToEquityTickQuotes()
{
// This test ensures that all Ticks with TickType == TickType.Quote have adjusted BidPrice and AskPrice.
// Relevant issue: https://github.com/QuantConnect/Lean/issues/4788
var algo = new QCAlgorithm();
var dataFeed = new NullDataFeed();
algo.SubscriptionManager = new SubscriptionManager();
algo.SubscriptionManager.SetDataManager(new DataManager(
dataFeed,
new UniverseSelection(
algo,
new SecurityService(
new CashBook(),
MarketHoursDatabase.FromDataFolder(),
SymbolPropertiesDatabase.FromDataFolder(),
algo,
null,
null
),
new DataPermissionManager(),
new DefaultDataProvider()
),
algo,
new TimeKeeper(DateTime.UtcNow),
MarketHoursDatabase.FromDataFolder(),
false,
null,
new DataPermissionManager()
));
using (var zipDataCacheProvider = new ZipDataCacheProvider(new DefaultDataProvider()))
{
algo.HistoryProvider = new SubscriptionDataReaderHistoryProvider();
algo.HistoryProvider.Initialize(
new HistoryProviderInitializeParameters(
null,
null,
null,
zipDataCacheProvider,
new LocalDiskMapFileProvider(),
new LocalDiskFactorFileProvider(),
(_) => {},
false,
new DataPermissionManager()));
algo.SetStartDate(DateTime.UtcNow.AddDays(-1));
var history = algo.History(new[] { Symbols.IBM }, new DateTime(2013, 10, 7), new DateTime(2013, 10, 8), Resolution.Tick).ToList();
Assert.AreEqual(57460, history.Count);
foreach (var slice in history)
{
if (!slice.Ticks.ContainsKey(Symbols.IBM))
{
continue;
}
foreach (var tick in slice.Ticks[Symbols.IBM])
{
if (tick.BidPrice != 0)
{
Assert.LessOrEqual(Math.Abs(tick.Value - tick.BidPrice), 0.05);
}
if (tick.AskPrice != 0)
{
Assert.LessOrEqual(Math.Abs(tick.Value - tick.AskPrice), 0.05);
}
}
}
}
}
[Test]
[TestCase(PositionSide.Long, OrderDirection.Buy)]
[TestCase(PositionSide.Short, OrderDirection.Sell)]
[TestCase(PositionSide.None, OrderDirection.Hold)]
public void ToOrderDirection(PositionSide side, OrderDirection expected)
{
Assert.AreEqual(expected, side.ToOrderDirection());
}
[Test]
[TestCase(OrderDirection.Buy, PositionSide.Long, false)]
[TestCase(OrderDirection.Buy, PositionSide.Short, true)]
[TestCase(OrderDirection.Buy, PositionSide.None, false)]
[TestCase(OrderDirection.Sell, PositionSide.Long, true)]
[TestCase(OrderDirection.Sell, PositionSide.Short, false)]
[TestCase(OrderDirection.Sell, PositionSide.None, false)]
[TestCase(OrderDirection.Hold, PositionSide.Long, false)]
[TestCase(OrderDirection.Hold, PositionSide.Short, false)]
[TestCase(OrderDirection.Hold, PositionSide.None, false)]
public void Closes(OrderDirection direction, PositionSide side, bool expected)
{
Assert.AreEqual(expected, direction.Closes(side));
}
[Test]
public void ListEquals()
{
var left = new[] {1, 2, 3};
var right = new[] {1, 2, 3};
Assert.IsTrue(left.ListEquals(right));
right[2] = 4;
Assert.IsFalse(left.ListEquals(right));
}
[Test]
public void GetListHashCode()
{
var ints1 = new[] {1, 2, 3};
var ints2 = new[] {1, 3, 2};
var longs = new[] {1L, 2L, 3L};
var decimals = new[] {1m, 2m, 3m};
// ordering dependent
Assert.AreNotEqual(ints1.GetListHashCode(), ints2.GetListHashCode());
Assert.AreEqual(ints1.GetListHashCode(), decimals.GetListHashCode());
// known type collision - long has same hash code as int within the int range
// we could take a hash of typeof(T) but this would require ListEquals to enforce exact types
// and we would prefer to allow typeof(T)'s GetHashCode and Equals to make this determination.
Assert.AreEqual(ints1.GetListHashCode(), longs.GetListHashCode());
// deterministic
Assert.AreEqual(ints1.GetListHashCode(), new[] {1, 2, 3}.GetListHashCode());
}
[Test]
[TestCase("0.999", "0.0001", "0.999")]
[TestCase("0.999", "0.001", "0.999")]
[TestCase("0.999", "0.01", "1.000")]
[TestCase("0.999", "0.1", "1.000")]
[TestCase("0.999", "1", "1.000")]
[TestCase("0.999", "2", "0")]
[TestCase("1.0", "0.15", "1.05")]
[TestCase("1.05", "0.15", "1.05")]
[TestCase("0.975", "0.15", "1.05")]
[TestCase("-0.975", "0.15", "-1.05")]
[TestCase("-1.0", "0.15", "-1.05")]
[TestCase("-1.05", "0.15", "-1.05")]
public void DiscretelyRoundBy(string valueString, string quantaString, string expectedString)
{
var value = decimal.Parse(valueString, CultureInfo.InvariantCulture);
var quanta = decimal.Parse(quantaString, CultureInfo.InvariantCulture);
var expected = decimal.Parse(expectedString, CultureInfo.InvariantCulture);
var actual = value.DiscretelyRoundBy(quanta);
Assert.AreEqual(expected, actual);
}
private PyObject ConvertToPyObject(object value)
{
using (Py.GIL())
{
return value.ToPython();
}
}
private class Super<T>
{
}
private class Derived1 : Super<int>
{
}
private class Derived2 : Derived1
{
}
}
}
| |
// 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.Reflection;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters;
namespace System.Runtime.Serialization
{
public static class FormatterServices
{
private static readonly ConcurrentDictionary<MemberHolder, MemberInfo[]> s_memberInfoTable = new ConcurrentDictionary<MemberHolder, MemberInfo[]>();
private static FieldInfo[] GetSerializableFields(Type type)
{
if (type.GetTypeInfo().IsInterface)
{
return Array.Empty<FieldInfo>();
}
if (!type.GetTypeInfo().IsSerializable)
{
throw new SerializationException(SR.Format(SR.Serialization_NonSerType, type.GetTypeInfo().FullName, type.GetTypeInfo().Assembly.FullName));
}
var results = new List<FieldInfo>();
for (Type t = type; t != typeof(object); t = t.GetTypeInfo().BaseType)
{
foreach (FieldInfo field in t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if ((field.Attributes & FieldAttributes.NotSerialized) != FieldAttributes.NotSerialized)
{
results.Add(field);
}
}
}
return results.ToArray();
}
public static MemberInfo[] GetSerializableMembers(Type type)
{
return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All));
}
public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
// If we've already gathered the members for this type, just return them.
// Otherwise, get them and add them.
return s_memberInfoTable.GetOrAdd(
new MemberHolder(type, context),
mh => GetSerializableFields(mh._memberType));
}
public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel)
{
// nop
}
// TODO #8133: Fix this to avoid reflection
private static readonly Func<Type, object> s_getUninitializedObjectDelegate = (Func<Type, object>)
typeof(string).GetTypeInfo().Assembly
.GetType("System.Runtime.Serialization.FormatterServices")
.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
.CreateDelegate(typeof(Func<Type, object>));
public static object GetUninitializedObject(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return s_getUninitializedObjectDelegate(type);
}
public static object GetSafeUninitializedObject(Type type) => GetUninitializedObject(type);
internal static void SerializationSetValue(MemberInfo fi, object target, object value)
{
Debug.Assert(fi != null);
var serField = fi as FieldInfo;
if (serField != null)
{
serField.SetValue(target, value);
return;
}
throw new ArgumentException(SR.Argument_InvalidFieldInfo);
}
public static object PopulateObjectMembers(object obj, MemberInfo[] members, object[] data)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
if (members == null)
{
throw new ArgumentNullException(nameof(members));
}
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (members.Length != data.Length)
{
throw new ArgumentException(SR.Argument_DataLengthDifferent);
}
for (int i = 0; i < members.Length; i++)
{
MemberInfo member = members[i];
if (member == null)
{
throw new ArgumentNullException(nameof(members), SR.Format(SR.ArgumentNull_NullMember, i));
}
// If we find an empty, it means that the value was never set during deserialization.
// This is either a forward reference or a null. In either case, this may break some of the
// invariants mantained by the setter, so we'll do nothing with it for right now.
object value = data[i];
if (value == null)
{
continue;
}
// If it's a field, set its value.
FieldInfo field = member as FieldInfo;
if (field != null)
{
field.SetValue(obj, data[i]);
continue;
}
// Otherwise, it's not supported.
throw new SerializationException(SR.Serialization_UnknownMemberInfo);
}
return obj;
}
public static object[] GetObjectData(object obj, MemberInfo[] members)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
if (members == null)
{
throw new ArgumentNullException(nameof(members));
}
object[] data = new object[members.Length];
for (int i = 0; i < members.Length; i++)
{
MemberInfo member = members[i];
if (member == null)
{
throw new ArgumentNullException(nameof(members), SR.Format(SR.ArgumentNull_NullMember, i));
}
FieldInfo field = member as FieldInfo;
if (field == null)
{
throw new SerializationException(SR.Serialization_UnknownMemberInfo);
}
data[i] = field.GetValue(obj);
}
return data;
}
public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
{
if (innerSurrogate == null)
{
throw new ArgumentNullException(nameof(innerSurrogate));
}
return new SurrogateForCyclicalReference(innerSurrogate);
}
public static Type GetTypeFromAssembly(Assembly assem, string name)
{
if (assem == null)
{
throw new ArgumentNullException(nameof(assem));
}
return assem.GetType(name, throwOnError: false, ignoreCase: false);
}
internal static Assembly LoadAssemblyFromString(string assemblyName)
{
return Assembly.Load(new AssemblyName(assemblyName));
}
internal static Assembly LoadAssemblyFromStringNoThrow(string assemblyName)
{
try
{
return LoadAssemblyFromString(assemblyName);
}
catch (Exception) { }
return null;
}
internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
foreach (Attribute first in type.GetTypeInfo().GetCustomAttributes(typeof(TypeForwardedFromAttribute), false))
{
hasTypeForwardedFrom = true;
return ((TypeForwardedFromAttribute)first).AssemblyFullName;
}
hasTypeForwardedFrom = false;
return type.GetTypeInfo().Assembly.FullName;
}
internal static string GetClrTypeFullName(Type type)
{
return type.IsArray ?
GetClrTypeFullNameForArray(type) :
GetClrTypeFullNameForNonArrayTypes(type);
}
private static string GetClrTypeFullNameForArray(Type type)
{
int rank = type.GetArrayRank();
Debug.Assert(rank >= 1);
string typeName = GetClrTypeFullName(type.GetElementType());
return rank == 1 ?
typeName + "[]" :
typeName + "[" + new string(',', rank - 1) + "]";
}
private static string GetClrTypeFullNameForNonArrayTypes(Type type)
{
if (!type.GetTypeInfo().IsGenericType)
{
return type.FullName;
}
var builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("[");
bool hasTypeForwardedFrom;
foreach (Type genericArgument in type.GetGenericArguments())
{
builder.Append("[").Append(GetClrTypeFullName(genericArgument)).Append(", ");
builder.Append(GetClrAssemblyName(genericArgument, out hasTypeForwardedFrom)).Append("],");
}
//remove the last comma and close typename for generic with a close bracket
return builder.Remove(builder.Length - 1, 1).Append("]").ToString();
}
}
internal sealed class SurrogateForCyclicalReference : ISerializationSurrogate
{
private readonly ISerializationSurrogate _innerSurrogate;
internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
{
Debug.Assert(innerSurrogate != null);
_innerSurrogate = innerSurrogate;
}
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
_innerSurrogate.GetObjectData(obj, info, context);
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return _innerSurrogate.SetObjectData(obj, info, context, selector);
}
}
}
| |
#if !NETSTANDARD
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using FileHelpers.Options;
namespace FileHelpers
{
/// <summary>
/// This class only has <b>static methods</b> to work with files and
/// strings (most of the common tools)
/// </summary>
public static class CommonEngine
{
// Nothing to instantiate
#region " FileHelperEngine "
/// <summary>
/// Used to read a file without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="recordClass">The record class.</param>
/// <param name="fileName">The file name</param>
/// <returns>The read records.</returns>
public static object[] ReadFile(Type recordClass, string fileName)
{
return ReadFile(recordClass, fileName, int.MaxValue);
}
/// <summary>
/// Used to read a file without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="recordClass">The record class.</param>
/// <param name="fileName">The file name</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The read records.</returns>
public static object[] ReadFile(Type recordClass, string fileName, int maxRecords)
{
var engine = new FileHelperEngine(recordClass);
return engine.ReadFile(fileName, maxRecords);
}
/// <summary>
/// Used to read a file as a DataTable without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="recordClass">The record class.</param>
/// <param name="fileName">The file name</param>
/// <returns>The DataTable representing all the read records.</returns>
public static DataTable ReadFileAsDT(Type recordClass, string fileName)
{
return ReadFileAsDT(recordClass, fileName, -1);
}
/// <summary>
/// Used to read a file as a DataTable without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="recordClass">The record class.</param>
/// <param name="fileName">The file name</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable representing all the read records.</returns>
public static DataTable ReadFileAsDT(Type recordClass, string fileName, int maxRecords)
{
var engine = new FileHelperEngine(recordClass);
#pragma warning disable 618
return engine.ReadFileAsDT(fileName, maxRecords);
#pragma warning restore 618
}
/// <summary>
/// Used to read a file without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="fileName">The file name</param>
/// <returns>The read records.</returns>
public static T[] ReadFile<T>(string fileName) where T : class
{
return ReadFile<T>(fileName, int.MaxValue);
}
/// <summary>
/// Used to read a file without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="fileName">The file name</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The read records.</returns>
public static T[] ReadFile<T>(string fileName, int maxRecords) where T : class
{
var engine = new FileHelperEngine<T>();
return engine.ReadFile(fileName, maxRecords);
}
/// <summary>
/// Used to read a string without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="recordClass">The record class.</param>
/// <param name="input">The input string.</param>
/// <returns>The read records.</returns>
public static object[] ReadString(Type recordClass, string input)
{
return ReadString(recordClass, input, -1);
}
/// <summary>
/// Used to read a string without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="recordClass">The record class.</param>
/// <param name="input">The input string.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The read records.</returns>
public static object[] ReadString(Type recordClass, string input, int maxRecords)
{
var engine = new FileHelperEngine(recordClass);
return engine.ReadString(input, maxRecords);
}
/// <summary>
/// Used to read a string without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The read records.</returns>
public static T[] ReadString<T>(string input) where T : class
{
var engine = new FileHelperEngine<T>();
return engine.ReadString(input);
}
/// <summary>
/// Used to write a file without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="fileName">The file name</param>
/// <param name="records">The records to write (Can be an array, List, etc)</param>
public static void WriteFile<T>(string fileName, IEnumerable<T> records) where T : class
{
var engine = new FileHelperEngine<T>();
engine.WriteFile(fileName, records);
}
/// <summary>
/// Used to write a string without instantiating the engine.<br />
/// <b>This method has limited features. We recommend using the non static methods.</b>
/// </summary>
/// <param name="records">The records to write (Can be an array, List, etc)</param>
/// <returns>The string with the written records.</returns>
public static string WriteString<T>(IEnumerable<T> records) where T : class
{
var engine = new FileHelperEngine<T>();
return engine.WriteString(records);
}
#endregion
/// <summary>
/// <b>Faster way</b> to Transform the records of type sourceType in
/// the sourceFile in records of type destType and write them to the
/// destFile.
/// </summary>
/// <param name="sourceFile">The file with records to be transformed</param>
/// <param name="destFile">The destination file with the transformed records</param>
/// <returns>The number of transformed records</returns>
public static int TransformFileFast<TSource, TDest>(string sourceFile, string destFile)
where TSource : class, ITransformable<TDest>
where TDest : class
{
var engine = new FileTransformEngine<TSource, TDest>();
return engine.TransformFileFast(sourceFile, destFile);
}
/// <summary>
/// Transform the records of type sourceType in the sourceFile in
/// records of type destType and write them to the destFile. (but
/// returns the transformed records) WARNING: this is a slower method
/// that the TransformFileAssync.
/// </summary>
/// <param name="sourceFile">The file with records to be transformed</param>
/// <param name="destFile">The destination file with the transformed records</param>
/// <returns>The transformed records.</returns>
public static object[] TransformFile<TSource, TDest>(string sourceFile, string destFile)
where TSource : class, ITransformable<TDest>
where TDest : class
{
var engine = new FileTransformEngine<TSource, TDest>();
return engine.TransformFile(sourceFile, destFile);
}
/// <summary>
/// Read the contents of a file and sort the records.
/// </summary>
/// <param name="recordClass">
/// Record Class (remember that need to implement the IComparer
/// interface, or you can use SortFileByfield)
/// </param>
/// <param name="fileName">The file to read.</param>
public static object[] ReadSortedFile(Type recordClass, string fileName)
{
if (typeof (IComparable).IsAssignableFrom(recordClass) == false) {
throw new BadUsageException(
"The record class must implement the interface IComparable to use the Sort feature.");
}
var engine = new FileHelperEngine(recordClass);
object[] res = engine.ReadFile(fileName);
if (res.Length == 0)
return res;
Array.Sort(res);
return res;
}
/// <summary>
/// Sort the contents of the source file and write them to the destination file.
/// </summary>
/// <param name="recordClass">
/// Record Class (remember that need to implement the IComparable
/// interface or use the SortFileByfield instead)
/// </param>
/// <param name="sourceFile">The source file.</param>
/// <param name="sortedFile">The destination File.</param>
public static void SortFile(Type recordClass, string sourceFile, string sortedFile)
{
if (typeof (IComparable).IsAssignableFrom(recordClass) == false) {
throw new BadUsageException(
"The record class must implement the interface IComparable to use the Sort feature.");
}
var engine = new FileHelperEngine(recordClass);
object[] res = engine.ReadFile(sourceFile);
if (res.Length == 0)
engine.WriteFile(sortedFile, res);
Array.Sort(res);
engine.WriteFile(sortedFile, res);
}
/// <summary>
/// Sort the content of a File using the field name provided
/// </summary>
/// <param name="recordClass">The class for each record of the file.</param>
/// <param name="fieldName">The name of the field used to sort the file.</param>
/// <param name="asc">The sort direction.</param>
/// <param name="sourceFile">The source file.</param>
/// <param name="sortedFile">The destination File.</param>
public static void SortFileByField(Type recordClass,
string fieldName,
bool asc,
string sourceFile,
string sortedFile)
{
var engine = new FileHelperEngine(recordClass);
FieldInfo fi = engine.RecordInfo.GetFieldInfo(fieldName);
if (fi == null)
throw new BadUsageException("The record class does not contain the field " + fieldName);
object[] res = engine.ReadFile(sourceFile);
IComparer comparer = new FieldComparer(fi, asc);
Array.Sort(res, comparer);
engine.WriteFile(sortedFile, res);
}
/// <summary>
/// Sort the Record Array using the field name provided. (for
/// advanced sorting use SortRecords)
/// </summary>
/// <param name="fieldName">The field name.</param>
/// <param name="records">The records Array.</param>
public static void SortRecordsByField(object[] records, string fieldName)
{
SortRecordsByField(records, fieldName, true);
}
/// <summary>
/// Sort the Record Array using the field name provided. (for
/// advanced sorting use SortRecords)
/// </summary>
/// <param name="fieldName">The field name.</param>
/// <param name="records">The records Array.</param>
/// <param name="ascending">The direction of the sort. True means Ascending.</param>
public static void SortRecordsByField(object[] records, string fieldName, bool ascending)
{
if (records.Length > 0 &&
records[0] != null) {
var engine = new FileHelperEngine(records[0].GetType());
FieldInfo fi = engine.RecordInfo.GetFieldInfo(fieldName);
if (fi == null)
throw new BadUsageException("The record class does not contain the field " + fieldName);
IComparer comparer = new FieldComparer(fi, ascending);
Array.Sort(records, comparer);
}
}
/// <summary>
/// Sort the Record Array. The records must be of a Type that
/// implements the IComparable interface.
/// </summary>
/// <param name="records">The records Array.</param>
public static void SortRecords(object[] records)
{
if (records.Length > 0 &&
records[0] != null) {
Type recordClass = records[0].GetType();
if (typeof (IComparable).IsAssignableFrom(recordClass) == false) {
throw new BadUsageException(
"The record class must implement the interface IComparable to use the Sort feature.");
}
Array.Sort(records);
}
}
#region " FieldComparer "
/// <summary>
/// Compare one field to another
/// </summary>
private class FieldComparer : IComparer
{
private readonly FieldInfo mFieldInfo;
private readonly int mAscending;
public FieldComparer(FieldInfo fi, bool asc)
{
mFieldInfo = fi;
mAscending = asc
? 1
: -1;
if (typeof (IComparable).IsAssignableFrom(mFieldInfo.FieldType) == false) {
throw new BadUsageException("The field " + mFieldInfo.Name +
" needs to implement the interface IComparable");
}
}
/// <summary>
/// Compare object 1 to object 2
/// </summary>
/// <param name="x">First object to test</param>
/// <param name="y">Second object to test</param>
/// <returns>0 if equal, -1 if x < y, 1 otherwise</returns>
public int Compare(object x, object y)
{
var xv = mFieldInfo.GetValue(x) as IComparable;
return xv.CompareTo(mFieldInfo.GetValue(y)) * mAscending;
}
}
#endregion
/// <summary>
/// Converts any collection of records to a DataTable using reflection.
/// WARNING: this methods returns null if the number of records is 0,
/// pass the Type of the records to get an empty DataTable.
/// </summary>
/// <param name="records">The records to be converted to a DataTable</param>
/// <returns>The DataTable containing the records as DataRows</returns>
public static DataTable RecordsToDataTable(ICollection records)
{
return RecordsToDataTable(records, -1);
}
/// <summary>
/// Converts any collection of records to a DataTable using reflection.
/// WARNING: this methods returns null if the number of records is 0,
/// pass the Type of the records to get an empty DataTable.
/// </summary>
/// <param name="records">The records to be converted to a DataTable</param>
/// <param name="maxRecords">The max number of records to add to the DataTable. -1 for all.</param>
/// <returns>The DataTable containing the records as DataRows</returns>
public static DataTable RecordsToDataTable(ICollection records, int maxRecords)
{
IRecordInfo ri = null;
foreach (var obj in records) {
if (obj != null) {
ri = RecordInfo.Resolve(obj.GetType());
break;
}
}
if (ri == null)
return new DataTable();
return ri.Operations.RecordsToDataTable(records, maxRecords);
}
/// <summary>
/// Converts any collection of records to a DataTable using reflection.
/// If the number of records is 0 this methods returns an empty
/// DataTable with the columns based on the fields of the
/// Type.
/// </summary>
/// <param name="records">The records to be converted to a DataTable</param>
/// <returns>The DataTable containing the records as DataRows</returns>
/// <param name="recordType">The type of the inner records.</param>
public static DataTable RecordsToDataTable(ICollection records, Type recordType)
{
return RecordsToDataTable(records, recordType, -1);
}
/// <summary>
/// Converts any collection of records to a DataTable using reflection.
/// If the number of records is 0 this methods returns an empty
/// DataTable with the columns based on the fields of the
/// Type.
/// </summary>
/// <param name="records">The records to be converted to a DataTable</param>
/// <returns>The DataTable containing the records as DataRows</returns>
/// <param name="maxRecords">The max number of records to add to the DataTable. -1 for all.</param>
/// <param name="recordType">The type of the inner records.</param>
public static DataTable RecordsToDataTable(ICollection records, Type recordType, int maxRecords)
{
IRecordInfo ri = RecordInfo.Resolve(recordType);
return ri.Operations.RecordsToDataTable(records, maxRecords);
}
/// <summary>
/// Reads the file1 and file2 using the recordType and write it to
/// destinationFile
/// </summary>
public static void MergeFiles(Type recordType, string file1, string file2, string destinationFile)
{
using (var engineRead = new FileHelperAsyncEngine(recordType))
using (var engineWrite = new FileHelperAsyncEngine(recordType)) {
engineWrite.BeginWriteFile(destinationFile);
object[] readRecords;
// Read FILE 1
engineRead.BeginReadFile(file1);
readRecords = engineRead.ReadNexts(50);
while (readRecords.Length > 0) {
engineWrite.WriteNexts(readRecords);
readRecords = engineRead.ReadNexts(50);
}
engineRead.Close();
// Read FILE 2
engineRead.BeginReadFile(file2);
readRecords = engineRead.ReadNexts(50);
while (readRecords.Length > 0) {
engineWrite.WriteNexts(readRecords);
readRecords = engineRead.ReadNexts(50);
}
}
}
/// <summary>
/// Merge the contents of 2 files and write them sorted to a destination file.
/// </summary>
/// <param name="recordType">The record Type.</param>
/// <param name="file1">File with contents to be merged.</param>
/// <param name="file2">File with contents to be merged.</param>
/// <param name="field">The name of the field used to sort the records.</param>
/// <param name="destFile">The destination file.</param>
/// <returns>The merged and sorted records.</returns>
public static object[] MergeAndSortFile(Type recordType,
string file1,
string file2,
string destFile,
string field)
{
return MergeAndSortFile(recordType, file1, file2, destFile, field, true);
}
/// <summary>
/// Merge the contents of 2 files and write them sorted to a destination file.
/// </summary>
/// <param name="recordType">The record Type.</param>
/// <param name="file1">File with contents to be merged.</param>
/// <param name="file2">File with contents to be merged.</param>
/// <param name="field">The name of the field used to sort the records.</param>
/// <param name="ascending">Indicate the order of sort.</param>
/// <param name="destFile">The destination file.</param>
/// <returns>The merged and sorted records.</returns>
public static object[] MergeAndSortFile(Type recordType,
string file1,
string file2,
string destFile,
string field,
bool ascending)
{
var engine = new FileHelperEngine(recordType);
#pragma warning disable 618
var list = engine.ReadFileAsList(file1);
list.AddRange(engine.ReadFileAsList(file2));
#pragma warning restore 618
var res = list.ToArray();
list = null; // <- better performance (memory)
SortRecordsByField(res, field, ascending);
engine.WriteFile(destFile, res);
return res;
}
/// <summary>
/// Merge the contents of 2 files and write them sorted to a
/// destination file.
/// </summary>
/// <param name="recordType">The record Type.</param>
/// <param name="file1">File with contents to be merged.</param>
/// <param name="file2">File with contents to be merged.</param>
/// <param name="destFile">The destination file.</param>
/// <returns>The merged and sorted records.</returns>
public static object[] MergeAndSortFile(Type recordType, string file1, string file2, string destFile)
{
var engine = new FileHelperEngine(recordType);
#pragma warning disable 618
var list = engine.ReadFileAsList(file1);
list.AddRange(engine.ReadFileAsList(file2));
#pragma warning restore 618
var res = list.ToArray();
list = null; // <- better performance (memory)
SortRecords(res);
engine.WriteFile(destFile, res);
return res;
}
/// <summary>
/// Simply dumps the DataTable contents to a delimited file using a ','
/// as delimiter.
/// </summary>
/// <param name="dt">The source Data Table</param>
/// <param name="filename">The destination file.</param>
public static void DataTableToCsv(DataTable dt, string filename)
{
CsvEngine.DataTableToCsv(dt, filename);
}
/// <summary>Simply dumps the DataTable contents to a delimited file. Only allows to set the delimiter.</summary>
/// <param name="dt">The source Data Table</param>
/// <param name="filename">The destination file.</param>
/// <param name="delimiter">The delimiter used to write the file</param>
public static void DataTableToCsv(DataTable dt, string filename, char delimiter)
{
CsvEngine.DataTableToCsv(dt, filename, new CsvOptions("Tempo", delimiter, dt.Columns.Count));
}
/// <summary>
/// Simply dumps the DataTable contents to a delimited file. Only
/// allows to set the delimiter.
/// </summary>
/// <param name="dt">The source Data Table</param>
/// <param name="filename">The destination file.</param>
/// <param name="options">The options used to write the file</param>
public static void DataTableToCsv(DataTable dt, string filename, CsvOptions options)
{
CsvEngine.DataTableToCsv(dt, filename, options);
}
/// <summary>
/// Reads a CSV File and return their contents as DataTable (The file
/// must have the field names in the first row)
/// </summary>
/// <param name="delimiter">The delimiter for each field</param>
/// <param name="filename">The file to read.</param>
/// <returns>The contents of the file as a DataTable</returns>
public static DataTable CsvToDataTable(string filename, char delimiter)
{
return CsvEngine.CsvToDataTable(filename, delimiter);
}
/// <summary>
/// Reads a CSV File and return their contents as DataTable (The file
/// must have the field names in the first row)
/// </summary>
/// <param name="classname">The name of the record class</param>
/// <param name="delimiter">The delimiter for each field</param>
/// <param name="filename">The file to read.</param>
/// <returns>The contents of the file as a DataTable</returns>
public static DataTable CsvToDataTable(string filename, string classname, char delimiter)
{
return CsvEngine.CsvToDataTable(filename, classname, delimiter);
}
/// <summary>Reads a Csv File and return their contents as DataTable</summary>
/// <param name="classname">The name of the record class</param>
/// <param name="delimiter">The delimiter for each field</param>
/// <param name="filename">The file to read.</param>
/// <param name="hasHeader">Indicates if the file contains a header with the field names.</param>
/// <returns>The contents of the file as a DataTable</returns>
public static DataTable CsvToDataTable(string filename, string classname, char delimiter, bool hasHeader)
{
return CsvEngine.CsvToDataTable(filename, classname, delimiter, hasHeader);
}
/// <summary>Reads a Csv File and return their contents as DataTable</summary>
/// <param name="filename">The file to read.</param>
/// <param name="options">The options used to create the record mapping class.</param>
/// <returns>The contents of the file as a DataTable</returns>
public static DataTable CsvToDataTable(string filename, CsvOptions options)
{
return CsvEngine.CsvToDataTable(filename, options);
}
#region " RemoveDuplicateRecords "
/// <summary>
/// This method allow to remove the duplicated records from an array.
/// </summary>
/// <param name="arr">The array with the records to be checked.</param>
/// <returns>An array with the result of remove the duplicate records from the source array.</returns>
public static T[] RemoveDuplicateRecords<T>(T[] arr) where T : IComparable<T>
{
if (arr == null ||
arr.Length <= 1)
return arr;
var nodup = new List<T>();
for (int i = 0; i < arr.Length; i++) {
bool isUnique = true;
for (int j = i + 1; j < arr.Length; j++) {
if (arr[i].CompareTo(arr[j]) == 0) {
isUnique = false;
break;
}
}
if (isUnique)
nodup.Add(arr[i]);
}
return nodup.ToArray();
}
#endregion
#region " ReadCSV "
/// <summary>
/// A fast way to read record by record a CSV file delimited by ','.
/// The fields can be quoted.
/// </summary>
/// <param name="filename">The CSV file to read</param>
/// <returns>An enumeration of <see cref="RecordIndexer"/></returns>
public static IEnumerable<RecordIndexer> ReadCsv(string filename)
{
return ReadCsv(filename, ',');
}
/// <summary>
/// A fast way to read record by record a CSV file with a custom
/// delimiter. The fields can be quoted.
/// </summary>
/// <param name="filename">The CSV file to read</param>
/// <param name="delimiter">The field delimiter.</param>
/// <returns>An enumeration of <see cref="RecordIndexer"/></returns>
public static IEnumerable<RecordIndexer> ReadCsv(string filename, char delimiter)
{
return ReadCsv(filename, delimiter, 0);
}
/// <summary>
/// A fast way to read record by record a CSV file with a custom
/// delimiter. The fields can be quoted.
/// </summary>
/// <param name="filename">The CSV file to read</param>
/// <param name="delimiter">The field delimiter.</param>
/// <param name="headerLines">The number of header lines in the CSV file</param>
/// <returns>An enumeration of <see cref="RecordIndexer"/></returns>
public static IEnumerable<RecordIndexer> ReadCsv(string filename, char delimiter, int headerLines)
{
return ReadCsv(filename, delimiter, headerLines, Encoding.GetEncoding(0));
}
/// <summary>
/// A fast way to read record by record a CSV file with a custom
/// delimiter. The fields can be quoted.
/// </summary>
/// <param name="filename">The CSV file to read</param>
/// <param name="delimiter">The field delimiter.</param>
/// <param name="encoding">The file <see cref="Encoding"/></param>
/// <returns>An enumeration of <see cref="RecordIndexer"/></returns>
public static IEnumerable<RecordIndexer> ReadCsv(string filename, char delimiter, Encoding encoding)
{
return ReadCsv(filename, delimiter, 0, encoding);
}
/// <summary>
/// A fast way to read record by record a CSV file with a custom
/// delimiter. The fields can be quoted.
/// </summary>
/// <param name="filename">The CSV file to read</param>
/// <param name="delimiter">The field delimiter.</param>
/// <param name="encoding">The file <see cref="Encoding"/></param>
/// <param name="headerLines">The number of header lines in the CSV file</param>
/// <returns>An enumeration of <see cref="RecordIndexer"/></returns>
public static IEnumerable<RecordIndexer> ReadCsv(string filename,
char delimiter,
int headerLines,
Encoding encoding)
{
var engine = new FileHelperAsyncEngine<RecordIndexer>(encoding);
((DelimitedRecordOptions) engine.Options).Delimiter = delimiter.ToString();
engine.Options.IgnoreFirstLines = headerLines;
engine.BeginReadFile(filename);
return engine;
}
#endregion
/// <summary>
/// A fast way to sort a big file. For more options you need to
/// instantiate the BigFileSorter class instead of using static methods
/// </summary>
public static void SortBigFile<T>(string source, string destination)
where T: class, IComparable<T>
{
var sorter = new BigFileSorter<T>();
sorter.Sort(source, destination);
}
/// <summary>
/// A fast way to sort a big file. For more options you need to
/// instantiate the BigFileSorter class instead of using static methods
/// </summary>
public static void SortBigFile<T>(Encoding encoding, string source, string destination)
where T : class, IComparable<T>
{
var sorter = new BigFileSorter<T>(encoding);
sorter.Sort(source, destination);
}
}
}
#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 System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using pCampBot.Interfaces;
namespace pCampBot
{
/// <summary>
/// Thread/Bot manager for the application
/// </summary>
public class BotManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int DefaultLoginDelay = 5000;
/// <summary>
/// Delay between logins of multiple bots.
/// </summary>
/// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
public int LoginDelay { get; set; }
/// <summary>
/// Command console
/// </summary>
protected CommandConsole m_console;
/// <summary>
/// Created bots, whether active or inactive.
/// </summary>
protected List<Bot> m_lBot;
/// <summary>
/// Random number generator.
/// </summary>
public Random Rng { get; private set; }
/// <summary>
/// Overall configuration.
/// </summary>
public IConfig Config { get; private set; }
/// <summary>
/// Track the assets we have and have not received so we don't endlessly repeat requests.
/// </summary>
public Dictionary<UUID, bool> AssetsReceived { get; private set; }
/// <summary>
/// The regions that we know about.
/// </summary>
public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
/// <summary>
/// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
/// </summary>
public BotManager()
{
LoginDelay = DefaultLoginDelay;
Rng = new Random(Environment.TickCount);
AssetsReceived = new Dictionary<UUID, bool>();
RegionsKnown = new Dictionary<ulong, GridRegion>();
m_console = CreateConsole();
MainConsole.Instance = m_console;
// Make log4net see the console
//
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
OpenSimAppender consoleAppender = null;
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
consoleAppender = (OpenSimAppender)appender;
consoleAppender.Console = m_console;
break;
}
}
m_console.Commands.AddCommand("bot", false, "shutdown",
"shutdown",
"Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand("bot", false, "quit",
"quit",
"Shutdown bots and exit",
HandleShutdown);
m_console.Commands.AddCommand("bot", false, "show regions",
"show regions",
"Show regions known to bots",
HandleShowRegions);
m_console.Commands.AddCommand("bot", false, "show bots",
"show bots",
"Shows the status of all bots",
HandleShowStatus);
// m_console.Commands.AddCommand("bot", false, "add bots",
// "add bots <number>",
// "Add more bots", HandleAddBots);
m_lBot = new List<Bot>();
}
/// <summary>
/// Startup number of bots specified in the starting arguments
/// </summary>
/// <param name="botcount">How many bots to start up</param>
/// <param name="cs">The configuration for the bots to use</param>
public void dobotStartup(int botcount, IConfig cs)
{
Config = cs;
string firstName = cs.GetString("firstname");
string lastNameStem = cs.GetString("lastname");
string password = cs.GetString("password");
string loginUri = cs.GetString("loginuri");
HashSet<string> behaviourSwitches = new HashSet<string>();
Array.ForEach<string>(
cs.GetString("behaviours", "p").Split(new char[] { ',' }), b => behaviourSwitches.Add(b));
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Starting {0} bots connecting to {1}, named {2} {3}_<n>",
botcount,
loginUri,
firstName,
lastNameStem);
MainConsole.Instance.OutputFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
for (int i = 0; i < botcount; i++)
{
string lastName = string.Format("{0}_{1}", lastNameStem, i);
// We must give each bot its own list of instantiated behaviours since they store state.
List<IBehaviour> behaviours = new List<IBehaviour>();
// Hard-coded for now
if (behaviourSwitches.Contains("p"))
behaviours.Add(new PhysicsBehaviour());
if (behaviourSwitches.Contains("g"))
behaviours.Add(new GrabbingBehaviour());
if (behaviourSwitches.Contains("t"))
behaviours.Add(new TeleportBehaviour());
if (behaviourSwitches.Contains("c"))
behaviours.Add(new CrossBehaviour());
StartBot(this, behaviours, firstName, lastName, password, loginUri);
}
}
// /// <summary>
// /// Add additional bots (and threads) to our bot pool
// /// </summary>
// /// <param name="botcount">How Many of them to add</param>
// public void addbots(int botcount)
// {
// int len = m_td.Length;
// Thread[] m_td2 = new Thread[len + botcount];
// for (int i = 0; i < len; i++)
// {
// m_td2[i] = m_td[i];
// }
// m_td = m_td2;
// int newlen = len + botcount;
// for (int i = len; i < newlen; i++)
// {
// startupBot(Config);
// }
// }
/// <summary>
/// This starts up the bot and stores the thread for the bot in the thread array
/// </summary>
/// <param name="bm"></param>
/// <param name="behaviours">Behaviours for this bot to perform.</param>
/// <param name="firstName">First name</param>
/// <param name="lastName">Last name</param>
/// <param name="password">Password</param>
/// <param name="loginUri">Login URI</param>
public void StartBot(
BotManager bm, List<IBehaviour> behaviours,
string firstName, string lastName, string password, string loginUri)
{
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Starting bot {0} {1}, behaviours are {2}",
firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
Bot pb = new Bot(bm, behaviours, firstName, lastName, password, loginUri);
pb.OnConnected += handlebotEvent;
pb.OnDisconnected += handlebotEvent;
lock (m_lBot)
m_lBot.Add(pb);
Thread pbThread = new Thread(pb.startup);
pbThread.Name = pb.Name;
pbThread.IsBackground = true;
pbThread.Start();
// Stagger logins
Thread.Sleep(LoginDelay);
}
/// <summary>
/// High level connnected/disconnected events so we can keep track of our threads by proxy
/// </summary>
/// <param name="callbot"></param>
/// <param name="eventt"></param>
private void handlebotEvent(Bot callbot, EventType eventt)
{
switch (eventt)
{
case EventType.CONNECTED:
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
break;
case EventType.DISCONNECTED:
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
lock (m_lBot)
{
if (m_lBot.TrueForAll(b => b.ConnectionState == ConnectionState.Disconnected))
Environment.Exit(0);
break;
}
}
}
/// <summary>
/// Shut down all bots
/// </summary>
/// <remarks>
/// We launch each shutdown on its own thread so that a slow shutting down bot doesn't hold up all the others.
/// </remarks>
public void doBotShutdown()
{
lock (m_lBot)
{
foreach (Bot bot in m_lBot)
{
Bot thisBot = bot;
Util.FireAndForget(o => thisBot.shutdown());
}
}
}
/// <summary>
/// Standard CreateConsole routine
/// </summary>
/// <returns></returns>
protected CommandConsole CreateConsole()
{
return new LocalConsole("pCampbot");
}
private void HandleShutdown(string module, string[] cmd)
{
m_log.Info("[BOTMANAGER]: Shutting down bots");
doBotShutdown();
}
private void HandleShowRegions(string module, string[] cmd)
{
string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
lock (RegionsKnown)
{
foreach (GridRegion region in RegionsKnown.Values)
{
MainConsole.Instance.OutputFormat(
outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
}
}
}
private void HandleShowStatus(string module, string[] cmd)
{
string outputFormat = "{0,-30} {1, -30} {2,-14}";
MainConsole.Instance.OutputFormat(outputFormat, "Name", "Region", "Status");
lock (m_lBot)
{
foreach (Bot pb in m_lBot)
{
Simulator currentSim = pb.Client.Network.CurrentSim;
MainConsole.Instance.OutputFormat(
outputFormat,
pb.Name, currentSim != null ? currentSim.Name : "(none)", pb.ConnectionState);
}
}
}
/*
private void HandleQuit(string module, string[] cmd)
{
m_console.Warn("DANGER", "This should only be used to quit the program if you've already used the shutdown command and the program hasn't quit");
Environment.Exit(0);
}
*/
//
// private void HandleAddBots(string module, string[] cmd)
// {
// int newbots = 0;
//
// if (cmd.Length > 2)
// {
// Int32.TryParse(cmd[2], out newbots);
// }
// if (newbots > 0)
// addbots(newbots);
// }
internal void Grid_GridRegion(object o, GridRegionEventArgs args)
{
lock (RegionsKnown)
{
GridRegion newRegion = args.Region;
if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
{
return;
}
else
{
m_log.DebugFormat(
"[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
RegionsKnown[newRegion.RegionHandle] = newRegion;
}
}
}
}
}
| |
/*
Copyright (c) 2005-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Collections;
using Process = System.Diagnostics.Process;
using PHP.Core;
using PHP.Core.Reflection;
namespace PHP.Library
{
#region PhpProcessHandle
public class PhpProcessHandle : PhpResource
{
public Process/*!*/ Process { get { return process; } }
private Process/*!*/ process;
public string/*!*/ Command { get { return command; } }
private string/*!*/ command;
internal PhpProcessHandle(Process/*!*/ process, string/*!*/ command)
: base("process")
{
Debug.Assert(process != null && command != null);
this.process = process;
this.command = command;
}
protected override void FreeManaged()
{
process.Close();
base.FreeManaged();
}
internal static PhpProcessHandle Validate(PhpResource resource)
{
PhpProcessHandle result = resource as PhpProcessHandle;
if (result == null || !result.IsValid)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("invalid_process_resource"));
return null;
}
return result;
}
}
#endregion
public static class Processes
{
#region popen, pclose
private sealed class ProcessWrapper : StreamWrapper
{
public Process/*!*/ process;
public ProcessWrapper(Process/*!*/ process)
{
this.process = process;
}
public override bool IsUrl { get { return false; } }
public override string Label { get { return null; } }
public override string Scheme { get { return null; } }
public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)
{
return null;
}
}
/// <summary>
/// Starts a process and creates a pipe to its standard input or output.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="mode">Pipe open mode (<c>"r"</c> or <c>"w"</c>).</param>
/// <returns>Opened pipe or <B>null</B> on error.</returns>
[ImplementsFunction("popen")]
public static PhpResource OpenPipe(string command, string mode)
{
if (String.IsNullOrEmpty(mode))
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_file_mode", mode));
return null;
}
bool read = mode[0] == 'r';
bool write = mode[0] == 'w' || mode[0] == 'a' || mode[0] == 'x';
if (!read && !write)
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_file_mode", mode));
return null;
}
Process process = CreateProcessExecutingCommand(ref command, false);
if (process == null) return null;
process.StartInfo.RedirectStandardOutput = read;
process.StartInfo.RedirectStandardInput = write;
if (!StartProcess(process, true))
return null;
Stream stream = (read) ? process.StandardOutput.BaseStream : process.StandardInput.BaseStream;
StreamAccessOptions access = (read) ? StreamAccessOptions.Read : StreamAccessOptions.Write;
ProcessWrapper wrapper = new ProcessWrapper(process);
PhpStream php_stream = new NativeStream(stream, wrapper, access, String.Empty, StreamContext.Default);
return php_stream;
}
/// <summary>
/// Closes a pipe and a process opened by <see cref="OpenPipe"/>.
/// </summary>
/// <param name="pipeHandle">The pipe handle returned by <see cref="OpenPipe"/>.</param>
/// <returns>An exit code of the process.</returns>
[ImplementsFunction("pclose")]
public static int ClosePipe(PhpResource pipeHandle)
{
PhpStream php_stream = PhpStream.GetValid(pipeHandle);
if (php_stream == null) return -1;
ProcessWrapper wrapper = php_stream.Wrapper as ProcessWrapper;
if (wrapper == null) return -1;
var code = CloseProcess(wrapper.process);
php_stream.Close();
return code;
}
#endregion
#region proc_open
/// <summary>
/// Opens a process.
/// </summary>
[ImplementsFunction("proc_open")]
public static PhpResource Open(string command, PhpArray descriptorSpec, out PhpArray pipes)
{
return Open(command, descriptorSpec, out pipes, null, null, null);
}
/// <summary>
/// Opens a process.
/// </summary>
[ImplementsFunction("proc_open")]
public static PhpResource Open(string command, PhpArray descriptorSpec, out PhpArray pipes,
string workingDirectory)
{
return Open(command, descriptorSpec, out pipes, workingDirectory, null, null);
}
/// <summary>
/// Opens a process.
/// </summary>
[ImplementsFunction("proc_open")]
public static PhpResource Open(string command, PhpArray descriptorSpec, out PhpArray pipes,
string workingDirectory, PhpArray envVariables)
{
return Open(command, descriptorSpec, out pipes, workingDirectory, envVariables, null);
}
/// <summary>
/// Starts a process and otpionally redirects its input/output/error streams to specified PHP streams.
/// </summary>
/// <param name="command"></param>
/// <param name="descriptors"></param>
/// Indexed array where the key represents the descriptor number (0 for STDIN, 1 for STDOUT, 2 for STDERR)
/// and the value represents how to pass that descriptor to the child process.
/// A descriptor is either an opened file resources or an integer indexed arrays
/// containing descriptor name followed by options. Supported descriptors:
/// <list type="bullet">
/// <term><c>array("pipe",{mode})</c></term><description>Pipe is opened in the specified mode .</description>
/// <term><c>array("file",{path},{mode})</c></term><description>The file is opened in the specified mode.</description>
/// </list>
/// <param name="pipes">
/// Set to indexed array of file resources corresponding to the current process's ends of created pipes.
/// </param>
/// <param name="workingDirectory">
/// Working directory.
/// </param>
/// <param name="envVariables"></param>
/// <param name="options">
/// Associative array containing following key-value pairs.
/// <list type="bullet">
/// <term>"suppress_errors"</term><description></description>
/// </list>
/// </param>
/// <returns>
/// Resource representing the process.
/// </returns>
[ImplementsFunction("proc_open")]
public static PhpResource Open(string command, PhpArray descriptors, out PhpArray pipes,
string workingDirectory, PhpArray envVariables, PhpArray options)
{
if (descriptors == null)
{
PhpException.ArgumentNull("descriptors");
pipes = null;
return null;
}
pipes = new PhpArray();
PhpResource result = Open(command, descriptors, pipes, workingDirectory, envVariables, options);
return result;
}
/// <summary>
/// Opens a process.
/// </summary>
private static PhpResource Open(string command, PhpArray/*!*/ descriptors, PhpArray/*!*/ pipes,
string workingDirectory, PhpArray envVariables, PhpArray options)
{
if (descriptors == null)
throw new ArgumentNullException("descriptors");
if (pipes == null)
throw new ArgumentNullException("pipes");
bool bypass_shell = options != null && Core.Convert.ObjectToBoolean(options["bypass_shell"]); // quiet
Process process = CreateProcessExecutingCommand(ref command, bypass_shell);
if (process == null)
return null;
if (!SetupStreams(process, descriptors))
return null;
if (envVariables != null)
SetupEnvironment(process, envVariables);
if (workingDirectory != null)
process.StartInfo.WorkingDirectory = workingDirectory;
bool suppress_errors = false;
if (options != null)
{
suppress_errors = Core.Convert.ObjectToBoolean(options["suppress_errors"]);
}
if (!StartProcess(process, !suppress_errors))
return null;
if (!RedirectStreams(process, descriptors, pipes))
return null;
return new PhpProcessHandle(process, command);
}
private const string CommandLineSplitterPattern = @"(?<filename>^""[^""]*""|\S*) *(?<arguments>.*)?";
private static readonly System.Text.RegularExpressions.Regex/*!*/CommandLineSplitter = new System.Text.RegularExpressions.Regex(CommandLineSplitterPattern, System.Text.RegularExpressions.RegexOptions.Singleline);
private static Process CreateProcessExecutingCommand(ref string command, bool bypass_shell)
{
if (!Execution.MakeCommandSafe(ref command))
return null;
Process process = new Process();
if (bypass_shell)
{
var match = CommandLineSplitter.Match(command);
if (match == null || !match.Success)
{
PhpException.InvalidArgument("command");
return null;
}
process.StartInfo.FileName = match.Groups["filename"].Value;
process.StartInfo.Arguments = match.Groups["arguments"].Value;
}
else
{
process.StartInfo.FileName = (Environment.OSVersion.Platform != PlatformID.Win32Windows) ? "cmd.exe" : "command.com";
process.StartInfo.Arguments = "/c " + command;
}
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = ScriptContext.CurrentContext.WorkingDirectory;
return process;
}
private static bool StartProcess(Process/*!*/ process, bool reportError)
{
try
{
process.Start();
return true;
}
catch (Exception e)
{
if (reportError)
PhpException.Throw(PhpError.Warning, LibResources.GetString("error_starting_process", e.Message));
return false;
}
}
private static void SetupEnvironment(Process/*!*/ process, IDictionary/*!*/ envVariables)
{
foreach (DictionaryEntry entry in envVariables)
{
string s = entry.Key as string;
if (s != null)
process.StartInfo.EnvironmentVariables.Add(s, Core.Convert.ObjectToString(entry.Value));
}
}
private static bool SetupStreams(Process/*!*/ process, IDictionary/*!*/ descriptors)
{
foreach (DictionaryEntry entry in descriptors)
{
// key must be an integer:
if (!(entry.Key is int))
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("argument_not_integer_indexed_array", "descriptors"));
return false;
}
int desc_no = (int)entry.Key;
switch (desc_no)
{
case 0: process.StartInfo.RedirectStandardInput = true; break;
case 1: process.StartInfo.RedirectStandardOutput = true; break;
case 2: process.StartInfo.RedirectStandardError = true; break;
default:
PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_unsupported", desc_no));
return false;
}
}
return true;
}
private static bool RedirectStreams(Process/*!*/ process, PhpArray/*!*/ descriptors, PhpArray/*!*/ pipes)
{
using (var descriptors_enum = descriptors.GetFastEnumerator())
while (descriptors_enum.MoveNext())
{
int desc_no = descriptors_enum.CurrentKey.Integer;
StreamAccessOptions access;
Stream stream;
switch (desc_no)
{
case 0: stream = process.StandardInput.BaseStream; access = StreamAccessOptions.Write; break;
case 1: stream = process.StandardOutput.BaseStream; access = StreamAccessOptions.Read; break;
case 2: stream = process.StandardError.BaseStream; access = StreamAccessOptions.Read; break;
default: Debug.Fail(null); return false;
}
object value = PhpVariable.Dereference(descriptors_enum.CurrentValue);
PhpResource resource;
PhpArray array;
if ((array = PhpArray.AsPhpArray(value)) != null)
{
if (!array.Contains(0))
{
// value must be either a resource or an array:
PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_missing_qualifier", desc_no));
return false;
}
string qualifier = Core.Convert.ObjectToString(array[0]);
switch (qualifier)
{
case "pipe":
{
// mode is ignored (it's determined by the stream):
PhpStream php_stream = new NativeStream(stream, null, access, String.Empty, StreamContext.Default);
pipes.Add(desc_no, php_stream);
break;
}
case "file":
{
if (!array.Contains(1))
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_missing_file_name", desc_no));
return false;
}
if (!array.Contains(2))
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_missing_mode", desc_no));
return false;
}
string path = Core.Convert.ObjectToString(array[1]);
string mode = Core.Convert.ObjectToString(array[2]);
PhpStream php_stream = PhpStream.Open(path, mode, StreamOpenOptions.Empty, StreamContext.Default);
if (php_stream == null)
return false;
if (!ActivePipe.BeginIO(stream, php_stream, access, desc_no)) return false;
break;
}
default:
PhpException.Throw(PhpError.Warning, LibResources.GetString("invalid_handle_qualifier", qualifier));
return false;
}
}
else if ((resource = value as PhpResource) != null)
{
PhpStream php_stream = PhpStream.GetValid(resource);
if (php_stream == null) return false;
if (!ActivePipe.BeginIO(stream, php_stream, access, desc_no)) return false;
}
else
{
// value must be either a resource or an array:
PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_not_array_nor_resource", desc_no));
return false;
}
}
return true;
}
private sealed class ActivePipe
{
private const int BufferSize = 1024;
Stream stream;
StreamAccessOptions access;
PhpStream phpStream;
public AsyncCallback callback;
public PhpBytes buffer;
public static bool BeginIO(Stream stream, PhpStream phpStream, StreamAccessOptions access, int desc_no)
{
if (access == StreamAccessOptions.Read && !phpStream.CanWrite ||
access == StreamAccessOptions.Write && !phpStream.CanRead)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_invalid_mode", desc_no));
return false;
}
ActivePipe pipe = new ActivePipe();
pipe.stream = stream;
pipe.phpStream = phpStream;
pipe.access = access;
pipe.callback = new AsyncCallback(pipe.Callback);
if (access == StreamAccessOptions.Read)
{
var buffer = new byte[BufferSize];
stream.BeginRead(buffer, 0, buffer.Length, pipe.callback, null);
pipe.buffer = new PhpBytes(buffer);
}
else
{
pipe.buffer = phpStream.ReadBytes(BufferSize);
if (pipe.buffer != null)
stream.BeginWrite(pipe.buffer.ReadonlyData, 0, pipe.buffer.Length, pipe.callback, null);
else
stream.Close();
}
return true;
}
private void Callback(IAsyncResult ar)
{
if (access == StreamAccessOptions.Read)
{
int count = stream.EndRead(ar);
if (count > 0)
{
if (count != buffer.Length)
{
// TODO: improve streams
var buf = new byte[count];
Buffer.BlockCopy(buffer.ReadonlyData, 0, buf, 0, count);
phpStream.WriteBytes(new PhpBytes(buf));
}
else
{
phpStream.WriteBytes(buffer);
}
stream.BeginRead(buffer.Data, 0, buffer.Length, callback, ar.AsyncState);
}
else
{
stream.Close();
}
}
else
{
buffer = phpStream.ReadBytes(BufferSize);
if (buffer != null)
{
stream.BeginWrite(buffer.ReadonlyData, 0, buffer.Length, callback, ar.AsyncState);
}
else
{
stream.EndWrite(ar);
stream.Close();
}
}
}
}
#endregion
#region proc_close, proc_get_status, proc_terminate
[ImplementsFunction("proc_close")]
public static int Close(PhpResource process)
{
PhpProcessHandle handle = PhpProcessHandle.Validate(process);
if (handle == null) return -1;
var code = CloseProcess(handle.Process);
handle.Close();
return code;
}
private static int CloseProcess(Process/*!*/ process)
{
try
{
process.WaitForExit();
}
catch (Exception e)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("error_waiting_for_process_exit", e.Message));
return -1;
}
return process.ExitCode;
}
/// <summary>
///
/// </summary>
/// <param name="process"></param>
/// <returns>
/// <list type="bullet">
/// <term>"command"</term><description>The command string that was passed to proc_open()</description>
/// <term>"pid"</term><description>process id</description>
/// <term>"running"</term><description>TRUE if the process is still running, FALSE if it has terminated</description>
/// <term>"signaled"</term><description>TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows.</description>
/// <term>"stopped"</term><description>TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows.</description>
/// <term>"exitcode"</term><description>the exit code returned by the process (which is only meaningful if running is FALSE)</description>
/// <term>"termsig"</term><description>the number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE)</description>
/// <term>"stopsig"</term><description>the number of the signal that caused the child process to stop its execution (only meaningful if stopped is TRUE)</description>
/// </list>
/// </returns>
[ImplementsFunction("proc_get_status")]
public static PhpArray GetStatus(PhpResource process)
{
PhpProcessHandle handle = PhpProcessHandle.Validate(process);
if (handle == null) return null;
PhpArray result = new PhpArray(0, 8);
result.Add("command", handle.Command);
result.Add("pid", handle.Process.Id);
result.Add("running", !handle.Process.HasExited);
result.Add("signaled", false); // UNIX
result.Add("stopped", false); // UNIX
result.Add("exitcode", handle.Process.HasExited ? handle.Process.ExitCode : -1);
result.Add("termsig", 0); // UNIX
result.Add("stopsig", 0); // UNIX
return result;
}
[ImplementsFunction("proc_terminate")]
public static int Terminate(PhpResource process)
{
return Terminate(process, 255);
}
[ImplementsFunction("proc_terminate")]
public static int Terminate(PhpResource process, int signal)
{
PhpProcessHandle handle = PhpProcessHandle.Validate(process);
if (handle == null) return -1;
try
{
handle.Process.Kill();
}
catch (Exception e)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("error_terminating_process",
handle.Process.ProcessName, handle.Process.Id, e.Message));
return -1;
}
return handle.Process.ExitCode;
}
#endregion
#region NS: proc_nice
[ImplementsFunction("proc_nice", FunctionImplOptions.NotSupported)]
public static bool SetPriority(int priority)
{
PhpException.FunctionNotSupported(); // even in PHP for Windows, it is not available
return false;
}
#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.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal static class X500NameEncoder
{
private const string OidTagPrefix = "OID.";
private static readonly char[] s_quoteNeedingChars =
{
',',
'+',
'=',
'\"',
'\n',
// \r is NOT in this list, because it isn't in Windows.
'<',
'>',
'#',
';',
};
private static readonly List<char> s_useSemicolonSeparators = new List<char>(1) { ';' };
private static readonly List<char> s_useCommaSeparators = new List<char>(1) { ',' };
private static readonly List<char> s_useNewlineSeparators = new List<char>(2) { '\r', '\n' };
private static readonly List<char> s_defaultSeparators = new List<char>(2) { ',', ';' };
internal static string X500DistinguishedNameDecode(
byte[] encodedName,
bool printOid,
X500DistinguishedNameFlags flags,
bool addTrailingDelimieter=false)
{
bool reverse = (flags & X500DistinguishedNameFlags.Reversed) == X500DistinguishedNameFlags.Reversed;
bool quoteIfNeeded = (flags & X500DistinguishedNameFlags.DoNotUseQuotes) != X500DistinguishedNameFlags.DoNotUseQuotes;
string dnSeparator;
if ((flags & X500DistinguishedNameFlags.UseSemicolons) == X500DistinguishedNameFlags.UseSemicolons)
{
dnSeparator = "; ";
}
else if ((flags & X500DistinguishedNameFlags.UseNewLines) == X500DistinguishedNameFlags.UseNewLines)
{
dnSeparator = Environment.NewLine;
}
else
{
// This is matching Windows (native) behavior, UseCommas does not need to be asserted,
// it is just what happens if neither UseSemicolons nor UseNewLines is specified.
dnSeparator = ", ";
}
using (SafeX509NameHandle x509Name = Interop.Crypto.DecodeX509Name(encodedName, encodedName.Length))
{
if (x509Name.IsInvalid)
{
return "";
}
// We need to allocate a StringBuilder to hold the data as we're building it, and there's the usual
// arbitrary process of choosing a number that's "big enough" to minimize reallocations without wasting
// too much space in the average case.
//
// So, let's look at an example of what our output might be.
//
// GitHub.com's SSL cert has a "pretty long" subject (partially due to the unknown OIDs):
// businessCategory=Private Organization
// 1.3.6.1.4.1.311.60.2.1.3=US
// 1.3.6.1.4.1.311.60.2.1.2=Delaware
// serialNumber=5157550
// street=548 4th Street
// postalCode=94107
// C=US
// ST=California
// L=San Francisco
// O=GitHub, Inc.
// CN=github.com
//
// Which comes out to 228 characters using OpenSSL's default pretty-print
// (openssl x509 -in github.cer -text -noout)
// Throw in some "maybe-I-need-to-quote-this" quotes, and a couple of extra/extra-long O/OU values
// and round that up to the next programmer number, and you get that 512 should avoid reallocations
// in all but the most dire of cases.
StringBuilder decodedName = new StringBuilder(512);
int entryCount = Interop.Crypto.GetX509NameEntryCount(x509Name);
bool printSpacing = false;
for (int i = 0; i < entryCount; i++)
{
int loc = reverse ? entryCount - i - 1 : i;
using (SafeSharedX509NameEntryHandle nameEntry = Interop.Crypto.GetX509NameEntry(x509Name, loc))
{
Interop.Crypto.CheckValidOpenSslHandle(nameEntry);
string thisOidValue;
using (SafeSharedAsn1ObjectHandle oidHandle = Interop.Crypto.GetX509NameEntryOid(nameEntry))
{
thisOidValue = Interop.Crypto.GetOidValue(oidHandle);
}
if (printSpacing)
{
decodedName.Append(dnSeparator);
}
else
{
printSpacing = true;
}
if (printOid)
{
AppendOid(decodedName, thisOidValue);
}
string rdnValue;
using (SafeSharedAsn1StringHandle valueHandle = Interop.Crypto.GetX509NameEntryData(nameEntry))
{
rdnValue = Interop.Crypto.Asn1StringToManagedString(valueHandle);
}
bool quote = quoteIfNeeded && NeedsQuoting(rdnValue);
if (quote)
{
decodedName.Append('"');
// If the RDN itself had a quote within it, that quote needs to be escaped
// with another quote.
rdnValue = rdnValue.Replace("\"", "\"\"");
}
decodedName.Append(rdnValue);
if (quote)
{
decodedName.Append('"');
}
}
}
if (addTrailingDelimieter)
{
decodedName.Append(dnSeparator);
}
return decodedName.ToString();
}
}
internal static byte[] X500DistinguishedNameEncode(
string stringForm,
X500DistinguishedNameFlags flags)
{
bool reverse = (flags & X500DistinguishedNameFlags.Reversed) == X500DistinguishedNameFlags.Reversed;
bool noQuotes = (flags & X500DistinguishedNameFlags.DoNotUseQuotes) == X500DistinguishedNameFlags.DoNotUseQuotes;
List<char> dnSeparators;
// This rank ordering is based off of testing against the Windows implementation.
if ((flags & X500DistinguishedNameFlags.UseSemicolons) == X500DistinguishedNameFlags.UseSemicolons)
{
// Just semicolon.
dnSeparators = s_useSemicolonSeparators;
}
else if ((flags & X500DistinguishedNameFlags.UseCommas) == X500DistinguishedNameFlags.UseCommas)
{
// Just comma
dnSeparators = s_useCommaSeparators;
}
else if ((flags & X500DistinguishedNameFlags.UseNewLines) == X500DistinguishedNameFlags.UseNewLines)
{
// CR or LF. Not "and". Whichever is first was the separator, the later one is trimmed as whitespace.
dnSeparators = s_useNewlineSeparators;
}
else
{
// Comma or semicolon, but not CR or LF.
dnSeparators = s_defaultSeparators;
}
Debug.Assert(dnSeparators.Count != 0);
List<byte[][]> encodedSets = ParseDistinguishedName(stringForm, dnSeparators, noQuotes);
if (reverse)
{
encodedSets.Reverse();
}
return DerEncoder.ConstructSequence(encodedSets);
}
private static bool NeedsQuoting(string rdnValue)
{
if (string.IsNullOrEmpty(rdnValue))
{
return true;
}
if (IsQuotableWhitespace(rdnValue[0]) ||
IsQuotableWhitespace(rdnValue[rdnValue.Length - 1]))
{
return true;
}
int index = rdnValue.IndexOfAny(s_quoteNeedingChars);
return index != -1;
}
private static bool IsQuotableWhitespace(char c)
{
// There's a whole lot of Unicode whitespace that isn't covered here; but this
// matches what Windows deems quote-worthy.
//
// 0x20: Space
// 0x09: Character Tabulation (tab)
// 0x0A: Line Feed
// 0x0B: Line Tabulation (vertical tab)
// 0x0C: Form Feed
// 0x0D: Carriage Return
return (c == ' ' || (c >= 0x09 && c <= 0x0D));
}
private static void AppendOid(StringBuilder decodedName, string oidValue)
{
Oid oid = new Oid(oidValue);
if (StringComparer.Ordinal.Equals(oid.FriendlyName, oidValue) ||
string.IsNullOrEmpty(oid.FriendlyName))
{
decodedName.Append(OidTagPrefix);
decodedName.Append(oid.Value);
}
else
{
decodedName.Append(oid.FriendlyName);
}
decodedName.Append('=');
}
private enum ParseState
{
Invalid,
SeekTag,
SeekTagEnd,
SeekEquals,
SeekValueStart,
SeekValueEnd,
SeekEndQuote,
MaybeEndQuote,
SeekComma,
}
private static List<byte[][]> ParseDistinguishedName(
string stringForm,
List<char> dnSeparators,
bool noQuotes)
{
// 16 is way more RDNs than we should ever need. A fairly standard set of values is
// { E, CN, O, OU, L, S, C } = 7;
// The EV values add in
// {
// STREET, PostalCode, SERIALNUMBER, 2.5.4.15,
// 1.3.6.1.4.1.311.60.2.1.2, 1.3.6.1.4.1.311.60.2.1.3
// } = 6
//
// 7 + 6 = 13, round up to the nearest power-of-two.
const int InitalRdnSize = 16;
List<byte[][]> encodedSets = new List<byte[][]>(InitalRdnSize);
char[] chars = stringForm.ToCharArray();
int pos;
int end = chars.Length;
int tagStart = -1;
int tagEnd = -1;
Oid tagOid = null;
int valueStart = -1;
int valueEnd = -1;
bool hadEscapedQuote = false;
const char KeyValueSeparator = '=';
const char QuotedValueChar = '"';
ParseState state = ParseState.SeekTag;
for (pos = 0; pos < end; pos++)
{
char c = chars[pos];
switch (state)
{
case ParseState.SeekTag:
if (char.IsWhiteSpace(c))
{
continue;
}
if (char.IsControl(c))
{
state = ParseState.Invalid;
break;
}
// The first character in the tag start.
// We know that there's at least one valid
// character, so make end be start+1.
//
// Single letter values with no whitespace padding them
// (e.g. E=) would otherwise be ambiguous with length.
// (SeekEquals can't set the tagEnd value because it
// doesn't know if it was preceded by whitespace)
// Note that we make no check here for the dnSeparator(s).
// Two separators in a row is invalid (except for UseNewlines,
// and they are only allowed because they are whitespace).
//
// But the throw for an invalid value will come from when the
// OID fails to encode.
tagStart = pos;
tagEnd = pos + 1;
state = ParseState.SeekTagEnd;
break;
case ParseState.SeekTagEnd:
if (c == KeyValueSeparator)
{
goto case ParseState.SeekEquals;
}
if (char.IsWhiteSpace(c))
{
// Tag values aren't permitted whitespace, but there
// can be whitespace between the tag and the separator.
state = ParseState.SeekEquals;
break;
}
if (char.IsControl(c))
{
state = ParseState.Invalid;
break;
}
// We found another character in the tag, so move the
// end (non-inclusive) to the next character.
tagEnd = pos + 1;
break;
case ParseState.SeekEquals:
if (c == KeyValueSeparator)
{
Debug.Assert(tagStart >= 0);
tagOid = ParseOid(stringForm, tagStart, tagEnd);
tagStart = -1;
state = ParseState.SeekValueStart;
break;
}
if (!char.IsWhiteSpace(c))
{
state = ParseState.Invalid;
break;
}
break;
case ParseState.SeekValueStart:
if (char.IsWhiteSpace(c))
{
continue;
}
// If the first non-whitespace character is a quote,
// this is a quoted string. Unless the flags say to
// not interpret quoted strings.
if (c == QuotedValueChar && !noQuotes)
{
state = ParseState.SeekEndQuote;
valueStart = pos + 1;
break;
}
// It's possible to just write "CN=,O=". So we might
// run into the RDN separator here.
if (dnSeparators.Contains(c))
{
valueStart = pos;
valueEnd = pos;
goto case ParseState.SeekComma;
}
state = ParseState.SeekValueEnd;
valueStart = pos;
valueEnd = pos + 1;
break;
case ParseState.SeekEndQuote:
// The only escape sequence in DN parsing is that a quoted
// value can embed quotes via "", the same as a C# verbatim
// string. So, if we see a quote while looking for a close
// quote we need to remember that this might have been the
// end, but be open to the possibility that there's another
// quote coming.
if (c == QuotedValueChar)
{
state = ParseState.MaybeEndQuote;
valueEnd = pos;
break;
}
// Everything else is okay.
break;
case ParseState.MaybeEndQuote:
if (c == QuotedValueChar)
{
state = ParseState.SeekEndQuote;
hadEscapedQuote = true;
valueEnd = -1;
break;
}
// If the character wasn't another quote:
// dnSeparator: process value, state transition to SeekTag
// whitespace: state transition to SeekComma
// anything else: invalid.
// since that's the same table as SeekComma, just change state
// and go there.
state = ParseState.SeekComma;
goto case ParseState.SeekComma;
case ParseState.SeekValueEnd:
// Every time we see a non-whitespace character we need to mark it
if (dnSeparators.Contains(c))
{
goto case ParseState.SeekComma;
}
if (char.IsWhiteSpace(c))
{
continue;
}
// Including control characters.
valueEnd = pos + 1;
break;
case ParseState.SeekComma:
if (dnSeparators.Contains(c))
{
Debug.Assert(tagOid != null);
Debug.Assert(valueEnd != -1);
Debug.Assert(valueStart != -1);
encodedSets.Add(ParseRdn(tagOid, chars, valueStart, valueEnd, hadEscapedQuote));
tagOid = null;
valueStart = -1;
valueEnd = -1;
state = ParseState.SeekTag;
break;
}
if (!char.IsWhiteSpace(c))
{
state = ParseState.Invalid;
break;
}
break;
default:
Debug.Fail(
string.Format(
"Invalid parser state. Position {0}, State {1}, Character {2}, String \"{3}\"",
pos,
state,
c,
stringForm));
throw new CryptographicException(SR.Cryptography_Invalid_X500Name);
}
if (state == ParseState.Invalid)
{
break;
}
}
// Okay, so we've run out of input. There are a couple of valid states we can be in.
// * 'CN='
// state: SeekValueStart. Neither valueStart nor valueEnd has a value yet.
// * 'CN=a'
// state: SeekValueEnd. valueEnd was set to pos(a) + 1, close it off.
// * 'CN=a '
// state: SeekValueEnd. valueEnd is marking at the start of the whitespace.
// * 'CN="a"'
// state: MaybeEndQuote. valueEnd is marking at the end-quote.
// * 'CN="a" '
// state: SeekComma. This is the same as MaybeEndQuote.
// * 'CN=a,'
// state: SeekTag. There's nothing to do here.
// * ''
// state: SeekTag. There's nothing to do here.
//
// And, of course, invalid ones.
// * 'CN="'
// state: SeekEndQuote. Throw.
// * 'CN':
// state: SeekEndTag. Throw.
switch (state)
{
// The last semantic character parsed was =.
case ParseState.SeekValueStart:
valueStart = chars.Length;
valueEnd = valueStart;
goto case ParseState.SeekComma;
// If we were in an unquoted value and just ran out of text
case ParseState.SeekValueEnd:
Debug.Assert(!hadEscapedQuote);
goto case ParseState.SeekComma;
// If the last character was a close quote, or it was a close quote
// then some whitespace.
case ParseState.MaybeEndQuote:
case ParseState.SeekComma:
Debug.Assert(tagOid != null);
Debug.Assert(valueStart != -1);
Debug.Assert(valueEnd != -1);
encodedSets.Add(ParseRdn(tagOid, chars, valueStart, valueEnd, hadEscapedQuote));
break;
// If the entire string was empty, or ended in a dnSeparator.
case ParseState.SeekTag:
break;
default:
// While this is an error, it should be due to bad input, so no Debug.Fail.
throw new CryptographicException(SR.Cryptography_Invalid_X500Name);
}
return encodedSets;
}
private static Oid ParseOid(string stringForm, int tagStart, int tagEnd)
{
int length = tagEnd - tagStart;
if (length > OidTagPrefix.Length)
{
// Since we only care if the match starts exactly at tagStart, tell IndexOf
// that we're only examining OidTagPrefix.Length characters. So it won't do
// more than one linear equality check.
int prefixIndex = stringForm.IndexOf(
OidTagPrefix,
tagStart,
OidTagPrefix.Length,
StringComparison.OrdinalIgnoreCase);
if (prefixIndex == tagStart)
{
return new Oid(stringForm.Substring(tagStart + OidTagPrefix.Length, length - OidTagPrefix.Length));
}
}
return new Oid(stringForm.Substring(tagStart, length));
}
private static byte[][] ParseRdn(Oid tagOid, char[] chars, int valueStart, int valueEnd, bool hadEscapedQuote)
{
bool ia5String = (tagOid.Value == Oids.EmailAddress);
byte[][] encodedOid;
try
{
encodedOid = DerEncoder.SegmentedEncodeOid(tagOid);
}
catch (CryptographicException e)
{
throw new CryptographicException(SR.Cryptography_Invalid_X500Name, e);
}
if (hadEscapedQuote)
{
char[] value = ExtractValue(chars, valueStart, valueEnd);
return ParseRdn(encodedOid, value, ia5String);
}
return ParseRdn(encodedOid, chars, valueStart, valueEnd, ia5String);
}
private static byte[][] ParseRdn(
byte[][] encodedOid,
char[] chars,
int valueStart,
int valueEnd,
bool ia5String)
{
byte[][] encodedValue;
int length = valueEnd - valueStart;
if (ia5String)
{
// An email address with an invalid value will throw.
encodedValue = DerEncoder.SegmentedEncodeIA5String(chars, valueStart, length);
}
else if (DerEncoder.IsValidPrintableString(chars, valueStart, length))
{
encodedValue = DerEncoder.SegmentedEncodePrintableString(chars, valueStart, length);
}
else
{
encodedValue = DerEncoder.SegmentedEncodeUtf8String(chars, valueStart, length);
}
return DerEncoder.ConstructSegmentedSet(
DerEncoder.ConstructSegmentedSequence(
encodedOid,
encodedValue));
}
private static byte[][] ParseRdn(byte[][] encodedOid, char[] value, bool ia5String)
{
byte[][] encodedValue;
if (ia5String)
{
// An email address with an invalid value will throw.
encodedValue = DerEncoder.SegmentedEncodeIA5String(value);
}
else if (DerEncoder.IsValidPrintableString(value))
{
encodedValue = DerEncoder.SegmentedEncodePrintableString(value);
}
else
{
encodedValue = DerEncoder.SegmentedEncodeUtf8String(value);
}
return DerEncoder.ConstructSegmentedSet(
DerEncoder.ConstructSegmentedSequence(
encodedOid,
encodedValue));
}
private static char[] ExtractValue(char[] chars, int valueStart, int valueEnd)
{
// The string is guaranteed to be between ((valueEnd - valueStart) / 2) (all quotes) and
// (valueEnd - valueStart - 1) (one escaped quote)
List<char> builder = new List<char>(valueEnd - valueStart - 1);
bool skippedQuote = false;
for (int i = valueStart; i < valueEnd; i++)
{
char c = chars[i];
if (c == '"' && !skippedQuote)
{
skippedQuote = true;
continue;
}
// If we just skipped a quote, this will be one.
// If this is a quote, we should have just skipped one.
Debug.Assert(skippedQuote == (c == '"'));
skippedQuote = false;
builder.Add(c);
}
return builder.ToArray();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Collections;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Reflection;
using System.Xml;
using System.ServiceModel.Diagnostics;
using System.Diagnostics;
using System.Runtime;
class PrimitiveOperationFormatter : IClientMessageFormatter, IDispatchMessageFormatter
{
OperationDescription operation;
MessageDescription responseMessage;
MessageDescription requestMessage;
XmlDictionaryString action;
XmlDictionaryString replyAction;
ActionHeader actionHeaderNone;
ActionHeader actionHeader10;
ActionHeader actionHeaderAugust2004;
ActionHeader replyActionHeaderNone;
ActionHeader replyActionHeader10;
ActionHeader replyActionHeaderAugust2004;
XmlDictionaryString requestWrapperName;
XmlDictionaryString requestWrapperNamespace;
XmlDictionaryString responseWrapperName;
XmlDictionaryString responseWrapperNamespace;
PartInfo[] requestParts;
PartInfo[] responseParts;
PartInfo returnPart;
XmlDictionaryString xsiNilLocalName;
XmlDictionaryString xsiNilNamespace;
public PrimitiveOperationFormatter(OperationDescription description, bool isRpc)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
OperationFormatter.Validate(description, isRpc, false/*isEncoded*/);
this.operation = description;
#pragma warning suppress 56506 // [....], OperationDescription.Messages never be null
this.requestMessage = description.Messages[0];
if (description.Messages.Count == 2)
this.responseMessage = description.Messages[1];
int stringCount = 3 + requestMessage.Body.Parts.Count;
if (responseMessage != null)
stringCount += 2 + responseMessage.Body.Parts.Count;
XmlDictionary dictionary = new XmlDictionary(stringCount * 2);
xsiNilLocalName = dictionary.Add("nil");
xsiNilNamespace = dictionary.Add(System.Xml.Schema.XmlSchema.InstanceNamespace);
OperationFormatter.GetActions(description, dictionary, out this.action, out this.replyAction);
if (requestMessage.Body.WrapperName != null)
{
requestWrapperName = AddToDictionary(dictionary, requestMessage.Body.WrapperName);
requestWrapperNamespace = AddToDictionary(dictionary, requestMessage.Body.WrapperNamespace);
}
requestParts = AddToDictionary(dictionary, requestMessage.Body.Parts, isRpc);
if (responseMessage != null)
{
if (responseMessage.Body.WrapperName != null)
{
responseWrapperName = AddToDictionary(dictionary, responseMessage.Body.WrapperName);
responseWrapperNamespace = AddToDictionary(dictionary, responseMessage.Body.WrapperNamespace);
}
responseParts = AddToDictionary(dictionary, responseMessage.Body.Parts, isRpc);
if (responseMessage.Body.ReturnValue != null && responseMessage.Body.ReturnValue.Type != typeof(void))
{
returnPart = AddToDictionary(dictionary, responseMessage.Body.ReturnValue, isRpc);
}
}
}
ActionHeader ActionHeaderNone
{
get
{
if (actionHeaderNone == null)
{
actionHeaderNone =
ActionHeader.Create(this.action, AddressingVersion.None);
}
return actionHeaderNone;
}
}
ActionHeader ActionHeader10
{
get
{
if (actionHeader10 == null)
{
actionHeader10 =
ActionHeader.Create(this.action, AddressingVersion.WSAddressing10);
}
return actionHeader10;
}
}
ActionHeader ActionHeaderAugust2004
{
get
{
if (actionHeaderAugust2004 == null)
{
actionHeaderAugust2004 =
ActionHeader.Create(this.action, AddressingVersion.WSAddressingAugust2004);
}
return actionHeaderAugust2004;
}
}
ActionHeader ReplyActionHeaderNone
{
get
{
if (replyActionHeaderNone == null)
{
replyActionHeaderNone =
ActionHeader.Create(this.replyAction, AddressingVersion.None);
}
return replyActionHeaderNone;
}
}
ActionHeader ReplyActionHeader10
{
get
{
if (replyActionHeader10 == null)
{
replyActionHeader10 =
ActionHeader.Create(this.replyAction, AddressingVersion.WSAddressing10);
}
return replyActionHeader10;
}
}
ActionHeader ReplyActionHeaderAugust2004
{
get
{
if (replyActionHeaderAugust2004 == null)
{
replyActionHeaderAugust2004 =
ActionHeader.Create(this.replyAction, AddressingVersion.WSAddressingAugust2004);
}
return replyActionHeaderAugust2004;
}
}
static XmlDictionaryString AddToDictionary(XmlDictionary dictionary, string s)
{
XmlDictionaryString dictionaryString;
if (!dictionary.TryLookup(s, out dictionaryString))
{
dictionaryString = dictionary.Add(s);
}
return dictionaryString;
}
static PartInfo[] AddToDictionary(XmlDictionary dictionary, MessagePartDescriptionCollection parts, bool isRpc)
{
PartInfo[] partInfos = new PartInfo[parts.Count];
for (int i = 0; i < parts.Count; i++)
{
partInfos[i] = AddToDictionary(dictionary, parts[i], isRpc);
}
return partInfos;
}
ActionHeader GetActionHeader(AddressingVersion addressing)
{
if (this.action == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressingAugust2004)
{
return ActionHeaderAugust2004;
}
else if (addressing == AddressingVersion.WSAddressing10)
{
return ActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.AddressingVersionNotSupported, addressing)));
}
}
ActionHeader GetReplyActionHeader(AddressingVersion addressing)
{
if (this.replyAction == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressingAugust2004)
{
return ReplyActionHeaderAugust2004;
}
else if (addressing == AddressingVersion.WSAddressing10)
{
return ReplyActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ReplyActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.AddressingVersionNotSupported, addressing)));
}
}
static string GetArrayItemName(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
return "boolean";
case TypeCode.DateTime:
return "dateTime";
case TypeCode.Decimal:
return "decimal";
case TypeCode.Int32:
return "int";
case TypeCode.Int64:
return "long";
case TypeCode.Single:
return "float";
case TypeCode.Double:
return "double";
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidUseOfPrimitiveOperationFormatter)));
}
}
static PartInfo AddToDictionary(XmlDictionary dictionary, MessagePartDescription part, bool isRpc)
{
Type type = part.Type;
XmlDictionaryString itemName = null;
XmlDictionaryString itemNamespace = null;
if (type.IsArray && type != typeof(byte[]))
{
const string ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
string name = GetArrayItemName(type.GetElementType());
itemName = AddToDictionary(dictionary, name);
itemNamespace = AddToDictionary(dictionary, ns);
}
return new PartInfo(part,
AddToDictionary(dictionary, part.Name),
AddToDictionary(dictionary, isRpc ? string.Empty : part.Namespace),
itemName, itemNamespace);
}
public static bool IsContractSupported(OperationDescription description)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
OperationDescription operation = description;
#pragma warning suppress 56506 // [....], OperationDescription.Messages never be null
MessageDescription requestMessage = description.Messages[0];
MessageDescription responseMessage = null;
if (description.Messages.Count == 2)
responseMessage = description.Messages[1];
if (requestMessage.Headers.Count > 0)
return false;
if (requestMessage.Properties.Count > 0)
return false;
if (requestMessage.IsTypedMessage)
return false;
if (responseMessage != null)
{
if (responseMessage.Headers.Count > 0)
return false;
if (responseMessage.Properties.Count > 0)
return false;
if (responseMessage.IsTypedMessage)
return false;
}
if (!AreTypesSupported(requestMessage.Body.Parts))
return false;
if (responseMessage != null)
{
if (!AreTypesSupported(responseMessage.Body.Parts))
return false;
if (responseMessage.Body.ReturnValue != null && !IsTypeSupported(responseMessage.Body.ReturnValue))
return false;
}
return true;
}
static bool AreTypesSupported(MessagePartDescriptionCollection bodyDescriptions)
{
for (int i = 0; i < bodyDescriptions.Count; i++)
if (!IsTypeSupported(bodyDescriptions[i]))
return false;
return true;
}
static bool IsTypeSupported(MessagePartDescription bodyDescription)
{
Fx.Assert(bodyDescription != null, "");
Type type = bodyDescription.Type;
if (type == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxMessagePartDescriptionMissingType, bodyDescription.Name, bodyDescription.Namespace)));
if (bodyDescription.Multiple)
return false;
if (type == typeof(void))
return true;
if (type.IsEnum)
return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.String:
return true;
case TypeCode.Object:
if (type.IsArray && type.GetArrayRank() == 1 && IsArrayTypeSupported(type.GetElementType()))
return true;
break;
default:
break;
}
return false;
}
static bool IsArrayTypeSupported(Type type)
{
if (type.IsEnum)
return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
return true;
default:
return false;
}
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
if (parameters == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
return Message.CreateMessage(messageVersion, GetActionHeader(messageVersion.Addressing), new PrimitiveRequestBodyWriter(parameters, this));
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
if (parameters == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
return Message.CreateMessage(messageVersion, GetReplyActionHeader(messageVersion.Addressing), new PrimitiveResponseBodyWriter(parameters, result, this));
}
public object DeserializeReply(Message message, object[] parameters)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (parameters == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message);
try
{
if (message.IsEmpty)
{
if (responseWrapperName == null)
return null;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.SFxInvalidMessageBodyEmptyMessage)));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
object returnValue = DeserializeResponse(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
return returnValue;
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.GetString(SR.SFxErrorDeserializingReplyBodyMore, operation.Name, xe.Message), xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.GetString(SR.SFxErrorDeserializingReplyBodyMore, operation.Name, fe.Message), fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.GetString(SR.SFxErrorDeserializingReplyBodyMore, operation.Name, se.Message), se));
}
}
public void DeserializeRequest(Message message, object[] parameters)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (parameters == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message);
try
{
if (message.IsEmpty)
{
if (requestWrapperName == null)
return;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.SFxInvalidMessageBodyEmptyMessage)));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
DeserializeRequest(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
SR.GetString(SR.SFxErrorDeserializingRequestBodyMore, operation.Name, xe.Message),
xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
SR.GetString(SR.SFxErrorDeserializingRequestBodyMore, operation.Name, fe.Message),
fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.GetString(SR.SFxErrorDeserializingRequestBodyMore, operation.Name, se.Message),
se));
}
}
void DeserializeRequest(XmlDictionaryReader reader, object[] parameters)
{
if (requestWrapperName != null)
{
if (!reader.IsStartElement(requestWrapperName, requestWrapperNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.SFxInvalidMessageBody, requestWrapperName, requestWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return;
}
}
DeserializeParameters(reader, requestParts, parameters);
if (requestWrapperName != null)
{
reader.ReadEndElement();
}
}
object DeserializeResponse(XmlDictionaryReader reader, object[] parameters)
{
if (responseWrapperName != null)
{
if (!reader.IsStartElement(responseWrapperName, responseWrapperNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.SFxInvalidMessageBody, responseWrapperName, responseWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return null;
}
}
object returnValue = null;
if (returnPart != null)
{
while (true)
{
if (IsPartElement(reader, returnPart))
{
returnValue = DeserializeParameter(reader, returnPart);
break;
}
if (!reader.IsStartElement())
break;
if (IsPartElements(reader, responseParts))
break;
OperationFormatter.TraceAndSkipElement(reader);
}
}
DeserializeParameters(reader, responseParts, parameters);
if (responseWrapperName != null)
{
reader.ReadEndElement();
}
return returnValue;
}
void DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.GetString(SR.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
int nextPartIndex = 0;
while (reader.IsStartElement())
{
for (int i = nextPartIndex; i < parts.Length; i++)
{
PartInfo part = parts[i];
if (IsPartElement(reader, part))
{
parameters[part.Description.Index] = DeserializeParameter(reader, parts[i]);
nextPartIndex = i + 1;
}
else
parameters[part.Description.Index] = null;
}
if (reader.IsStartElement())
OperationFormatter.TraceAndSkipElement(reader);
}
}
private bool IsPartElements(XmlDictionaryReader reader, PartInfo[] parts)
{
foreach (PartInfo part in parts)
if (IsPartElement(reader, part))
return true;
return false;
}
bool IsPartElement(XmlDictionaryReader reader, PartInfo part)
{
return reader.IsStartElement(part.DictionaryName, part.DictionaryNamespace);
}
object DeserializeParameter(XmlDictionaryReader reader, PartInfo part)
{
if (reader.AttributeCount > 0 &&
reader.MoveToAttribute(xsiNilLocalName.Value, xsiNilNamespace.Value) &&
reader.ReadContentAsBoolean())
{
reader.Skip();
return null;
}
return part.ReadValue(reader);
}
void SerializeParameter(XmlDictionaryWriter writer, PartInfo part, object graph)
{
writer.WriteStartElement(part.DictionaryName, part.DictionaryNamespace);
if (graph == null)
{
writer.WriteStartAttribute(xsiNilLocalName, xsiNilNamespace);
writer.WriteValue(true);
writer.WriteEndAttribute();
}
else
part.WriteValue(writer, graph);
writer.WriteEndElement();
}
void SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.GetString(SR.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
for (int i = 0; i < parts.Length; i++)
{
PartInfo part = parts[i];
SerializeParameter(writer, part, parameters[part.Description.Index]);
}
}
void SerializeRequest(XmlDictionaryWriter writer, object[] parameters)
{
if (requestWrapperName != null)
writer.WriteStartElement(requestWrapperName, requestWrapperNamespace);
SerializeParameters(writer, requestParts, parameters);
if (requestWrapperName != null)
writer.WriteEndElement();
}
void SerializeResponse(XmlDictionaryWriter writer, object returnValue, object[] parameters)
{
if (responseWrapperName != null)
writer.WriteStartElement(responseWrapperName, responseWrapperNamespace);
if (returnPart != null)
SerializeParameter(writer, returnPart, returnValue);
SerializeParameters(writer, responseParts, parameters);
if (responseWrapperName != null)
writer.WriteEndElement();
}
class PartInfo
{
XmlDictionaryString dictionaryName;
XmlDictionaryString dictionaryNamespace;
XmlDictionaryString itemName;
XmlDictionaryString itemNamespace;
MessagePartDescription description;
TypeCode typeCode;
bool isArray;
public PartInfo(MessagePartDescription description, XmlDictionaryString dictionaryName, XmlDictionaryString dictionaryNamespace, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
this.dictionaryName = dictionaryName;
this.dictionaryNamespace = dictionaryNamespace;
this.itemName = itemName;
this.itemNamespace = itemNamespace;
this.description = description;
if (description.Type.IsArray)
{
this.isArray = true;
this.typeCode = Type.GetTypeCode(description.Type.GetElementType());
}
else
{
this.isArray = false;
this.typeCode = Type.GetTypeCode(description.Type);
}
}
public MessagePartDescription Description
{
get { return description; }
}
public XmlDictionaryString DictionaryName
{
get { return dictionaryName; }
}
public XmlDictionaryString DictionaryNamespace
{
get { return dictionaryNamespace; }
}
public object ReadValue(XmlDictionaryReader reader)
{
object value;
if (isArray)
{
switch (typeCode)
{
case TypeCode.Byte:
value = reader.ReadElementContentAsBase64();
break;
case TypeCode.Boolean:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadBooleanArray(itemName, itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = new bool[0];
}
break;
case TypeCode.DateTime:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDateTimeArray(itemName, itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = new DateTime[0];
}
break;
case TypeCode.Decimal:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDecimalArray(itemName, itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = new Decimal[0];
}
break;
case TypeCode.Int32:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt32Array(itemName, itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = new Int32[0];
}
break;
case TypeCode.Int64:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt64Array(itemName, itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = new Int64[0];
}
break;
case TypeCode.Single:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadSingleArray(itemName, itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = new Single[0];
}
break;
case TypeCode.Double:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDoubleArray(itemName, itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = new Double[0];
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidUseOfPrimitiveOperationFormatter)));
}
}
else
{
switch (typeCode)
{
case TypeCode.Boolean:
value = reader.ReadElementContentAsBoolean();
break;
case TypeCode.DateTime:
value = reader.ReadElementContentAsDateTime();
break;
case TypeCode.Decimal:
value = reader.ReadElementContentAsDecimal();
break;
case TypeCode.Double:
value = reader.ReadElementContentAsDouble();
break;
case TypeCode.Int32:
value = reader.ReadElementContentAsInt();
break;
case TypeCode.Int64:
value = reader.ReadElementContentAsLong();
break;
case TypeCode.Single:
value = reader.ReadElementContentAsFloat();
break;
case TypeCode.String:
return reader.ReadElementContentAsString();
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidUseOfPrimitiveOperationFormatter)));
}
}
return value;
}
public void WriteValue(XmlDictionaryWriter writer, object value)
{
if (isArray)
{
switch (typeCode)
{
case TypeCode.Byte:
{
byte[] arrayValue = (byte[])value;
writer.WriteBase64(arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Boolean:
{
bool[] arrayValue = (bool[])value;
writer.WriteArray(null, itemName, itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.DateTime:
{
DateTime[] arrayValue = (DateTime[])value;
writer.WriteArray(null, itemName, itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Decimal:
{
decimal[] arrayValue = (decimal[])value;
writer.WriteArray(null, itemName, itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int32:
{
Int32[] arrayValue = (Int32[])value;
writer.WriteArray(null, itemName, itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int64:
{
Int64[] arrayValue = (Int64[])value;
writer.WriteArray(null, itemName, itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Single:
{
float[] arrayValue = (float[])value;
writer.WriteArray(null, itemName, itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Double:
{
double[] arrayValue = (double[])value;
writer.WriteArray(null, itemName, itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidUseOfPrimitiveOperationFormatter)));
}
}
else
{
switch (typeCode)
{
case TypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case TypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case TypeCode.Decimal:
writer.WriteValue((Decimal)value);
break;
case TypeCode.Double:
writer.WriteValue((double)value);
break;
case TypeCode.Int32:
writer.WriteValue((int)value);
break;
case TypeCode.Int64:
writer.WriteValue((long)value);
break;
case TypeCode.Single:
writer.WriteValue((float)value);
break;
case TypeCode.String:
writer.WriteString((string)value);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidUseOfPrimitiveOperationFormatter)));
}
}
}
}
class PrimitiveRequestBodyWriter : BodyWriter
{
object[] parameters;
PrimitiveOperationFormatter primitiveOperationFormatter;
public PrimitiveRequestBodyWriter(object[] parameters, PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
this.parameters = parameters;
this.primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
primitiveOperationFormatter.SerializeRequest(writer, parameters);
}
}
class PrimitiveResponseBodyWriter : BodyWriter
{
object[] parameters;
object returnValue;
PrimitiveOperationFormatter primitiveOperationFormatter;
public PrimitiveResponseBodyWriter(object[] parameters, object returnValue,
PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
this.parameters = parameters;
this.returnValue = returnValue;
this.primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
primitiveOperationFormatter.SerializeResponse(writer, returnValue, parameters);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using ParentLoadRO.DataAccess;
using ParentLoadRO.DataAccess.ERCLevel;
namespace ParentLoadRO.DataAccess.Sql.ERCLevel
{
/// <summary>
/// DAL SQL Server implementation of <see cref="IB01_ContinentCollDal"/>
/// </summary>
public partial class B01_ContinentCollDal : IB01_ContinentCollDal
{
private List<B03_Continent_ChildDto> _b03_Continent_Child = new List<B03_Continent_ChildDto>();
private List<B03_Continent_ReChildDto> _b03_Continent_ReChild = new List<B03_Continent_ReChildDto>();
private List<B04_SubContinentDto> _b03_SubContinentColl = new List<B04_SubContinentDto>();
private List<B05_SubContinent_ChildDto> _b05_SubContinent_Child = new List<B05_SubContinent_ChildDto>();
private List<B05_SubContinent_ReChildDto> _b05_SubContinent_ReChild = new List<B05_SubContinent_ReChildDto>();
private List<B06_CountryDto> _b05_CountryColl = new List<B06_CountryDto>();
private List<B07_Country_ChildDto> _b07_Country_Child = new List<B07_Country_ChildDto>();
private List<B07_Country_ReChildDto> _b07_Country_ReChild = new List<B07_Country_ReChildDto>();
private List<B08_RegionDto> _b07_RegionColl = new List<B08_RegionDto>();
private List<B09_Region_ChildDto> _b09_Region_Child = new List<B09_Region_ChildDto>();
private List<B09_Region_ReChildDto> _b09_Region_ReChild = new List<B09_Region_ReChildDto>();
private List<B10_CityDto> _b09_CityColl = new List<B10_CityDto>();
private List<B11_City_ChildDto> _b11_City_Child = new List<B11_City_ChildDto>();
private List<B11_City_ReChildDto> _b11_City_ReChild = new List<B11_City_ReChildDto>();
private List<B12_CityRoadDto> _b11_CityRoadColl = new List<B12_CityRoadDto>();
/// <summary>
/// Gets the B03 Continent Single Object.
/// </summary>
/// <value>A list of <see cref="B03_Continent_ChildDto"/>.</value>
public List<B03_Continent_ChildDto> B03_Continent_Child
{
get { return _b03_Continent_Child; }
}
/// <summary>
/// Gets the B03 Continent ASingle Object.
/// </summary>
/// <value>A list of <see cref="B03_Continent_ReChildDto"/>.</value>
public List<B03_Continent_ReChildDto> B03_Continent_ReChild
{
get { return _b03_Continent_ReChild; }
}
/// <summary>
/// Gets the B03 SubContinent Objects.
/// </summary>
/// <value>A list of <see cref="B04_SubContinentDto"/>.</value>
public List<B04_SubContinentDto> B03_SubContinentColl
{
get { return _b03_SubContinentColl; }
}
/// <summary>
/// Gets the B05 SubContinent Single Object.
/// </summary>
/// <value>A list of <see cref="B05_SubContinent_ChildDto"/>.</value>
public List<B05_SubContinent_ChildDto> B05_SubContinent_Child
{
get { return _b05_SubContinent_Child; }
}
/// <summary>
/// Gets the B05 SubContinent ASingle Object.
/// </summary>
/// <value>A list of <see cref="B05_SubContinent_ReChildDto"/>.</value>
public List<B05_SubContinent_ReChildDto> B05_SubContinent_ReChild
{
get { return _b05_SubContinent_ReChild; }
}
/// <summary>
/// Gets the B05 Country Objects.
/// </summary>
/// <value>A list of <see cref="B06_CountryDto"/>.</value>
public List<B06_CountryDto> B05_CountryColl
{
get { return _b05_CountryColl; }
}
/// <summary>
/// Gets the B07 Country Single Object.
/// </summary>
/// <value>A list of <see cref="B07_Country_ChildDto"/>.</value>
public List<B07_Country_ChildDto> B07_Country_Child
{
get { return _b07_Country_Child; }
}
/// <summary>
/// Gets the B07 Country ASingle Object.
/// </summary>
/// <value>A list of <see cref="B07_Country_ReChildDto"/>.</value>
public List<B07_Country_ReChildDto> B07_Country_ReChild
{
get { return _b07_Country_ReChild; }
}
/// <summary>
/// Gets the B07 Region Objects.
/// </summary>
/// <value>A list of <see cref="B08_RegionDto"/>.</value>
public List<B08_RegionDto> B07_RegionColl
{
get { return _b07_RegionColl; }
}
/// <summary>
/// Gets the B09 Region Single Object.
/// </summary>
/// <value>A list of <see cref="B09_Region_ChildDto"/>.</value>
public List<B09_Region_ChildDto> B09_Region_Child
{
get { return _b09_Region_Child; }
}
/// <summary>
/// Gets the B09 Region ASingle Object.
/// </summary>
/// <value>A list of <see cref="B09_Region_ReChildDto"/>.</value>
public List<B09_Region_ReChildDto> B09_Region_ReChild
{
get { return _b09_Region_ReChild; }
}
/// <summary>
/// Gets the B09 City Objects.
/// </summary>
/// <value>A list of <see cref="B10_CityDto"/>.</value>
public List<B10_CityDto> B09_CityColl
{
get { return _b09_CityColl; }
}
/// <summary>
/// Gets the B11 City Single Object.
/// </summary>
/// <value>A list of <see cref="B11_City_ChildDto"/>.</value>
public List<B11_City_ChildDto> B11_City_Child
{
get { return _b11_City_Child; }
}
/// <summary>
/// Gets the B11 City ASingle Object.
/// </summary>
/// <value>A list of <see cref="B11_City_ReChildDto"/>.</value>
public List<B11_City_ReChildDto> B11_City_ReChild
{
get { return _b11_City_ReChild; }
}
/// <summary>
/// Gets the B11 CityRoad Objects.
/// </summary>
/// <value>A list of <see cref="B12_CityRoadDto"/>.</value>
public List<B12_CityRoadDto> B11_CityRoadColl
{
get { return _b11_CityRoadColl; }
}
/// <summary>
/// Loads a B01_ContinentColl collection from the database.
/// </summary>
/// <returns>A list of <see cref="B02_ContinentDto"/>.</returns>
public List<B02_ContinentDto> Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetB01_ContinentColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var dr = cmd.ExecuteReader();
return LoadCollection(dr);
}
}
}
private List<B02_ContinentDto> LoadCollection(IDataReader data)
{
var b01_ContinentColl = new List<B02_ContinentDto>();
using (var dr = new SafeDataReader(data))
{
while (dr.Read())
{
b01_ContinentColl.Add(Fetch(dr));
}
if (b01_ContinentColl.Count > 0)
FetchChildren(dr);
}
return b01_ContinentColl;
}
private B02_ContinentDto Fetch(SafeDataReader dr)
{
var b02_Continent = new B02_ContinentDto();
// Value properties
b02_Continent.Continent_ID = dr.GetInt32("Continent_ID");
b02_Continent.Continent_Name = dr.GetString("Continent_Name");
return b02_Continent;
}
private void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
while (dr.Read())
{
_b03_Continent_Child.Add(FetchB03_Continent_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b03_Continent_ReChild.Add(FetchB03_Continent_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b03_SubContinentColl.Add(FetchB04_SubContinent(dr));
}
dr.NextResult();
while (dr.Read())
{
_b05_SubContinent_Child.Add(FetchB05_SubContinent_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b05_SubContinent_ReChild.Add(FetchB05_SubContinent_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b05_CountryColl.Add(FetchB06_Country(dr));
}
dr.NextResult();
while (dr.Read())
{
_b07_Country_Child.Add(FetchB07_Country_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b07_Country_ReChild.Add(FetchB07_Country_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b07_RegionColl.Add(FetchB08_Region(dr));
}
dr.NextResult();
while (dr.Read())
{
_b09_Region_Child.Add(FetchB09_Region_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b09_Region_ReChild.Add(FetchB09_Region_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b09_CityColl.Add(FetchB10_City(dr));
}
dr.NextResult();
while (dr.Read())
{
_b11_City_Child.Add(FetchB11_City_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b11_City_ReChild.Add(FetchB11_City_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b11_CityRoadColl.Add(FetchB12_CityRoad(dr));
}
}
private B03_Continent_ChildDto FetchB03_Continent_Child(SafeDataReader dr)
{
var b03_Continent_Child = new B03_Continent_ChildDto();
// Value properties
b03_Continent_Child.Continent_Child_Name = dr.GetString("Continent_Child_Name");
// parent properties
b03_Continent_Child.Parent_Continent_ID = dr.GetInt32("Continent_ID1");
return b03_Continent_Child;
}
private B03_Continent_ReChildDto FetchB03_Continent_ReChild(SafeDataReader dr)
{
var b03_Continent_ReChild = new B03_Continent_ReChildDto();
// Value properties
b03_Continent_ReChild.Continent_Child_Name = dr.GetString("Continent_Child_Name");
// parent properties
b03_Continent_ReChild.Parent_Continent_ID = dr.GetInt32("Continent_ID2");
return b03_Continent_ReChild;
}
private B04_SubContinentDto FetchB04_SubContinent(SafeDataReader dr)
{
var b04_SubContinent = new B04_SubContinentDto();
// Value properties
b04_SubContinent.SubContinent_ID = dr.GetInt32("SubContinent_ID");
b04_SubContinent.SubContinent_Name = dr.GetString("SubContinent_Name");
// parent properties
b04_SubContinent.Parent_Continent_ID = dr.GetInt32("Parent_Continent_ID");
return b04_SubContinent;
}
private B05_SubContinent_ChildDto FetchB05_SubContinent_Child(SafeDataReader dr)
{
var b05_SubContinent_Child = new B05_SubContinent_ChildDto();
// Value properties
b05_SubContinent_Child.SubContinent_Child_Name = dr.GetString("SubContinent_Child_Name");
// parent properties
b05_SubContinent_Child.Parent_SubContinent_ID = dr.GetInt32("SubContinent_ID1");
return b05_SubContinent_Child;
}
private B05_SubContinent_ReChildDto FetchB05_SubContinent_ReChild(SafeDataReader dr)
{
var b05_SubContinent_ReChild = new B05_SubContinent_ReChildDto();
// Value properties
b05_SubContinent_ReChild.SubContinent_Child_Name = dr.GetString("SubContinent_Child_Name");
// parent properties
b05_SubContinent_ReChild.Parent_SubContinent_ID = dr.GetInt32("SubContinent_ID2");
return b05_SubContinent_ReChild;
}
private B06_CountryDto FetchB06_Country(SafeDataReader dr)
{
var b06_Country = new B06_CountryDto();
// Value properties
b06_Country.Country_ID = dr.GetInt32("Country_ID");
b06_Country.Country_Name = dr.GetString("Country_Name");
// parent properties
b06_Country.Parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID");
return b06_Country;
}
private B07_Country_ChildDto FetchB07_Country_Child(SafeDataReader dr)
{
var b07_Country_Child = new B07_Country_ChildDto();
// Value properties
b07_Country_Child.Country_Child_Name = dr.GetString("Country_Child_Name");
// parent properties
b07_Country_Child.Parent_Country_ID = dr.GetInt32("Country_ID1");
return b07_Country_Child;
}
private B07_Country_ReChildDto FetchB07_Country_ReChild(SafeDataReader dr)
{
var b07_Country_ReChild = new B07_Country_ReChildDto();
// Value properties
b07_Country_ReChild.Country_Child_Name = dr.GetString("Country_Child_Name");
// parent properties
b07_Country_ReChild.Parent_Country_ID = dr.GetInt32("Country_ID2");
return b07_Country_ReChild;
}
private B08_RegionDto FetchB08_Region(SafeDataReader dr)
{
var b08_Region = new B08_RegionDto();
// Value properties
b08_Region.Region_ID = dr.GetInt32("Region_ID");
b08_Region.Region_Name = dr.GetString("Region_Name");
// parent properties
b08_Region.Parent_Country_ID = dr.GetInt32("Parent_Country_ID");
return b08_Region;
}
private B09_Region_ChildDto FetchB09_Region_Child(SafeDataReader dr)
{
var b09_Region_Child = new B09_Region_ChildDto();
// Value properties
b09_Region_Child.Region_Child_Name = dr.GetString("Region_Child_Name");
// parent properties
b09_Region_Child.Parent_Region_ID = dr.GetInt32("Region_ID1");
return b09_Region_Child;
}
private B09_Region_ReChildDto FetchB09_Region_ReChild(SafeDataReader dr)
{
var b09_Region_ReChild = new B09_Region_ReChildDto();
// Value properties
b09_Region_ReChild.Region_Child_Name = dr.GetString("Region_Child_Name");
// parent properties
b09_Region_ReChild.Parent_Region_ID = dr.GetInt32("Region_ID2");
return b09_Region_ReChild;
}
private B10_CityDto FetchB10_City(SafeDataReader dr)
{
var b10_City = new B10_CityDto();
// Value properties
b10_City.City_ID = dr.GetInt32("City_ID");
b10_City.City_Name = dr.GetString("City_Name");
// parent properties
b10_City.Parent_Region_ID = dr.GetInt32("Parent_Region_ID");
return b10_City;
}
private B11_City_ChildDto FetchB11_City_Child(SafeDataReader dr)
{
var b11_City_Child = new B11_City_ChildDto();
// Value properties
b11_City_Child.City_Child_Name = dr.GetString("City_Child_Name");
// parent properties
b11_City_Child.Parent_City_ID = dr.GetInt32("City_ID1");
return b11_City_Child;
}
private B11_City_ReChildDto FetchB11_City_ReChild(SafeDataReader dr)
{
var b11_City_ReChild = new B11_City_ReChildDto();
// Value properties
b11_City_ReChild.City_Child_Name = dr.GetString("City_Child_Name");
// parent properties
b11_City_ReChild.Parent_City_ID = dr.GetInt32("City_ID2");
return b11_City_ReChild;
}
private B12_CityRoadDto FetchB12_CityRoad(SafeDataReader dr)
{
var b12_CityRoad = new B12_CityRoadDto();
// Value properties
b12_CityRoad.CityRoad_ID = dr.GetInt32("CityRoad_ID");
b12_CityRoad.CityRoad_Name = dr.GetString("CityRoad_Name");
// parent properties
b12_CityRoad.Parent_City_ID = dr.GetInt32("Parent_City_ID");
return b12_CityRoad;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.DataSnapshot.Interfaces;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.DataSnapshot.Providers
{
public class ObjectSnapshot : IDataSnapshotProvider
{
private Scene m_scene = null;
// private DataSnapshotManager m_parent = null;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_stale = true;
private static UUID m_DefaultImage = new UUID("89556747-24cb-43ed-920b-47caed15465f");
private static UUID m_BlankImage = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
public void Initialize(Scene scene, DataSnapshotManager parent)
{
m_scene = scene;
// m_parent = parent;
//To check for staleness, we must catch all incoming client packets.
m_scene.EventManager.OnNewClient += OnNewClient;
m_scene.EventManager.OnParcelPrimCountAdd += delegate(SceneObjectGroup obj) { this.Stale = true; };
}
public void OnNewClient(IClientAPI client)
{
//Detect object data changes by hooking into the IClientAPI.
//Very dirty, and breaks whenever someone changes the client API.
client.OnAddPrim += delegate (UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot,
PrimitiveBaseShape shape, byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
byte RayEndIsIntersection) { this.Stale = true; };
client.OnLinkObjects += delegate (IClientAPI remoteClient, uint parent, List<uint> children)
{ this.Stale = true; };
client.OnDelinkObjects += delegate(List<uint> primIds, IClientAPI clientApi) { this.Stale = true; };
client.OnGrabUpdate += delegate(UUID objectID, Vector3 offset, Vector3 grapPos,
IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { this.Stale = true; };
client.OnObjectAttach += delegate(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt,
bool silent) { this.Stale = true; };
client.OnObjectDuplicate += delegate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID,
UUID GroupID) { this.Stale = true; };
client.OnObjectDuplicateOnRay += delegate(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart, bool BypassRaycast,
bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates) { this.Stale = true; };
client.OnObjectIncludeInSearch += delegate(IClientAPI remoteClient, bool IncludeInSearch, uint localID)
{ this.Stale = true; };
client.OnObjectPermissions += delegate(IClientAPI controller, UUID agentID, UUID sessionID,
byte field, uint localId, uint mask, byte set) { this.Stale = true; };
client.OnRezObject += delegate(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd,
Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected,
bool RemoveItem, UUID fromTaskID) { this.Stale = true; };
}
public Scene GetParentScene
{
get { return m_scene; }
}
public XmlNode RequestSnapshotData(XmlDocument nodeFactory)
{
m_log.Debug("[DATASNAPSHOT]: Generating object data for scene " + m_scene.RegionInfo.RegionName);
XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "objectdata", "");
XmlNode node;
EntityBase[] entities = m_scene.Entities.GetEntities();
foreach (EntityBase entity in entities)
{
// only objects, not avatars
if (entity is SceneObjectGroup)
{
SceneObjectGroup obj = (SceneObjectGroup)entity;
// m_log.Debug("[DATASNAPSHOT]: Found object " + obj.Name + " in scene");
// libomv will complain about PrimFlags.JointWheel
// being obsolete, so we...
#pragma warning disable 0612
if ((obj.RootPart.Flags & PrimFlags.JointWheel) == PrimFlags.JointWheel)
{
SceneObjectPart m_rootPart = obj.RootPart;
if (m_rootPart != null)
{
ILandObject land = m_scene.LandChannel.GetLandObject(m_rootPart.AbsolutePosition.X, m_rootPart.AbsolutePosition.Y);
XmlNode xmlobject = nodeFactory.CreateNode(XmlNodeType.Element, "object", "");
node = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
node.InnerText = obj.UUID.ToString();
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "title", "");
node.InnerText = m_rootPart.Name;
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "description", "");
node.InnerText = m_rootPart.Description;
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "flags", "");
node.InnerText = String.Format("{0:x}", (uint)m_rootPart.Flags);
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "regionuuid", "");
node.InnerText = m_scene.RegionInfo.RegionSettings.RegionUUID.ToString();
xmlobject.AppendChild(node);
if (land != null && land.LandData != null)
{
node = nodeFactory.CreateNode(XmlNodeType.Element, "parceluuid", "");
node.InnerText = land.LandData.GlobalID.ToString();
xmlobject.AppendChild(node);
}
else
{
// Something is wrong with this object. Let's not list it.
m_log.WarnFormat("[DATASNAPSHOT]: Bad data for object {0} ({1}) in region {2}", obj.Name, obj.UUID, m_scene.RegionInfo.RegionName);
continue;
}
node = nodeFactory.CreateNode(XmlNodeType.Element, "location", "");
Vector3 loc = obj.AbsolutePosition;
node.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString();
xmlobject.AppendChild(node);
string bestImage = GuessImage(obj);
if (bestImage != string.Empty)
{
node = nodeFactory.CreateNode(XmlNodeType.Element, "image", "");
node.InnerText = bestImage;
xmlobject.AppendChild(node);
}
parent.AppendChild(xmlobject);
}
}
#pragma warning disable 0612
}
}
this.Stale = false;
return parent;
}
public String Name
{
get { return "ObjectSnapshot"; }
}
public bool Stale
{
get
{
return m_stale;
}
set
{
m_stale = value;
if (m_stale)
OnStale(this);
}
}
public event ProviderStale OnStale;
/// <summary>
/// Guesses the best image, based on a simple heuristic. It guesses only for boxes.
/// We're optimizing for boxes, because those are the most common objects
/// marked "Show in search" -- boxes with content inside.For other shapes,
/// it's really hard to tell which texture should be grabbed.
/// </summary>
/// <param name="sog"></param>
/// <returns></returns>
private string GuessImage(SceneObjectGroup sog)
{
string bestguess = string.Empty;
Dictionary<UUID, int> counts = new Dictionary<UUID, int>();
PrimitiveBaseShape shape = sog.RootPart.Shape;
if (shape != null && shape.ProfileShape == ProfileShape.Square)
{
Primitive.TextureEntry textures = shape.Textures;
if (textures != null)
{
if (textures.DefaultTexture != null &&
textures.DefaultTexture.TextureID != UUID.Zero &&
textures.DefaultTexture.TextureID != m_DefaultImage &&
textures.DefaultTexture.TextureID != m_BlankImage &&
textures.DefaultTexture.RGBA.A < 50f)
{
counts[textures.DefaultTexture.TextureID] = 8;
}
if (textures.FaceTextures != null)
{
foreach (Primitive.TextureEntryFace tentry in textures.FaceTextures)
{
if (tentry != null)
{
if (tentry.TextureID != UUID.Zero && tentry.TextureID != m_DefaultImage && tentry.TextureID != m_BlankImage && tentry.RGBA.A < 50)
{
int c = 0;
counts.TryGetValue(tentry.TextureID, out c);
counts[tentry.TextureID] = c + 1;
// decrease the default texture count
if (counts.ContainsKey(textures.DefaultTexture.TextureID))
counts[textures.DefaultTexture.TextureID] = counts[textures.DefaultTexture.TextureID] - 1;
}
}
}
}
// Let's pick the most unique texture
int min = 9999;
foreach (KeyValuePair<UUID, int> kv in counts)
{
if (kv.Value < min && kv.Value >= 1)
{
bestguess = kv.Key.ToString();
min = kv.Value;
}
}
}
}
return bestguess;
}
}
}
| |
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// 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.Collections;
using System.Collections.Generic;
namespace Microsoft.Cci.Pdb {
internal class PdbFunction {
static internal readonly Guid msilMetaData = new Guid(0xc6ea3fc9, 0x59b3, 0x49d6, 0xbc, 0x25,
0x09, 0x02, 0xbb, 0xab, 0xb4, 0x60);
static internal readonly IComparer byAddress = new PdbFunctionsByAddress();
static internal readonly IComparer byAddressAndToken = new PdbFunctionsByAddressAndToken();
//static internal readonly IComparer byToken = new PdbFunctionsByToken();
internal uint token;
internal uint slotToken;
internal uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod;
//internal string name;
//internal string module;
//internal ushort flags;
internal uint segment;
internal uint address;
//internal uint length;
//internal byte[] metadata;
internal PdbScope[] scopes;
internal PdbSlot[] slots;
internal PdbConstant[] constants;
internal string[] usedNamespaces;
internal PdbLines[] lines;
internal ushort[]/*?*/ usingCounts;
internal IEnumerable<INamespaceScope>/*?*/ namespaceScopes;
internal string/*?*/ iteratorClass;
internal List<ILocalScope>/*?*/ iteratorScopes;
internal PdbSynchronizationInformation/*?*/ synchronizationInformation;
private static string StripNamespace(string module) {
int li = module.LastIndexOf('.');
if (li > 0) {
return module.Substring(li + 1);
}
return module;
}
internal static PdbFunction[] LoadManagedFunctions(/*string module,*/
BitAccess bits, uint limit,
bool readStrings) {
//string mod = StripNamespace(module);
int begin = bits.Position;
int count = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.Position = (int)proc.end;
count++;
break;
case SYM.S_END:
bits.Position = stop;
break;
default:
//Console.WriteLine("{0,6}: {1:x2} {2}",
// bits.Position, rec, (SYM)rec);
bits.Position = stop;
break;
}
}
if (count == 0) {
return null;
}
bits.Position = begin;
PdbFunction[] funcs = new PdbFunction[count];
int func = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
//int offset = bits.Position;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.ReadUInt32(out proc.next);
bits.ReadUInt32(out proc.len);
bits.ReadUInt32(out proc.dbgStart);
bits.ReadUInt32(out proc.dbgEnd);
bits.ReadUInt32(out proc.token);
bits.ReadUInt32(out proc.off);
bits.ReadUInt16(out proc.seg);
bits.ReadUInt8(out proc.flags);
bits.ReadUInt16(out proc.retReg);
if (readStrings) {
bits.ReadCString(out proc.name);
} else {
bits.SkipCString(out proc.name);
}
//Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name);
bits.Position = stop;
funcs[func++] = new PdbFunction(/*module,*/ proc, bits);
break;
default: {
//throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
return funcs;
}
internal static void CountScopesAndSlots(BitAccess bits, uint limit,
out int constants, out int scopes, out int slots, out int usedNamespaces) {
int pos = bits.Position;
BlockSym32 block;
constants = 0;
slots = 0;
scopes = 0;
usedNamespaces = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_BLOCK32: {
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
scopes++;
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
slots++;
bits.Position = stop;
break;
case SYM.S_UNAMESPACE:
usedNamespaces++;
bits.Position = stop;
break;
case SYM.S_MANCONSTANT:
constants++;
bits.Position = stop;
break;
default:
bits.Position = stop;
break;
}
}
bits.Position = pos;
}
internal PdbFunction() {
}
internal PdbFunction(/*string module, */ManProcSym proc, BitAccess bits) {
this.token = proc.token;
//this.module = module;
//this.name = proc.name;
//this.flags = proc.flags;
this.segment = proc.seg;
this.address = proc.off;
//this.length = proc.len;
if (proc.seg != 1) {
throw new PdbDebugException("Segment is {0}, not 1.", proc.seg);
}
if (proc.parent != 0 || proc.next != 0) {
throw new PdbDebugException("Warning parent={0}, next={1}",
proc.parent, proc.next);
}
//if (proc.dbgStart != 0 || proc.dbgEnd != 0) {
// throw new PdbDebugException("Warning DBG start={0}, end={1}",
// proc.dbgStart, proc.dbgEnd);
//}
int constantCount;
int scopeCount;
int slotCount;
int usedNamespacesCount;
CountScopesAndSlots(bits, proc.end, out constantCount, out scopeCount, out slotCount, out usedNamespacesCount);
int scope = constantCount > 0 || slotCount > 0 || usedNamespacesCount > 0 ? 1 : 0;
int slot = 0;
int constant = 0;
int usedNs = 0;
scopes = new PdbScope[scopeCount+scope];
slots = new PdbSlot[slotCount];
constants = new PdbConstant[constantCount];
usedNamespaces = new string[usedNamespacesCount];
if (scope > 0)
scopes[0] = new PdbScope(this.address, proc.len, slots, constants, usedNamespaces);
while (bits.Position < proc.end) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_OEM: { // 0x0404
OemSymbol oem;
bits.ReadGuid(out oem.idOem);
bits.ReadUInt32(out oem.typind);
// internal byte[] rgl; // user data, force 4-byte alignment
if (oem.idOem == msilMetaData) {
string name = bits.ReadString();
if (name == "MD2") {
byte version;
bits.ReadUInt8(out version);
if (version == 4) {
byte count;
bits.ReadUInt8(out count);
bits.Align(4);
while (count-- > 0)
this.ReadCustomMetadata(bits);
}
} else if (name == "asyncMethodInfo") {
this.synchronizationInformation = new PdbSynchronizationInformation(bits);
}
bits.Position = stop;
break;
} else {
throw new PdbDebugException("OEM section: guid={0} ti={1}",
oem.idOem, oem.typind);
// bits.Position = stop;
}
}
case SYM.S_BLOCK32: {
BlockSym32 block = new BlockSym32();
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
bits.ReadUInt32(out block.len);
bits.ReadUInt32(out block.off);
bits.ReadUInt16(out block.seg);
bits.SkipCString(out block.name);
bits.Position = stop;
scopes[scope++] = new PdbScope(this.address, block, bits, out slotToken);
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
uint typind;
slots[slot++] = new PdbSlot(bits, out typind);
bits.Position = stop;
break;
case SYM.S_MANCONSTANT:
constants[constant++] = new PdbConstant(bits);
bits.Position = stop;
break;
case SYM.S_UNAMESPACE:
bits.ReadCString(out usedNamespaces[usedNs++]);
bits.Position = stop;
break;
case SYM.S_END:
bits.Position = stop;
break;
default: {
//throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
if (bits.Position != proc.end) {
throw new PdbDebugException("Not at S_END");
}
ushort esiz;
ushort erec;
bits.ReadUInt16(out esiz);
bits.ReadUInt16(out erec);
if (erec != (ushort)SYM.S_END) {
throw new PdbDebugException("Missing S_END");
}
}
private void ReadCustomMetadata(BitAccess bits) {
int savedPosition = bits.Position;
byte version;
bits.ReadUInt8(out version);
if (version != 4) {
throw new PdbDebugException("Unknown custom metadata item version: {0}", version);
}
byte kind;
bits.ReadUInt8(out kind);
bits.Align(4);
uint numberOfBytesInItem;
bits.ReadUInt32(out numberOfBytesInItem);
switch (kind) {
case 0: this.ReadUsingInfo(bits); break;
case 1: this.ReadForwardInfo(bits); break;
case 2: break; // this.ReadForwardedToModuleInfo(bits); break;
case 3: this.ReadIteratorLocals(bits); break;
case 4: this.ReadForwardIterator(bits); break;
default: throw new PdbDebugException("Unknown custom metadata item kind: {0}", kind);
}
bits.Position = savedPosition+(int)numberOfBytesInItem;
}
private void ReadForwardIterator(BitAccess bits) {
this.iteratorClass = bits.ReadString();
}
private void ReadIteratorLocals(BitAccess bits) {
uint numberOfLocals;
bits.ReadUInt32(out numberOfLocals);
this.iteratorScopes = new List<ILocalScope>((int)numberOfLocals);
while (numberOfLocals-- > 0) {
uint ilStartOffset;
uint ilEndOffset;
bits.ReadUInt32(out ilStartOffset);
bits.ReadUInt32(out ilEndOffset);
this.iteratorScopes.Add(new PdbIteratorScope(ilStartOffset, ilEndOffset-ilStartOffset));
}
}
//private void ReadForwardedToModuleInfo(BitAccess bits) {
//}
private void ReadForwardInfo(BitAccess bits) {
bits.ReadUInt32(out this.tokenOfMethodWhoseUsingInfoAppliesToThisMethod);
}
private void ReadUsingInfo(BitAccess bits) {
ushort numberOfNamespaces;
bits.ReadUInt16(out numberOfNamespaces);
this.usingCounts = new ushort[numberOfNamespaces];
for (ushort i = 0; i < numberOfNamespaces; i++) {
bits.ReadUInt16(out this.usingCounts[i]);
}
}
internal class PdbFunctionsByAddress : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
} else if (fx.segment > fy.segment) {
return 1;
} else if (fx.address < fy.address) {
return -1;
} else if (fx.address > fy.address) {
return 1;
} else {
return 0;
}
}
}
internal class PdbFunctionsByAddressAndToken : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
} else if (fx.segment > fy.segment) {
return 1;
} else if (fx.address < fy.address) {
return -1;
} else if (fx.address > fy.address) {
return 1;
} else {
if (fx.token < fy.token)
return -1;
else if (fx.token > fy.token)
return 1;
else
return 0;
}
}
}
//internal class PdbFunctionsByToken : IComparer {
// public int Compare(Object x, Object y) {
// PdbFunction fx = (PdbFunction)x;
// PdbFunction fy = (PdbFunction)y;
// if (fx.token < fy.token) {
// return -1;
// } else if (fx.token > fy.token) {
// return 1;
// } else {
// return 0;
// }
// }
//}
}
internal class PdbSynchronizationInformation : ISynchronizationInformation {
internal uint kickoffMethodToken;
internal IMethodDefinition asyncMethod;
internal IMethodDefinition moveNextMethod;
internal uint generatedCatchHandlerIlOffset;
internal PdbSynchronizationPoint[] synchronizationPoints;
internal PdbSynchronizationInformation(BitAccess bits) {
uint asyncStepInfoCount;
bits.ReadUInt32(out this.kickoffMethodToken);
bits.ReadUInt32(out this.generatedCatchHandlerIlOffset);
bits.ReadUInt32(out asyncStepInfoCount);
this.synchronizationPoints = new PdbSynchronizationPoint[asyncStepInfoCount];
for (uint i = 0; i < asyncStepInfoCount; i += 1) {
this.synchronizationPoints[i] = new PdbSynchronizationPoint(bits);
}
this.asyncMethod = Dummy.MethodDefinition;
this.moveNextMethod = Dummy.MethodDefinition;
}
public IMethodDefinition AsyncMethod {
get { return this.asyncMethod; }
}
public IMethodDefinition MoveNextMethod {
get { return this.moveNextMethod; }
}
public uint GeneratedCatchHandlerOffset {
get { return this.generatedCatchHandlerIlOffset; }
}
public IEnumerable<ISynchronizationPoint> SynchronizationPoints {
get { return IteratorHelper.GetConversionEnumerable<PdbSynchronizationPoint, ISynchronizationPoint>(this.synchronizationPoints); }
}
}
internal class PdbSynchronizationPoint : ISynchronizationPoint {
internal uint synchronizeOffset;
internal uint continuationMethodToken;
internal IMethodDefinition/*?*/ continuationMethod;
internal uint continuationOffset;
internal PdbSynchronizationPoint(BitAccess bits) {
bits.ReadUInt32(out this.synchronizeOffset);
bits.ReadUInt32(out this.continuationMethodToken);
bits.ReadUInt32(out this.continuationOffset);
}
public uint SynchronizeOffset {
get { return this.synchronizeOffset; }
}
public IMethodDefinition/*?*/ ContinuationMethod {
get { return this.continuationMethod; }
}
public uint ContinuationOffset {
get { return this.continuationOffset; }
}
}
}
| |
namespace FancyApps.Services.Areas.HelpPage.ModelDescriptions
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using Debug = System.Diagnostics.Debug;
using Microsoft.SPOT.Debugger.WireProtocol;
using BreakpointDef = Microsoft.SPOT.Debugger.WireProtocol.Commands.Debugging_Execution_BreakpointDef;
namespace Microsoft.SPOT.Debugger
{
[Serializable]
public enum CorDebugExceptionCallbackType
{
DEBUG_EXCEPTION_FIRST_CHANCE = 1,
DEBUG_EXCEPTION_USER_FIRST_CHANCE = 2,
DEBUG_EXCEPTION_CATCH_HANDLER_FOUND = 3,
DEBUG_EXCEPTION_UNHANDLED = 4,
}
//Superclass for all tinyclr breakpoints
public abstract class CorDebugBreakpointBase
{
static ushort s_idNull = 0;
static ushort s_idNext = 1;
private CorDebugProcess m_process;
private CorDebugAppDomain m_appDomain;
private bool m_fActive;
protected readonly BreakpointDef m_breakpointDef;
protected CorDebugBreakpointBase (CorDebugProcess process)
{
m_breakpointDef = new BreakpointDef ();
m_breakpointDef.m_id = s_idNext++;
m_breakpointDef.m_pid = BreakpointDef.c_PID_ANY;
m_appDomain = null;
m_process = process;
Debug.Assert (s_idNext != s_idNull);
}
protected CorDebugBreakpointBase (CorDebugAppDomain appDomain) : this (appDomain.Process)
{
m_appDomain = appDomain;
}
public CorDebugAppDomain AppDomain {
[System.Diagnostics.DebuggerHidden]
get { return m_appDomain; }
}
public virtual bool IsMatch (BreakpointDef breakpointDef)
{
return breakpointDef.m_id == this.m_breakpointDef.m_id;
}
public ushort Kind {
[System.Diagnostics.DebuggerHidden]
get { return m_breakpointDef.m_flags; }
set {
m_breakpointDef.m_flags = value;
Dirty ();
}
}
protected CorDebugProcess Process {
[System.Diagnostics.DebuggerHidden]
get { return m_process; }
}
public bool Active {
[System.Diagnostics.DebuggerHidden]
get { return m_fActive; }
set {
if (m_fActive != value) {
m_fActive = value;
m_process.RegisterBreakpoint (this, m_fActive);
Dirty ();
}
}
}
public void Dirty ()
{
m_process.DirtyBreakpoints ();
}
public virtual void Hit (BreakpointDef breakpointDef)
{
}
public virtual bool ShouldBreak (BreakpointDef breakpointDef)
{
return true;
}
public virtual bool Equals (CorDebugBreakpointBase breakpoint)
{
return this.Equals ((object)breakpoint);
}
public BreakpointDef Debugging_Execution_BreakpointDef {
[System.Diagnostics.DebuggerHidden]
get { return m_breakpointDef; }
}
}
public class CLREventsBreakpoint : CorDebugBreakpointBase
{
public CLREventsBreakpoint (CorDebugProcess process) : base (process)
{
this.Kind = BreakpointDef.c_EXCEPTION_THROWN |
BreakpointDef.c_EXCEPTION_CAUGHT |
#if NO_THREAD_CREATED_EVENTS
BreakpointDef.c_EVAL_COMPLETE |
#else
BreakpointDef.c_THREAD_CREATED |
BreakpointDef.c_THREAD_TERMINATED |
#endif
BreakpointDef.c_ASSEMBLIES_LOADED |
BreakpointDef.c_BREAK;
this.Active = true;
}
public override void Hit (BreakpointDef breakpointDef)
{
#if NO_THREAD_CREATED_EVENTS
if ((breakpointDef.m_flags & BreakpointDef.c_EVAL_COMPLETE) != 0)
EvalComplete(breakpointDef);
#else
if ((breakpointDef.m_flags & BreakpointDef.c_THREAD_CREATED) != 0)
ThreadCreated (breakpointDef);
else if ((breakpointDef.m_flags & BreakpointDef.c_THREAD_TERMINATED) != 0)
ThreadTerminated (breakpointDef);
#endif
else if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_THROWN) != 0)
ExceptionThrown (breakpointDef);
else if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_CAUGHT) != 0)
ExceptionCaught (breakpointDef);
else if ((breakpointDef.m_flags & BreakpointDef.c_ASSEMBLIES_LOADED) != 0)
AssembliesLoaded (breakpointDef);
else if ((breakpointDef.m_flags & BreakpointDef.c_BREAK) != 0)
Break (breakpointDef);
else
Debug.Assert (false, "unknown CLREvent breakpoint");
}
#if NO_THREAD_CREATED_EVENTS
private void EvalComplete(BreakpointDef breakpointDef)
{
CorDebugThread thread = Process.GetThread(breakpointDef.m_pid);
//This currently gets called after BreakpointHit updates the list of threads.
//This should nop as long as func-eval happens on separate threads.
Debug.Assert(thread == null);
Process.RemoveThread(thread);
}
#else
private void ThreadTerminated (BreakpointDef breakpointDef)
{
CorDebugThread thread = Process.GetThread (breakpointDef.m_pid);
// Thread could be NULL if this function is called as result of Thread.Abort in
// managed application and application does not catch expeption.
// ThreadTerminated is called after thread exits in managed application.
if (thread != null) {
Process.RemoveThread (thread);
}
}
private void ThreadCreated (BreakpointDef breakpointDef)
{
CorDebugThread thread = this.Process.GetThread (breakpointDef.m_pid);
Debug.Assert (thread == null || thread.IsVirtualThread);
if (thread == null) {
thread = new CorDebugThread (this.Process, breakpointDef.m_pid, null);
this.Process.AddThread (thread);
}
}
#endif
public override bool ShouldBreak (Commands.Debugging_Execution_BreakpointDef breakpointDef)
{
if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_CAUGHT) != 0) {
//This if statement remains for compatibility with TinyCLR pre exception filtering support.
if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_UNWIND) == 0)
return false;
}
return true;
}
private void ExceptionThrown (BreakpointDef breakpointDef)
{
CorDebugThread thread = this.Process.GetThread (breakpointDef.m_pid);
thread.StoppedOnException ();
CorDebugFrame frame = thread.Chain.GetFrameFromDepthTinyCLR (breakpointDef.m_depth);
bool fIsEval = thread.IsVirtualThread;
bool fUnhandled = (breakpointDef.m_depthExceptionHandler == BreakpointDef.c_DEPTH_UNCAUGHT);
if (this.Process.Engine.Capabilities.ExceptionFilters) {
switch (breakpointDef.m_depthExceptionHandler) {
case BreakpointDef.c_DEPTH_EXCEPTION_FIRST_CHANCE:
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE));
break;
case BreakpointDef.c_DEPTH_EXCEPTION_USERS_CHANCE:
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE));
break;
case BreakpointDef.c_DEPTH_EXCEPTION_HANDLER_FOUND:
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND));
break;
}
} else {
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE));
uint depthMin = (fUnhandled) ? 0 : breakpointDef.m_depthExceptionHandler;
for (uint depth = breakpointDef.m_depth; depth >= depthMin; depth--) {
frame = thread.Chain.GetFrameFromDepthTinyCLR (depth);
if (frame != null && frame.Function.HasSymbols && frame.Function.PdbxMethod.IsJMC) {
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, frame, frame.IP_TinyCLR, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE));
break;
}
if (depth == 0) {
break;
}
}
if (!fUnhandled) {
frame = thread.Chain.GetFrameFromDepthTinyCLR (breakpointDef.m_depthExceptionHandler);
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND));
}
}
if (fUnhandled) {
//eval threads are virtual, and although the physical thread has an unhandled exception, the
//virtual thread does not. The eval thread will get killed, but the rest of the thread chain will
//survive, no need to confuse cpde by throwing an unhandled exception
if (fIsEval) {
CorDebugEval eval = thread.CurrentEval;
eval.StoppedOnUnhandledException ();
Debug.Assert (thread.IsVirtualThread);
CorDebugThread threadT = thread.GetRealCorDebugThread ();
CorDebugFrame frameT = threadT.Chain.ActiveFrame;
//fake event to let debugging of unhandled exception occur.
//Frame probably needs to be an InternalStubFrame???
frame = thread.Chain.GetFrameFromDepthCLR (thread.Chain.NumFrames - 1);
#if DEBUG
CorDebugInternalFrame internalFrame = frame as CorDebugInternalFrame;
Debug.Assert (internalFrame != null && internalFrame.FrameInternalType == CorDebugInternalFrameType.STUBFRAME_FUNC_EVAL);
#endif
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, frame, 0, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND));
} else {
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackException (thread, null, uint.MaxValue, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_UNHANDLED));
}
}
}
private void ExceptionCaught (BreakpointDef breakpointDef)
{
CorDebugThread thread = this.Process.GetThread (breakpointDef.m_pid);
CorDebugFrame frame = thread.Chain.GetFrameFromDepthTinyCLR (breakpointDef.m_depth);
Debug.Assert ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_UNWIND) != 0);
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackExceptionUnwind (thread, frame, CorDebugExceptionUnwindCallbackType.DEBUG_EXCEPTION_INTERCEPTED));
}
private void AssembliesLoaded (BreakpointDef breakpointDef)
{
this.Process.UpdateAssemblies ();
}
private void Break (BreakpointDef breakpointDef)
{
CorDebugThread thread = Process.GetThread (breakpointDef.m_pid);
Process.EnqueueEvent (new ManagedCallbacks.ManagedCallbackBreak (thread));
}
}
}
| |
// 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.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="ConversionActionServiceClient"/> instances.</summary>
public sealed partial class ConversionActionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ConversionActionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ConversionActionServiceSettings"/>.</returns>
public static ConversionActionServiceSettings GetDefault() => new ConversionActionServiceSettings();
/// <summary>
/// Constructs a new <see cref="ConversionActionServiceSettings"/> object with default settings.
/// </summary>
public ConversionActionServiceSettings()
{
}
private ConversionActionServiceSettings(ConversionActionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateConversionActionsSettings = existing.MutateConversionActionsSettings;
OnCopy(existing);
}
partial void OnCopy(ConversionActionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionActionServiceClient.MutateConversionActions</c> and
/// <c>ConversionActionServiceClient.MutateConversionActionsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateConversionActionsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ConversionActionServiceSettings"/> object.</returns>
public ConversionActionServiceSettings Clone() => new ConversionActionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ConversionActionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class ConversionActionServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionActionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ConversionActionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ConversionActionServiceClientBuilder()
{
UseJwtAccessWithScopes = ConversionActionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ConversionActionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionActionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ConversionActionServiceClient Build()
{
ConversionActionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ConversionActionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ConversionActionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ConversionActionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ConversionActionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ConversionActionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ConversionActionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ConversionActionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionActionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionActionServiceClient.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>ConversionActionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion actions.
/// </remarks>
public abstract partial class ConversionActionServiceClient
{
/// <summary>
/// The default endpoint for the ConversionActionService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default ConversionActionService scopes.</summary>
/// <remarks>
/// The default ConversionActionService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ConversionActionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionActionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ConversionActionServiceClient"/>.</returns>
public static stt::Task<ConversionActionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ConversionActionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ConversionActionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionActionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ConversionActionServiceClient"/>.</returns>
public static ConversionActionServiceClient Create() => new ConversionActionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ConversionActionServiceClient"/> 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="ConversionActionServiceSettings"/>.</param>
/// <returns>The created <see cref="ConversionActionServiceClient"/>.</returns>
internal static ConversionActionServiceClient Create(grpccore::CallInvoker callInvoker, ConversionActionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ConversionActionService.ConversionActionServiceClient grpcClient = new ConversionActionService.ConversionActionServiceClient(callInvoker);
return new ConversionActionServiceClientImpl(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 ConversionActionService client</summary>
public virtual ConversionActionService.ConversionActionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </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 MutateConversionActionsResponse MutateConversionActions(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, st::CancellationToken cancellationToken) =>
MutateConversionActionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion actions.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateConversionActionsResponse MutateConversionActions(string customerId, scg::IEnumerable<ConversionActionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionActions(new MutateConversionActionsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion actions.
/// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(string customerId, scg::IEnumerable<ConversionActionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionActionsAsync(new MutateConversionActionsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion actions.
/// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(string customerId, scg::IEnumerable<ConversionActionOperation> operations, st::CancellationToken cancellationToken) =>
MutateConversionActionsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ConversionActionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion actions.
/// </remarks>
public sealed partial class ConversionActionServiceClientImpl : ConversionActionServiceClient
{
private readonly gaxgrpc::ApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse> _callMutateConversionActions;
/// <summary>
/// Constructs a client wrapper for the ConversionActionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="ConversionActionServiceSettings"/> used within this client.
/// </param>
public ConversionActionServiceClientImpl(ConversionActionService.ConversionActionServiceClient grpcClient, ConversionActionServiceSettings settings)
{
GrpcClient = grpcClient;
ConversionActionServiceSettings effectiveSettings = settings ?? ConversionActionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateConversionActions = clientHelper.BuildApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse>(grpcClient.MutateConversionActionsAsync, grpcClient.MutateConversionActions, effectiveSettings.MutateConversionActionsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateConversionActions);
Modify_MutateConversionActionsApiCall(ref _callMutateConversionActions);
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_MutateConversionActionsApiCall(ref gaxgrpc::ApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse> call);
partial void OnConstruction(ConversionActionService.ConversionActionServiceClient grpcClient, ConversionActionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ConversionActionService client</summary>
public override ConversionActionService.ConversionActionServiceClient GrpcClient { get; }
partial void Modify_MutateConversionActionsRequest(ref MutateConversionActionsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </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 MutateConversionActionsResponse MutateConversionActions(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionActionsRequest(ref request, ref callSettings);
return _callMutateConversionActions.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionActionsRequest(ref request, ref callSettings);
return _callMutateConversionActions.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wintellect.PowerCollections;
internal class Program
{
private static StringBuilder output = new StringBuilder();
internal static void Main(string[] args)
{
while (ExecuteNextCommand())
{
Console.WriteLine(output);
}
}
private static bool ExecuteNextCommand()
{
string command = Console.ReadLine();
if (command[0] == 'A')
{
AddEvent(command);
return true;
}
if (command[0] == 'D')
{
DeleteEvents(command);
return true;
}
if (command[0] == 'L')
{
ListEvents(command);
return true;
}
if (command[0] == 'E')
{
return false;
}
return false;
}
private static void ListEvents(string command)
{
int pipeIndex = command.IndexOf('|');
DateTime date = GetDate(command, "ListEvents");
string countString = command.Substring(pipeIndex + 1);
int count = int.Parse(countString);
events.ListEvents(date, count);
}
private static void DeleteEvents(string command)
{
string title = command.Substring("DeleteEvents".Length + 1);
events.DeleteEvents(title);
}
private static void AddEvent(string command)
{
DateTime date;
string title;
string location;
GetParameters(command, "AddEvent", out date, out title, out location);
events.AddEvent(date, title, location);
}
private static void GetParameters(string commandForExecution, string commandType,
out DateTime dateAndTime, out string eventTitle, out string eventLocation)
{
dateAndTime = GetDate(commandForExecution, commandType);
int firstPipeIndex = commandForExecution.IndexOf('|');
int lastPipeIndex = commandForExecution.LastIndexOf('|');
if (firstPipeIndex == lastPipeIndex)
{
eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim();
eventLocation = string.Empty;
}
else
{
eventTitle = commandForExecution.Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1).Trim();
eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim();
}
}
private static DateTime GetDate(string command, string commandType)
{
DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20));
return date;
}
internal static class Messages
{
public static void EventAdded()
{
output.Append("Event added\n");
}
public static void EventDeleted(int x)
{
if (x == 0)
{
NoEventsFound();
}
else
{
output.AppendFormat("{0} events deleted\n", x);
}
}
public static void NoEventsFound()
{
output.Append("No events found\n");
}
public static void PrintEvent(Event eventToPrint)
{
if (eventToPrint != null)
{
output.Append(eventToPrint + "\n");
}
}
}
internal class EventHolder
{
private static EventHolder events = new EventHolder();
private MultiDictionary<string, Event> title = new MultiDictionary<string, Event>(true);
private OrderedBag<Event> date = new OrderedBag<Event>();
public void AddEvent(DateTime date, string title, string location)
{
Event newEvent = new Event(date, title, location);
title.Add(title.ToLower(), newEvent);
date.Add(newEvent);
Messages.EventAdded();
}
public void DeleteEvents(string titleToDelete)
{
string title = titleToDelete.ToLower();
int removed = 0;
foreach (var eventToRemove in title[title])
{
removed++;
this.date.Remove(eventToRemove);
}
title.Remove(title);
Messages.EventDeleted(removed);
}
public void ListEvents(DateTime date, int count)
{
OrderedBag<Event>.View eventsToShow = date.RangeFrom(new Event(date, string.Empty, string.Empty), true);
int showed = 0;
foreach (var eventToShow in eventsToShow)
{
if (showed == count)
{
break;
}
Messages.PrintEvent(eventToShow);
showed++;
}
if (showed == 0)
{
Messages.NoEventsFound();
}
}
}
internal class Event : IComparable
{
private DateTime date;
private string title;
private string location;
public Event(DateTime date, string title, string location)
{
this.date = date;
this.title = title;
this.location = location;
}
public int CompareTo(object obj)
{
Event other = obj as Event;
int date = this.date.CompareTo(other.date);
int title = this.title.CompareTo(other.title);
int location = this.location.CompareTo(other.location);
if (date == 0)
{
if (title == 0)
{
return location;
}
else
{
return title;
}
}
else
{
return date;
}
}
public override string ToString()
{
StringBuilder toString = new StringBuilder();
toString.Append(this.date.ToString("yyyy-MM-ddTHH:mm:ss"));
toString.Append(" | " + this.title);
if (this.location != null && this.location != string.Empty)
{
toString.Append(" | " + this.location);
}
return toString.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System.Net.Http
{
internal static class HttpRuleParser
{
private static readonly bool[] s_tokenChars = CreateTokenChars();
private const int MaxNestedCount = 5;
internal const char CR = (char)13;
internal const char LF = (char)10;
internal const int MaxInt64Digits = 19;
internal const int MaxInt32Digits = 10;
// iso-8859-1, Western European (ISO)
internal static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding(28591);
private static bool[] CreateTokenChars()
{
// token = 1*<any CHAR except CTLs or separators>
// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
var tokenChars = new bool[128]; // All elements default to "false".
for (int i = 33; i < 127; i++) // Skip Space (32) & DEL (127).
{
tokenChars[i] = true;
}
// Remove separators: these are not valid token characters.
tokenChars[(byte)'('] = false;
tokenChars[(byte)')'] = false;
tokenChars[(byte)'<'] = false;
tokenChars[(byte)'>'] = false;
tokenChars[(byte)'@'] = false;
tokenChars[(byte)','] = false;
tokenChars[(byte)';'] = false;
tokenChars[(byte)':'] = false;
tokenChars[(byte)'\\'] = false;
tokenChars[(byte)'"'] = false;
tokenChars[(byte)'/'] = false;
tokenChars[(byte)'['] = false;
tokenChars[(byte)']'] = false;
tokenChars[(byte)'?'] = false;
tokenChars[(byte)'='] = false;
tokenChars[(byte)'{'] = false;
tokenChars[(byte)'}'] = false;
return tokenChars;
}
internal static bool IsTokenChar(char character)
{
// Must be between 'space' (32) and 'DEL' (127).
if (character > 127)
{
return false;
}
return s_tokenChars[character];
}
internal static int GetTokenLength(string input, int startIndex)
{
Debug.Assert(input != null);
if (startIndex >= input.Length)
{
return 0;
}
int current = startIndex;
while (current < input.Length)
{
if (!IsTokenChar(input[current]))
{
return current - startIndex;
}
current++;
}
return input.Length - startIndex;
}
internal static bool IsToken(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (!IsTokenChar(input[i]))
{
return false;
}
}
return true;
}
internal static bool IsToken(ReadOnlySpan<byte> input)
{
for (int i = 0; i < input.Length; i++)
{
if (!IsTokenChar((char)input[i]))
{
return false;
}
}
return true;
}
internal static string GetTokenString(ReadOnlySpan<byte> input)
{
Debug.Assert(IsToken(input));
return Encoding.ASCII.GetString(input);
}
internal static int GetWhitespaceLength(string input, int startIndex)
{
Debug.Assert(input != null);
if (startIndex >= input.Length)
{
return 0;
}
int current = startIndex;
char c;
while (current < input.Length)
{
c = input[current];
if ((c == ' ') || (c == '\t'))
{
current++;
continue;
}
if (c == '\r')
{
// If we have a #13 char, it must be followed by #10 and then at least one SP or HT.
if ((current + 2 < input.Length) && (input[current + 1] == '\n'))
{
char spaceOrTab = input[current + 2];
if ((spaceOrTab == ' ') || (spaceOrTab == '\t'))
{
current += 3;
continue;
}
}
}
return current - startIndex;
}
// All characters between startIndex and the end of the string are LWS characters.
return input.Length - startIndex;
}
internal static bool ContainsInvalidNewLine(string value)
{
return ContainsInvalidNewLine(value, 0);
}
internal static bool ContainsInvalidNewLine(string value, int startIndex)
{
// Search for newlines followed by non-whitespace: This is not allowed in any header (be it a known or
// custom header). E.g. "value\r\nbadformat: header" is invalid. However "value\r\n goodformat: header"
// is valid: newlines followed by whitespace are allowed in header values.
int current = startIndex;
while (current < value.Length)
{
if (value[current] == '\r')
{
int char10Index = current + 1;
if ((char10Index < value.Length) && (value[char10Index] == '\n'))
{
current = char10Index + 1;
if (current == value.Length)
{
return true; // We have a string terminating with \r\n. This is invalid.
}
char c = value[current];
if ((c != ' ') && (c != '\t'))
{
return true;
}
}
}
current++;
}
return false;
}
internal static int GetNumberLength(string input, int startIndex, bool allowDecimal)
{
Debug.Assert(input != null);
Debug.Assert((startIndex >= 0) && (startIndex < input.Length));
int current = startIndex;
char c;
// If decimal values are not allowed, we pretend to have read the '.' character already. I.e. if a dot is
// found in the string, parsing will be aborted.
bool haveDot = !allowDecimal;
// The RFC doesn't allow decimal values starting with dot. I.e. value ".123" is invalid. It must be in the
// form "0.123". Also, there are no negative values defined in the RFC. So we'll just parse non-negative
// values.
// The RFC only allows decimal dots not ',' characters as decimal separators. Therefore value "1,23" is
// considered invalid and must be represented as "1.23".
if (input[current] == '.')
{
return 0;
}
while (current < input.Length)
{
c = input[current];
if ((c >= '0') && (c <= '9'))
{
current++;
}
else if (!haveDot && (c == '.'))
{
// Note that value "1." is valid.
haveDot = true;
current++;
}
else
{
break;
}
}
return current - startIndex;
}
internal static int GetHostLength(string input, int startIndex, bool allowToken, out string host)
{
Debug.Assert(input != null);
Debug.Assert(startIndex >= 0);
host = null;
if (startIndex >= input.Length)
{
return 0;
}
// A 'host' is either a token (if 'allowToken' == true) or a valid host name as defined by the URI RFC.
// So we first iterate through the string and search for path delimiters and whitespace. When found, stop
// and try to use the substring as token or URI host name. If it works, we have a host name, otherwise not.
int current = startIndex;
bool isToken = true;
while (current < input.Length)
{
char c = input[current];
if (c == '/')
{
return 0; // Host header must not contain paths.
}
if ((c == ' ') || (c == '\t') || (c == '\r') || (c == ','))
{
break; // We hit a delimiter (',' or whitespace). Stop here.
}
isToken = isToken && IsTokenChar(c);
current++;
}
int length = current - startIndex;
if (length == 0)
{
return 0;
}
string result = input.Substring(startIndex, length);
if ((!allowToken || !isToken) && !IsValidHostName(result))
{
return 0;
}
host = result;
return length;
}
internal static HttpParseResult GetCommentLength(string input, int startIndex, out int length)
{
return GetExpressionLength(input, startIndex, '(', ')', true, 1, out length);
}
internal static HttpParseResult GetQuotedStringLength(string input, int startIndex, out int length)
{
return GetExpressionLength(input, startIndex, '"', '"', false, 1, out length);
}
// quoted-pair = "\" CHAR
// CHAR = <any US-ASCII character (octets 0 - 127)>
internal static HttpParseResult GetQuotedPairLength(string input, int startIndex, out int length)
{
Debug.Assert(input != null);
Debug.Assert((startIndex >= 0) && (startIndex < input.Length));
length = 0;
if (input[startIndex] != '\\')
{
return HttpParseResult.NotParsed;
}
// Quoted-char has 2 characters. Check whether there are 2 chars left ('\' + char)
// If so, check whether the character is in the range 0-127. If not, it's an invalid value.
if ((startIndex + 2 > input.Length) || (input[startIndex + 1] > 127))
{
return HttpParseResult.InvalidFormat;
}
// It doesn't matter what the char next to '\' is so we can skip along.
length = 2;
return HttpParseResult.Parsed;
}
// TEXT = <any OCTET except CTLs, but including LWS>
// LWS = [CRLF] 1*( SP | HT )
// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
//
// Since we don't really care about the content of a quoted string or comment, we're more tolerant and
// allow these characters. We only want to find the delimiters ('"' for quoted string and '(', ')' for comment).
//
// 'nestedCount': Comments can be nested. We allow a depth of up to 5 nested comments, i.e. something like
// "(((((comment)))))". If we wouldn't define a limit an attacker could send a comment with hundreds of nested
// comments, resulting in a stack overflow exception. In addition having more than 1 nested comment (if any)
// is unusual.
private static HttpParseResult GetExpressionLength(string input, int startIndex, char openChar,
char closeChar, bool supportsNesting, int nestedCount, out int length)
{
Debug.Assert(input != null);
Debug.Assert((startIndex >= 0) && (startIndex < input.Length));
length = 0;
if (input[startIndex] != openChar)
{
return HttpParseResult.NotParsed;
}
int current = startIndex + 1; // Start parsing with the character next to the first open-char.
while (current < input.Length)
{
// Only check whether we have a quoted char, if we have at least 3 characters left to read (i.e.
// quoted char + closing char). Otherwise the closing char may be considered part of the quoted char.
int quotedPairLength = 0;
if ((current + 2 < input.Length) &&
(GetQuotedPairLength(input, current, out quotedPairLength) == HttpParseResult.Parsed))
{
// We ignore invalid quoted-pairs. Invalid quoted-pairs may mean that it looked like a quoted pair,
// but we actually have a quoted-string: e.g. "\\u00FC" ('\' followed by a char >127 - quoted-pair only
// allows ASCII chars after '\'; qdtext allows both '\' and >127 chars).
current = current + quotedPairLength;
continue;
}
// If we support nested expressions and we find an open-char, then parse the nested expressions.
if (supportsNesting && (input[current] == openChar))
{
// Check if we exceeded the number of nested calls.
if (nestedCount > MaxNestedCount)
{
return HttpParseResult.InvalidFormat;
}
int nestedLength = 0;
HttpParseResult nestedResult = GetExpressionLength(input, current, openChar, closeChar,
supportsNesting, nestedCount + 1, out nestedLength);
switch (nestedResult)
{
case HttpParseResult.Parsed:
current += nestedLength; // Add the length of the nested expression and continue.
break;
case HttpParseResult.NotParsed:
Debug.Fail("'NotParsed' is unexpected: We started nested expression " +
"parsing, because we found the open-char. So either it's a valid nested " +
"expression or it has invalid format.");
break;
case HttpParseResult.InvalidFormat:
// If the nested expression is invalid, we can't continue, so we fail with invalid format.
return HttpParseResult.InvalidFormat;
default:
Debug.Fail("Unknown enum result: " + nestedResult);
break;
}
// after nested call we continue with parsing
continue;
}
if (input[current] == closeChar)
{
length = current - startIndex + 1;
return HttpParseResult.Parsed;
}
current++;
}
// We didn't find the final quote, therefore we have an invalid expression string.
return HttpParseResult.InvalidFormat;
}
private static bool IsValidHostName(string host)
{
// Also add user info (u@) to make sure 'host' doesn't include user info.
Uri hostUri;
return Uri.TryCreate("http://u@" + host + "/", UriKind.Absolute, out hostUri);
}
}
}
| |
using System.Drawing;
using System.Windows.Forms;
namespace Andi.Utils.Renderer
{
internal class VisualStudio2012 : ProfessionalColorTable
{
public override Color ButtonSelectedHighlight
{
get { return ButtonSelectedGradientMiddle; }
}
public override Color ButtonSelectedHighlightBorder
{
get { return ButtonSelectedBorder; }
}
public override Color ButtonPressedHighlight
{
get { return ButtonPressedGradientMiddle; }
}
public override Color ButtonPressedHighlightBorder
{
get { return ButtonPressedBorder; }
}
public override Color ButtonCheckedHighlight
{
get { return ButtonCheckedGradientMiddle; }
}
public override Color ButtonCheckedHighlightBorder
{
get { return ButtonSelectedBorder; }
}
public override Color ButtonPressedBorder
{
get { return ButtonSelectedBorder; }
}
public override Color ButtonSelectedBorder
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color ButtonCheckedGradientBegin
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color ButtonCheckedGradientMiddle
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color ButtonCheckedGradientEnd
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color ButtonSelectedGradientBegin
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color ButtonSelectedGradientMiddle
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color ButtonSelectedGradientEnd
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color ButtonPressedGradientBegin
{
get { return Color.FromArgb(255, 32, 172, 232); }
}
public override Color ButtonPressedGradientMiddle
{
get { return Color.FromArgb(255, 32, 172, 232); }
}
public override Color ButtonPressedGradientEnd
{
get { return Color.FromArgb(255, 32, 172, 232); }
}
public override Color CheckBackground
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color CheckSelectedBackground
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color CheckPressedBackground
{
get { return Color.FromArgb(255, 32, 172, 232); }
}
public override Color GripDark
{
get { return Color.FromArgb(255, 221, 226, 236); }
}
public override Color GripLight
{
get { return Color.FromArgb(255, 204, 204, 219); }
}
public override Color ImageMarginGradientBegin
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color ImageMarginGradientMiddle
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color ImageMarginGradientEnd
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color ImageMarginRevealedGradientBegin
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color ImageMarginRevealedGradientMiddle
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color ImageMarginRevealedGradientEnd
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color MenuStripGradientBegin
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color MenuStripGradientEnd
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color MenuItemSelected
{
get { return Color.FromArgb(255, 248, 249, 250); }
}
public override Color MenuItemBorder
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color MenuBorder
{
get { return Color.FromArgb(255, 204, 206, 219); }
}
public override Color MenuItemSelectedGradientBegin
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color MenuItemSelectedGradientEnd
{
get { return Color.FromArgb(255, 254, 254, 254); }
}
public override Color MenuItemPressedGradientBegin
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color MenuItemPressedGradientMiddle
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color MenuItemPressedGradientEnd
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color RaftingContainerGradientBegin
{
get { return Color.FromArgb(255, 186, 192, 201); }
}
public override Color RaftingContainerGradientEnd
{
get { return Color.FromArgb(255, 186, 192, 201); }
}
public override Color SeparatorDark
{
get { return Color.FromArgb(255, 204, 206, 219); }
}
public override Color SeparatorLight
{
get { return Color.FromArgb(255, 246, 246, 246); }
}
public override Color StatusStripGradientBegin
{
get { return Color.FromArgb(255, 0, 122, 204); }
}
public override Color StatusStripGradientEnd
{
get { return Color.FromArgb(255, 0, 122, 204); }
}
public override Color ToolStripBorder
{
get { return Color.FromArgb(0, 0, 0, 0); }
}
public override Color ToolStripDropDownBackground
{
get { return Color.FromArgb(255, 231, 232, 236); }
}
public override Color ToolStripGradientBegin
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color ToolStripGradientMiddle
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color ToolStripGradientEnd
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color ToolStripContentPanelGradientBegin
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color ToolStripContentPanelGradientEnd
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color ToolStripPanelGradientBegin
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color ToolStripPanelGradientEnd
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color OverflowButtonGradientBegin
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color OverflowButtonGradientMiddle
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
public override Color OverflowButtonGradientEnd
{
get { return Color.FromArgb(255, 239, 239, 242); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace GitHub.Unity
{
static class ProcessTaskExtensions
{
public static T Configure<T>(this T task, IProcessManager processManager, bool withInput)
where T : IProcess
{
return processManager.Configure(task, withInput: withInput);
}
public static T Configure<T>(this T task, IProcessManager processManager, string executable = null,
string arguments = null,
NPath workingDirectory = null,
bool withInput = false)
where T : IProcess
{
return processManager.Configure(task, executable?.ToNPath(), arguments, workingDirectory, withInput);
}
}
public interface IProcess
{
void Configure(Process existingProcess);
void Configure(ProcessStartInfo psi);
event Action<string> OnErrorData;
StreamWriter StandardInput { get; }
int ProcessId { get; }
string ProcessName { get; }
string ProcessArguments { get; }
Process Process { get; set; }
event Action<IProcess> OnStartProcess;
event Action<IProcess> OnEndProcess;
}
interface IProcessTask<T> : ITask<T>, IProcess
{
void Configure(ProcessStartInfo psi, IOutputProcessor<T> processor);
}
interface IProcessTask<TData, T> : ITask<TData, T>, IProcess
{
void Configure(ProcessStartInfo psi, IOutputProcessor<TData, T> processor);
}
class ProcessWrapper
{
private readonly IOutputProcessor outputProcessor;
private readonly Action onStart;
private readonly Action onEnd;
private readonly Action<Exception, string> onError;
private readonly CancellationToken token;
private readonly List<string> errors = new List<string>();
public Process Process { get; }
public StreamWriter Input { get; private set; }
private ILogging logger;
protected ILogging Logger { get { return logger = logger ?? Logging.GetLogger(GetType()); } }
public ProcessWrapper(Process process, IOutputProcessor outputProcessor,
Action onStart, Action onEnd, Action<Exception, string> onError,
CancellationToken token)
{
this.outputProcessor = outputProcessor;
this.onStart = onStart;
this.onEnd = onEnd;
this.onError = onError;
this.token = token;
this.Process = process;
}
public void Run()
{
if (Process.StartInfo.RedirectStandardError)
{
Process.ErrorDataReceived += (s, e) =>
{
//if (e.Data != null)
//{
// Logger.Trace("ErrorData \"" + (e.Data == null ? "'null'" : e.Data) + "\"");
//}
string encodedData = null;
if (e.Data != null)
{
encodedData = Encoding.UTF8.GetString(Encoding.Default.GetBytes(e.Data));
errors.Add(encodedData);
}
};
}
try
{
Process.Start();
}
catch (Win32Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Error code " + ex.NativeErrorCode);
if (ex.NativeErrorCode == 2)
{
sb.AppendLine("The system cannot find the file specified.");
}
foreach (string env in Process.StartInfo.EnvironmentVariables.Keys)
{
sb.AppendFormat("{0}:{1}", env, Process.StartInfo.EnvironmentVariables[env]);
sb.AppendLine();
}
onError?.Invoke(ex, String.Format("{0} {1}", ex.Message, sb.ToString()));
onEnd?.Invoke();
return;
}
if (Process.StartInfo.RedirectStandardInput)
Input = new StreamWriter(Process.StandardInput.BaseStream, new UTF8Encoding(false));
if (Process.StartInfo.RedirectStandardError)
Process.BeginErrorReadLine();
onStart?.Invoke();
if (Process.StartInfo.RedirectStandardOutput)
{
var outputStream = Process.StandardOutput;
var line = outputStream.ReadLine();
while (line != null)
{
outputProcessor.LineReceived(line);
if (token.IsCancellationRequested)
{
if (!Process.HasExited)
Process.Kill();
Process.Close();
onEnd?.Invoke();
token.ThrowIfCancellationRequested();
}
line = outputStream.ReadLine();
}
outputProcessor.LineReceived(null);
}
if (Process.StartInfo.CreateNoWindow)
{
while (!WaitForExit(500))
{
if (token.IsCancellationRequested)
Process.Kill();
Process.Close();
onEnd?.Invoke();
token.ThrowIfCancellationRequested();
}
if (Process.ExitCode != 0 && errors.Count > 0)
{
onError?.Invoke(null, string.Join(Environment.NewLine, errors.ToArray()));
}
}
onEnd?.Invoke();
}
private bool WaitForExit(int milliseconds)
{
//Logger.Debug("WaitForExit - time: {0}ms", milliseconds);
// Workaround for a bug in which some data may still be processed AFTER this method returns true, thus losing the data.
// http://connect.microsoft.com/VisualStudio/feedback/details/272125/waitforexit-and-waitforexit-int32-provide-different-and-undocumented-implementations
bool waitSucceeded = Process.WaitForExit(milliseconds);
if (waitSucceeded)
{
Process.WaitForExit();
}
return waitSucceeded;
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T">The type of the results. If it's a List<> or similar, then specify the full List<> type here and the inner type of the List in <typeparam name="TData"/>
/// <typeparam name="TData">If <typeparam name="TData"/> is a list or similar, then specify its inner type here</typeparam>
class ProcessTask<T> : TaskBase<T>, IProcessTask<T>
{
private IOutputProcessor<T> outputProcessor;
private ProcessWrapper wrapper;
public event Action<string> OnErrorData;
public event Action<IProcess> OnStartProcess;
public event Action<IProcess> OnEndProcess;
private Exception thrownException = null;
public ProcessTask(CancellationToken token, IOutputProcessor<T> outputProcessor = null)
: base(token)
{
this.outputProcessor = outputProcessor;
}
/// <summary>
/// Process that calls git with the passed arguments
/// </summary>
/// <param name="token"></param>
/// <param name="arguments"></param>
/// <param name="outputProcessor"></param>
public ProcessTask(CancellationToken token, string arguments, IOutputProcessor<T> outputProcessor = null)
: base(token)
{
Guard.ArgumentNotNull(token, nameof(token));
this.outputProcessor = outputProcessor;
ProcessArguments = arguments;
}
public virtual void Configure(ProcessStartInfo psi)
{
Guard.ArgumentNotNull(psi, "psi");
ConfigureOutputProcessor();
Guard.NotNull(this, outputProcessor, nameof(outputProcessor));
Process = new Process { StartInfo = psi, EnableRaisingEvents = true };
ProcessName = psi.FileName;
}
public virtual void Configure(ProcessStartInfo psi, IOutputProcessor<T> processor)
{
outputProcessor = processor ?? outputProcessor;
ConfigureOutputProcessor();
Guard.NotNull(this, outputProcessor, nameof(outputProcessor));
Process = new Process { StartInfo = psi, EnableRaisingEvents = true };
ProcessName = psi.FileName;
}
public void Configure(Process existingProcess)
{
Guard.ArgumentNotNull(existingProcess, "existingProcess");
ConfigureOutputProcessor();
Guard.NotNull(this, outputProcessor, nameof(outputProcessor));
Process = existingProcess;
ProcessName = existingProcess.StartInfo.FileName;
}
protected override void RaiseOnStart()
{
base.RaiseOnStart();
OnStartProcess?.Invoke(this);
}
protected override void RaiseOnEnd()
{
base.RaiseOnEnd();
OnEndProcess?.Invoke(this);
}
protected virtual void ConfigureOutputProcessor()
{
}
protected override void Run(bool success)
{
throw new NotImplementedException();
}
protected override T RunWithReturn(bool success)
{
var result = base.RunWithReturn(success);
wrapper = new ProcessWrapper(Process, outputProcessor,
RaiseOnStart,
() =>
{
if (outputProcessor != null)
result = outputProcessor.Result;
if (result == null && !Process.StartInfo.CreateNoWindow && typeof(T) == typeof(string))
result = (T)(object)"Process running";
RaiseOnEnd(result);
if (Errors != null)
{
OnErrorData?.Invoke(Errors);
thrownException = thrownException ?? new ProcessException(this);
if (!RaiseFaultHandlers(thrownException))
throw thrownException;
}
},
(ex, error) =>
{
thrownException = ex;
Errors = error;
},
Token);
wrapper.Run();
return result;
}
public override string ToString()
{
return $"{Task?.Id ?? -1} {Name} {GetType()} {ProcessName} {ProcessArguments}";
}
public Process Process { get; set; }
public int ProcessId { get { return Process.Id; } }
public override bool Successful { get { return Task.Status == TaskStatus.RanToCompletion && Process.ExitCode == 0; } }
public StreamWriter StandardInput { get { return wrapper?.Input; } }
public virtual string ProcessName { get; protected set; }
public virtual string ProcessArguments { get; }
}
class ProcessTaskWithListOutput<T> : DataTaskBase<T, List<T>>, IProcessTask<T, List<T>>
{
private IOutputProcessor<T, List<T>> outputProcessor;
private Exception thrownException = null;
private ProcessWrapper wrapper;
public event Action<string> OnErrorData;
public event Action<IProcess> OnStartProcess;
public event Action<IProcess> OnEndProcess;
public ProcessTaskWithListOutput(CancellationToken token)
: base(token)
{}
public ProcessTaskWithListOutput(CancellationToken token, IOutputProcessor<T, List<T>> outputProcessor = null)
: base(token)
{
this.outputProcessor = outputProcessor;
}
public virtual void Configure(ProcessStartInfo psi)
{
Guard.ArgumentNotNull(psi, "psi");
ConfigureOutputProcessor();
Guard.NotNull(this, outputProcessor, nameof(outputProcessor));
Process = new Process { StartInfo = psi, EnableRaisingEvents = true };
ProcessName = psi.FileName;
}
public void Configure(Process existingProcess)
{
Guard.ArgumentNotNull(existingProcess, "existingProcess");
ConfigureOutputProcessor();
Guard.NotNull(this, outputProcessor, nameof(outputProcessor));
Process = existingProcess;
ProcessName = existingProcess.StartInfo.FileName;
}
public virtual void Configure(ProcessStartInfo psi, IOutputProcessor<T, List<T>> processor)
{
Guard.ArgumentNotNull(psi, "psi");
Guard.ArgumentNotNull(processor, "processor");
outputProcessor = processor ?? outputProcessor;
ConfigureOutputProcessor();
Process = new Process { StartInfo = psi, EnableRaisingEvents = true };
ProcessName = psi.FileName;
}
protected override void RaiseOnStart()
{
base.RaiseOnStart();
OnStartProcess?.Invoke(this);
}
protected override void RaiseOnEnd()
{
base.RaiseOnEnd();
OnEndProcess?.Invoke(this);
}
protected virtual void ConfigureOutputProcessor()
{
if (outputProcessor == null && (typeof(T) != typeof(string)))
{
throw new InvalidOperationException("ProcessTask without an output processor must be defined as IProcessTask<string>");
}
outputProcessor.OnEntry += x => RaiseOnData(x);
}
protected override List<T> RunWithReturn(bool success)
{
var result = base.RunWithReturn(success);
wrapper = new ProcessWrapper(Process, outputProcessor,
RaiseOnStart,
() =>
{
if (outputProcessor != null)
result = outputProcessor.Result;
if (result == null)
result = new List<T>();
RaiseOnEnd(result);
if (Errors != null)
{
OnErrorData?.Invoke(Errors);
thrownException = thrownException ?? new ProcessException(this);
if (!RaiseFaultHandlers(thrownException))
throw thrownException;
}
},
(ex, error) =>
{
thrownException = ex;
Errors = error;
},
Token);
wrapper.Run();
return result;
}
public override string ToString()
{
return $"{Task?.Id ?? -1} {Name} {GetType()} {ProcessName} {ProcessArguments}";
}
public Process Process { get; set; }
public int ProcessId { get { return Process.Id; } }
public override bool Successful { get { return Task.Status == TaskStatus.RanToCompletion && Process.ExitCode == 0; } }
public StreamWriter StandardInput { get { return wrapper?.Input; } }
public virtual string ProcessName { get; protected set; }
public virtual string ProcessArguments { get; }
}
class FirstNonNullLineProcessTask : ProcessTask<string>
{
private readonly NPath fullPathToExecutable;
private readonly string arguments;
public FirstNonNullLineProcessTask(CancellationToken token, NPath fullPathToExecutable, string arguments)
: base(token, new FirstNonNullLineOutputProcessor())
{
this.fullPathToExecutable = fullPathToExecutable;
this.arguments = arguments;
}
public override string ProcessName => fullPathToExecutable.FileName;
public override string ProcessArguments => arguments;
}
class SimpleProcessTask : ProcessTask<string>
{
private readonly NPath fullPathToExecutable;
private readonly string arguments;
public SimpleProcessTask(CancellationToken token, NPath fullPathToExecutable, string arguments)
: base(token, new SimpleOutputProcessor())
{
this.fullPathToExecutable = fullPathToExecutable;
this.arguments = arguments;
}
public SimpleProcessTask(CancellationToken token, string arguments)
: base(token, new SimpleOutputProcessor())
{
this.arguments = arguments;
}
public override string ProcessName => fullPathToExecutable?.FileName;
public override string ProcessArguments => arguments;
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using Scriban.Helpers;
using Scriban.Parsing;
using Scriban.Runtime;
using Scriban.Syntax;
namespace Scriban
{
/// <summary>
/// Rewriter context used to write an AST/<see cref="ScriptNode"/> tree back to a text.
/// </summary>
public partial class ScriptPrinter
{
private readonly IScriptOutput _output;
private readonly bool _isScriptOnly;
private bool _isInCode;
private bool _expectSpace;
private bool _expectEndOfStatement;
// Gets a boolean indicating whether the last character written has a whitespace.
private bool _previousHasSpace;
private bool _hasEndOfStatement;
private bool _hasComma;
private FastStack<bool> _isWhileLoop;
public ScriptPrinter(IScriptOutput output, ScriptPrinterOptions options = default(ScriptPrinterOptions))
{
_isWhileLoop = new FastStack<bool>(4);
Options = options;
if (options.Mode != ScriptMode.Default && options.Mode != ScriptMode.ScriptOnly)
{
throw new ArgumentException($"The rendering mode `{options.Mode}` is not supported. Only `ScriptMode.Default` or `ScriptMode.ScriptOnly` are currently supported");
}
_isScriptOnly = options.Mode == ScriptMode.ScriptOnly;
_isInCode = _isScriptOnly || (options.Mode == ScriptMode.FrontMatterOnly || options.Mode == ScriptMode.FrontMatterAndContent);
_output = output;
_hasEndOfStatement = true; // We start as if we were on a new line
}
/// <summary>
/// Gets the options for rendering
/// </summary>
public readonly ScriptPrinterOptions Options;
public bool PreviousHasSpace => _previousHasSpace;
public bool IsInWhileLoop => _isWhileLoop.Count > 0 && _isWhileLoop.Peek();
public ScriptPrinter Write(ScriptNode node)
{
if (node != null)
{
bool pushedWhileLoop = false;
if (node is ScriptLoopStatementBase)
{
_isWhileLoop.Push(node is ScriptWhileStatement);
pushedWhileLoop = true;
}
try
{
WriteBegin(node);
// Reset comma before node
if (node is IScriptTerminal) _hasComma = false;
node.PrintTo(this);
WriteEnd(node);
}
finally
{
if (pushedWhileLoop)
{
_isWhileLoop.Pop();
}
}
}
return this;
}
public ScriptPrinter Write(string text)
{
_previousHasSpace = text.Length > 0 && char.IsWhiteSpace(text[text.Length - 1]);
_output.Write(text);
return this;
}
public ScriptPrinter Write(ScriptStringSlice slice)
{
_previousHasSpace = slice.Length > 0 && char.IsWhiteSpace(slice[slice.Length - 1]);
_output.Write(slice);
return this;
}
public ScriptPrinter ExpectEos()
{
if (!_hasEndOfStatement)
{
_expectEndOfStatement = true;
}
return this;
}
public ScriptPrinter ExpectSpace()
{
_expectSpace = true;
return this;
}
public ScriptPrinter WriteListWithCommas<T>(IList<T> list) where T : ScriptNode
{
if (list == null)
{
return this;
}
for(int i = 0; i < list.Count; i++)
{
var value = list[i];
// If the value didn't have any Comma Trivia, we can emit it
if (i > 0 && !_hasComma)
{
Write(",");
_hasComma = true;
}
Write(value);
}
return this;
}
public ScriptPrinter WriteEnterCode(int escape = 0)
{
Write("{");
for (int i = 0; i < escape; i++)
{
Write("%");
}
Write("{");
_expectEndOfStatement = false;
_expectSpace = false;
_hasEndOfStatement = true;
_isInCode = true;
return this;
}
public ScriptPrinter WriteExitCode(int escape = 0)
{
Write("}");
for (int i = 0; i < escape; i++)
{
Write("%");
}
Write("}");
_expectEndOfStatement = false;
_expectSpace = false;
_hasEndOfStatement = false;
_isInCode = false;
return this;
}
private void WriteBegin(ScriptNode node)
{
WriteTrivias(node, true);
HandleEos(node);
if (_hasEndOfStatement)
{
_hasEndOfStatement = false;
_expectEndOfStatement = false;
}
// Add a space if this is required and no trivia are providing it
if (node.CanHaveLeadingTrivia())
{
if (_expectSpace && !_previousHasSpace)
{
Write(" ");
}
_expectSpace = false;
}
}
private void WriteEnd(ScriptNode node)
{
WriteTrivias(node, false);
if (node is ScriptPage)
{
if (_isInCode && !_isScriptOnly)
{
WriteExitCode();
}
}
}
private static bool IsFrontMarker(ScriptNode node) => node is ScriptToken token && token.TokenType == TokenType.FrontMatterMarker;
private void HandleEos(ScriptNode node)
{
var isFrontMarker = IsFrontMarker(node);
if ((node is ScriptStatement || isFrontMarker) && !IsBlockOrPage(node) && _isInCode && _expectEndOfStatement)
{
if (!_hasEndOfStatement)
{
if (!(node is ScriptEscapeStatement))
{
Write(isFrontMarker ? "\n" : "; ");
}
}
_expectEndOfStatement = false; // We expect always a end of statement before and after
_hasEndOfStatement = false;
_hasComma = false;
}
}
private static bool IsBlockOrPage(ScriptNode node)
{
return node is ScriptBlockStatement || node is ScriptPage;
}
private void WriteTrivias(ScriptNode node, bool before)
{
if (!(node is IScriptTerminal terminal)) return;
var trivias = terminal.Trivias;
if (trivias != null)
{
foreach (var trivia in (before ? trivias.Before : trivias.After))
{
trivia.Write(this);
if (trivia.Type == ScriptTriviaType.NewLine || trivia.Type == ScriptTriviaType.SemiColon)
{
_hasEndOfStatement = true;
if (trivia.Type == ScriptTriviaType.SemiColon)
{
_hasComma = false;
}
// If expect a space and we have a NewLine or SemiColon, we can safely discard the required space
if (_expectSpace)
{
_expectSpace = false;
}
}
if (trivia.Type == ScriptTriviaType.Comma)
{
_hasComma = true;
}
}
}
}
}
}
| |
#region License
// Copyright 2010-2011 J.W.Marsden
//
// 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;
using System.Collections.Generic;
namespace Kinetic.IO
{
//Keyboard Events
public class ResizeArgs : EventArgs
{
protected Display display;
protected int width;
protected int height;
public ResizeArgs (Display display, int width, int height)
{
this.display = display;
this.width = width;
this.height = height;
}
public Display Display {
get { return display; }
set { display = value; }
}
public int Width {
get { return width; }
set { width = value; }
}
public int Height {
get { return height; }
set { height = value; }
}
public override string ToString ()
{
return string.Format ("[ResizeArgs: Display={0}, Width={1}, Height={2}]", Display, Width, Height);
}
}
/// <summary>
/// Keboard Event Arguments.
/// </summary>
public class KeyEventArgs : EventArgs
{
protected Key key;
public KeyEventArgs (Key key)
{
this.key = key;
}
public Key Key {
get { return Key; }
}
}
//public delegate void KeyDownEventHandler (object sender, KeyEventArgs e);
//public delegate void KeyUpEventHandler (object sender, KeyEventArgs e);
//public delegate void KeyPressedEventHandler (object sender, KeyEventArgs e);
/*
* Mouse Events
*/
/// <summary>
/// Mouse Move Normal Event Arguments
/// </summary>
public class MouseMoveEventArgs : EventArgs
{
protected int x;
protected int y;
protected int xDelta;
protected int yDelta;
public MouseMoveEventArgs (int x, int y, int xDelta, int yDelta)
{
this.x = x;
this.y = y;
this.xDelta = xDelta;
this.yDelta = yDelta;
}
public int X {
get { return x; }
}
public int Y {
get { return y; }
}
public int XDelta {
get { return xDelta; }
}
public int YDelta {
get { return yDelta; }
}
public override string ToString ()
{
return string.Format ("[MouseMoveEventArgs: X={0}, Y={1}, XDelta={2}, YDelta={3}]", X, Y, XDelta, YDelta);
}
}
/// <summary>
/// Mouse Move Delta Event Arguments (used when the display is held).
/// </summary>
public class MouseMoveDeltaEventArgs : EventArgs
{
protected int xDelta;
protected int yDelta;
public MouseMoveDeltaEventArgs (int xDelta, int yDelta)
{
this.xDelta = xDelta;
this.yDelta = yDelta;
}
public int XDelta {
get { return xDelta; }
}
public int YDelta {
get { return yDelta; }
}
public override string ToString ()
{
return string.Format ("[MouseMoveDeltaEventArgs: XDelta={0}, YDelta={1}]", XDelta, YDelta);
}
}
//public delegate void MouseMoveEventHandler (object sender, MouseMoveEventArgs e);
//public delegate void MouseMoveDeltaEventHandler (object sender, MouseMoveDeltaEventArgs e);
/// <summary>
/// Mouse click event arguments
/// </summary>
public class MouseClickEventArgs : EventArgs
{
protected int x;
protected int y;
public MouseClickEventArgs(int x, int y)
{
this.x = x;
this.y = y;
}
public int X {
get { return x; }
}
public int Y {
get { return y; }
}
}
/*
public delegate void MouseLeftDownEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseLeftUpEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseLeftClickEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseMiddleDownEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseMiddleUpEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseMiddleClickEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseRightDownEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseRightUpEventHandler (object sender, MouseClickEventArgs e);
public delegate void MouseRightClickEventHandler (object sender, MouseClickEventArgs e);
*/
/// <summary>
/// Mouse Scroll Wheel Event
/// </summary>
//public delegate void MouseScrollWheelEventHandler (object sender, EventArgs e);
public class InputRegister
{
bool[] register = new bool[130];
bool[] mouse = new bool[3];
bool collectMouseMove;
float xMoveHolder;
float yMoveHolder;
public InputRegister ()
{
for (int i = 0; i < 130; i++) {
register[i] = false;
}
mouse[0] = false;
mouse[1] = false;
mouse[2] = false;
collectMouseMove = false;
xMoveHolder = 0;
yMoveHolder = 0;
}
public bool CollectMouseMoves {
get { return collectMouseMove; }
set {
collectMouseMove = value;
if(collectMouseMove == false) {
xMoveHolder = 0;
yMoveHolder = 0;
}
}
}
public event EventHandler<ResizeArgs> ResizeDisplay;
protected virtual void OnResizeDisplay (ResizeArgs e)
{
if (ResizeDisplay != null) {
ResizeDisplay (this, e);
}
}
// Key Down Event
public event EventHandler<KeyEventArgs> KeyDown;
protected virtual void OnKeyDown (KeyEventArgs e)
{
if (KeyDown != null) {
KeyDown (this, e);
}
}
// Key Up Event
public event EventHandler<KeyEventArgs> KeyUp;
protected virtual void OnKeyUp (KeyEventArgs e)
{
if (KeyUp != null) {
KeyUp (this, e);
}
}
// Key Pressed Event
public event EventHandler<KeyEventArgs> KeyPressed;
protected virtual void OnKeyPressed (KeyEventArgs e)
{
if (KeyPressed != null) {
KeyPressed (this, e);
}
}
// Mouse Move Event
public event EventHandler<MouseMoveEventArgs> MouseMove;
protected virtual void OnMouseMove (MouseMoveEventArgs e)
{
if (MouseMove != null) {
MouseMove (this, e);
}
}
public event EventHandler<MouseMoveDeltaEventArgs> MouseMoveDelta;
protected virtual void OnMouseMoveDelta (MouseMoveDeltaEventArgs e)
{
if (MouseMoveDelta != null) {
MouseMoveDelta (this, e);
}
}
// Mouse Left Click
public event EventHandler<MouseClickEventArgs> MouseLeftDown;
protected virtual void OnMouseLeftDown (MouseClickEventArgs e)
{
if (MouseLeftDown != null) {
MouseLeftDown (this, e);
}
}
public event EventHandler<MouseClickEventArgs> MouseLeftUp;
protected virtual void OnMouseLeftUp (MouseClickEventArgs e)
{
if (MouseLeftUp != null) {
MouseLeftUp (this, e);
}
}
public event EventHandler<MouseClickEventArgs> MouseLeftClick;
protected virtual void OnMouseLeftClick (MouseClickEventArgs e)
{
if (MouseLeftClick != null) {
MouseLeftClick (this, e);
}
}
// Mouse Right Click
public event EventHandler<MouseClickEventArgs> MouseRightDown;
protected virtual void OnMouseRightDown (MouseClickEventArgs e)
{
if (MouseRightDown != null) {
MouseRightDown (this, e);
}
}
public event EventHandler<MouseClickEventArgs> MouseRightUp;
protected virtual void OnMouseRightUp (MouseClickEventArgs e)
{
if (MouseRightUp != null) {
MouseRightUp (this, e);
}
}
public event EventHandler<MouseClickEventArgs> MouseRightClick;
protected virtual void OnMouseRightClick (MouseClickEventArgs e)
{
if (MouseRightClick != null) {
MouseRightClick (this, e);
}
}
// Mouse Middle Click
public event EventHandler<MouseClickEventArgs> MouseMiddleDown;
protected virtual void OnMouseMiddleDown (MouseClickEventArgs e)
{
if (MouseMiddleDown != null) {
MouseMiddleDown (this, e);
}
}
public event EventHandler<MouseClickEventArgs> MouseMiddleUp;
protected virtual void OnMouseMiddleUp (MouseClickEventArgs e)
{
if (MouseMiddleUp != null) {
MouseMiddleUp (this, e);
}
}
public event EventHandler<MouseClickEventArgs> MouseMiddleClick;
protected virtual void OnMouseMiddleClick (MouseClickEventArgs e)
{
if (MouseMiddleClick != null) {
MouseMiddleClick (this, e);
}
}
// Mouse Scroll Wheel
/****************************
* Public Callable methods
***************************/
public void ResizeInput(Display display, int width, int height)
{
OnResizeDisplay(new ResizeArgs(display, width, height));
}
public void KeyDownInput (Kinetic.IO.Key key)
{
int keyPressed = (int)key;
OnKeyDown (new KeyEventArgs (key));
register[keyPressed] = true;
}
public void KeyUpInput (Kinetic.IO.Key key)
{
int keyPressed = (int)key;
OnKeyUp (new KeyEventArgs (key));
if (register[keyPressed]) {
register[keyPressed] = false;
OnKeyPressed (new KeyEventArgs (key));
}
}
public void MouseMoveInput (int x, int y, int xDelta, int yDelta)
{
OnMouseMove (new MouseMoveEventArgs (x, y, xDelta, yDelta));
}
public void MouseMoveDeltaInput (int xDelta, int yDelta)
{
if(collectMouseMove) {
xMoveHolder += xDelta;
yMoveHolder += yDelta;
}
OnMouseMoveDelta (new MouseMoveDeltaEventArgs(xDelta, yDelta));
}
public void MouseButtonDownInput(Kinetic.IO.MouseButton button, int x, int y) {
int mouseButton = (int)button;
mouse[mouseButton] = true;
if(button == MouseButton.Left) {
OnMouseLeftDown(new MouseClickEventArgs(x,y));
} else if(button == MouseButton.Middle) {
OnMouseMiddleDown(new MouseClickEventArgs(x,y));
} else if(button == MouseButton.Right) {
OnMouseRightDown(new MouseClickEventArgs(x,y));
}
}
public void MouseButtonUpInput(Kinetic.IO.MouseButton button, int x, int y) {
int mouseButton = (int)button;
if(mouse[mouseButton]) {
mouse[mouseButton] = false;
MouseClickEventArgs mouseClickEventArgs = new MouseClickEventArgs(x,y);
if(button == MouseButton.Left) {
OnMouseLeftUp(mouseClickEventArgs);
OnMouseLeftClick(mouseClickEventArgs);
} else if(button == MouseButton.Middle) {
OnMouseMiddleUp(mouseClickEventArgs);
OnMouseMiddleClick(mouseClickEventArgs);
} else if(button == MouseButton.Right) {
OnMouseRightUp(mouseClickEventArgs);
OnMouseRightClick(mouseClickEventArgs);
}
}
}
public bool KeyIsPressed (Kinetic.IO.Key key) {
int keyPressed = (int)key;
return register[keyPressed];
}
public bool MouseButtonIsPressed(Kinetic.IO.MouseButton button) {
int mouseButton = (int)button;
return mouse[mouseButton];
}
public MouseMoveDeltaEventArgs MouseMoveDeltaRead() {
MouseMoveDeltaEventArgs mouseMoveDetla = new MouseMoveDeltaEventArgs((int) xMoveHolder, (int) yMoveHolder);
xMoveHolder = 0;
yMoveHolder = 0;
return mouseMoveDetla;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Internal
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal unsafe struct MemoryBlock
{
internal readonly byte* Pointer;
internal readonly int Length;
internal MemoryBlock(byte* buffer, int length)
{
Debug.Assert(length >= 0 && (buffer != null || length == 0));
this.Pointer = buffer;
this.Length = length;
}
internal static MemoryBlock CreateChecked(byte* buffer, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (buffer == null && length != 0)
{
throw new ArgumentNullException(nameof(buffer));
}
// the reader performs little-endian specific operations
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired);
}
return new MemoryBlock(buffer, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length)
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowValueOverflow()
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
internal byte[] ToArray()
{
return Pointer == null ? null : PeekBytes(0, Length);
}
private string GetDebuggerDisplay()
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
return GetDebuggerDisplay(out displayedBytes);
}
internal string GetDebuggerDisplay(out int displayedBytes)
{
displayedBytes = Math.Min(Length, 64);
string result = BitConverter.ToString(PeekBytes(0, displayedBytes));
if (displayedBytes < Length)
{
result += "-...";
}
return result;
}
internal string GetDebuggerDisplay(int offset)
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = GetDebuggerDisplay(out displayedBytes);
if (offset < displayedBytes)
{
display = display.Insert(offset * 3, "*");
}
else if (displayedBytes == Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(Pointer + offset, length);
}
internal byte PeekByte(int offset)
{
CheckBounds(offset, sizeof(byte));
return Pointer[offset];
}
internal int PeekInt32(int offset)
{
uint result = PeekUInt32(offset);
if (unchecked((int)result != result))
{
ThrowValueOverflow();
}
return (int)result;
}
internal uint PeekUInt32(int offset)
{
CheckBounds(offset, sizeof(uint));
return *(uint*)(Pointer + offset);
}
/// <summary>
/// Decodes a compressed integer value starting at offset.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="offset">Offset to the start of the compressed data.</param>
/// <param name="numberOfBytesRead">Bytes actually read.</param>
/// <returns>
/// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid.
/// </returns>
internal int PeekCompressedInteger(int offset, out int numberOfBytesRead)
{
CheckBounds(offset, 0);
byte* ptr = Pointer + offset;
long limit = Length - offset;
if (limit == 0)
{
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
byte headerByte = ptr[0];
if ((headerByte & 0x80) == 0)
{
numberOfBytesRead = 1;
return headerByte;
}
else if ((headerByte & 0x40) == 0)
{
if (limit >= 2)
{
numberOfBytesRead = 2;
return ((headerByte & 0x3f) << 8) | ptr[1];
}
}
else if ((headerByte & 0x20) == 0)
{
if (limit >= 4)
{
numberOfBytesRead = 4;
return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
}
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
internal ushort PeekUInt16(int offset)
{
CheckBounds(offset, sizeof(ushort));
return *(ushort*)(Pointer + offset);
}
// When reference has tag bits.
internal uint PeekTaggedReference(int offset, bool smallRefSize)
{
return PeekReferenceUnchecked(offset, smallRefSize);
}
// Use when searching for a tagged or non-tagged reference.
// The result may be an invalid reference and shall only be used to compare with a valid reference.
internal uint PeekReferenceUnchecked(int offset, bool smallRefSize)
{
return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset);
}
// When reference has at most 24 bits.
internal int PeekReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!TokenTypeIds.IsValidRowId(value))
{
Throw.ReferenceOverflow();
}
return (int)value;
}
// #String, #Blob heaps
internal int PeekHeapReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!HeapHandleType.IsValidHeapOffset(value))
{
Throw.ReferenceOverflow();
}
return (int)value;
}
internal Guid PeekGuid(int offset)
{
CheckBounds(offset, sizeof(Guid));
return *(Guid*)(Pointer + offset);
}
internal string PeekUtf16(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
// doesn't allocate a new string if byteCount == 0
return new string((char*)(Pointer + offset), 0, byteCount / sizeof(char));
}
internal string PeekUtf8(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
return Encoding.UTF8.GetString(Pointer + offset, byteCount);
}
/// <summary>
/// Read UTF8 at the given offset up to the given terminator, null terminator, or end-of-block.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="prefix">UTF8 encoded prefix to prepend to the bytes at the offset before decoding.</param>
/// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocating a new one.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <returns>The decoded string.</returns>
internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0')
{
Debug.Assert(terminator <= 0x7F);
CheckBounds(offset, 0);
int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator);
return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder);
}
/// <summary>
/// Get number of bytes from offset to given terminator, null terminator, or end-of-block (whichever comes first).
/// Returned length does not include the terminator, but numberOfBytesRead out parameter does.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <returns>Length (byte count) not including terminator.</returns>
internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0')
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7f);
byte* start = Pointer + offset;
byte* end = Pointer + Length;
byte* current = start;
while (current < end)
{
byte b = *current;
if (b == 0 || b == terminator)
{
break;
}
current++;
}
int length = (int)(current - start);
numberOfBytesRead = length;
if (current < end)
{
// we also read the terminator
numberOfBytesRead++;
}
return length;
}
internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar)
{
CheckBounds(startOffset, 0);
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
for (int i = startOffset; i < Length; i++)
{
byte b = Pointer[i];
if (b == 0)
{
break;
}
if (b == asciiChar)
{
return i;
}
}
return -1;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase)
{
int firstDifference;
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifference, terminator, ignoreCase);
if (result == FastComparisonResult.Inconclusive)
{
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return result == FastComparisonResult.Equal;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase)
{
int endIndex;
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out endIndex, terminator, ignoreCase);
switch (result)
{
case FastComparisonResult.Equal:
case FastComparisonResult.BytesStartWithText:
return true;
case FastComparisonResult.Unequal:
case FastComparisonResult.TextStartsWithBytes:
return false;
default:
Debug.Assert(result == FastComparisonResult.Inconclusive);
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
}
internal enum FastComparisonResult
{
Equal,
BytesStartWithText,
TextStartsWithBytes,
Unequal,
Inconclusive
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, int textStart, out int firstDifferenceIndex, char terminator, bool ignoreCase)
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7F);
byte* startPointer = Pointer + offset;
byte* endPointer = Pointer + Length;
byte* currentPointer = startPointer;
int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase);
int currentIndex = textStart;
while (currentIndex < text.Length && currentPointer != endPointer)
{
byte currentByte = *currentPointer;
// note that terminator is not compared case-insensitively even if ignore case is true
if (currentByte == 0 || currentByte == terminator)
{
break;
}
char currentChar = text[currentIndex];
if ((currentByte & 0x80) == 0 && StringUtils.IsEqualAscii(currentChar, currentByte, ignoreCaseMask))
{
currentIndex++;
currentPointer++;
}
else
{
firstDifferenceIndex = currentIndex;
// uncommon non-ascii case --> fall back to slow allocating comparison.
return (currentChar > 0x7F) ? FastComparisonResult.Inconclusive : FastComparisonResult.Unequal;
}
}
firstDifferenceIndex = currentIndex;
bool textTerminated = currentIndex == text.Length;
bool bytesTerminated = currentPointer == endPointer || *currentPointer == 0 || *currentPointer == terminator;
if (textTerminated && bytesTerminated)
{
return FastComparisonResult.Equal;
}
return textTerminated ? FastComparisonResult.BytesStartWithText : FastComparisonResult.TextStartsWithBytes;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
// Make sure that we won't read beyond the block even if the block doesn't end with 0 byte.
if (asciiPrefix.Length > Length - offset)
{
return false;
}
byte* p = Pointer + offset;
for (int i = 0; i < asciiPrefix.Length; i++)
{
Debug.Assert(asciiPrefix[i] > 0 && asciiPrefix[i] <= 0x7f);
if (asciiPrefix[i] != *p)
{
return false;
}
p++;
}
return true;
}
internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
byte* p = Pointer + offset;
int limit = Length - offset;
for (int i = 0; i < asciiString.Length; i++)
{
Debug.Assert(asciiString[i] > 0 && asciiString[i] <= 0x7f);
if (i > limit)
{
// Heap value is shorter.
return -1;
}
if (*p != asciiString[i])
{
// If we hit the end of the heap value (*p == 0)
// the heap value is shorter than the string, so we return negative value.
return *p - asciiString[i];
}
p++;
}
// Either the heap value name matches exactly the given string or
// it is longer so it is considered "greater".
return (*p == 0) ? 0 : +1;
}
internal byte[] PeekBytes(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
if (byteCount == 0)
{
return EmptyArray<byte>.Instance;
}
byte[] result = new byte[byteCount];
Marshal.Copy((IntPtr)(Pointer + offset), result, 0, byteCount);
return result;
}
internal int IndexOf(byte b, int start)
{
CheckBounds(start, 0);
byte* p = Pointer + start;
byte* end = Pointer + Length;
while (p < end)
{
if (*p == b)
{
return (int)(p - Pointer);
}
p++;
}
return -1;
}
// same as Array.BinarySearch, but without using IComparer
internal int BinarySearch(string[] asciiKeys, int offset)
{
var low = 0;
var high = asciiKeys.Length - 1;
while (low <= high)
{
var middle = low + ((high - low) >> 1);
var midValue = asciiKeys[middle];
int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue);
if (comparison == 0)
{
return middle;
}
if (comparison < 0)
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return ~low;
}
/// <summary>
/// In a table that specifies children via a list field (e.g. TypeDef.FieldList, TypeDef.MethodList),
/// searches for the parent given a reference to a child.
/// </summary>
/// <returns>Returns row number [0..RowCount).</returns>
internal int BinarySearchForSlot(
int rowCount,
int rowSize,
int referenceListOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
uint startValue = PeekReferenceUnchecked(startRowNumber * rowSize + referenceListOffset, isReferenceSmall);
uint endValue = PeekReferenceUnchecked(endRowNumber * rowSize + referenceListOffset, isReferenceSmall);
if (endRowNumber == 1)
{
if (referenceValue >= endValue)
{
return endRowNumber;
}
return startRowNumber;
}
while (endRowNumber - startRowNumber > 1)
{
if (referenceValue <= startValue)
{
return referenceValue == startValue ? startRowNumber : startRowNumber - 1;
}
if (referenceValue >= endValue)
{
return referenceValue == endValue ? endRowNumber : endRowNumber + 1;
}
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceListOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber;
startValue = midReferenceValue;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber;
endValue = midReferenceValue;
}
else
{
return midRowNumber;
}
}
return startRowNumber;
}
/// <summary>
/// In a table ordered by a column containing entity references searches for a row with the specified reference.
/// </summary>
/// <returns>Returns row number [0..RowCount) or -1 if not found.</returns>
internal int BinarySearchReference(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
// Row number [0, ptrTable.Length) or -1 if not found.
internal int BinarySearchReference(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = ptrTable.Length - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked((ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, rowCount) or -1
out int endRowNumber) // [0, rowCount) or -1
{
int foundRowNumber = BinarySearchReference(
rowCount,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < rowCount &&
PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, ptrTable.Length) or -1
out int endRowNumber) // [0, ptrTable.Length) or -1
{
int foundRowNumber = BinarySearchReference(
ptrTable,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < ptrTable.Length &&
PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
// Always RowNumber....
internal int LinearSearchReference(
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int currOffset = referenceOffset;
int totalSize = this.Length;
while (currOffset < totalSize)
{
uint currReference = PeekReferenceUnchecked(currOffset, isReferenceSmall);
if (currReference == referenceValue)
{
return currOffset / rowSize;
}
currOffset += rowSize;
}
return -1;
}
internal bool IsOrderedByReferenceAscending(
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
uint previous = 0;
while (offset < totalSize)
{
uint current = PeekReferenceUnchecked(offset, isReferenceSmall);
if (current < previous)
{
return false;
}
previous = current;
offset += rowSize;
}
return true;
}
internal int[] BuildPtrTable(
int numberOfRows,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int[] ptrTable = new int[numberOfRows];
uint[] unsortedReferences = new uint[numberOfRows];
for (int i = 0; i < ptrTable.Length; i++)
{
ptrTable[i] = i + 1;
}
ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall);
Array.Sort(ptrTable, (int a, int b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); });
return ptrTable;
}
private void ReadColumn(
uint[] result,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
int i = 0;
while (offset < totalSize)
{
result[i] = PeekReferenceUnchecked(offset, isReferenceSmall);
offset += rowSize;
i++;
}
Debug.Assert(i == result.Length);
}
internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size)
{
int bytesRead;
int numberOfBytes = PeekCompressedInteger(index, out bytesRead);
if (numberOfBytes == BlobReader.InvalidCompressedInteger)
{
offset = 0;
size = 0;
return false;
}
offset = index + bytesRead;
size = numberOfBytes;
return true;
}
}
}
| |
using UnityEngine;
using System.Collections;
[ExecuteInEditMode()]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
public class TimeCircle : MonoBehaviour {
public float lineRadius = 640.0f;
public Vector2 largeLineSize = new Vector2(2.0f, 12.0f);
public Vector2 smallLineSize = new Vector2(1.5f, 8.0f);
public int largeLineCount = 60;
public int partLineCount = 10;
public Color largeLineColor = Color.white;
public Color smallLineColor = Color.gray;
public int textureOffsetX = 0;
public int textureOffsetY = 0;
float prevLineRadius = 0;
Vector2 prevLargeLineSize = Vector2.zero;
Vector2 prevSmallLineSize = Vector2.zero;
int prevLargeLineCount = 0;
int prevPartLineCount = 0;
Color prevLargeLineColor = Color.clear;
Color prevSmallLineColor = Color.clear;
int prevTextureOffsetX = -1;
int prevTextureOffsetY = -1;
public GameObject numberPrefab;
public float numberRadius = 620.0f;
float prevNumberRadius = 0;
GameObject numberRoot = null;
string numberRootName = "NumberRoot";
MeshFilter meshFilter;
void Start () {
UpdateLines();
UpdateNumbers();
}
void Update () {
if (IsLinePropertyChanged()) {
UpdateLines();
}
if (IsNumberPropertyChanged()) {
UpdateNumbers();
}
}
bool IsLinePropertyChanged() {
if (lineRadius != prevLineRadius ||
largeLineSize != prevLargeLineSize ||
smallLineSize != prevSmallLineSize ||
largeLineCount != prevLargeLineCount ||
partLineCount != prevPartLineCount ||
largeLineColor != prevLargeLineColor ||
smallLineColor != prevSmallLineColor ||
textureOffsetX != prevTextureOffsetX ||
textureOffsetY != prevTextureOffsetY) {
return true;
}
return false;
}
bool IsNumberPropertyChanged() {
if (numberRadius != prevNumberRadius) {
return true;
}
return false;
}
void UpdateLines()
{
if (meshFilter == null) {
meshFilter = GetComponent<MeshFilter>();
}
Mesh mesh = meshFilter.sharedMesh;
if (mesh == null) return;
mesh.Clear();
Material mat = renderer.sharedMaterial;
if (mat == null) return;
Texture tex = mat.mainTexture;
if (tex == null) return;
Texture2D tex2d = (Texture2D)mat.mainTexture;
if (tex2d == null) return;
// Draw Texture
int padding = 1;
int border = 1;
int scale = 2;
int originX = textureOffsetX;
int originY = textureOffsetY;
int texWidth = tex2d.width;
int texHeight = tex2d.height;
Rect largeClearRect = BSWUtility.CreateRectForClear(originX, originY, largeLineSize, padding, border, scale);
BSWUtility.DrawRect(tex2d, largeClearRect, Color.clear);
Rect largeDrawRect = BSWUtility.CreateRectForDraw(originX, originY, largeLineSize, padding, border, scale);
BSWUtility.DrawRect(tex2d, largeDrawRect, largeLineColor);
Vector2[] largeUv = BSWUtility.CreateUv(originX, originY, largeLineSize, texWidth, texHeight, padding, border, scale);
originX += (int)(padding * 2 + (largeLineSize.x + border * 2) * scale);
Rect smallClearRect = BSWUtility.CreateRectForClear(originX, originY, smallLineSize, padding, border, scale);
BSWUtility.DrawRect(tex2d, smallClearRect, Color.clear);
Rect smallDrawRect = BSWUtility.CreateRectForDraw(originX, originY, smallLineSize, padding, border, scale);
BSWUtility.DrawRect(tex2d, smallDrawRect, smallLineColor);
Vector2[] smallUv = BSWUtility.CreateUv(originX, originY, smallLineSize, texWidth, texHeight, padding, border, scale);
tex2d.Apply();
renderer.sharedMaterial.mainTexture = tex2d;
// Create Mesh
int lineCount = largeLineCount * partLineCount;
int vertexCount = lineCount * 4;
int triangleCount = lineCount * 6;
Vector3[] vertices = new Vector3[vertexCount];
int[] triangles = new int[triangleCount];
Vector2[] uv = new Vector2[vertexCount];
Vector3[] largeLinePos = CreateLinePositions(largeLineSize, border, lineRadius);
Vector3[] smallLinePos = CreateLinePositions(smallLineSize, border, lineRadius);
for (int i = 0; i < lineCount; i++) {
int vTopIndex = i * 4;
int tTopIndex = i * 6;
float angle = - ((float)i / lineCount) * 360.0f;
var rot = Quaternion.Euler(0, 0, angle);
var m = Matrix4x4.TRS(Vector3.zero, rot, Vector3.one);
Vector3[] currentPos;
Vector2[] currentUv;
if (i % partLineCount == 0) {
currentPos = largeLinePos;
currentUv = largeUv;
} else {
currentPos = smallLinePos;
currentUv = smallUv;
}
for (int j = 0; j < 4; j++) {
int index = vTopIndex + j;
vertices[index] = m.MultiplyPoint3x4(currentPos[j]);
uv[index] = currentUv[j];
}
triangles[tTopIndex] = vTopIndex;
triangles[tTopIndex + 2] = triangles[tTopIndex + 3] = vTopIndex + 1;
triangles[tTopIndex + 1] = triangles[tTopIndex + 4] = vTopIndex + 2;
triangles[tTopIndex + 5] = vTopIndex + 3;
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uv;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();
// Keep Properties
prevLineRadius = lineRadius;
prevLargeLineSize = largeLineSize;
prevSmallLineSize = smallLineSize;
prevLargeLineCount = largeLineCount;
prevPartLineCount = partLineCount;
prevLargeLineColor = largeLineColor;
prevSmallLineColor = smallLineColor;
prevTextureOffsetX = textureOffsetX;
prevTextureOffsetY = textureOffsetY;
}
static public Vector3[] CreateLinePositions(Vector2 lineSize, int border, float radius) {
float minX = - lineSize.x * 0.5f - border;
float maxX = lineSize.x * 0.5f + border;
float minY = - lineSize.y * 0.5f - border + radius;
float maxY = lineSize.y * 0.5f + border + radius;
return new Vector3[] {
new Vector3(minX, minY, 0.0f),
new Vector3(maxX, minY, 0.0f),
new Vector3(minX, maxY, 0.0f),
new Vector3(maxX, maxY, 0.0f)
};
}
void UpdateNumbers()
{
if (numberPrefab == null)
return;
foreach (Transform child in transform) {
if (child.gameObject.name == numberRootName) {
DestroyImmediate(child.gameObject);
}
}
numberRoot = new GameObject(numberRootName);
numberRoot.transform.parent = transform;
numberRoot.transform.localScale = Vector3.one;
numberRoot.transform.localPosition = Vector3.zero;
numberRoot.transform.localRotation = Quaternion.identity;
for (int i = 0; i < largeLineCount; i++) {
GameObject handleObj = new GameObject("NumberHandle_"+i);
handleObj.transform.parent = numberRoot.transform;
handleObj.transform.localRotation = Quaternion.Euler(0, 0, - (float)i / largeLineCount * 360.0f);
handleObj.transform.localScale = Vector3.one;
handleObj.transform.localPosition = Vector3.zero;
GameObject numObj = Instantiate(numberPrefab) as GameObject;
numObj.transform.parent = handleObj.transform;
numObj.transform.localScale = Vector3.one;
numObj.transform.localRotation = Quaternion.identity;
TextMesh textMesh = numObj.GetComponent<TextMesh>();
if (textMesh != null) {
textMesh.text = i.ToString();
numObj.name = "Number_" + textMesh.text;
textMesh.transform.localPosition = new Vector3(0, numberRadius, 0);
}
}
prevNumberRadius = numberRadius;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestAllOnesInt16()
{
var test = new BooleanComparisonOpTest__TestAllOnesInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanComparisonOpTest__TestAllOnesInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector128<Int16> _clsVar;
private Vector128<Int16> _fld;
private BooleanUnaryOpTest__DataTable<Int16> _dataTable;
static BooleanComparisonOpTest__TestAllOnesInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
}
public BooleanComparisonOpTest__TestAllOnesInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new BooleanUnaryOpTest__DataTable<Int16>(_data, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestAllOnes(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr)
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestAllOnes(
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestAllOnes(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestAllOnes), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr)
});
ValidateResult(_dataTable.inArrayPtr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestAllOnes), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestAllOnes), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (bool)(result));
}
public void RunClsVarScenario()
{
var result = Sse41.TestAllOnes(
_clsVar
);
ValidateResult(_clsVar, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var value = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr);
var result = Sse41.TestAllOnes(value);
ValidateResult(value, result);
}
public void RunLclVarScenario_Load()
{
var value = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse41.TestAllOnes(value);
ValidateResult(value, result);
}
public void RunLclVarScenario_LoadAligned()
{
var value = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse41.TestAllOnes(value);
ValidateResult(value, result);
}
public void RunLclFldScenario()
{
var test = new BooleanComparisonOpTest__TestAllOnesInt16();
var result = Sse41.TestAllOnes(test._fld);
ValidateResult(test._fld, result);
}
public void RunFldScenario()
{
var result = Sse41.TestAllOnes(_fld);
ValidateResult(_fld, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> value, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), value);
ValidateResult(inArray, result, method);
}
private void ValidateResult(void* value, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(value), VectorSize);
ValidateResult(inArray, result, method);
}
private void ValidateResult(Int16[] value, bool result, [CallerMemberName] string method = "")
{
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((~value[i] & -1) == 0);
}
if (expectedResult != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestAllOnes)}<Int16>(Vector128<Int16>): {method} failed:");
Console.WriteLine($" value: ({string.Join(", ", value)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Containers
{
public class TestSceneFrontToBackBox : FrameworkTestScene
{
[Resolved]
private FrameworkDebugConfigManager debugConfig { get; set; }
private TestBox blendedBox;
[SetUp]
public void Setup() => Schedule(() =>
{
Clear();
});
[TearDownSteps]
public void TearDownSteps()
{
AddToggleStep("disable front to back", val => debugConfig.SetValue(DebugSetting.BypassFrontToBackPass, val));
}
[Test]
public void TestOpaqueBoxWithMixedBlending()
{
createBlendedBox();
AddAssert("renders interior", () => blendedBox.CanDrawOpaqueInterior);
}
[Test]
public void TestTransparentBoxWithMixedBlending()
{
createBlendedBox(b => b.Alpha = 0.5f);
AddAssert("doesn't render interior", () => !blendedBox.CanDrawOpaqueInterior);
}
[Test]
public void TestOpaqueBoxWithAdditiveBlending()
{
createBlendedBox(b => b.Blending = BlendingParameters.Additive);
AddAssert("doesn't render interior", () => !blendedBox.CanDrawOpaqueInterior);
}
[Test]
public void TestTransparentBoxWithAdditiveBlending()
{
createBlendedBox(b =>
{
b.Blending = BlendingParameters.Additive;
b.Alpha = 0.5f;
});
AddAssert("doesn't render interior", () => !blendedBox.CanDrawOpaqueInterior);
}
[TestCase(BlendingEquation.Max)]
[TestCase(BlendingEquation.Min)]
[TestCase(BlendingEquation.Subtract)]
[TestCase(BlendingEquation.ReverseSubtract)]
public void TestOpaqueBoxWithNonAddRGBEquation(BlendingEquation equationMode)
{
createBlendedBox(b =>
{
var blending = BlendingParameters.Inherit;
blending.RGBEquation = equationMode;
b.Blending = blending;
});
AddAssert("doesn't render interior", () => !blendedBox.CanDrawOpaqueInterior);
}
[TestCase(BlendingEquation.Max)]
[TestCase(BlendingEquation.Min)]
[TestCase(BlendingEquation.Subtract)]
[TestCase(BlendingEquation.ReverseSubtract)]
public void TestOpaqueBoxWithNonAddAlphaEquation(BlendingEquation equationMode)
{
createBlendedBox(b =>
{
var blending = BlendingParameters.Inherit;
blending.AlphaEquation = equationMode;
b.Blending = blending;
});
AddAssert("doesn't render interior", () => !blendedBox.CanDrawOpaqueInterior);
}
[Test]
public void TestSmallSizeMasking()
{
AddStep("create test", () =>
{
Children = new Drawable[]
{
new SpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Y = -120,
Text = "No rounded corners should be visible below",
},
new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(20),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Green
},
new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Masking = true,
CornerRadius = 40,
Child = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = Color4.Green
}
}
}
}
};
});
}
[Test]
public void TestNegativeSizeMasking()
{
AddStep("create test", () =>
{
Children = new Drawable[]
{
new SpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Y = -120,
Text = "No rounded corners should be visible below",
},
new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Green
},
new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(-1f),
Masking = true,
CornerRadius = 20,
Child = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = Color4.Green
}
}
}
}
};
});
}
private void createBlendedBox(Action<Box> setupAction = null) => AddStep("create box", () =>
{
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = new Color4(50, 50, 50, 255)
},
blendedBox = new TestBox
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = new Color4(100, 100, 100, 255),
Size = new Vector2(0.5f),
}
}
};
setupAction?.Invoke(blendedBox);
});
private class TestBox : Box
{
public bool CanDrawOpaqueInterior => currentDrawNode.CanDrawOpaqueInterior;
private DrawNode currentDrawNode;
protected override DrawNode CreateDrawNode() => new TestBoxDrawNode(this);
internal override DrawNode GenerateDrawNodeSubtree(ulong frame, int treeIndex, bool forceNewDrawNode)
=> currentDrawNode = base.GenerateDrawNodeSubtree(frame, treeIndex, forceNewDrawNode);
private class TestBoxDrawNode : SpriteDrawNode
{
public TestBoxDrawNode(Box source)
: base(source)
{
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.SiteRecovery;
using Microsoft.Azure.Management.SiteRecovery.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of Network operations for the Site Recovery extension.
/// </summary>
internal partial class NetworkOperations : IServiceOperations<SiteRecoveryManagementClient>, INetworkOperations
{
/// <summary>
/// Initializes a new instance of the NetworkOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal NetworkOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets a VM network.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric unique name.
/// </param>
/// <param name='networkName'>
/// Required. Network name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Network object.
/// </returns>
public async Task<NetworkResponse> GetAsync(string fabricName, string networkName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (fabricName == null)
{
throw new ArgumentNullException("fabricName");
}
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("networkName", networkName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationFabrics/";
url = url + Uri.EscapeDataString(fabricName);
url = url + "/replicationNetworks/";
url = url + Uri.EscapeDataString(networkName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
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-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-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
NetworkResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Network networkInstance = new Network();
result.Network = networkInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
NetworkProperties propertiesInstance = new NetworkProperties();
networkInstance.Properties = propertiesInstance;
JToken fabricTypeValue = propertiesValue["fabricType"];
if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
{
string fabricTypeInstance = ((string)fabricTypeValue);
propertiesInstance.FabricType = fabricTypeInstance;
}
JToken subnetsArray = propertiesValue["subnets"];
if (subnetsArray != null && subnetsArray.Type != JTokenType.Null)
{
foreach (JToken subnetsValue in ((JArray)subnetsArray))
{
Subnet subnetInstance = new Subnet();
propertiesInstance.Subnets.Add(subnetInstance);
JToken nameValue = subnetsValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
subnetInstance.Name = nameInstance;
}
JToken friendlyNameValue = subnetsValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
subnetInstance.FriendlyName = friendlyNameInstance;
}
JToken addressListArray = subnetsValue["addressList"];
if (addressListArray != null && addressListArray.Type != JTokenType.Null)
{
foreach (JToken addressListValue in ((JArray)addressListArray))
{
subnetInstance.AddressList.Add(((string)addressListValue));
}
}
}
}
JToken friendlyNameValue2 = propertiesValue["friendlyName"];
if (friendlyNameValue2 != null && friendlyNameValue2.Type != JTokenType.Null)
{
string friendlyNameInstance2 = ((string)friendlyNameValue2);
propertiesInstance.FriendlyName = friendlyNameInstance2;
}
JToken networkTypeValue = propertiesValue["networkType"];
if (networkTypeValue != null && networkTypeValue.Type != JTokenType.Null)
{
string networkTypeInstance = ((string)networkTypeValue);
propertiesInstance.NetworkType = networkTypeInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
networkInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
networkInstance.Name = nameInstance2;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
networkInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
networkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
networkInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get list of Networks.
/// </summary>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list of Networks.
/// </returns>
public async Task<NetworksListResponse> GetAllAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
// 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, "GetAllAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationNetworks";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
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-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-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
NetworksListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworksListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Network networkInstance = new Network();
result.NetworksList.Add(networkInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
NetworkProperties propertiesInstance = new NetworkProperties();
networkInstance.Properties = propertiesInstance;
JToken fabricTypeValue = propertiesValue["fabricType"];
if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
{
string fabricTypeInstance = ((string)fabricTypeValue);
propertiesInstance.FabricType = fabricTypeInstance;
}
JToken subnetsArray = propertiesValue["subnets"];
if (subnetsArray != null && subnetsArray.Type != JTokenType.Null)
{
foreach (JToken subnetsValue in ((JArray)subnetsArray))
{
Subnet subnetInstance = new Subnet();
propertiesInstance.Subnets.Add(subnetInstance);
JToken nameValue = subnetsValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
subnetInstance.Name = nameInstance;
}
JToken friendlyNameValue = subnetsValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
subnetInstance.FriendlyName = friendlyNameInstance;
}
JToken addressListArray = subnetsValue["addressList"];
if (addressListArray != null && addressListArray.Type != JTokenType.Null)
{
foreach (JToken addressListValue in ((JArray)addressListArray))
{
subnetInstance.AddressList.Add(((string)addressListValue));
}
}
}
}
JToken friendlyNameValue2 = propertiesValue["friendlyName"];
if (friendlyNameValue2 != null && friendlyNameValue2.Type != JTokenType.Null)
{
string friendlyNameInstance2 = ((string)friendlyNameValue2);
propertiesInstance.FriendlyName = friendlyNameInstance2;
}
JToken networkTypeValue = propertiesValue["networkType"];
if (networkTypeValue != null && networkTypeValue.Type != JTokenType.Null)
{
string networkTypeInstance = ((string)networkTypeValue);
propertiesInstance.NetworkType = networkTypeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
networkInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
networkInstance.Name = nameInstance2;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
networkInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
networkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
networkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get list of Networks.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list of Networks.
/// </returns>
public async Task<NetworksListResponse> ListAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (fabricName == null)
{
throw new ArgumentNullException("fabricName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationFabrics/";
url = url + Uri.EscapeDataString(fabricName);
url = url + "/replicationNetworks";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
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-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-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
NetworksListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworksListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Network networkInstance = new Network();
result.NetworksList.Add(networkInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
NetworkProperties propertiesInstance = new NetworkProperties();
networkInstance.Properties = propertiesInstance;
JToken fabricTypeValue = propertiesValue["fabricType"];
if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
{
string fabricTypeInstance = ((string)fabricTypeValue);
propertiesInstance.FabricType = fabricTypeInstance;
}
JToken subnetsArray = propertiesValue["subnets"];
if (subnetsArray != null && subnetsArray.Type != JTokenType.Null)
{
foreach (JToken subnetsValue in ((JArray)subnetsArray))
{
Subnet subnetInstance = new Subnet();
propertiesInstance.Subnets.Add(subnetInstance);
JToken nameValue = subnetsValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
subnetInstance.Name = nameInstance;
}
JToken friendlyNameValue = subnetsValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
subnetInstance.FriendlyName = friendlyNameInstance;
}
JToken addressListArray = subnetsValue["addressList"];
if (addressListArray != null && addressListArray.Type != JTokenType.Null)
{
foreach (JToken addressListValue in ((JArray)addressListArray))
{
subnetInstance.AddressList.Add(((string)addressListValue));
}
}
}
}
JToken friendlyNameValue2 = propertiesValue["friendlyName"];
if (friendlyNameValue2 != null && friendlyNameValue2.Type != JTokenType.Null)
{
string friendlyNameInstance2 = ((string)friendlyNameValue2);
propertiesInstance.FriendlyName = friendlyNameInstance2;
}
JToken networkTypeValue = propertiesValue["networkType"];
if (networkTypeValue != null && networkTypeValue.Type != JTokenType.Null)
{
string networkTypeInstance = ((string)networkTypeValue);
propertiesInstance.NetworkType = networkTypeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
networkInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
networkInstance.Name = nameInstance2;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
networkInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
networkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
networkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Xml.Serialization;
namespace Wyam.Feeds.Syndication.Atom
{
/// <summary>
/// http://tools.ietf.org/html/rfc4287#section-4.2.7
/// </summary>
[Serializable]
public class AtomLink : AtomCommonAttributes, IUriProvider
{
private AtomLinkRelation _relation = AtomLinkRelation.None;
private Uri _rel = null;
private string _type = null;
private Uri _href = null;
private string _hreflang = null;
private string _title = null;
private string _length = null;
private int _threadCount = 0;
private AtomDate _threadUpdated;
/// <summary>
/// Ctor
/// </summary>
public AtomLink()
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="link"></param>
public AtomLink(string link)
{
Href = link;
}
[XmlIgnore]
[DefaultValue(AtomLinkRelation.None)]
public AtomLinkRelation Relation
{
get
{
// http://tools.ietf.org/html/rfc4685#section-4
if (ThreadCount > 0)
{
return AtomLinkRelation.Replies;
}
return _relation;
}
set
{
_relation = value;
_rel = null;
}
}
[XmlAttribute("rel")]
[DefaultValue(null)]
public string Rel
{
get
{
if (Relation == AtomLinkRelation.None)
{
return ConvertToString(_rel);
}
// TODO: use XmlEnum values
switch (_relation)
{
case AtomLinkRelation.NextArchive:
{
return "next-archive";
}
case AtomLinkRelation.PrevArchive:
{
return "prev-archive";
}
default:
{
return _relation.ToString().ToLowerInvariant();
}
}
}
set
{
if (string.IsNullOrEmpty(value))
{
_relation = AtomLinkRelation.None;
_rel = null;
}
try
{
// TODO: use XmlEnum values
_relation = (AtomLinkRelation)Enum.Parse(typeof(AtomLinkRelation), value.Replace("-",""), true);
}
catch
{
_relation = AtomLinkRelation.None;
_rel = ConvertToUri(value);
}
}
}
[XmlAttribute("type")]
[DefaultValue(null)]
public string Type
{
get
{
// http://tools.ietf.org/html/rfc4685#section-4
string value = _type;
if (ThreadCount > 0 && string.IsNullOrEmpty(value))
{
return AtomFeed.MimeType;
}
return value;
}
set { _type = string.IsNullOrEmpty(value) ? null : value; }
}
[XmlAttribute("href")]
[DefaultValue(null)]
public string Href
{
get { return ConvertToString(_href); }
set { _href = ConvertToUri(value); }
}
[XmlAttribute("hreflang")]
[DefaultValue(null)]
public string HrefLang
{
get { return _hreflang; }
set { _hreflang = string.IsNullOrEmpty(value) ? null : value; }
}
[XmlAttribute("length")]
[DefaultValue(null)]
public string Length
{
get { return _length; }
set { _length = string.IsNullOrEmpty(value) ? null : value; }
}
[XmlAttribute("title")]
[DefaultValue(null)]
public string Title
{
get { return _title; }
set { _title = string.IsNullOrEmpty(value) ? null : value; }
}
/// <summary>
/// http://tools.ietf.org/html/rfc4685#section-4
/// </summary>
[XmlAttribute("count", Namespace=ThreadingNamespace)]
public int ThreadCount
{
get { return _threadCount; }
set { _threadCount = (value < 0) ? 0 : value; }
}
[XmlIgnore]
public bool ThreadCountSpecified
{
get { return (Relation == AtomLinkRelation.Replies); }
set { }
}
/// <summary>
/// http://tools.ietf.org/html/rfc4685#section-4
/// </summary>
[XmlIgnore]
public AtomDate ThreadUpdated
{
get { return _threadUpdated; }
set { _threadUpdated = value; }
}
/// <summary>
/// Gets and sets the DateTime using ISO-8601 date format.
/// For serialization purposes only, use the ThreadUpdated property instead.
/// </summary>
[DefaultValue(null)]
[XmlAttribute("updated", Namespace=ThreadingNamespace)]
public string ThreadUpdatedIso8601
{
get { return _threadUpdated.ValueIso8601; }
set { _threadUpdated.ValueIso8601 = value; }
}
[XmlIgnore]
public bool ThreadUpdatedSpecified
{
get { return (Relation == AtomLinkRelation.Replies) && _threadUpdated.HasValue; }
set { }
}
Uri IUriProvider.Uri => _href;
public override string ToString()
{
return Href;
}
public override void AddNamespaces(XmlSerializerNamespaces namespaces)
{
if (ThreadCount > 0)
{
namespaces.Add(ThreadingPrefix, ThreadingNamespace);
}
base.AddNamespaces(namespaces);
}
}
}
| |
using System;
using System.IO;
using System.Xml;
using GCheckout.AutoGen;
using GCheckout.Util;
using Vevo.Base.Domain;
using Vevo.Deluxe.Domain.Marketing;
//using GCheckout.OrderProcessing;
using Vevo.Domain;
using Vevo.Domain.Orders;
using Vevo.Domain.Payments;
using Vevo.Domain.Payments.Google;
using Vevo.Domain.Products;
using Vevo.Domain.Shipping;
using Vevo.Domain.Shipping.Custom;
using Vevo.Domain.Stores;
using Vevo.Domain.Users;
using Vevo.WebAppLib;
using Vevo.WebUI;
using Vevo.Deluxe.WebUI.Marketing;
using Vevo.WebUI.Orders;
using Vevo.Deluxe.Domain.Orders;
public partial class GoogleNotification : System.Web.UI.Page
{
#region Private
private string _serialNumber = String.Empty;
private string GetPaymentName()
{
PaymentMethod payment;
payment = new GoogleCheckoutPaymentMethod();
return payment.Name;
}
private string ConvertToString( string source )
{
string result;
if (!String.IsNullOrEmpty( source ))
{
result = source;
}
else
{
result = "";
}
return result;
}
private void SendChargeFailureEmail( Order order )
{
WebUtilities.SendMail(
NamedConfig.AutoSenderEmail,
DataAccessContext.Configurations.GetValue( "ErrorLogEmail" ),
"Failed charging order ID " + order.OrderID,
"There is an error while trying to charge credit card.\n" +
" Shopping Cart Order ID: " + order.OrderID + "\n" +
" Google Order ID: " + order.GatewayOrderID + "\n" +
"\nPlease verify this order in your Google Checkout Merchant account.\n" );
}
private string GetGiftCertificateCode( object[] obj )
{
if (obj == null)
return String.Empty;
foreach (object o in obj)
{
if (o is GiftCertificateAdjustment)
{
GiftCertificateAdjustment result = (GiftCertificateAdjustment) o;
return result.code;
}
}
return String.Empty;
}
private string GetCouponCode( object[] obj )
{
if (obj == null)
return String.Empty;
foreach (object o in obj)
{
if (o is CouponAdjustment)
{
CouponAdjustment result = (CouponAdjustment) o;
return result.code;
}
}
return String.Empty;
}
private void BuildShoppingCart( string requestXml, NewOrderNotification notification )
{
foreach (Item item in notification.shoppingcart.items)
{
XmlNode[] node = item.merchantprivateitemdata.Any;
Product product = DataAccessContext.ProductRepository.GetOne(
StoreContext.Culture,
item.merchantitemid,
new StoreRetriever().GetCurrentStoreID()
);
if (node.Length <= 1)
{
StoreContext.ShoppingCart.AddItem(
product, item.quantity );
}
else
{
// Creating option item from google checkout is not details of option type is text.
OptionItemValueCollection optionCollection = OptionItemValueCollection.Null;
if (!String.IsNullOrEmpty( node[1].InnerText ))
optionCollection = new OptionItemValueCollection(
StoreContext.Culture, node[1].InnerText, item.merchantitemid );
StoreContext.ShoppingCart.AddItem(
product, item.quantity, optionCollection );
}
}
Log.Debug( "SetShippingDetails" );
Vevo.Base.Domain.Address address = new Vevo.Base.Domain.Address(
notification.buyershippingaddress.contactname,
"",
notification.buyerbillingaddress.companyname,
notification.buyershippingaddress.address1,
notification.buyershippingaddress.address2,
notification.buyershippingaddress.city,
notification.buyershippingaddress.region,
notification.buyershippingaddress.postalcode,
notification.buyershippingaddress.countrycode,
notification.buyerbillingaddress.phone,
notification.buyerbillingaddress.fax );
StoreContext.CheckoutDetails.ShippingAddress = new ShippingAddress( address, false );
Log.Debug( "Set Shipping " );
MerchantCalculatedShippingAdjustment shippingAdjust = (MerchantCalculatedShippingAdjustment) notification.orderadjustment.shipping.Item;
string shippingID = DataAccessContext.ShippingOptionRepository.GetIDFromName( shippingAdjust.shippingname );
ShippingMethod shipping = ShippingFactory.CreateShipping( shippingID );
shipping.Name = shippingAdjust.shippingname;
StoreContext.CheckoutDetails.SetShipping( shipping );
StoreContext.CheckoutDetails.SetCustomerComments( "" );
PaymentOption paymentOption = DataAccessContext.PaymentOptionRepository.GetOne(
StoreContext.Culture, PaymentOption.GoogleCheckout );
StoreContext.CheckoutDetails.SetPaymentMethod(
paymentOption.CreatePaymentMethod() );
Log.Debug( "Set Coupon ID" );
StoreContext.CheckoutDetails.SetCouponID( GetCouponCode( notification.orderadjustment.merchantcodes.Items ) );
Log.Debug( "Set Gift" );
string giftID = GetGiftCertificateCode( notification.orderadjustment.merchantcodes.Items );
if (giftID != String.Empty)
StoreContext.CheckoutDetails.SetGiftCertificate( giftID );
StoreContext.CheckoutDetails.SetGiftRegistryID( "0" );
StoreContext.CheckoutDetails.SetShowShippingAddress( true );
}
private void PaymentLogUpdateNewOrderNotification( NewOrderNotification notification )
{
string paymentResponse = "new-order-notification :: ";
paymentResponse += String.Format( "Buyerbillingaddress: {0},", notification.buyerbillingaddress );
paymentResponse += String.Format( "BuyerID: {0},", notification.buyerid );
paymentResponse += String.Format( "Buyermarketingpreferences: {0},",
notification.buyermarketingpreferences );
paymentResponse += String.Format( "Buyershippingaddress: {0},", notification.buyershippingaddress );
paymentResponse += String.Format( "Financialorderstate: {0},", notification.financialorderstate );
paymentResponse += String.Format( "Fulfillmentorderstate: {0},", notification.fulfillmentorderstate );
paymentResponse += String.Format( "Orderadjustment: {0},", notification.orderadjustment );
paymentResponse += String.Format( "Ordertotal: {0},", notification.ordertotal );
paymentResponse += String.Format( "Serialnumber: {0},", notification.serialnumber );
paymentResponse += String.Format( "ShoppingCart: {0},", notification.shoppingcart );
paymentResponse += String.Format( "Timestamp: {0},", notification.timestamp );
Log.Debug( "Start Save Payment Log" );
PaymentLog paymentLog = new PaymentLog();
paymentLog.OrderID = notification.googleordernumber;
paymentLog.PaymentResponse = paymentResponse;
paymentLog.PaymentGateway = GetPaymentName();
paymentLog.PaymentType = String.Empty;
DataAccessContext.PaymentLogRepository.Save( paymentLog );
Log.Debug( "End Save Payment Log" );
}
private void PaymentLogUpdateRiskInformation( RiskInformationNotification notification )
{
string paymentResponse = "risk-information-notification :: ";
paymentResponse += "AvsResponse: " + notification.riskinformation.avsresponse + ",";
paymentResponse += "BuyerAccountage: " + notification.riskinformation.buyeraccountage.ToString() + ",";
paymentResponse += "CvnResponse: " + notification.riskinformation.cvnresponse + ",";
paymentResponse += "EligibleForProtection: " + notification.riskinformation.eligibleforprotection + ",";
paymentResponse += "IP Address: " + notification.riskinformation.ipaddress + ",";
paymentResponse += "PartialNumber: " + notification.riskinformation.partialccnumber;
Log.Debug( "Start Create Log" );
string orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( notification.googleordernumber );
PaymentLog paymentLog = new PaymentLog();
paymentLog.OrderID = orderID;
paymentLog.PaymentResponse = paymentResponse;
paymentLog.PaymentGateway = GetPaymentName();
paymentLog.PaymentType = String.Empty;
DataAccessContext.PaymentLogRepository.Save( paymentLog );
Log.Debug( "End Create Log" );
}
private void VerifyAvsAndCvv( RiskInformationNotification notification )
{
string orderID
= DataAccessContext.OrderRepository.GetOrderIDByGatewayID( notification.googleordernumber );
Order order = DataAccessContext.OrderRepository.GetOne( orderID );
string avs = notification.riskinformation.avsresponse.ToUpper();
string cvv = notification.riskinformation.cvnresponse.ToUpper();
switch (avs)
{
case "Y":
{
order.AvsZipStatus = "Pass";
order.AvsAddrStatus = "Pass";
break;
}
case "P":
{
order.AvsZipStatus = "Pass";
order.AvsAddrStatus = "Fail";
break;
}
case "A":
{
order.AvsZipStatus = "Fail";
order.AvsAddrStatus = "Pass";
break;
}
case "N":
{
order.AvsZipStatus = "Fail";
order.AvsAddrStatus = "Fail";
break;
}
default:
{
order.AvsZipStatus = "Unavailable";
order.AvsAddrStatus = "Unavailable";
break;
}
}
switch (cvv)
{
case "M":
{
order.CvvStatus = "Pass";
break;
}
case "N":
{
order.CvvStatus = "Fail";
break;
}
case "E":
{
order.CvvStatus = "Fail";
break;
}
default:
{
order.CvvStatus = "Unavailable";
break;
}
}
DataAccessContext.OrderRepository.Save( order );
}
private void PaymentLogUpdateOrderStateChange( OrderStateChangeNotification notification )
{
string paymentResponse = "order-state-change-notification :: ";
paymentResponse += "NewFinancialOrderState :" + notification.newfinancialorderstate.ToString() + ",";
paymentResponse += "NewFulFillmentOrderState :" + notification.newfulfillmentorderstate.ToString() + ",";
paymentResponse += "PreviousFinancialOrderState :" +
notification.previousfinancialorderstate.ToString() + ",";
paymentResponse += "PreviousFulFillmentOrderState :" +
notification.previousfulfillmentorderstate.ToString() + ",";
paymentResponse += "Reason :" + notification.reason + ",";
paymentResponse += "SerialNumber :" + notification.serialnumber + ",";
paymentResponse += "TimeStamp :" + notification.timestamp.ToString();
Log.Debug( "-*************** Check PaymentLog **************-" );
Log.Debug( "notification.googleordernumber = " + notification.googleordernumber );
Log.Debug( "paymentResponse = " + paymentResponse );
Log.Debug( "GetPaymentName = " + GetPaymentName() );
string orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( notification.googleordernumber );
PaymentLog paymentLog = new PaymentLog();
paymentLog.OrderID = orderID;
paymentLog.PaymentResponse = paymentResponse;
paymentLog.PaymentGateway = GetPaymentName();
paymentLog.PaymentType = String.Empty;
DataAccessContext.PaymentLogRepository.Save( paymentLog );
Log.Debug( "-************* End Check PaymentLog ************-" );
}
private void PaymentLogUpdateRefundAmount( RefundAmountNotification notification )
{
string paymentResponse = "refund-amount-notification :: ";
paymentResponse += "latestrefundamount :" + notification.latestrefundamount.Value.ToString() + ",";
paymentResponse += "serialnumber :" + notification.serialnumber + ",";
paymentResponse += "timestamp :" + notification.timestamp.ToString() + ",";
paymentResponse += "totalrefundamount :" + notification.totalrefundamount.Value.ToString();
string orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( notification.googleordernumber );
PaymentLog paymentLog = new PaymentLog();
paymentLog.OrderID = orderID;
paymentLog.PaymentResponse = paymentResponse;
paymentLog.PaymentGateway = GetPaymentName();
paymentLog.PaymentType = String.Empty;
DataAccessContext.PaymentLogRepository.Save( paymentLog );
}
private void PaymentLogUpdateChargeback( ChargebackAmountNotification notification )
{
string paymentResponse = "chargeback-amount-notification :: ";
paymentResponse += "latestchargebackamount :" + notification.latestchargebackamount.Value.ToString();
string orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( notification.googleordernumber );
PaymentLog paymentLog = new PaymentLog();
paymentLog.OrderID = orderID;
paymentLog.PaymentResponse = paymentResponse;
paymentLog.PaymentGateway = GetPaymentName();
paymentLog.PaymentType = String.Empty;
DataAccessContext.PaymentLogRepository.Save( paymentLog );
}
private void GoogleChargeOrder( string gatewayOrderID )
{
string orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( gatewayOrderID );
Order order = DataAccessContext.OrderRepository.GetOne( orderID );
Log.Debug( "Start Auto Charge for Google" );
GCheckout.OrderProcessing.ChargeOrderRequest Req =
new GCheckout.OrderProcessing.ChargeOrderRequest(
WebConfiguration.GoogleMerchantID,
WebConfiguration.GoogleMerchantKey,
WebConfiguration.GoogleEnvironment,
order.GatewayOrderID,
DataAccessContext.Configurations.GetValue( "PaymentCurrency" ),
order.Total );
GCheckoutResponse R = Req.Send();
if (!R.IsGood)
{
Log.Debug( "Can not charge - Response: " + R.ResponseXml + "\n" );
Log.Debug( "Can not charge - RedirectUrl: " + R.RedirectUrl + "\n" );
Log.Debug( "Can not charge - IsGood: " + R.IsGood + "\n" );
Log.Debug( "Can not charge - ErrorMessage: " + R.ErrorMessage + "\n" );
SendChargeFailureEmail( order );
}
Log.Debug( "End Auto Charge for Google" );
}
private void PaymentLogChargeAmountUpdate( ChargeAmountNotification N4 )
{
string paymentResponse = "charge-amount-notification :: ";
paymentResponse += "LatestChargeAmount :" + N4.latestchargeamount.Value.ToString() + ",";
paymentResponse += "SerialNumber :" + N4.serialnumber + ",";
paymentResponse += "TimeStamp :" + N4.timestamp.ToString() + ",";
paymentResponse += "TotalChargeAmount :" + N4.totalchargeamount.Value.ToString();
string orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( N4.googleordernumber );
PaymentLog paymentLog = new PaymentLog();
paymentLog.OrderID = orderID;
paymentLog.PaymentResponse = paymentResponse;
paymentLog.PaymentGateway = GetPaymentName();
paymentLog.PaymentType = String.Empty;
DataAccessContext.PaymentLogRepository.Save( paymentLog );
}
private void SendErrorEmail( OrderStateChangeNotification notification )
{
string orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( notification.googleordernumber );
Order order = DataAccessContext.OrderRepository.GetOne( orderID );
WebUtilities.SendMail(
NamedConfig.AutoSenderEmail,
DataAccessContext.Configurations.GetValue( "ErrorLogEmail" ),
"Failed processing order ID " + order.OrderID,
"There is an error while processing this order.\n" +
" Shopping Cart Order ID: " + order.OrderID + "\n" +
" Google Order ID: " + order.GatewayOrderID + "\n" +
" Financial Order State: " + notification.newfinancialorderstate.ToString() + "\n" +
" Fulfillment Order State: " + notification.newfulfillmentorderstate.ToString() + "\n" +
"\nPlease verify this order in your Google Checkout Merchant account.\n" );
}
private Vevo.Base.Domain.Address CreateBuyerBillingAddress( NewOrderNotification n1 )
{
return new Vevo.Base.Domain.Address(
ConvertToString( n1.buyerbillingaddress.contactname ),
" ",
String.Empty,
ConvertToString( n1.buyerbillingaddress.address1 ),
ConvertToString( n1.buyerbillingaddress.address2 ),
ConvertToString( n1.buyerbillingaddress.city ),
ConvertToString( n1.buyerbillingaddress.region ),
ConvertToString( n1.buyerbillingaddress.postalcode ),
ConvertToString( n1.buyerbillingaddress.countrycode ),
String.Empty,
String.Empty );
}
#endregion
#region Protected
protected string SerialNumber
{
get { return _serialNumber; }
}
protected void Page_PreInit( object sender, EventArgs e )
{
Page.Theme = String.Empty;
}
protected void Page_Load( object sender, EventArgs e )
{
// Extract the XML from the request.
Stream RequestStream = Request.InputStream;
StreamReader RequestStreamReader = new StreamReader( RequestStream );
string RequestXml = RequestStreamReader.ReadToEnd();
RequestStream.Close();
Log.Debug( "Request XML:\n" + RequestXml );
string gatewayOrderID = "";
string orderID;
OrderNotifyService orderBusiness;
try
{
// Act on the XML.
switch (EncodeHelper.GetTopElement( RequestXml ))
{
case "new-order-notification":
Log.Debug( "Start new-order-notification" );
NewOrderNotification N1 =
(NewOrderNotification) EncodeHelper.Deserialize( RequestXml,
typeof( NewOrderNotification ) );
string OrderNumber1 = N1.googleordernumber;
PaymentLogUpdateNewOrderNotification( N1 );
_serialNumber = N1.serialnumber;
Log.Debug( "-********************- Check DataAccessContext.GetOrderIDByGateWayID Data -**********************-" );
Log.Debug( "GetOrderIDByGateWayID ( "
+ OrderNumber1 + " ) = " + DataAccessContext.OrderRepository.GetOrderIDByGatewayID( OrderNumber1 ) );
Log.Debug( "-********************- END Check DataAccessContext.GetOrderIDByGateWayID Data -**********************-" );
if (DataAccessContext.OrderRepository.GetOrderIDByGatewayID( OrderNumber1 ) == "0")
{
BuildShoppingCart( RequestXml, N1 );
Log.Debug( "Start converting to order" );
OrderCreateService orderCreateService = new OrderCreateService(
StoreContext.ShoppingCart,
StoreContext.CheckoutDetails,
StoreContext.Culture,
StoreContext.Currency,
AffiliateHelper.GetAffiliateCode(),
WebUtilities.GetVisitorIP() );
string storeID = EncodeHelper.GetElementValue( RequestXml, "StoreID" );
DataAccessContext.SetStoreRetriever( new StoreRetriever( storeID ) );
OrderAmount orderAmount = orderCreateService.GetOrderAmount( Customer.Null )
.Add( CartItemPromotion.CalculatePromotionShippingAndTax(
StoreContext.CheckoutDetails,
StoreContext.ShoppingCart.SeparateCartItemGroups(),
Customer.Null ) );
Order order = orderCreateService.PlaceOrderAnonymous(orderAmount,
SystemConst.UnknownUser,
CreateBuyerBillingAddress( N1 ),
ConvertToString( N1.buyerbillingaddress.email ), DataAccessContext.StoreRetriever, StoreContext.Culture );
AffiliateOrder affiliateorder = new AffiliateOrder();
affiliateorder.AffiliateCode = AffiliateHelper.GetAffiliateCode();
affiliateorder.CreateAffiliateOrder( order.OrderID, orderAmount.Subtotal, orderAmount.Discount );
orderBusiness = new OrderNotifyService( order.OrderID );
Log.Debug( "End converting to order" );
Log.Debug( "Start sending order email" );
orderBusiness.SendOrderEmail();
Log.Debug( "End sending order email" );
Order orderDetail = DataAccessContext.OrderRepository.GetOne( order.OrderID );
orderDetail.GatewayOrderID = OrderNumber1;
Log.Debug( "OrderDetail.GatewayOrderID = " + OrderNumber1 );
Log.Debug( "Start Save Order Detail" );
DataAccessContext.OrderRepository.Save( orderDetail );
Log.Debug( "End Save Order Detail" );
DataAccessContext.SetStoreRetriever( new StoreRetriever() );
}
else
{
Order orderDetail = DataAccessContext.OrderRepository.GetOne(
DataAccessContext.OrderRepository.GetOrderIDByGatewayID( OrderNumber1 ) );
Log.Debug( "-**************************- start Check Error -**************************-" );
Log.Debug( "N1.googleOrderNumber = " + N1.googleordernumber );
Log.Debug( "OrderNumber1 = " + OrderNumber1 );
Log.Debug( "N1.buyerbillingaddress.contactname = " + ConvertToString( N1.buyerbillingaddress.contactname ) );
Log.Debug( "N1.buyerbillingaddress.address1 = " + ConvertToString( N1.buyerbillingaddress.address1 ) );
Log.Debug( "N1.buyerbillingaddress.city = " + ConvertToString( N1.buyerbillingaddress.city ) );
Log.Debug( "N1.buyerbillingaddress.region = " + ConvertToString( N1.buyerbillingaddress.contactname ) );
Log.Debug( "N1.buyerbillingaddress.postalcode = " + ConvertToString( N1.buyerbillingaddress.postalcode ) );
Log.Debug( "orderDetail.Billing.Company = " + orderDetail.Billing.Company );
Log.Debug( "orderDetail.Billing.Country = " + orderDetail.Billing.Country );
Log.Debug( "orderDetail.Billing.Phone = " + orderDetail.Billing.Phone );
Log.Debug( "orderDetail.Billing.Fax = " + orderDetail.Billing.Fax );
Log.Debug( "-**************************- End Check Error -**************************-" );
orderDetail.Billing = new Vevo.Base.Domain.Address( ConvertToString( N1.buyerbillingaddress.contactname ),
String.Empty, orderDetail.Billing.Company,
ConvertToString( N1.buyerbillingaddress.address1 ),
ConvertToString( N1.buyerbillingaddress.address2 ),
ConvertToString( N1.buyerbillingaddress.city ),
ConvertToString( N1.buyerbillingaddress.region ),
ConvertToString( N1.buyerbillingaddress.postalcode ),
orderDetail.Billing.Country, orderDetail.Billing.Phone,
orderDetail.Billing.Fax );
orderDetail.Email = ConvertToString( N1.buyerbillingaddress.email );
DataAccessContext.OrderRepository.Save( orderDetail );
}
Log.Debug( "End new-order-notification" );
break;
case "risk-information-notification":
Log.Debug( "risk-information-notification" );
RiskInformationNotification N2 = (RiskInformationNotification) EncodeHelper.Deserialize(
RequestXml, typeof( RiskInformationNotification ) );
// This notification tells us that Google has authorized the order
// and it has passed the fraud check.
// Use the data below to determine if you want to accept the order, then start processing it.
gatewayOrderID = N2.googleordernumber;
_serialNumber = N2.serialnumber;
PaymentLogUpdateRiskInformation( N2 );
VerifyAvsAndCvv( N2 );
break;
case "order-state-change-notification":
Log.Debug( "Start order-state-change-notification" );
OrderStateChangeNotification N3 = (OrderStateChangeNotification) EncodeHelper.Deserialize(
RequestXml, typeof( OrderStateChangeNotification ) );
_serialNumber = N3.serialnumber;
PaymentLogUpdateOrderStateChange( N3 );
if (N3.newfinancialorderstate != N3.previousfinancialorderstate)
{
Order orderDetail = DataAccessContext.OrderRepository.GetOne(
DataAccessContext.OrderRepository.GetOrderIDByGatewayID( N3.googleordernumber ) );
orderDetail.GatewayPaymentStatus = N3.newfinancialorderstate.ToString();
DataAccessContext.OrderRepository.Save( orderDetail );
switch (N3.newfinancialorderstate)
{
case FinancialOrderState.PAYMENT_DECLINED:
case FinancialOrderState.CANCELLED_BY_GOOGLE:
SendErrorEmail( N3 );
break;
case FinancialOrderState.CHARGEABLE:
if (DataAccessContext.Configurations.GetBoolValueNoThrow( "GCheckoutChargeAuto" ))
{
GoogleChargeOrder( N3.googleordernumber );
}
break;
}
}
Log.Debug( "End order-state-change-notification" );
break;
case "charge-amount-notification":
Log.Debug( "Start charge-amount-notification" );
ChargeAmountNotification N4 = (ChargeAmountNotification) EncodeHelper.Deserialize( RequestXml,
typeof( ChargeAmountNotification ) );
// Google has successfully charged the customer's credit card.
gatewayOrderID = N4.googleordernumber;
_serialNumber = N4.serialnumber;
PaymentLogChargeAmountUpdate( N4 );
orderID = DataAccessContext.OrderRepository.GetOrderIDByGatewayID( gatewayOrderID );
orderBusiness = new OrderNotifyService( orderID );
orderBusiness.ProcessPaymentComplete();
Log.Debug( "End charge-amount-notification" );
break;
case "refund-amount-notification":
Log.Debug( "Start refund-amount-notification" );
RefundAmountNotification N5 =
(RefundAmountNotification) EncodeHelper.Deserialize(
RequestXml,
typeof( RefundAmountNotification ) );
// Google has successfully refunded the customer's credit card.
gatewayOrderID = N5.googleordernumber;
_serialNumber = N5.serialnumber;
//decimal RefundedAmount = N5.latestrefundamount.Value;
PaymentLogUpdateRefundAmount( N5 );
Order orderDetails = DataAccessContext.OrderRepository.GetOne(
DataAccessContext.OrderRepository.GetOrderIDByGatewayID( gatewayOrderID ) );
orderDetails.PaymentComplete = false;
DataAccessContext.OrderRepository.Save( orderDetails );
Log.Debug( "End refund-amount-notification" );
break;
case "chargeback-amount-notification":
Log.Debug( "Start chargeback-amount-notification" );
ChargebackAmountNotification N6 = (ChargebackAmountNotification) EncodeHelper.Deserialize(
RequestXml, typeof( ChargebackAmountNotification ) );
// A customer initiated a chargeback with his credit card company to get her money back.
gatewayOrderID = N6.googleordernumber;
_serialNumber = N6.serialnumber;
decimal ChargebackAmount = N6.latestchargebackamount.Value;
PaymentLogUpdateChargeback( N6 );
orderDetails = DataAccessContext.OrderRepository.GetOne(
DataAccessContext.OrderRepository.GetOrderIDByGatewayID( gatewayOrderID ) );
orderDetails.GatewayPaymentStatus = "ChargeBack";
DataAccessContext.OrderRepository.Save( orderDetails );
Log.Debug( "End chargeback-amount-notification" );
break;
default:
break;
}
}
catch (Exception ex)
{
DataAccessContext.SetStoreRetriever( new StoreRetriever() );
Log.Debug( ex.ToString() );
}
}
#endregion
#region Public Properties
public override string StyleSheetTheme
{
get
{
return String.Empty;
}
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for AccountOperations.
/// </summary>
public static partial class AccountOperationsExtensions
{
/// <summary>
/// Tests whether the specified Azure Storage account is linked to the given Data
/// Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// Azure storage account existence.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure Storage account for which to test for existence.
/// </param>
public static bool StorageAccountExists(this IAccountOperations operations, string resourceGroupName, string accountName, string storageAccountName)
{
return Task.Factory.StartNew(s => ((IAccountOperations)s).StorageAccountExistsAsync(resourceGroupName, accountName, storageAccountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Tests whether the specified Azure Storage account is linked to the given Data
/// Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// Azure storage account existence.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure Storage account for which to test for existence.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool> StorageAccountExistsAsync(this IAccountOperations operations, string resourceGroupName, string accountName, string storageAccountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StorageAccountExistsWithHttpMessagesAsync(resourceGroupName, accountName, storageAccountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Tests the existence of the specified Azure Storage container associated with the
/// given Data Lake Analytics and Azure Storage accounts.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to retrieve
/// blob container.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure storage account from which to test the
/// blob container's existence.
/// </param>
/// <param name='containerName'>
/// The name of the Azure storage container to test for existence.
/// </param>
public static bool StorageContainerExists(this IAccountOperations operations, string resourceGroupName, string accountName, string storageAccountName, string containerName)
{
return Task.Factory.StartNew(s => ((IAccountOperations)s).StorageContainerExistsAsync(resourceGroupName, accountName, storageAccountName, containerName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Tests the existence of the specified Azure Storage container associated with the
/// given Data Lake Analytics and Azure Storage accounts.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to retrieve
/// blob container.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure storage account from which to test the
/// blob container's existence.
/// </param>
/// <param name='containerName'>
/// The name of the Azure storage container to test for existence.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool> StorageContainerExistsAsync(this IAccountOperations operations, string resourceGroupName, string accountName, string storageAccountName, string containerName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StorageContainerExistsWithHttpMessagesAsync(resourceGroupName, accountName, storageAccountName, containerName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Tests whether the specified Data Lake Store account is linked to the
/// specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// the existence of the Data Lake Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to test for existence
/// </param>
public static bool DataLakeStoreAccountExists(this IAccountOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName)
{
return Task.Factory.StartNew(s => ((IAccountOperations)s).DataLakeStoreAccountExistsAsync(resourceGroupName, accountName, dataLakeStoreAccountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Tests whether the specified Data Lake Store account is linked to the
/// specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// the existence of the Data Lake Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to test for existence
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool> DataLakeStoreAccountExistsAsync(this IAccountOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DataLakeStoreAccountExistsWithHttpMessagesAsync(resourceGroupName, accountName, dataLakeStoreAccountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Tests for the existence of the specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to test existence of.
/// </param>
public static bool Exists(this IAccountOperations operations, string resourceGroupName, string accountName)
{
return Task.Factory.StartNew(s => ((IAccountOperations)s).ExistsAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Tests for the existence of the specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to test existence of.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool> ExistsAsync(this IAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ExistsWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
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 WebApiEfDemo.Areas.HelpPage.ModelDescriptions;
using WebApiEfDemo.Areas.HelpPage.Models;
namespace WebApiEfDemo.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);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void XorDouble()
{
var test = new SimpleBinaryOpTest__XorDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__XorDouble testClass)
{
var result = Avx.Xor(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__XorDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.Xor(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__XorDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleBinaryOpTest__XorDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Xor(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Xor(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Xor(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
{
var result = Avx.Xor(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__XorDouble();
var result = Avx.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__XorDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
{
var result = Avx.Xor(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.Xor(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Xor(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((BitConverter.DoubleToInt64Bits(left[0]) ^ BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((BitConverter.DoubleToInt64Bits(left[i]) ^ BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Xor)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
namespace IronPython.Runtime {
/// <summary>
/// Summary description for ConstantValue.
/// </summary>
public static class LiteralParser {
public static string ParseString(string text, bool isRaw) {
return ParseString(text.ToCharArray(), 0, text.Length, isRaw, false);
}
public static string ParseString(char[] text, int start, int length, bool isRaw, bool normalizeLineEndings) {
Debug.Assert(text != null);
if (isRaw && !normalizeLineEndings) return new String(text, start, length);
StringBuilder buf = null;
int i = start;
int l = start + length;
int val;
while (i < l) {
char ch = text[i++];
if (ch == '\\') {
if (buf == null) {
buf = new StringBuilder(length);
buf.Append(text, start, i - start - 1);
}
if (i >= l) {
if (isRaw) {
buf.Append('\\');
break;
} else {
throw PythonOps.ValueError("Trailing \\ in string");
}
}
ch = text[i++];
if (ch == 'u' || ch == 'U') {
int len = (ch == 'u') ? 4 : 8;
int max = 16;
if (!isRaw) {
if (TryParseInt(text, i, len, max, out val)) {
if (val < 0 || val > 0x10ffff) {
throw PythonOps.StandardError(@"'unicodeescape' codec can't decode bytes in position {0}: illegal Unicode character", i);
}
if (val < 0x010000) {
buf.Append((char)val);
} else {
#if !SILVERLIGHT
buf.Append(char.ConvertFromUtf32(val));
#else
throw PythonOps.StandardError(@"'unicodeescape' codec can't decode bytes in position {0}: Unicode character out of range (Silverlight)", i);
#endif
}
i += len;
} else {
throw PythonOps.UnicodeEncodeError(@"'unicodeescape' codec can't decode bytes in position {0}: truncated \uXXXX escape", i);
}
} else {
buf.Append('\\');
buf.Append(ch);
}
} else {
if (isRaw) {
buf.Append('\\');
buf.Append(ch);
continue;
}
switch (ch) {
case 'a': buf.Append('\a'); continue;
case 'b': buf.Append('\b'); continue;
case 'f': buf.Append('\f'); continue;
case 'n': buf.Append('\n'); continue;
case 'r': buf.Append('\r'); continue;
case 't': buf.Append('\t'); continue;
case 'v': buf.Append('\v'); continue;
case '\\': buf.Append('\\'); continue;
case '\'': buf.Append('\''); continue;
case '\"': buf.Append('\"'); continue;
case '\r': if (i < l && text[i] == '\n') i++; continue;
case '\n': continue;
#if FEATURE_COMPRESSION
case 'N': {
if (i < l && text[i] == '{') {
i++;
StringBuilder namebuf = new StringBuilder();
bool namecomplete = false;
while (i < l) {
char namech = text[i++];
if (namech != '}') {
namebuf.Append(namech);
} else {
namecomplete = true;
break;
}
}
if(!namecomplete || namebuf.Length == 0)
throw PythonOps.StandardError(@"'unicodeescape' codec can't decode bytes in position {0}: malformed \N character escape", i);
try {
string uval = IronPython.Modules.unicodedata.lookup(namebuf.ToString());
buf.Append(uval);
} catch(KeyNotFoundException) {
throw PythonOps.StandardError(@"'unicodeescape' codec can't decode bytes in position {0}: unknown Unicode character name", i);
}
} else {
throw PythonOps.StandardError(@"'unicodeescape' codec can't decode bytes in position {0}: malformed \N character escape", i);
}
}
continue;
#endif
case 'x': //hex
if (!TryParseInt(text, i, 2, 16, out val)) {
goto default;
}
buf.Append((char)val);
i += 2;
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': {
int onechar;
val = ch - '0';
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
}
}
}
buf.Append((char)val);
continue;
default:
buf.Append("\\");
buf.Append(ch);
continue;
}
}
} else if (ch == '\r' && normalizeLineEndings) {
if (buf == null) {
buf = new StringBuilder(length);
buf.Append(text, start, i - start - 1);
}
// normalize line endings
if (i < text.Length && text[i] == '\n') {
i++;
}
buf.Append('\n');
} else if (buf != null) {
buf.Append(ch);
}
}
if (buf != null) {
return buf.ToString();
}
return new String(text, start, length);
}
internal static List<byte> ParseBytes(char[] text, int start, int length, bool isRaw, bool normalizeLineEndings) {
Debug.Assert(text != null);
List<byte> buf = new List<byte>(length);
int i = start;
int l = start + length;
int val;
while (i < l) {
char ch = text[i++];
if (!isRaw && ch == '\\') {
if (i >= l) {
throw PythonOps.ValueError("Trailing \\ in string");
}
ch = text[i++];
switch (ch) {
case 'a': buf.Add((byte)'\a'); continue;
case 'b': buf.Add((byte)'\b'); continue;
case 'f': buf.Add((byte)'\f'); continue;
case 'n': buf.Add((byte)'\n'); continue;
case 'r': buf.Add((byte)'\r'); continue;
case 't': buf.Add((byte)'\t'); continue;
case 'v': buf.Add((byte)'\v'); continue;
case '\\': buf.Add((byte)'\\'); continue;
case '\'': buf.Add((byte)'\''); continue;
case '\"': buf.Add((byte)'\"'); continue;
case '\r': if (i < l && text[i] == '\n') i++; continue;
case '\n': continue;
case 'x': //hex
if (!TryParseInt(text, i, 2, 16, out val)) {
goto default;
}
buf.Add((byte)val);
i += 2;
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': {
int onechar;
val = ch - '0';
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
if (i < l && HexValue(text[i], out onechar) && onechar < 8) {
val = val * 8 + onechar;
i++;
}
}
}
buf.Add((byte)val);
continue;
default:
buf.Add((byte)'\\');
buf.Add((byte)ch);
continue;
}
} else if (ch == '\r' && normalizeLineEndings) {
// normalize line endings
if (i < text.Length && text[i] == '\n') {
i++;
}
buf.Add((byte)'\n');
} else {
buf.Add((byte)ch);
}
}
return buf;
}
private static bool HexValue(char ch, out int value) {
switch (ch) {
case '0':
case '\x660': value = 0; break;
case '1':
case '\x661': value = 1; break;
case '2':
case '\x662': value = 2; break;
case '3':
case '\x663': value = 3; break;
case '4':
case '\x664': value = 4; break;
case '5':
case '\x665': value = 5; break;
case '6':
case '\x666': value = 6; break;
case '7':
case '\x667': value = 7; break;
case '8':
case '\x668': value = 8; break;
case '9':
case '\x669': value = 9; break;
default:
if (ch >= 'a' && ch <= 'z') {
value = ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'Z') {
value = ch - 'A' + 10;
} else {
value = -1;
return false;
}
break;
}
return true;
}
private static int HexValue(char ch) {
int value;
if (!HexValue(ch, out value)) {
throw new ValueErrorException("bad char for integer value: " + ch);
}
return value;
}
private static int CharValue(char ch, int b) {
int val = HexValue(ch);
if (val >= b) {
throw new ValueErrorException(String.Format("bad char for the integer value: '{0}' (base {1})", ch, b));
}
return val;
}
private static bool ParseInt(string text, int b, out int ret) {
ret = 0;
long m = 1;
for (int i = text.Length - 1; i >= 0; i--) {
// avoid the exception here. Not only is throwing it expensive,
// but loading the resources for it is also expensive
long lret = (long)ret + m * CharValue(text[i], b);
if (Int32.MinValue <= lret && lret <= Int32.MaxValue) {
ret = (int)lret;
} else {
return false;
}
m *= b;
if (Int32.MinValue > m || m > Int32.MaxValue) {
return false;
}
}
return true;
}
private static bool TryParseInt(char[] text, int start, int length, int b, out int value) {
value = 0;
if (start + length > text.Length) {
return false;
}
for (int i = start, end = start + length; i < end; i++) {
int onechar;
if (HexValue(text[i], out onechar) && onechar < b) {
value = value * b + onechar;
} else {
return false;
}
}
return true;
}
public static object ParseInteger(string text, int b) {
Debug.Assert(b != 0);
int iret;
if (!ParseInt(text, b, out iret)) {
BigInteger ret = ParseBigInteger(text, b);
if (!ret.AsInt32(out iret)) {
return ret;
}
}
return ScriptingRuntimeHelpers.Int32ToObject(iret);
}
public static object ParseIntegerSign(string text, int b) {
int start = 0, end = text.Length, saveb = b;
short sign = 1;
if (b < 0 || b == 1 || b > 36) {
throw new ValueErrorException("base must be >= 2 and <= 36");
}
ParseIntegerStart(text, ref b, ref start, end, ref sign);
int ret = 0;
try {
int saveStart = start;
for (; ; ) {
int digit;
if (start >= end) {
if (saveStart == start) {
throw new ValueErrorException("Invalid integer literal");
}
break;
}
if (!HexValue(text[start], out digit)) break;
if (!(digit < b)) {
if (text[start] == 'l' || text[start] == 'L') {
break;
}
throw new ValueErrorException("Invalid integer literal");
}
checked {
// include sign here so that System.Int32.MinValue won't overflow
ret = ret * b + sign * digit;
}
start++;
}
} catch (OverflowException) {
return ParseBigIntegerSign(text, saveb);
}
ParseIntegerEnd(text, start, end);
return ScriptingRuntimeHelpers.Int32ToObject(ret);
}
private static void ParseIntegerStart(string text, ref int b, ref int start, int end, ref short sign) {
// Skip whitespace
while (start < end && Char.IsWhiteSpace(text, start)) start++;
// Sign?
if (start < end) {
switch (text[start]) {
case '-':
sign = -1;
goto case '+';
case '+':
start++;
break;
}
}
// Skip whitespace
while (start < end && Char.IsWhiteSpace(text, start)) start++;
// Determine base
if (b == 0) {
if (start < end && text[start] == '0') {
// Hex, oct, or bin
if (++start < end) {
switch(text[start]) {
case 'x':
case 'X':
start++;
b = 16;
break;
case 'o':
case 'O':
b = 8;
start++;
break;
case 'b':
case 'B':
start++;
b = 2;
break;
}
}
if (b == 0) {
// Keep the leading zero
start--;
b = 8;
}
} else {
b = 10;
}
}
}
private static void ParseIntegerEnd(string text, int start, int end) {
// Skip whitespace
while (start < end && Char.IsWhiteSpace(text, start)) start++;
if (start < end) {
throw new ValueErrorException("invalid integer number literal");
}
}
public static BigInteger ParseBigInteger(string text, int b) {
Debug.Assert(b != 0);
BigInteger ret = BigInteger.Zero;
BigInteger m = BigInteger.One;
int i = text.Length - 1;
if (text[i] == 'l' || text[i] == 'L') i -= 1;
int groupMax = 7;
if (b <= 10) groupMax = 9;// 2 147 483 647
while (i >= 0) {
// extract digits in a batch
int smallMultiplier = 1;
uint uval = 0;
for (int j = 0; j < groupMax && i >= 0; j++) {
uval = (uint)(CharValue(text[i--], b) * smallMultiplier + uval);
smallMultiplier *= b;
}
// this is more generous than needed
ret += m * (BigInteger)uval;
if (i >= 0) m = m * (smallMultiplier);
}
return ret;
}
public static BigInteger ParseBigIntegerSign(string text, int b) {
int start = 0, end = text.Length;
short sign = 1;
if (b < 0 || b == 1 || b > 36) {
throw new ValueErrorException("base must be >= 2 and <= 36");
}
ParseIntegerStart(text, ref b, ref start, end, ref sign);
BigInteger ret = BigInteger.Zero;
int saveStart = start;
for (; ; ) {
int digit;
if (start >= end) {
if (start == saveStart) {
throw new ValueErrorException("Invalid integer literal");
}
break;
}
if (!HexValue(text[start], out digit)) break;
if (!(digit < b)) {
if (text[start] == 'l' || text[start] == 'L') {
break;
}
throw new ValueErrorException("Invalid integer literal");
}
ret = ret * b + digit;
start++;
}
if (start < end && (text[start] == 'l' || text[start] == 'L')) {
start++;
}
ParseIntegerEnd(text, start, end);
return sign < 0 ? -ret : ret;
}
public static double ParseFloat(string text) {
try {
//
// Strings that end with '\0' is the specific case that CLR libraries allow,
// however Python doesn't. Since we use CLR floating point number parser,
// we must check explicitly for the strings that end with '\0'
//
if (text != null && text.Length > 0 && text[text.Length - 1] == '\0') {
throw PythonOps.ValueError("null byte in float literal");
}
return ParseFloatNoCatch(text);
} catch (OverflowException) {
return text.lstrip().StartsWith("-") ? Double.NegativeInfinity : Double.PositiveInfinity;
}
}
private static double ParseFloatNoCatch(string text) {
string s = ReplaceUnicodeDigits(text);
switch (s.ToLowerAsciiTriggered().lstrip()) {
case "nan":
case "+nan":
case "-nan":
return double.NaN;
case "inf":
case "+inf":
return double.PositiveInfinity;
case "-inf":
return double.NegativeInfinity;
default:
// pass NumberStyles to disallow ,'s in float strings.
double res = double.Parse(s, NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
return (res == 0.0 && text.lstrip().StartsWith("-")) ? DoubleOps.NegativeZero : res;
}
}
private static string ReplaceUnicodeDigits(string text) {
StringBuilder replacement = null;
for (int i = 0; i < text.Length; i++) {
if (text[i] >= '\x660' && text[i] <= '\x669') {
if (replacement == null) replacement = new StringBuilder(text);
replacement[i] = (char)(text[i] - '\x660' + '0');
}
}
if (replacement != null) {
text = replacement.ToString();
}
return text;
}
// ParseComplex helpers
private static char[] signs = new char[] { '+', '-' };
private static Exception ExnMalformed() {
return PythonOps.ValueError("complex() arg is a malformed string");
}
public static Complex ParseComplex(string s) {
// remove no-meaning spaces and convert to lowercase
string text = s.Trim().ToLower();
if (String.IsNullOrEmpty(text) || text.IndexOf(' ') != -1) {
throw ExnMalformed();
}
// remove 1 layer of parens
if (text.StartsWith("(") && text.EndsWith(")")) {
text = text.Substring(1, text.Length - 2);
}
try {
int len = text.Length;
string real, imag;
if (text[len - 1] == 'j') {
// last sign delimits real and imaginary...
int signPos = text.LastIndexOfAny(signs);
// ... unless it's after 'e', so we bypass up to 2 of those here
for (int i = 0; signPos > 0 && text[signPos - 1] == 'e'; i++) {
if (i == 2) {
// too many 'e's
throw ExnMalformed();
}
signPos = text.Substring(0, signPos - 1).LastIndexOfAny(signs);
}
// no real component
if (signPos < 0) {
return MathUtils.MakeImaginary((len == 1) ? 1 : ParseFloatNoCatch(text.Substring(0, len - 1)));
}
real = text.Substring(0, signPos);
imag = text.Substring(signPos, len - signPos - 1);
if (imag.Length == 1) {
imag += "1"; // convert +/- to +1/-1
}
} else {
// 'j' delimits real and imaginary
string[] splitText = text.Split(new char[] { 'j' });
// no imaginary component
if (splitText.Length == 1) {
return MathUtils.MakeReal(ParseFloatNoCatch(text));
}
// there should only be one j
if (splitText.Length != 2) {
throw ExnMalformed();
}
real = splitText[1];
imag = splitText[0];
// a sign must follow the 'j'
if (!(real.StartsWith("+") || real.StartsWith("-"))) {
throw ExnMalformed();
}
}
return new Complex(String.IsNullOrEmpty(real) ? 0 : ParseFloatNoCatch(real), ParseFloatNoCatch(imag));
} catch (OverflowException) {
throw PythonOps.ValueError("complex() literal too large to convert");
} catch {
throw ExnMalformed();
}
}
public static Complex ParseImaginary(string text) {
try {
return MathUtils.MakeImaginary(double.Parse(
text.Substring(0, text.Length - 1),
System.Globalization.CultureInfo.InvariantCulture.NumberFormat
));
} catch (OverflowException) {
return new Complex(0, Double.PositiveInfinity);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Runtime.Remoting.Messaging
{
public static class __MethodReturnMessageWrapper
{
public static IObservable<System.String> GetArgName(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.Int32> index)
{
return Observable.Zip(MethodReturnMessageWrapperValue, index,
(MethodReturnMessageWrapperValueLambda, indexLambda) =>
MethodReturnMessageWrapperValueLambda.GetArgName(indexLambda));
}
public static IObservable<System.Object> GetArg(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.Int32> argNum)
{
return Observable.Zip(MethodReturnMessageWrapperValue, argNum,
(MethodReturnMessageWrapperValueLambda, argNumLambda) =>
MethodReturnMessageWrapperValueLambda.GetArg(argNumLambda));
}
public static IObservable<System.Object> GetOutArg(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.Int32> argNum)
{
return Observable.Zip(MethodReturnMessageWrapperValue, argNum,
(MethodReturnMessageWrapperValueLambda, argNumLambda) =>
MethodReturnMessageWrapperValueLambda.GetOutArg(argNumLambda));
}
public static IObservable<System.String> GetOutArgName(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.Int32> index)
{
return Observable.Zip(MethodReturnMessageWrapperValue, index,
(MethodReturnMessageWrapperValueLambda, indexLambda) =>
MethodReturnMessageWrapperValueLambda.GetOutArgName(indexLambda));
}
public static IObservable<System.String> get_Uri(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.Uri);
}
public static IObservable<System.String> get_MethodName(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.MethodName);
}
public static IObservable<System.String> get_TypeName(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.TypeName);
}
public static IObservable<System.Object> get_MethodSignature(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.MethodSignature);
}
public static IObservable<System.Runtime.Remoting.Messaging.LogicalCallContext> get_LogicalCallContext(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.LogicalCallContext);
}
public static IObservable<System.Reflection.MethodBase> get_MethodBase(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.MethodBase);
}
public static IObservable<System.Int32> get_ArgCount(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.ArgCount);
}
public static IObservable<System.Object[]> get_Args(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.Args);
}
public static IObservable<System.Boolean> get_HasVarArgs(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.HasVarArgs);
}
public static IObservable<System.Int32> get_OutArgCount(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.OutArgCount);
}
public static IObservable<System.Object[]> get_OutArgs(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.OutArgs);
}
public static IObservable<System.Exception> get_Exception(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.Exception);
}
public static IObservable<System.Object> get_ReturnValue(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.ReturnValue);
}
public static IObservable<System.Collections.IDictionary> get_Properties(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue)
{
return Observable.Select(MethodReturnMessageWrapperValue,
(MethodReturnMessageWrapperValueLambda) => MethodReturnMessageWrapperValueLambda.Properties);
}
public static IObservable<System.Reactive.Unit> set_Uri(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(MethodReturnMessageWrapperValue, value,
(MethodReturnMessageWrapperValueLambda, valueLambda) =>
MethodReturnMessageWrapperValueLambda.Uri = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Args(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.Object[]> value)
{
return ObservableExt.ZipExecute(MethodReturnMessageWrapperValue, value,
(MethodReturnMessageWrapperValueLambda, valueLambda) =>
MethodReturnMessageWrapperValueLambda.Args = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Exception(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.Exception> value)
{
return ObservableExt.ZipExecute(MethodReturnMessageWrapperValue, value,
(MethodReturnMessageWrapperValueLambda, valueLambda) =>
MethodReturnMessageWrapperValueLambda.Exception = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_ReturnValue(
this IObservable<System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper>
MethodReturnMessageWrapperValue, IObservable<System.Object> value)
{
return ObservableExt.ZipExecute(MethodReturnMessageWrapperValue, value,
(MethodReturnMessageWrapperValueLambda, valueLambda) =>
MethodReturnMessageWrapperValueLambda.ReturnValue = valueLambda);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.CodeGeneration;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using Orleans.Serialization;
using Orleans.Transactions.Abstractions;
namespace Orleans.Transactions.State
{
internal class ReadWriteLock<TState>
where TState : class, new()
{
private readonly TransactionalStateOptions options;
private readonly TransactionQueue<TState> queue;
private BatchWorker lockWorker;
private BatchWorker storageWorker;
private readonly ILogger logger;
private readonly IActivationLifetime activationLifetime;
// the linked list of lock groups
// the head is the group that is currently holding the lock
private LockGroup currentGroup = null;
// cache the last known minimum so we don't have to recompute it as much
private DateTime cachedMin = DateTime.MaxValue;
private Guid cachedMinId;
// group of non-conflicting transactions collectively acquiring/releasing the lock
private class LockGroup : Dictionary<Guid, TransactionRecord<TState>>
{
public int FillCount;
public List<Action> Tasks; // the tasks for executing the waiting operations
public LockGroup Next; // queued-up transactions waiting to acquire lock
public DateTime? Deadline;
public void Reset()
{
FillCount = 0;
Tasks = null;
Deadline = null;
Clear();
}
}
public ReadWriteLock(
IOptions<TransactionalStateOptions> options,
TransactionQueue<TState> queue,
BatchWorker storageWorker,
ILogger logger,
IActivationLifetime activationLifetime)
{
this.options = options.Value;
this.queue = queue;
this.storageWorker = storageWorker;
this.logger = logger;
this.activationLifetime = activationLifetime;
this.lockWorker = new BatchWorkerFromDelegate(LockWork, this.activationLifetime.OnDeactivating);
}
public async Task<TResult> EnterLock<TResult>(Guid transactionId, DateTime priority,
AccessCounter counter, bool isRead, Func<TResult> task)
{
bool rollbacksOccurred = false;
List<Task> cleanup = new List<Task>();
await this.queue.Ready();
// search active transactions
if (Find(transactionId, isRead, out var group, out var record))
{
// check if we lost some reads or writes already
if (counter.Reads > record.NumberReads || counter.Writes > record.NumberWrites)
{
throw new OrleansBrokenTransactionLockException(transactionId.ToString(), "when re-entering lock");
}
// check if the operation conflicts with other transactions in the group
if (HasConflict(isRead, priority, transactionId, group, out var resolvable))
{
if (!resolvable)
{
throw new OrleansTransactionLockUpgradeException(transactionId.ToString());
}
else
{
// rollback all conflicts
var conflicts = Conflicts(transactionId, group).ToList();
if (conflicts.Count > 0)
{
foreach (var r in conflicts)
{
cleanup.Add(Rollback(r, true));
rollbacksOccurred = true;
}
}
}
}
}
else
{
// check if we were supposed to already hold this lock
if (counter.Reads + counter.Writes > 0)
{
throw new OrleansBrokenTransactionLockException(transactionId.ToString(), "when trying to re-enter lock");
}
// update the lock deadline
if (group == currentGroup)
{
group.Deadline = DateTime.UtcNow + this.options.LockTimeout;
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("set lock expiration at {Deadline}", group.Deadline.Value.ToString("o"));
}
// create a new record for this transaction
record = new TransactionRecord<TState>()
{
TransactionId = transactionId,
Priority = priority,
Deadline = DateTime.UtcNow + this.options.LockAcquireTimeout
};
group.Add(transactionId, record);
group.FillCount++;
if (logger.IsEnabled(LogLevel.Trace))
{
if (group == currentGroup)
logger.Trace($"enter-lock {transactionId} fc={group.FillCount}");
else
logger.Trace($"enter-lock-queue {transactionId} fc={group.FillCount}");
}
}
var result =
new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously);
Action completion = () =>
{
try
{
result.TrySetResult(task());
}
catch (Exception exception)
{
result.TrySetException(exception);
}
};
if (group != currentGroup)
{
// task will be executed once its group acquires the lock
if (group.Tasks == null)
group.Tasks = new List<Action>();
group.Tasks.Add(completion);
}
else
{
// execute task right now
completion();
}
if (isRead)
{
record.AddRead();
}
else
{
record.AddWrite();
}
if (rollbacksOccurred)
{
lockWorker.Notify();
}
else if (group.Deadline.HasValue)
{
lockWorker.Notify(group.Deadline.Value);
}
await Task.WhenAll(cleanup);
return await result.Task;
}
public async Task<Tuple<TransactionalStatus, TransactionRecord<TState>>> ValidateLock(Guid transactionId, AccessCounter accessCount)
{
if (currentGroup == null || !currentGroup.TryGetValue(transactionId, out TransactionRecord<TState> record))
{
return Tuple.Create(TransactionalStatus.BrokenLock, new TransactionRecord<TState>());
}
else if (record.NumberReads != accessCount.Reads
|| record.NumberWrites != accessCount.Writes)
{
await Rollback(transactionId, true);
return Tuple.Create(TransactionalStatus.LockValidationFailed, record);
}
else
{
return Tuple.Create(TransactionalStatus.Ok, record);
}
}
public void Notify()
{
this.lockWorker.Notify();
}
public bool TryGetRecord(Guid transactionId, out TransactionRecord<TState> record)
{
return this.currentGroup.TryGetValue(transactionId, out record);
}
public Task AbortExecutingTransactions()
{
if (currentGroup != null)
{
Task[] pending = currentGroup.Select(g => BreakLock(g.Key, g.Value)).ToArray();
currentGroup.Reset();
return Task.WhenAll(pending);
}
return Task.CompletedTask;
}
private Task BreakLock(Guid transactionId, TransactionRecord<TState> entry)
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("Break-lock for transaction {TransactionId}", transactionId);
return this.queue.NotifyOfAbort(entry, TransactionalStatus.BrokenLock);
}
public void AbortQueuedTransactions()
{
var pos = currentGroup?.Next;
while (pos != null)
{
if (pos.Tasks != null)
{
foreach (var t in pos.Tasks)
{
// running the task will abort the transaction because it is not in currentGroup
t();
}
}
pos.Clear();
pos = pos.Next;
}
if (currentGroup != null)
currentGroup.Next = null;
}
public async Task Rollback(Guid guid, bool notify)
{
// no-op if the transaction never happened or already rolled back
if (currentGroup == null || !currentGroup.TryGetValue(guid, out var record))
{
return;
}
// remove record for this transaction
currentGroup.Remove(guid);
// notify remote listeners
if (notify)
{
await this.queue.NotifyOfAbort(record, TransactionalStatus.BrokenLock);
}
}
private async Task LockWork()
{
// Stop pumping lock work if this activation is stopping/stopped.
if (this.activationLifetime.OnDeactivating.IsCancellationRequested) return;
using (this.activationLifetime.BlockDeactivation())
{
var now = DateTime.UtcNow;
if (currentGroup != null)
{
// check if there are any group members that are ready to exit the lock
if (currentGroup.Count > 0)
{
if (LockExits(out var single, out var multiple))
{
if (single != null)
{
await this.queue.EnqueueCommit(single);
}
else if (multiple != null)
{
foreach (var r in multiple)
{
await this.queue.EnqueueCommit(r);
}
}
lockWorker.Notify();
storageWorker.Notify();
}
else if (currentGroup.Deadline.HasValue)
{
if (currentGroup.Deadline.Value < now)
{
// the lock group has timed out.
string txlist = string.Join(",", currentGroup.Keys.Select(g => g.ToString()));
TimeSpan late = now - currentGroup.Deadline.Value;
logger.LogWarning("Break-lock timeout for transactions {TransactionIds}. {Late}ms late", txlist, Math.Floor(late.TotalMilliseconds));
await AbortExecutingTransactions();
lockWorker.Notify();
}
else
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("recheck lock expiration at {Deadline}", currentGroup.Deadline.Value.ToString("o"));
// check again when the group expires
lockWorker.Notify(currentGroup.Deadline.Value);
}
}
else
{
string txlist = string.Join(",", currentGroup.Keys.Select(g => g.ToString()));
logger.LogWarning("Deadline not set for transactions {TransactionIds}", txlist);
}
}
else
{
// the lock is empty, a new group can enter
currentGroup = currentGroup.Next;
if (currentGroup != null)
{
currentGroup.Deadline = now + this.options.LockTimeout;
// discard expired waiters that have no chance to succeed
// because they have been waiting for the lock for a longer timespan than the
// total transaction timeout
List<Guid> expiredWaiters = null;
foreach (var kvp in currentGroup)
{
if (now > kvp.Value.Deadline)
{
if (expiredWaiters == null)
expiredWaiters = new List<Guid>();
expiredWaiters.Add(kvp.Key);
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"expire-lock-waiter {kvp.Key}");
}
}
if (expiredWaiters != null)
{
foreach (var guid in expiredWaiters)
{
currentGroup.Remove(guid);
}
}
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace($"lock groupsize={currentGroup.Count} deadline={currentGroup.Deadline:o}");
foreach (var kvp in currentGroup)
logger.Trace($"enter-lock {kvp.Key}");
}
// execute all the read and update tasks
if (currentGroup.Tasks != null)
{
foreach (var t in currentGroup.Tasks)
{
t();
}
}
lockWorker.Notify();
}
}
}
}
}
private bool Find(Guid guid, bool isRead, out LockGroup group, out TransactionRecord<TState> record)
{
if (currentGroup == null)
{
group = currentGroup = new LockGroup();
record = null;
return false;
}
else
{
group = null;
var pos = currentGroup;
while (true)
{
if (pos.TryGetValue(guid, out record))
{
group = pos;
return true;
}
// if we have not found a place to insert this op yet, and there is room, and no conflicts, use this one
if (group == null
&& pos.FillCount < this.options.MaxLockGroupSize
&& !HasConflict(isRead, DateTime.MaxValue, guid, pos, out var resolvable))
{
group = pos;
}
if (pos.Next == null) // we did not find this tx.
{
// add a new empty group to insert this tx, if we have not found one yet
if (group == null)
{
group = pos.Next = new LockGroup();
}
return false;
}
pos = pos.Next;
}
}
}
private bool HasConflict(bool isRead, DateTime priority, Guid transactionId, LockGroup group, out bool resolvable)
{
bool foundResolvableConflicts = false;
foreach (var kvp in group)
{
if (kvp.Key != transactionId)
{
if (isRead && kvp.Value.NumberWrites == 0)
{
continue;
}
else
{
if (priority > kvp.Value.Priority)
{
resolvable = false;
return true;
}
else
{
foundResolvableConflicts = true;
}
}
}
}
resolvable = foundResolvableConflicts;
return foundResolvableConflicts;
}
private IEnumerable<Guid> Conflicts(Guid transactionId, LockGroup group)
{
foreach (var kvp in group)
{
if (kvp.Key != transactionId)
{
yield return kvp.Key;
}
}
}
private bool LockExits(out TransactionRecord<TState> single, out List<TransactionRecord<TState>> multiple)
{
single = null;
multiple = null;
// fast-path the one-element case
if (currentGroup.Count == 1)
{
var kvp = currentGroup.First();
if (kvp.Value.Role == CommitRole.NotYetDetermined) // has not received commit from TA
{
return false;
}
else
{
single = kvp.Value;
currentGroup.Remove(single.TransactionId);
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"exit-lock {single.TransactionId} {single.Timestamp:o}");
return true;
}
}
else
{
// find the current minimum, if we don't have a valid cache of it
if (cachedMin == DateTime.MaxValue
|| !currentGroup.TryGetValue(cachedMinId, out var record)
|| record.Role != CommitRole.NotYetDetermined
|| record.Timestamp != cachedMin)
{
cachedMin = DateTime.MaxValue;
foreach (var kvp in currentGroup)
{
if (kvp.Value.Role == CommitRole.NotYetDetermined) // has not received commit from TA
{
if (cachedMin > kvp.Value.Timestamp)
{
cachedMin = kvp.Value.Timestamp;
cachedMinId = kvp.Key;
}
}
}
}
// find released entries
foreach (var kvp in currentGroup)
{
if (kvp.Value.Role != CommitRole.NotYetDetermined) // ready to commit
{
if (kvp.Value.Timestamp < cachedMin)
{
if (multiple == null)
{
multiple = new List<TransactionRecord<TState>>();
}
multiple.Add(kvp.Value);
}
}
}
if (multiple == null)
{
return false;
}
else
{
multiple.Sort(Comparer);
for (int i = 0; i < multiple.Count; i++)
{
currentGroup.Remove(multiple[i].TransactionId);
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"exit-lock ({i}/{multiple.Count}) {multiple[i].TransactionId} {multiple[i].Timestamp:o}");
}
return true;
}
}
}
private static int Comparer(TransactionRecord<TState> a, TransactionRecord<TState> b)
{
return a.Timestamp.CompareTo(b.Timestamp);
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
using Quartz.Spi;
namespace Quartz
{
/// <summary>
/// TriggerBuilder is used to instantiate <see cref="ITrigger" />s.
/// </summary>
/// <remarks>
/// <para>
/// The builder will always try to keep itself in a valid state, with
/// reasonable defaults set for calling build() at any point. For instance
/// if you do not invoke <i>WithSchedule(..)</i> method, a default schedule
/// of firing once immediately will be used. As another example, if you
/// do not invoked <i>WithIdentity(..)</i> a trigger name will be generated
/// for you.
/// </para>
/// <para>
/// Quartz provides a builder-style API for constructing scheduling-related
/// entities via a Domain-Specific Language (DSL). The DSL can best be
/// utilized through the usage of static imports of the methods on the classes
/// <see cref="TriggerBuilder" />, <see cref="JobBuilder" />,
/// <see cref="DateBuilder" />, <see cref="JobKey" />, <see cref="TriggerKey" />
/// and the various <see cref="IScheduleBuilder" /> implementations.
/// </para>
/// <para>
/// Client code can then use the DSL to write code such as this:
/// </para>
/// <code>
/// IJobDetail job = JobBuilder.Create<MyJob>()
/// .WithIdentity("myJob")
/// .Build();
/// ITrigger trigger = TriggerBuilder.Create()
/// .WithIdentity("myTrigger", "myTriggerGroup")
/// .WithSimpleSchedule(x => x
/// .WithIntervalInHours(1)
/// .RepeatForever())
/// .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Minute))
/// .Build();
/// scheduler.scheduleJob(job, trigger);
/// </code>
/// </remarks>
/// <seealso cref="JobBuilder" />
/// <seealso cref="IScheduleBuilder" />
/// <seealso cref="DateBuilder" />
/// <seealso cref="ITrigger" />
public class TriggerBuilder
{
private TriggerKey key;
private string description;
private DateTimeOffset startTime = SystemTime.UtcNow();
private DateTimeOffset? endTime;
private int priority = TriggerConstants.DefaultPriority;
private string calendarName;
private JobKey jobKey;
private JobDataMap jobDataMap = new JobDataMap();
private IScheduleBuilder scheduleBuilder;
private TriggerBuilder()
{
}
/// <summary>
/// Create a new TriggerBuilder with which to define a
/// specification for a Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the new TriggerBuilder</returns>
public static TriggerBuilder Create()
{
return new TriggerBuilder();
}
/// <summary>
/// Produce the <see cref="ITrigger" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>a Trigger that meets the specifications of the builder.</returns>
public ITrigger Build()
{
if (scheduleBuilder == null)
{
scheduleBuilder = SimpleScheduleBuilder.Create();
}
IMutableTrigger trig = scheduleBuilder.Build();
trig.CalendarName = calendarName;
trig.Description = description;
trig.StartTimeUtc = startTime;
trig.EndTimeUtc = endTime;
if (key == null)
{
key = new TriggerKey(Guid.NewGuid().ToString(), null);
}
trig.Key = key;
if (jobKey != null)
{
trig.JobKey = jobKey;
}
trig.Priority = priority;
if (!jobDataMap.IsEmpty)
{
trig.JobDataMap = jobDataMap;
}
return trig;
}
/// <summary>
/// Use a <see cref="TriggerKey" /> with the given name and default group to
/// identify the Trigger.
/// </summary>
/// <remarks>
/// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder,
/// then a random, unique TriggerKey will be generated.</para>
/// </remarks>
/// <param name="name">the name element for the Trigger's TriggerKey</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerKey" />
/// <seealso cref="ITrigger.Key" />
public TriggerBuilder WithIdentity(string name)
{
key = new TriggerKey(name, null);
return this;
}
/// <summary>
/// Use a TriggerKey with the given name and group to
/// identify the Trigger.
/// </summary>
/// <remarks>
/// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder,
/// then a random, unique TriggerKey will be generated.</para>
/// </remarks>
/// <param name="name">the name element for the Trigger's TriggerKey</param>
/// <param name="group">the group element for the Trigger's TriggerKey</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerKey" />
/// <seealso cref="ITrigger.Key" />
public TriggerBuilder WithIdentity(string name, string group)
{
key = new TriggerKey(name, group);
return this;
}
/// <summary>
/// Use the given TriggerKey to identify the Trigger.
/// </summary>
/// <remarks>
/// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder,
/// then a random, unique TriggerKey will be generated.</para>
/// </remarks>
/// <param name="key">the TriggerKey for the Trigger to be built</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerKey" />
/// <seealso cref="ITrigger.Key" />
public TriggerBuilder WithIdentity(TriggerKey key)
{
this.key = key;
return this;
}
/// <summary>
/// Set the given (human-meaningful) description of the Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="description">the description for the Trigger</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.Description" />
public TriggerBuilder WithDescription(string description)
{
this.description = description;
return this;
}
/// <summary>
/// Set the Trigger's priority. When more than one Trigger have the same
/// fire time, the scheduler will fire the one with the highest priority
/// first.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="priority">the priority for the Trigger</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerConstants.DefaultPriority" />
/// <seealso cref="ITrigger.Priority" />
public TriggerBuilder WithPriority(int priority)
{
this.priority = priority;
return this;
}
/// <summary>
/// Set the name of the <see cref="ICalendar" /> that should be applied to this
/// Trigger's schedule.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="calendarName">the name of the Calendar to reference.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ICalendar" />
/// <seealso cref="ITrigger.CalendarName" />
public TriggerBuilder ModifiedByCalendar(string calendarName)
{
this.calendarName = calendarName;
return this;
}
/// <summary>
/// Set the time the Trigger should start at - the trigger may or may
/// not fire at this time - depending upon the schedule configured for
/// the Trigger. However the Trigger will NOT fire before this time,
/// regardless of the Trigger's schedule.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="startTimeUtc">the start time for the Trigger.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.StartTimeUtc" />
/// <seealso cref="DateBuilder" />
public TriggerBuilder StartAt(DateTimeOffset startTimeUtc)
{
startTime = startTimeUtc;
return this;
}
/// <summary>
/// Set the time the Trigger should start at to the current moment -
/// the trigger may or may not fire at this time - depending upon the
/// schedule configured for the Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.StartTimeUtc" />
public TriggerBuilder StartNow()
{
startTime = SystemTime.UtcNow();
return this;
}
/// <summary>
/// Set the time at which the Trigger will no longer fire - even if it's
/// schedule has remaining repeats.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="endTimeUtc">the end time for the Trigger. If null, the end time is indefinite.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.EndTimeUtc" />
/// <seealso cref="DateBuilder" />
public TriggerBuilder EndAt(DateTimeOffset? endTimeUtc)
{
endTime = endTimeUtc;
return this;
}
/// <summary>
/// Set the <see cref="IScheduleBuilder" /> that will be used to define the
/// Trigger's schedule.
/// </summary>
/// <remarks>
/// <para>The particular <see cref="IScheduleBuilder" /> used will dictate
/// the concrete type of Trigger that is produced by the TriggerBuilder.</para>
/// </remarks>
/// <param name="scheduleBuilder">the SchedulerBuilder to use.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="IScheduleBuilder" />
/// <seealso cref="SimpleScheduleBuilder" />
/// <seealso cref="CronScheduleBuilder" />
/// <seealso cref="CalendarIntervalScheduleBuilder" />
public TriggerBuilder WithSchedule(IScheduleBuilder scheduleBuilder)
{
this.scheduleBuilder = scheduleBuilder;
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobKey">the identity of the Job to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(JobKey jobKey)
{
this.jobKey = jobKey;
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger - a <see cref="JobKey" /> will be produced with the given
/// name and default group.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobName">the name of the job (in default group) to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(string jobName)
{
jobKey = new JobKey(jobName, null);
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger - a <see cref="JobKey" /> will be produced with the given
/// name and group.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobName">the name of the job to fire.</param>
/// <param name="jobGroup">the group of the job to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(string jobName, string jobGroup)
{
jobKey = new JobKey(jobName, jobGroup);
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger, by extracting the JobKey from the given job.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobDetail">the Job to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(IJobDetail jobDetail)
{
JobKey k = jobDetail.Key;
if (k.Name == null)
{
throw new ArgumentException("The given job has not yet had a name assigned to it.");
}
jobKey = k;
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, string value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, int value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, long value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, float value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, double value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, decimal value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, bool value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(JobDataMap newJobDataMap)
{
// add data from new map to existing map (overrides old values)
foreach (string k in newJobDataMap.Keys)
{
jobDataMap.Put(k, newJobDataMap.Get(k));
}
return this;
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Globalization;
using NDoc.Core;
using NDoc.Core.Reflection;
namespace NDoc.Documenter.Msdn
{
/// <summary>
/// Provides an extension object for the xslt transformations.
/// </summary>
public class MsdnXsltUtilities
{
private const string sdkDoc10BaseNamespace = "MS.NETFrameworkSDK";
private const string sdkDoc11BaseNamespace = "MS.NETFrameworkSDKv1.1";
private const string helpURL = "ms-help://";
private const string sdkRoot = "/cpref/html/frlrf";
private const string sdkDocPageExt = ".htm";
private const string msdnOnlineSdkBaseUrl = "http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrf";
private const string msdnOnlineSdkPageExt = ".asp";
private const string systemPrefix = "System.";
private string sdkDocBaseUrl;
private string sdkDocExt;
private StringDictionary fileNames;
private StringDictionary elemNames;
private StringCollection descriptions;
private string encodingString;
/// <summary>
/// Initializes a new instance of class MsdnXsltUtilities
/// </summary>
/// <param name="fileNames">A StringDictionary holding id to file name mappings.</param>
/// <param name="elemNames">A StringDictionary holding id to element name mappings</param>
/// <param name="linkToSdkDocVersion">Specifies the version of the SDK documentation.</param>
/// <param name="linkToSdkDocLangauge">Specifies the version of the SDK documentation.</param>
/// <param name="SdkLinksOnWeb">Specifies if links should be to ms online documentation.</param>
/// <param name="fileEncoding">Specifies if links should be to ms online documentation.</param>
public MsdnXsltUtilities(
StringDictionary fileNames,
StringDictionary elemNames,
SdkVersion linkToSdkDocVersion,
string linkToSdkDocLangauge,
bool SdkLinksOnWeb,
System.Text.Encoding fileEncoding)
{
Reset();
this.fileNames = fileNames;
this.elemNames = elemNames;
if (SdkLinksOnWeb)
{
sdkDocBaseUrl = msdnOnlineSdkBaseUrl;
sdkDocExt = msdnOnlineSdkPageExt;
}
else
{
switch (linkToSdkDocVersion)
{
case SdkVersion.SDK_v1_0:
sdkDocBaseUrl = GetLocalizedFrameworkURL(sdkDoc10BaseNamespace,linkToSdkDocLangauge);
sdkDocExt = sdkDocPageExt;
break;
case SdkVersion.SDK_v1_1:
sdkDocBaseUrl = GetLocalizedFrameworkURL(sdkDoc11BaseNamespace,linkToSdkDocLangauge);
sdkDocExt = sdkDocPageExt;
break;
}
}
encodingString = "text/html; charset=" + fileEncoding.WebName;
}
/// <summary>
/// Reset Overload method checking state.
/// </summary>
public void Reset()
{
descriptions = new StringCollection();
}
/// <summary>
/// Gets the base Url for system types links.
/// </summary>
public string SdkDocBaseUrl
{
get { return sdkDocBaseUrl; }
}
/// <summary>
/// Gets the page file extension for system types links.
/// </summary>
public string SdkDocExt
{
get { return sdkDocExt; }
}
/// <summary>
/// Returns an HRef for a CRef.
/// </summary>
/// <param name="cref">CRef for which the HRef will be looked up.</param>
public string GetHRef(string cref)
{
if ((cref.Length < 2) || (cref[1] != ':'))
return string.Empty;
/*
if ((cref.Length < 9)
|| (cref.Substring(2, 7) != systemPrefix))
*/
{
string fileName = fileNames[cref];
if ((fileName == null) && cref.StartsWith("F:"))
fileName = fileNames["E:" + cref.Substring(2)];
if (fileName == null)
return "";
else
return fileName;
}
/*
else
{
switch (cref.Substring(0, 2))
{
case "N:": // Namespace
return sdkDocBaseUrl + cref.Substring(2).Replace(".", "") + sdkDocExt;
case "T:": // Type: class, interface, struct, enum, delegate
// pointer types link to the type being pointed to
return sdkDocBaseUrl + cref.Substring(2).Replace(".", "").Replace( "*", "" ) + "ClassTopic" + sdkDocExt;
case "F:": // Field
case "P:": // Property
case "M:": // Method
case "E:": // Event
return GetFilenameForSystemMember(cref);
default:
return string.Empty;
}
}
*/
}
/// <summary>
/// Returns a name for a CRef.
/// </summary>
/// <param name="cref">CRef for which the name will be looked up.</param>
public string GetName(string cref)
{
if (cref.Length < 2)
return cref;
if (cref[1] == ':')
{
if ((cref.Length < 9)
|| (cref.Substring(2, 7) != systemPrefix))
{
string name = elemNames[cref];
if (name != null)
return name;
}
int index;
if ((index = cref.IndexOf(".#c")) >= 0)
cref = cref.Substring(2, index - 2);
else if ((index = cref.IndexOf("(")) >= 0)
cref = cref.Substring(2, index - 2);
else
cref = cref.Substring(2);
}
return cref.Substring(cref.LastIndexOf(".") + 1);
}
private string GetFilenameForSystemMember(string id)
{
string crefName;
int index;
if ((index = id.IndexOf(".#c")) >= 0)
crefName = id.Substring(2, index - 2) + ".ctor";
else if ((index = id.IndexOf("(")) >= 0)
crefName = id.Substring(2, index - 2);
else
crefName = id.Substring(2);
index = crefName.LastIndexOf(".");
string crefType = crefName.Substring(0, index);
string crefMember = crefName.Substring(index + 1);
return sdkDocBaseUrl + crefType.Replace(".", "") + "Class" + crefMember + "Topic" + sdkDocExt;
}
/// <summary>
/// Looks up, whether a member has similar overloads, that have already been documented.
/// </summary>
/// <param name="description">A string describing this overload.</param>
/// <returns>true, if there has been a member with the same description.</returns>
/// <remarks>
/// <para>On the members pages overloads are cumulated. Instead of adding all overloads
/// to the members page, a link is added to the members page, that points
/// to an overloads page.</para>
/// <para>If for example one overload is public, while another one is protected,
/// we want both to appear on the members page. This is to make the search
/// for suitable members easier.</para>
/// <para>This leads us to the similarity of overloads. Two overloads are considered
/// similar, if they have the same name, declaring type, access (public, protected, ...)
/// and contract (static, non static). The description contains these four attributes
/// of the member. This means, that two members are similar, when they have the same
/// description.</para>
/// <para>Asking for the first time, if a member has similar overloads, will return false.
/// After that, if asking with the same description again, it will return true, so
/// the overload does not need to be added to the members page.</para>
/// </remarks>
public bool HasSimilarOverloads(string description)
{
if (descriptions.Contains(description))
return true;
descriptions.Add(description);
return false;
}
/// <summary>
/// Exposes <see cref="String.Replace(string, string)"/> to XSLT
/// </summary>
/// <param name="str">The string to search</param>
/// <param name="oldValue">The string to search for</param>
/// <param name="newValue">The string to replace</param>
/// <returns>A new string</returns>
public string Replace( string str, string oldValue, string newValue )
{
return str.Replace( oldValue, newValue );
}
/// <summary>
/// returns a localized sdk url if one exists for the <see cref="CultureInfo.CurrentCulture"/>.
/// </summary>
/// <param name="searchNamespace">base namespace to search for</param>
/// <param name="langCode">the localization language code</param>
/// <returns>ms-help url for sdk</returns>
private string GetLocalizedFrameworkURL(string searchNamespace, string langCode)
{
if (langCode!="en")
{
return helpURL + searchNamespace + "." + langCode.ToUpper() + sdkRoot;
}
else
{
//default to non-localized namespace
return helpURL + searchNamespace + sdkRoot;
}
}
/// <summary>
/// Gets HTML ContentType for the system's current ANSI code page.
/// </summary>
/// <returns>ContentType attribute string</returns>
public string GetContentType()
{
return encodingString;
}
}
}
| |
//*********************************************************
//
// 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.Threading.Tasks;
using Windows.Devices.PointOfService;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario2_MultipleScanners : Page
{
// 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;
BarcodeScanner barcodeScannerInstance1 = null;
BarcodeScanner barcodeScannerInstance2 = null;
ClaimedBarcodeScanner claimedBarcodeScannerInstance1 = null;
ClaimedBarcodeScanner claimedBarcodeScannerInstance2 = null;
public Scenario2_MultipleScanners()
{
this.InitializeComponent();
}
/// <summary>
/// Enumerator for current active Instance.
/// </summary>
private enum BarcodeScannerInstance
{
Instance1,
Instance2
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ResetTheScenarioState();
base.OnNavigatedTo(e);
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e">Event data that describes how this page was exited. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ResetTheScenarioState();
base.OnNavigatedFrom(e);
}
/// <summary>
/// This is the click handler for the 'ScenarioStartScanningInstance1' button. It initiates creation of scanner instance 1.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void ButtonStartScanningInstance1_Click(object sender, RoutedEventArgs e)
{
//Get the handle to the default scanner
if (await CreateDefaultScannerObjectAsync(BarcodeScannerInstance.Instance1))
{
//Claim the scanner
if (await ClaimBarcodeScannerAsync(BarcodeScannerInstance.Instance1))
{
//add the event handlers
claimedBarcodeScannerInstance1.ReleaseDeviceRequested += claimedBarcodeScannerInstance1_ReleaseDeviceRequested;
claimedBarcodeScannerInstance1.DataReceived += claimedBarcodeScannerInstance1_DataReceived;
claimedBarcodeScannerInstance1.IsDecodeDataEnabled = true;
//Enable the Scanner
if (await EnableBarcodeScannerAsync(BarcodeScannerInstance.Instance1))
{
//Set the UI state
ResetUI();
SetUI(BarcodeScannerInstance.Instance1);
}
}
else
{
if (barcodeScannerInstance1 != null)
{
barcodeScannerInstance1.Dispose();
barcodeScannerInstance1 = null;
}
}
}
}
/// <summary>
/// This method is called upon when a claim request is made on instance 1. If a retain request was placed on the device it rejects the new claim.
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
async void claimedBarcodeScannerInstance1_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
{
await MainPage.Current.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
//check if the instance wants to retain the device
if (Retain1.IsChecked == true)
{
try
{
//Retain the device
claimedBarcodeScannerInstance1.RetainDevice();
}
catch (Exception exception)
{
rootPage.NotifyUser("Retain instance 1 failed: " + exception.Message, NotifyType.ErrorMessage);
}
}
//Release the device
else
{
claimedBarcodeScannerInstance1.Dispose();
claimedBarcodeScannerInstance1 = null;
if (barcodeScannerInstance1 != null)
{
barcodeScannerInstance1.Dispose();
barcodeScannerInstance1 = null;
}
}
}
);
}
/// <summary>
/// This is the click handler for the 'ScenarioStartScanningInstance2' button. Initiates creation of scanner instance 2
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void ButtonStartScanningInstance2_Click(object sender, RoutedEventArgs e)
{
//Get the handle to the default scanner
if (await CreateDefaultScannerObjectAsync(BarcodeScannerInstance.Instance2))
{
//Claim the scanner
if (await ClaimBarcodeScannerAsync(BarcodeScannerInstance.Instance2))
{
//set the handlers
claimedBarcodeScannerInstance2.ReleaseDeviceRequested += claimedBarcodeScannerInstance2_ReleaseDeviceRequested;
claimedBarcodeScannerInstance2.DataReceived += claimedBarcodeScannerInstance2_DataReceived;
//enable the scanner to decode the scanned data
claimedBarcodeScannerInstance2.IsDecodeDataEnabled = true;
//Enable the Scanner
if (await EnableBarcodeScannerAsync(BarcodeScannerInstance.Instance2))
{
//Set the UI state
ResetUI();
SetUI(BarcodeScannerInstance.Instance2);
}
}
else
{
if (barcodeScannerInstance2 != null)
{
barcodeScannerInstance2.Dispose();
barcodeScannerInstance2 = null;
}
}
}
}
/// <summary>
/// This method is called upon when a claim request is made on instance 2. If a retain request was placed on the device it rejects the new claim.
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
async void claimedBarcodeScannerInstance2_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
{
await MainPage.Current.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
//check if the instance wants to retain the device
if (Retain2.IsChecked == true)
{
try
{
//Retain the device
claimedBarcodeScannerInstance2.RetainDevice();
}
catch (Exception exception)
{
rootPage.NotifyUser("Retain instance 1 failed: " + exception.Message, NotifyType.ErrorMessage);
}
}
//Release the device
else
{
claimedBarcodeScannerInstance2.Dispose();
claimedBarcodeScannerInstance2 = null;
if (barcodeScannerInstance2 != null)
{
barcodeScannerInstance2.Dispose();
barcodeScannerInstance2 = null;
}
}
}
);
}
/// <summary>
/// This is the click handler for the 'ScenarioEndScanningInstance1' button.
/// Initiates the disposal of scanner instance 1.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonEndScanningInstance1_Click(object sender, RoutedEventArgs e)
{
if (claimedBarcodeScannerInstance1 != null)
{
//remove the event handlers
claimedBarcodeScannerInstance1.DataReceived -= claimedBarcodeScannerInstance1_DataReceived;
claimedBarcodeScannerInstance1.ReleaseDeviceRequested -= claimedBarcodeScannerInstance1_ReleaseDeviceRequested;
//dispose the instance
claimedBarcodeScannerInstance1.Dispose();
claimedBarcodeScannerInstance1 = null;
}
if (barcodeScannerInstance1 != null)
{
barcodeScannerInstance1.Dispose();
barcodeScannerInstance1 = null;
}
//reset the UI
ResetUI();
rootPage.NotifyUser("Click a start scanning button to begin.", NotifyType.StatusMessage);
}
/// <summary>
/// This is the click handler for the 'ScenarioEndScanningInstance2' button.
/// Initiates the disposal fo scanner instance 2.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonEndScanningInstance2_Click(object sender, RoutedEventArgs e)
{
if (claimedBarcodeScannerInstance2 != null)
{
//remove the event handlers
claimedBarcodeScannerInstance2.DataReceived -= claimedBarcodeScannerInstance2_DataReceived;
claimedBarcodeScannerInstance2.ReleaseDeviceRequested -= claimedBarcodeScannerInstance2_ReleaseDeviceRequested;
//dispose the instance
claimedBarcodeScannerInstance2.Dispose();
claimedBarcodeScannerInstance2 = null;
}
if (barcodeScannerInstance2 != null)
{
barcodeScannerInstance2.Dispose();
barcodeScannerInstance2 = null;
}
//reset the UI
ResetUI();
rootPage.NotifyUser("Click a start scanning button to begin.", NotifyType.StatusMessage);
}
/// <summary>
/// This method returns the first available Barcode Scanner. To enumerate and find a particular device use the device enumeration code.
/// </summary>
/// <returns>a boolean value based on whether it found a compatible scanner connected</returns>
private async Task<bool> CreateDefaultScannerObjectAsync(BarcodeScannerInstance instance)
{
BarcodeScanner scanner = null;
scanner = await DeviceHelpers.GetFirstBarcodeScannerAsync();
if (scanner == null)
{
rootPage.NotifyUser("Barcode scanner not found. Please connect a barcode scanner.", NotifyType.ErrorMessage);
return false;
}
switch (instance)
{
case BarcodeScannerInstance.Instance1:
barcodeScannerInstance1 = scanner;
break;
case BarcodeScannerInstance.Instance2:
barcodeScannerInstance2 = scanner;
break;
default:
return false;
}
return true;
}
/// <summary>
/// This method claims the connected scanner.
/// </summary>
/// <returns>a boolean based on whether it was able to claim the scanner.</returns>
private async Task<bool> ClaimBarcodeScannerAsync(BarcodeScannerInstance instance)
{
bool bClaimAsyncStatus = false;
//select the instance to claim
switch (instance)
{
case BarcodeScannerInstance.Instance1:
claimedBarcodeScannerInstance1 = await barcodeScannerInstance1.ClaimScannerAsync();
if (claimedBarcodeScannerInstance1 == null)
rootPage.NotifyUser("Instance 1 claim barcode scanner failed.", NotifyType.ErrorMessage);
else
bClaimAsyncStatus = true;
break;
case BarcodeScannerInstance.Instance2:
claimedBarcodeScannerInstance2 = await barcodeScannerInstance2.ClaimScannerAsync();
if (claimedBarcodeScannerInstance2 == null)
rootPage.NotifyUser("Instance 2 claim barcode scanner failed.", NotifyType.ErrorMessage);
else
bClaimAsyncStatus = true;
break;
default:
return bClaimAsyncStatus;
}
return bClaimAsyncStatus;
}
/// <summary>
/// This method enables the connected scanner.
/// </summary>
/// <returns>a boolean based on whether it was able to enable the scanner.</returns>
private async Task<bool> EnableBarcodeScannerAsync(BarcodeScannerInstance instance)
{
switch (instance)
{
case BarcodeScannerInstance.Instance1:
await claimedBarcodeScannerInstance1.EnableAsync();
rootPage.NotifyUser("Instance 1 ready to scan. Device ID: " + claimedBarcodeScannerInstance1.DeviceId, NotifyType.StatusMessage);
break;
case BarcodeScannerInstance.Instance2:
await claimedBarcodeScannerInstance2.EnableAsync();
rootPage.NotifyUser("Instance 2 ready to scan. Device ID: " + claimedBarcodeScannerInstance2.DeviceId, NotifyType.StatusMessage);
break;
default:
return false;
}
return true;
}
/// <summary>
/// Reset the Scenario state
/// </summary>
private void ResetTheScenarioState()
{
if (claimedBarcodeScannerInstance1 != null)
{
claimedBarcodeScannerInstance1.Dispose();
claimedBarcodeScannerInstance1 = null;
}
if (barcodeScannerInstance1 != null)
{
barcodeScannerInstance1.Dispose();
barcodeScannerInstance1 = null;
}
if (claimedBarcodeScannerInstance2 != null)
{
claimedBarcodeScannerInstance2.Dispose();
claimedBarcodeScannerInstance2 = null;
}
if (barcodeScannerInstance2 != null)
{
barcodeScannerInstance2.Dispose();
barcodeScannerInstance2 = null;
}
ResetUI();
}
/// <summary>
/// Resets the display Elements to original state
/// </summary>
private void ResetUI()
{
Instance1Border.BorderBrush = new SolidColorBrush(Colors.Gray);
Instance2Border.BorderBrush = new SolidColorBrush(Colors.Gray);
ScanDataType1.Text = String.Format("No data");
ScanData1.Text = String.Format("No data");
DataLabel1.Text = String.Format("No data");
ScanDataType2.Text = String.Format("No data");
ScanData2.Text = String.Format("No data");
DataLabel2.Text = String.Format("No data");
ScenarioStartScanningInstance1.IsEnabled = true;
ScenarioStartScanningInstance2.IsEnabled = true;
ScenarioEndScanningInstance1.IsEnabled = false;
ScenarioEndScanningInstance2.IsEnabled = false;
}
/// <summary>
/// Sets the UI elements to a state corresponding to the current active Instance.
/// </summary>
/// <param name="instance">Corresponds to the current active instance</param>
private async void SetUI(BarcodeScannerInstance instance)
{
Instance1Border.BorderBrush = new SolidColorBrush(Colors.Gray);
Instance2Border.BorderBrush = new SolidColorBrush(Colors.Gray);
switch (instance)
{
case BarcodeScannerInstance.Instance1:
await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
ScenarioStartScanningInstance1.IsEnabled = false;
ScenarioStartScanningInstance2.IsEnabled = true;
ScenarioEndScanningInstance1.IsEnabled = true;
ScenarioEndScanningInstance2.IsEnabled = false;
Instance1Border.BorderBrush = new SolidColorBrush(Colors.DarkBlue);
}
);
break;
case BarcodeScannerInstance.Instance2:
await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
ScenarioStartScanningInstance1.IsEnabled = true;
ScenarioStartScanningInstance2.IsEnabled = false;
ScenarioEndScanningInstance1.IsEnabled = false;
ScenarioEndScanningInstance2.IsEnabled = true;
Instance2Border.BorderBrush = new SolidColorBrush(Colors.DarkBlue);
}
);
break;
}
}
/// <summary>
/// This is an event handler for the claimed scanner Instance 1 when it scans and recieves data
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private async void claimedBarcodeScannerInstance1_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
await MainPage.Current.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
ScanDataType1.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
DataLabel1.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
ScanData1.Text = DataHelpers.GetDataString(args.Report.ScanData);
rootPage.NotifyUser("Instance 1 received data from the barcode scanner.", NotifyType.StatusMessage);
}
);
}
/// <summary>
/// This is an event handler for the claimed scanner Instance 2 when it scans and recieves data
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private async void claimedBarcodeScannerInstance2_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
await MainPage.Current.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
ScanDataType2.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
DataLabel2.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
ScanData2.Text = DataHelpers.GetDataString(args.Report.ScanData);
rootPage.NotifyUser("Instance 2 received data from the barcode scanner.", NotifyType.StatusMessage);
}
);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using RaptorDB.Common;
using fastBinaryJSON;
using fastJSON;
namespace RaptorDB
{
internal class StorageData<T>
{
public StorageItem<T> meta;
public byte[] data;
}
public class StorageItem<T>
{
public T key;
public string typename;
public DateTime date = FastDateTime.Now;
public bool isDeleted;
public bool isReplicated;
public int dataLength;
public byte isCompressed; // 0 = no, 1 = MiniLZO
}
public interface IDocStorage<T>
{
int RecordCount();
byte[] GetBytes(int rowid, out StorageItem<T> meta);
object GetObject(int rowid, out StorageItem<T> meta);
StorageItem<T> GetMeta(int rowid);
bool GetObject(T key, out object doc);
}
public enum SF_FORMAT
{
BSON,
JSON
}
internal struct SplitFile
{
public long start;
public long uptolength;
public FileStream file;
}
public class StorageFile<T>
{
FileStream _datawrite;
FileStream _recfilewrite;
FileStream _recfileread = null;
FileStream _dataread = null;
private string _filename = "";
private string _recfilename = "";
private long _lastRecordNum = 0;
private long _lastWriteOffset = _fileheader.Length;
private object _readlock = new object();
private bool _dirty = false;
IGetBytes<T> _T = null;
ILog _log = LogManager.GetLogger(typeof(StorageFile<T>));
private SF_FORMAT _saveFormat = SF_FORMAT.BSON;
// **** change this if storage format changed ****
internal static int _CurrentVersion = 2;
//private ushort _splitMegaBytes = 0; // 0 = off
//private bool _enableSplits = false;
private List<SplitFile> _files = new List<SplitFile>();
private List<long> _uptoindexes = new List<long>();
// no splits in view mode
private bool _viewmode = false;
private SplitFile _lastsplitfile;
public static byte[] _fileheader = { (byte)'M', (byte)'G', (byte)'D', (byte)'B',
0, // 4 -- storage file version number,
0 // 5 -- not used
};
private static string _splitfileExtension = "00000";
private const int _KILOBYTE = 1024;
// record format :
// 1 type (0 = raw no meta data, 1 = bson meta, 2 = json meta)
// 4 byte meta/data length,
// n byte meta serialized data if exists
// m byte data (if meta exists then m is in meta.dataLength)
/// <summary>
/// View data storage mode (no splits, bson save)
/// </summary>
/// <param name="filename"></param>
public StorageFile(string filename)
{
_viewmode = true;
_saveFormat = SF_FORMAT.BSON;
// add version number
_fileheader[5] = (byte)_CurrentVersion;
Initialize(filename, false);
}
/// <summary>
///
/// </summary>
/// <param name="filename"></param>
/// <param name="format"></param>
/// <param name="StorageOnlyMode">= true -> don't create mgrec files (used for backup and replication mode)</param>
public StorageFile(string filename, SF_FORMAT format, bool StorageOnlyMode)
{
_saveFormat = format;
if (StorageOnlyMode) _viewmode = true; // no file splits
// add version number
_fileheader[5] = (byte)_CurrentVersion;
Initialize(filename, StorageOnlyMode);
}
private StorageFile(string filename, bool StorageOnlyMode)
{
Initialize(filename, StorageOnlyMode);
}
private void Initialize(string filename, bool StorageOnlyMode)
{
_T = RDBDataType<T>.ByteHandler();
_filename = filename;
// search for mgdat00000 extensions -> split files load
if (File.Exists(filename + _splitfileExtension))
{
LoadSplitFiles(filename);
}
if (File.Exists(filename) == false)
_datawrite = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
else
_datawrite = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
_dataread = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (_datawrite.Length == 0)
{
// new file
_datawrite.Write(_fileheader, 0, _fileheader.Length);
_datawrite.Flush();
_lastWriteOffset = _fileheader.Length;
}
else
{
long i = _datawrite.Seek(0L, SeekOrigin.End);
if (_files.Count == 0)
_lastWriteOffset = i;
else
_lastWriteOffset += i; // add to the splits
}
if (StorageOnlyMode == false)
{
// load rec pointers
_recfilename = filename.Substring(0, filename.LastIndexOf('.')) + ".mgrec";
if (File.Exists(_recfilename) == false)
_recfilewrite = new FileStream(_recfilename, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
else
_recfilewrite = new FileStream(_recfilename, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
_recfileread = new FileStream(_recfilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
_lastRecordNum = (int)(_recfilewrite.Length / 8);
_recfilewrite.Seek(0L, SeekOrigin.End);
}
}
private void LoadSplitFiles(string filename)
{
_log.Debug("Loading split files...");
_lastWriteOffset = 0;
for (int i = 0; ; i++)
{
string _filename = filename + i.ToString(_splitfileExtension);
if (File.Exists(_filename) == false)
break;
FileStream file = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
SplitFile sf = new SplitFile();
sf.start = _lastWriteOffset;
_lastWriteOffset += file.Length;
sf.file = file;
sf.uptolength = _lastWriteOffset;
_files.Add(sf);
_uptoindexes.Add(sf.uptolength);
}
_lastsplitfile = _files[_files.Count - 1];
_log.Debug("Number of split files = " + _files.Count);
}
public static int GetStorageFileHeaderVersion(string filename)
{
string fn = filename + _splitfileExtension; // if split files -> load the header from the first file -> mgdat00000
if (File.Exists(fn) == false)
fn = filename; // else use the mgdat file
if (File.Exists(fn))
{
var fs = new FileStream(fn, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Seek(0L, SeekOrigin.Begin);
byte[] b = new byte[_fileheader.Length];
fs.Read(b, 0, _fileheader.Length);
fs.Close();
return b[5];
}
return _CurrentVersion;
}
public int Count()
{
return (int)_lastRecordNum;// (int)(_recfilewrite.Length >> 3);
}
public long WriteRawData(byte[] b)
{
return internalWriteData(null, b, true);
}
public long Delete(T key)
{
StorageItem<T> meta = new StorageItem<T>();
meta.key = key;
meta.isDeleted = true;
return internalWriteData(meta, null, false);
}
public long DeleteReplicated(T key)
{
StorageItem<T> meta = new StorageItem<T>();
meta.key = key;
meta.isReplicated = true;
meta.isDeleted = true;
return internalWriteData(meta, null, false);
}
public long WriteObject(T key, object obj)
{
StorageItem<T> meta = new StorageItem<T>();
meta.key = key;
meta.typename = Reflection.Instance.GetTypeAssemblyName(obj.GetType());
byte[] data;
if (_saveFormat == SF_FORMAT.BSON)
data = BJSON.ToBJSON(obj);
else
data = Helper.GetBytes(JSON.ToJSON(obj));
if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE)
{
meta.isCompressed = 1;
data = MiniLZO.Compress(data); //MiniLZO
}
return internalWriteData(meta, data, false);
}
public long WriteReplicationObject(T key, object obj)
{
StorageItem<T> meta = new StorageItem<T>();
meta.key = key;
meta.isReplicated = true;
meta.typename = Reflection.Instance.GetTypeAssemblyName(obj.GetType());
byte[] data;
if (_saveFormat == SF_FORMAT.BSON)
data = BJSON.ToBJSON(obj);
else
data = Helper.GetBytes(JSON.ToJSON(obj));
if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE)
{
meta.isCompressed = 1;
data = MiniLZO.Compress(data);
}
return internalWriteData(meta, data, false);
}
public long WriteData(T key, byte[] data)
{
StorageItem<T> meta = new StorageItem<T>();
meta.key = key;
if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE)
{
meta.isCompressed = 1;
data = MiniLZO.Compress(data);
}
return internalWriteData(meta, data, false);
}
public byte[] ReadBytes(long recnum)
{
StorageItem<T> meta;
return ReadBytes(recnum, out meta);
}
public object ReadObject(long recnum)
{
StorageItem<T> meta = null;
return ReadObject(recnum, out meta);
}
public object ReadObject(long recnum, out StorageItem<T> meta)
{
byte[] b = ReadBytes(recnum, out meta);
if (b == null)
return null;
if (b[0] < 32)
return BJSON.ToObject(b);
else
return JSON.ToObject(Encoding.ASCII.GetString(b));
}
/// <summary>
/// used for views only
/// </summary>
/// <param name="recnum"></param>
/// <returns></returns>
public byte[] ViewReadRawBytes(long recnum)
{
// views can't be split
if (recnum >= _lastRecordNum)
return null;
lock (_readlock)
{
long offset = ComputeOffset(recnum);
_dataread.Seek(offset, System.IO.SeekOrigin.Begin);
byte[] hdr = new byte[5];
// read header
_dataread.Read(hdr, 0, 5); // meta length
int len = Helper.ToInt32(hdr, 1);
int type = hdr[0];
if (type == 0)
{
byte[] data = new byte[len];
_dataread.Read(data, 0, len);
return data;
}
return null;
}
}
public void Shutdown()
{
if (_files.Count > 0)
_files.ForEach(s => FlushClose(s.file));
FlushClose(_dataread);
FlushClose(_recfileread);
FlushClose(_recfilewrite);
FlushClose(_datawrite);
_dataread = null;
_recfileread = null;
_recfilewrite = null;
_datawrite = null;
}
public static StorageFile<Guid> ReadForward(string filename)
{
StorageFile<Guid> sf = new StorageFile<Guid>(filename, true);
return sf;
}
public StorageItem<T> ReadMeta(long rowid)
{
if (rowid >= _lastRecordNum)
return null;
lock (_readlock)
{
int metalen = 0;
long off = ComputeOffset(rowid);
FileStream fs = GetReadFileStreamWithSeek(off);
StorageItem<T> meta = ReadMetaData(fs, out metalen);
return meta;
}
}
#region [ private / internal ]
private long internalWriteData(StorageItem<T> meta, byte[] data, bool raw)
{
lock (_readlock)
{
_dirty = true;
// seek end of file
long offset = _lastWriteOffset;
if (_viewmode == false && Global.SplitStorageFilesMegaBytes > 0)
{
// current file size > _splitMegaBytes --> new file
if (offset > (long)Global.SplitStorageFilesMegaBytes * 1024 * 1024)
CreateNewStorageFile();
}
if (raw == false)
{
if (data != null)
meta.dataLength = data.Length;
byte[] metabytes = BJSON.ToBJSON(meta, new BJSONParameters { UseExtensions = false, UseTypedArrays = false });
// write header info
_datawrite.Write(new byte[] { 1 }, 0, 1); // FEATURE : add json here, write bson for now
_datawrite.Write(Helper.GetBytes(metabytes.Length, false), 0, 4);
_datawrite.Write(metabytes, 0, metabytes.Length);
// update pointer
_lastWriteOffset += metabytes.Length + 5;
}
else
{
// write header info
_datawrite.Write(new byte[] { 0 }, 0, 1); // write raw
_datawrite.Write(Helper.GetBytes(data.Length, false), 0, 4);
// update pointer
_lastWriteOffset += 5;
}
if (data != null)
{
// write data block
_datawrite.Write(data, 0, data.Length);
_lastWriteOffset += data.Length;
}
// return starting offset -> recno
long recno = _lastRecordNum++;
if (_recfilewrite != null)
_recfilewrite.Write(Helper.GetBytes(offset, false), 0, 8);
if (Global.FlushStorageFileImmediately)
{
_datawrite.Flush();
if (_recfilewrite != null)
_recfilewrite.Flush();
}
return recno;
}
}
private void CreateNewStorageFile()
{
_log.Debug("Split limit reached = " + _datawrite.Length);
int i = _files.Count;
// close files
FlushClose(_datawrite);
FlushClose(_dataread);
long start = 0;
if (i > 0)
start = _lastsplitfile.uptolength; // last file offset
// rename mgdat to mgdat0000n
File.Move(_filename, _filename + i.ToString(_splitfileExtension));
FileStream file = new FileStream(_filename + i.ToString(_splitfileExtension), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
SplitFile sf = new SplitFile();
sf.start = start;
sf.uptolength = _lastWriteOffset;
sf.file = file;
_files.Add(sf);
_uptoindexes.Add(sf.uptolength);
_lastsplitfile = sf;
// new mgdat file
_datawrite = new FileStream(_filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
_dataread = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
_log.Debug("New storage file created, count = " + _files.Count);
}
internal byte[] ReadBytes(long recnum, out StorageItem<T> meta)
{
meta = null;
if (recnum >= _lastRecordNum)
return null;
lock (_readlock)
{
long off = ComputeOffset(recnum);
FileStream fs = GetReadFileStreamWithSeek(off);
byte[] data = internalReadBytes(fs, out meta);
if (meta.isCompressed > 0)
data = MiniLZO.Decompress(data);
return data;
}
}
private long ComputeOffset(long recnum)
{
if (_dirty)
{
_datawrite.Flush();
_recfilewrite.Flush();
}
long off = recnum << 3;// *8L;
byte[] b = new byte[8];
_recfileread.Seek(off, SeekOrigin.Begin);
_recfileread.Read(b, 0, 8);
off = Helper.ToInt64(b, 0);
if (off == 0)// kludge
off = 6;
return off;
}
private byte[] internalReadBytes(FileStream fs, out StorageItem<T> meta)
{
int metalen = 0;
meta = ReadMetaData(fs, out metalen);
if (meta != null)
{
if (meta.isDeleted == false)
{
byte[] data = new byte[meta.dataLength];
fs.Read(data, 0, meta.dataLength);
return data;
}
}
else
{
byte[] data = new byte[metalen];
fs.Read(data, 0, metalen);
return data;
}
return null;
}
private StorageItem<T> ReadMetaData(FileStream fs, out int metasize)
{
byte[] hdr = new byte[5];
// read header
fs.Read(hdr, 0, 5); // meta length
int len = Helper.ToInt32(hdr, 1);
int type = hdr[0];
if (type > 0)
{
metasize = len + 5;
hdr = new byte[len];
fs.Read(hdr, 0, len);
StorageItem<T> meta;
if (type == 1)
meta = BJSON.ToObject<StorageItem<T>>(hdr);
else
{
string str = Helper.GetString(hdr, 0, (short)hdr.Length);
meta = JSON.ToObject<StorageItem<T>>(str);
}
return meta;
}
else
{
metasize = len;
return null;
}
}
private void FlushClose(FileStream st)
{
if (st != null)
{
st.Flush(true);
st.Close();
}
}
internal T GetKey(long recnum, out bool deleted)
{
lock (_readlock)
{
deleted = false;
long off = ComputeOffset(recnum);
FileStream fs = GetReadFileStreamWithSeek(off);
int metalen = 0;
StorageItem<T> meta = ReadMetaData(fs, out metalen);
deleted = meta.isDeleted;
return meta.key;
}
}
internal int CopyTo(StorageFile<T> storageFile, long startrecord)
{
FileStream fs;
bool inthefiles = false;
// copy data here
lock (_readlock)
{
long off = ComputeOffset(startrecord);
fs = GetReadFileStreamWithSeek(off);
if (fs != _dataread)
inthefiles = true;
Pump(fs, storageFile._datawrite);
}
// pump the remainder of the files also
if (inthefiles && _files.Count > 0)
{
long off = ComputeOffset(startrecord);
int i = binarysearch(off);
i++; // next file stream
for (int j = i; j < _files.Count; j++)
{
lock (_readlock)
{
fs = _files[j].file;
fs.Seek(0L, SeekOrigin.Begin);
Pump(fs, storageFile._datawrite);
}
}
// pump the current mgdat
lock (_readlock)
{
_dataread.Seek(0L, SeekOrigin.Begin);
Pump(_dataread, storageFile._datawrite);
}
}
return (int)_lastRecordNum;
}
private static void Pump(Stream input, Stream output)
{
byte[] bytes = new byte[4096 * 2];
int n;
while ((n = input.Read(bytes, 0, bytes.Length)) != 0)
output.Write(bytes, 0, n);
}
internal IEnumerable<StorageData<T>> ReadOnlyEnumerate()
{
// MGREC files may not exist
//// the total number of records
//long count = _recfileread.Length >> 3;
//for (long i = 0; i < count; i++)
//{
// StorageItem<T> meta;
// byte[] data = ReadBytes(i, out meta);
// StorageData<T> sd = new StorageData<T>();
// sd.meta = meta;
// if (meta.dataLength > 0)
// sd.data = data;
// yield return sd;
//}
long offset = _fileheader.Length;// start; // skip header
long size = _dataread.Length;
while (offset < size)
{
StorageData<T> sd = new StorageData<T>();
lock (_readlock)
{
_dataread.Seek(offset, SeekOrigin.Begin);
int metalen = 0;
StorageItem<T> meta = ReadMetaData(_dataread, out metalen);
offset += metalen;
sd.meta = meta;
if (meta.dataLength > 0)
{
byte[] data = new byte[meta.dataLength];
_dataread.Read(data, 0, meta.dataLength);
sd.data = data;
}
offset += meta.dataLength;
}
yield return sd;
}
}
private FileStream GetReadFileStreamWithSeek(long offset)
{
long fileoffset = offset;
// search split _files for offset and compute fileoffset in the file
if (_files.Count > 0) // we have splits
{
if (offset < _lastsplitfile.uptolength) // offset is in the list
{
int i = binarysearch(offset);
var f = _files[i];
fileoffset -= f.start; // offset in the file
f.file.Seek(fileoffset, SeekOrigin.Begin);
return f.file;
}
else
fileoffset -= _lastsplitfile.uptolength; // offset in the mgdat file
}
// seek to position in file
_dataread.Seek(fileoffset, SeekOrigin.Begin);
return _dataread;
}
private int binarysearch(long offset)
{
//// binary search
int low = 0;
int high = _files.Count - 1;
int midpoint = 0;
int lastlower = 0;
while (low <= high)
{
midpoint = low + (high - low) / 2;
long k = _uptoindexes[midpoint];
// check to see if value is equal to item in array
if (offset == k)
return midpoint + 1;
else if (offset < k)
{
high = midpoint - 1;
lastlower = midpoint;
}
else
low = midpoint + 1;
}
return lastlower;
}
#endregion
}
}
| |
//
// FormattedText.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using Xwt.Drawing;
using System.Text;
using System.Globalization;
namespace Xwt
{
public class FormattedText
{
List<TextAttribute> attributes = new List<TextAttribute> ();
public List<TextAttribute> Attributes {
get { return attributes; }
}
public string Text { get; set; }
class SpanInfo: List<TextAttribute>
{
public string Tag;
}
public static FormattedText FromMarkup (string markup)
{
FormattedText t = new FormattedText ();
t.ParseMarkup (markup);
return t;
}
void ParseMarkup (string markup)
{
Stack<SpanInfo> formatStack = new Stack<SpanInfo> ();
StringBuilder sb = new StringBuilder ();
int last = 0;
int i = markup.IndexOf ('<');
while (i != -1) {
sb.Append (markup, last, i - last);
if (PushSpan (formatStack, markup, sb.Length, ref i)) {
last = i;
i = markup.IndexOf ('<', i);
continue;
}
if (PopSpan (formatStack, markup, sb.Length, ref i)) {
last = i;
i = markup.IndexOf ('<', i);
continue;
}
last = i;
i = markup.IndexOf ('<', i + 1);
}
sb.Append (markup.Substring (last, markup.Length - last));
Text = sb.ToString ();
}
bool PushSpan (Stack<SpanInfo> formatStack, string markup, int textIndex, ref int i)
{
// <span kk="jj">
int k = i;
k++; // Skip the <
string tag;
if (!ReadId (markup, ref k, out tag))
return false;
SpanInfo span = new SpanInfo ();
span.Tag = tag;
switch (tag) {
case "b":
span.Add (new FontWeightTextAttribute () { Weight = FontWeight.Bold });
break;
case "i":
span.Add (new FontStyleTextAttribute () { Style = FontStyle.Italic });
break;
case "s":
span.Add (new StrikethroughTextAttribute ());
break;
case "u":
span.Add (new UnderlineTextAttribute ());
break;
case "a":
Uri href = null;
ReadXmlAttributes (markup, ref k, (name, val) => {
if (name == "href") {
href = new Uri (val, UriKind.RelativeOrAbsolute);
return true;
}
return false;
});
span.Add (new LinkTextAttribute () { Target = href });
break;
case "span":
ParseAttributes (span, markup, ref k);
break;
// case "small":
// case "big":
// case "tt":
}
if (span.Count == 0)
return false;
if (!ReadCharToken (markup, '>', ref k))
return false;
foreach (var att in span)
att.StartIndex = textIndex;
formatStack.Push (span);
i = k;
return true;
}
bool PopSpan (Stack<SpanInfo> formatStack, string markup, int textIndex, ref int i)
{
if (formatStack.Count == 0)
return false;
int k = i;
k++; // Skip the <
if (!ReadCharToken (markup, '/', ref k))
return false;
string tag;
if (!ReadId (markup, ref k, out tag))
return false;
// Make sure the closing tag matches the opened tag
if (!string.Equals (tag, formatStack.Peek ().Tag, StringComparison.InvariantCultureIgnoreCase))
return false;
if (!ReadCharToken (markup, '>', ref k))
return false;
var span = formatStack.Pop ();
foreach (var attr in span) {
attr.Count = textIndex - attr.StartIndex;
if (attr.Count > 0)
attributes.Add (attr);
}
i = k;
return true;
}
bool ParseAttributes (SpanInfo span, string markup, ref int i)
{
return ReadXmlAttributes (markup, ref i, (name, val) => {
var attr = CreateAttribute (name, val);
if (attr != null) {
span.Add (attr);
return true;
}
return false;
});
}
bool ReadXmlAttributes (string markup, ref int i, Func<string,string,bool> callback)
{
int k = i;
while (true) {
string name;
if (!ReadId (markup, ref k, out name))
return true; // No more attributes
if (!ReadCharToken (markup, '=', ref k))
return false;
char endChar;
if (ReadCharToken (markup, '"', ref k))
endChar = '"';
else if (ReadCharToken (markup, '\'', ref k))
endChar = '\'';
else
return false;
int n = markup.IndexOf (endChar, k);
if (n == -1)
return false;
string val = markup.Substring (k, n - k);
if (callback (name, val))
i = n + 1;
else
return false;
k = i;
}
}
TextAttribute CreateAttribute (string name, string val)
{
switch (name) {
case "font":
case "font-desc":
case "font_desc":
return new FontTextAttribute () { Font = Font.FromName (val) };
/* case "size":
case "font_size":
double s;
if (!double.TryParse (val, NumberStyles.Any, CultureInfo.InvariantCulture, out s))
return null;
return new FontSizeTextAttribute () { Size = s };
*/
case "font_weight":
case "font-weight":
case "weight":
FontWeight w;
if (!Enum.TryParse<FontWeight> (val, true, out w))
return null;
return new FontWeightTextAttribute () { Weight = w };
case "font_style":
case "font-style":
FontStyle s;
if (!Enum.TryParse<FontStyle> (val, true, out s))
return null;
return new FontStyleTextAttribute () { Style = s };
case "foreground":
case "fgcolor":
case "color":
Color c;
if (!Color.TryParse (val, out c))
return null;
return new ColorTextAttribute () { Color = c };
case "background":
case "background-color":
case "bgcolor":
Color bc;
if (!Color.TryParse (val, out bc))
return null;
return new BackgroundTextAttribute () { Color = bc };
case "underline":
return new UnderlineTextAttribute () {
Underline = ParseBool (val, false)
};
case "strikethrough":
return new StrikethroughTextAttribute () {
Strikethrough = ParseBool (val, false)
};
}
return null;
}
bool ParseBool (string s, bool defaultValue)
{
if (s.Length == 0)
return defaultValue;
return string.Equals (s, "true", StringComparison.OrdinalIgnoreCase);
}
bool ReadId (string markup, ref int i, out string tag)
{
tag = null;
int k = i;
if (!SkipWhitespace (markup, ref k))
return false;
var start = k;
while (k < markup.Length) {
char c = markup [k];
if (!char.IsLetterOrDigit (c) && c != '_' && c != '-')
break;
k++;
}
if (start == k)
return false;
tag = markup.Substring (start, k - start);
i = k;
return true;
}
bool ReadCharToken (string markup, char c, ref int i)
{
int k = i;
if (!SkipWhitespace (markup, ref k))
return false;
if (markup [k] == c) {
i = k + 1;
return true;
} else
return false;
}
bool SkipWhitespace (string markup, ref int k)
{
while (k < markup.Length) {
if (!char.IsWhiteSpace (markup [k]))
return true;
k++;
}
return false;
}
}
}
| |
#region License
/*
* EndPointManager.cs
*
* This code is derived from EndPointManager.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-2016 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@ximian.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
namespace WebSocketSharp.Net
{
internal sealed class EndPointManager
{
#region Private Fields
private static readonly Dictionary<IPAddress, Dictionary<int, EndPointListener>>
_addressToEndpoints;
#endregion
#region Static Constructor
static EndPointManager ()
{
_addressToEndpoints = new Dictionary<IPAddress, Dictionary<int, EndPointListener>> ();
}
#endregion
#region Private Constructors
private EndPointManager ()
{
}
#endregion
#region Private Methods
private static void addPrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix);
var path = pref.Path;
if (path.IndexOf ('%') != -1)
throw new HttpListenerException (87, "Includes an invalid path.");
if (path.IndexOf ("//", StringComparison.Ordinal) != -1)
throw new HttpListenerException (87, "Includes an invalid path.");
// Listens on all the interfaces if host name cannot be parsed by IPAddress.
getEndPointListener (pref, listener).AddPrefix (pref, listener);
}
private static IPAddress convertToIPAddress (string hostname)
{
if (hostname == "*" || hostname == "+")
return IPAddress.Any;
IPAddress addr;
if (IPAddress.TryParse (hostname, out addr))
return addr;
try {
var host = Dns.GetHostEntry (hostname);
return host != null ? host.AddressList[0] : IPAddress.Any;
}
catch {
return IPAddress.Any;
}
}
private static EndPointListener getEndPointListener (
HttpListenerPrefix prefix, HttpListener listener
)
{
var addr = convertToIPAddress (prefix.Host);
Dictionary<int, EndPointListener> eps = null;
if (_addressToEndpoints.ContainsKey (addr)) {
eps = _addressToEndpoints[addr];
}
else {
eps = new Dictionary<int, EndPointListener> ();
_addressToEndpoints[addr] = eps;
}
var port = prefix.Port;
EndPointListener lsnr = null;
if (eps.ContainsKey (port)) {
lsnr = eps[port];
}
else {
lsnr =
new EndPointListener (
addr,
port,
listener.ReuseAddress,
prefix.IsSecure,
listener.CertificateFolderPath,
listener.SslConfiguration
);
eps[port] = lsnr;
}
return lsnr;
}
private static void removePrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix);
var path = pref.Path;
if (path.IndexOf ('%') != -1)
return;
if (path.IndexOf ("//", StringComparison.Ordinal) != -1)
return;
getEndPointListener (pref, listener).RemovePrefix (pref, listener);
}
#endregion
#region Internal Methods
internal static void RemoveEndPoint (EndPointListener listener)
{
lock (((ICollection) _addressToEndpoints).SyncRoot) {
var addr = listener.Address;
var eps = _addressToEndpoints[addr];
eps.Remove (listener.Port);
if (eps.Count == 0)
_addressToEndpoints.Remove (addr);
listener.Close ();
}
}
#endregion
#region Public Methods
public static void AddListener (HttpListener listener)
{
var added = new List<string> ();
lock (((ICollection) _addressToEndpoints).SyncRoot) {
try {
foreach (var pref in listener.Prefixes) {
addPrefix (pref, listener);
added.Add (pref);
}
}
catch {
foreach (var pref in added)
removePrefix (pref, listener);
throw;
}
}
}
public static void AddPrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _addressToEndpoints).SyncRoot)
addPrefix (uriPrefix, listener);
}
public static void RemoveListener (HttpListener listener)
{
lock (((ICollection) _addressToEndpoints).SyncRoot) {
foreach (var pref in listener.Prefixes)
removePrefix (pref, listener);
}
}
public static void RemovePrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _addressToEndpoints).SyncRoot)
removePrefix (uriPrefix, listener);
}
#endregion
}
}
| |
/* ====================================================================
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.
==================================================================== */
/*
* FontFormatting.java
*
* Created on January 22, 2008, 10:05 PM
*/
namespace NPOI.HSSF.Record.CF
{
using System;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.SS.UserModel;
using NPOI.Util;
/**
* Border Formatting Block of the Conditional Formatting Rule Record.
*
* @author Dmitriy Kumshayev
*/
public class BorderFormatting
{
public BorderFormatting()
{
field_13_border_styles1 = (short)0;
field_14_border_styles2 = (short)0;
}
/** Creates new FontFormatting */
public BorderFormatting(RecordInputStream in1)
{
field_13_border_styles1 = in1.ReadInt();
field_14_border_styles2 = in1.ReadInt();
}
// BORDER FORMATTING BLOCK
// For Border Line Style codes see HSSFCellStyle.BORDER_XXXXXX
private int field_13_border_styles1;
private static BitField bordLeftLineStyle = BitFieldFactory.GetInstance(0x0000000F);
private static BitField bordRightLineStyle = BitFieldFactory.GetInstance(0x000000F0);
private static BitField bordTopLineStyle = BitFieldFactory.GetInstance(0x00000F00);
private static BitField bordBottomLineStyle = BitFieldFactory.GetInstance(0x0000F000);
private static BitField bordLeftLineColor = BitFieldFactory.GetInstance(0x007F0000);
private static BitField bordRightLineColor = BitFieldFactory.GetInstance(0x3F800000);
private static BitField bordTlBrLineOnOff = BitFieldFactory.GetInstance(0x40000000);
private static BitField bordBlTrtLineOnOff = BitFieldFactory.GetInstance(unchecked((int)0x80000000));
private int field_14_border_styles2;
private static BitField bordTopLineColor = BitFieldFactory.GetInstance(0x0000007F);
private static BitField bordBottomLineColor = BitFieldFactory.GetInstance(0x00003f80);
private static BitField bordDiagLineColor = BitFieldFactory.GetInstance(0x001FC000);
private static BitField bordDiagLineStyle = BitFieldFactory.GetInstance(0x01E00000);
/// <summary>
/// Get the type of border to use for the left border of the cell
/// </summary>
public BorderStyle BorderLeft {
get {
return (BorderStyle) bordLeftLineStyle.GetValue (field_13_border_styles1);
}
set {
field_13_border_styles1 = bordLeftLineStyle.SetValue (field_13_border_styles1, (int) value);
}
}
/// <summary>
/// Get the type of border to use for the right border of the cell
/// </summary>
public BorderStyle BorderRight {
get {
return (BorderStyle) bordRightLineStyle.GetValue (field_13_border_styles1);
}
set {
field_13_border_styles1 = bordRightLineStyle.SetValue (field_13_border_styles1, (int) value);
}
}
/// <summary>
/// Get the type of border to use for the top border of the cell
/// </summary>
public BorderStyle BorderTop {
get {
return (BorderStyle) bordTopLineStyle.GetValue (field_13_border_styles1);
}
set {
field_13_border_styles1 = bordTopLineStyle.SetValue (field_13_border_styles1, (int) value);
}
}
/// <summary>
/// Get the type of border to use for the bottom border of the cell
/// </summary>
public BorderStyle BorderBottom {
get {
return (BorderStyle) bordBottomLineStyle.GetValue (field_13_border_styles1);
}
set {
field_13_border_styles1 = bordBottomLineStyle.SetValue (field_13_border_styles1, (int) value);
}
}
/// <summary>
/// Get the type of border to use for the diagonal border of the cell
/// </summary>
public BorderStyle BorderDiagonal {
get {
return (BorderStyle) bordDiagLineStyle.GetValue (field_14_border_styles2);
}
set {
field_14_border_styles2 = bordDiagLineStyle.SetValue (field_14_border_styles2, (int) value);
}
}
/// <summary>
/// Get the color to use for the left border
/// </summary>
public short LeftBorderColor
{
get
{
return (short)bordLeftLineColor.GetValue(field_13_border_styles1);
}
set
{
field_13_border_styles1 = bordLeftLineColor.SetValue(field_13_border_styles1, value);
}
}
/// <summary>
/// Get the color to use for the right border
/// </summary>
public short RightBorderColor
{
get
{
return (short)bordRightLineColor.GetValue(field_13_border_styles1);
}
set
{
field_13_border_styles1 = bordRightLineColor.SetValue(field_13_border_styles1, value);
}
}
/// <summary>
/// Get the color to use for the top border
/// </summary>
public short TopBorderColor
{
get
{
return (short)bordTopLineColor.GetValue(field_14_border_styles2);
}
set
{
field_14_border_styles2 = bordTopLineColor.SetValue(field_14_border_styles2, value);
}
}
/// <summary>
/// Get the color to use for the bottom border
/// </summary>
public short BottomBorderColor
{
get
{
return (short)bordBottomLineColor.GetValue(field_14_border_styles2);
}
set
{
field_14_border_styles2 = bordBottomLineColor.SetValue(field_14_border_styles2, value);
}
}
/// <summary>
/// Get the color to use for the diagonal border
/// </summary>
public short DiagonalBorderColor
{
get
{
return (short)bordDiagLineColor.GetValue(field_14_border_styles2);
}
set
{
field_14_border_styles2 = bordDiagLineColor.SetValue(field_14_border_styles2, value);
}
}
/// <summary>
/// true if forward diagonal is on
/// </summary>
public bool IsForwardDiagonalOn
{
get
{
return bordBlTrtLineOnOff.IsSet(field_13_border_styles1);
}
set
{
field_13_border_styles1 = bordBlTrtLineOnOff.SetBoolean(field_13_border_styles1, value);
}
}
/// <summary>
/// true if backward diagonal Is on
/// </summary>
public bool IsBackwardDiagonalOn
{
get
{
return bordTlBrLineOnOff.IsSet(field_13_border_styles1);
}
set
{
field_13_border_styles1 = bordTlBrLineOnOff.SetBoolean(field_13_border_styles1, value);
}
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append(" [Border Formatting]\n");
buffer.Append(" .lftln = ").Append(StringUtil.ToHexString((int) BorderLeft)).Append("\n");
buffer.Append(" .rgtln = ").Append(StringUtil.ToHexString((int) BorderRight)).Append("\n");
buffer.Append(" .topln = ").Append(StringUtil.ToHexString((int) BorderTop)).Append("\n");
buffer.Append(" .btmln = ").Append(StringUtil.ToHexString((int) BorderBottom)).Append("\n");
buffer.Append(" .leftborder= ").Append(StringUtil.ToHexString(LeftBorderColor)).Append("\n");
buffer.Append(" .rghtborder= ").Append(StringUtil.ToHexString(RightBorderColor)).Append("\n");
buffer.Append(" .topborder= ").Append(StringUtil.ToHexString(TopBorderColor)).Append("\n");
buffer.Append(" .bottomborder= ").Append(StringUtil.ToHexString(BottomBorderColor)).Append("\n");
buffer.Append(" .fwdiag= ").Append(IsForwardDiagonalOn).Append("\n");
buffer.Append(" .bwdiag= ").Append(IsBackwardDiagonalOn).Append("\n");
buffer.Append(" [/Border Formatting]\n");
return buffer.ToString();
}
public Object Clone()
{
BorderFormatting rec = new BorderFormatting();
rec.field_13_border_styles1 = field_13_border_styles1;
rec.field_14_border_styles2 = field_14_border_styles2;
return rec;
}
public int Serialize(int offset, byte[] data)
{
LittleEndian.PutInt(data, offset, field_13_border_styles1);
offset += 4;
LittleEndian.PutInt(data, offset, field_14_border_styles2);
offset += 4;
return 8;
}
public void Serialize(ILittleEndianOutput out1)
{
out1.WriteInt(field_13_border_styles1);
out1.WriteInt(field_14_border_styles2);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Runtime.Remoting.Lifetime;
using System.Windows.Forms;
using System.Drawing;
using NationalInstruments;
using NationalInstruments.DAQmx;
using DAQ;
using DAQ.HAL;
using DAQ.Environment;
using DAQ.NIScope;
namespace ParityHardwareControl
{
/// <summary>
/// A Hardware controller for the Parity experiment.
/// For the moment, it's just operates the fast NI card and does a few DAQmx operations.
///
/// </summary>
public class Controller : MarshalByRefObject, NIScopeControllable
{
#region Constants
//Put any constants and stuff here
private static string profilesPath = (string)Environs.FileSystem.Paths["settingsPath"]
+ "ParityHardwareController\\";
private static Hashtable calibrations = Environs.Hardware.Calibrations;
#endregion
#region Setup
// Declare that there will be a controlWindow
ControlWindow controlWindow;
//There will be some 'slow' analog and digital tasks
Dictionary<string, Task> analogTasks;
Hashtable digitalTasks = new Hashtable();
NIScopeControlHelper scope;
// without this method, any remote connections to this object will time out after
// five minutes of inactivity.
// It just overrides the lifetime lease system completely.
public override Object InitializeLifetimeService()
{
return null;
}
public void Start()
{
// make the digital analogTasks. The function "CreateDigitalTask" is defined later
//e.g CreateDigitalTask("notEOnOff");
// CreateDigitalTask("eOnOff");
//This is to keep track of the various things which the HC controls.
analogTasks = new Dictionary<string, Task>();
//CreateDigitalTask("aom0enable");
// make the analog output analogTasks. The function "CreateAnalogOutputTask" is defined later
//e.g. bBoxAnalogOutputTask = CreateAnalogOutputTask("b");
// steppingBBiasAnalogOutputTask = CreateAnalogOutputTask("steppingBBias");
//CreateAnalogOutputTask("aom0amplitude");
// CreateAnalogInputTask("laserLockErrorSignal", -10, 10);
// make the control controlWindow
controlWindow = new ControlWindow();
controlWindow.controller = this;
scope = new NIScopeControlHelper();
System.Console.Out.Write("Startup complete. Opening control window. \n");
Application.Run(controlWindow);
}
#endregion
#region private methods for creating un-timed Tasks/channels
// a list of functions for creating various analogTasks
private void CreateAnalogInputTask(string channel)
{
analogTasks[channel] = new Task(channel);
((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
analogTasks[channel],
0,
10
);
analogTasks[channel].Control(TaskAction.Verify);
}
// an overload to specify input range
private void CreateAnalogInputTask(string channel, double lowRange, double highRange)
{
analogTasks[channel] = new Task(channel);
((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
analogTasks[channel],
lowRange,
highRange
);
analogTasks[channel].Control(TaskAction.Verify);
}
private void CreateAnalogOutputTask(string channel)
{
analogTasks[channel] = new Task(channel);
AnalogOutputChannel c = ((AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[channel]);
c.AddToTask(
analogTasks[channel],
c.RangeLow,
c.RangeHigh
);
analogTasks[channel].Control(TaskAction.Verify);
}
// setting an analog voltage to an output
public void SetAnalogOutput(string channel, double voltage)
{
SetAnalogOutput(channel, voltage, false);
}
//Overload for using a calibration before outputting to hardware
public void SetAnalogOutput(string channelName, double voltage, bool useCalibration)
{
AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(analogTasks[channelName].Stream);
double output;
if (useCalibration)
{
try
{
output = ((Calibration)calibrations[channelName]).Convert(voltage);
}
catch (DAQ.HAL.Calibration.CalibrationRangeException)
{
MessageBox.Show("The number you have typed is out of the calibrated range! \n Try typing something more sensible.");
throw new CalibrationException();
}
catch
{
MessageBox.Show("Calibration error");
throw new CalibrationException();
}
}
else
{
output = voltage;
}
try
{
writer.WriteSingleSample(true, output);
analogTasks[channelName].Control(TaskAction.Unreserve);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
public class CalibrationException : ArgumentOutOfRangeException { };
// reading an analog voltage from input
public double ReadAnalogInput(string channel)
{
return ReadAnalogInput(channel, false);
}
public double ReadAnalogInput(string channelName, bool useCalibration)
{
AnalogSingleChannelReader reader = new AnalogSingleChannelReader(analogTasks[channelName].Stream);
double val = reader.ReadSingleSample();
analogTasks[channelName].Control(TaskAction.Unreserve);
if (useCalibration)
{
try
{
return ((Calibration)calibrations[channelName]).Convert(val);
}
catch
{
MessageBox.Show("Calibration error");
return val;
}
}
else
{
return val;
}
}
// overload for reading multiple samples
public double ReadAnalogInput(string channel, double sampleRate, int numOfSamples, bool useCalibration)
{
//Configure the timing parameters of the task
analogTasks[channel].Timing.ConfigureSampleClock("", sampleRate,
SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, numOfSamples);
//Read in multiple samples
AnalogSingleChannelReader reader = new AnalogSingleChannelReader(analogTasks[channel].Stream);
double[] valArray = reader.ReadMultiSample(numOfSamples);
analogTasks[channel].Control(TaskAction.Unreserve);
//Calculate the average of the samples
double sum = 0;
for (int j = 0; j < numOfSamples; j++)
{
sum = sum + valArray[j];
}
double val = sum / numOfSamples;
if (useCalibration)
{
try
{
return ((Calibration)calibrations[channel]).Convert(val);
}
catch
{
MessageBox.Show("Calibration error");
return val;
}
}
else
{
return val;
}
}
private void CreateDigitalTask(String name)
{
Task digitalTask = new Task(name);
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[name]).AddToTask(digitalTask);
digitalTask.Control(TaskAction.Verify);
digitalTasks.Add(name, digitalTask);
}
public void SetDigitalLine(string name, bool value)
{
Task digitalTask = ((Task)digitalTasks[name]);
DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalTask.Stream);
writer.WriteSingleSampleSingleLine(true, value);
digitalTask.Control(TaskAction.Unreserve);
}
#endregion
#region Remoting stuff
/// <summary>
/// These SetValue functions are for giving commands to the hc from another program, while keeping the hc in control of hardware.
/// Use this if you want the HC to keep control, but you want to control the HC from some other program
/// </summary>
public void SetValue(string channel, double value)
{
SetAnalogOutput(channel, value, false);
}
public void SetValue(string channel, double value, bool useCalibration)
{
SetAnalogOutput(channel, value, useCalibration);
}
public void SetValue(string channel, bool value)
{
SetDigitalLine(channel, value);
}
#endregion
#region The Fast NIScope card
public double[] GetShot()
{
return scope.GetShot();
}
public void ArmAndWait()
{
scope.ArmAndWait();
}
public void StartAcquisition(string channelName, double sampleRate, double referencePosition,
double range, int numberOfPoints, int numberOfRecords)
{
System.Console.Out.Write("Initialising NI-Scope card and starting acquisition...");
scope.StartAcquisition(channelName, sampleRate, referencePosition, range, numberOfPoints, numberOfRecords);
System.Console.Out.Write("complete.\n");
}
public void StartScan()
{
scope.StartScan();
}
public void FinishScan()
{
scope.FinishScan();
}
public void FinishAcquisition()
{
System.Console.Out.Write("Finishing acquisition on NI-Scope card.");
scope.FinishAcquisition();
System.Console.Out.Write("complete.\n");
}
#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.Linq;
using System.Net.Test.Common;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
public class NegotiateStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(false, serverIdentity.IsAuthenticated);
Assert.Equal("", serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
string targetName = "testTargetName";
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName);
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
{
string targetName = "testTargetName";
// Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
// NetworkCredential object with empty user, password and domain.
NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync(emptyNetworkCredential, targetName);
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
// TODO #5241: Behavior difference:
Assert.Equal(false, clientIdentity.IsAuthenticated);
// On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
}
}
[ActiveIssue(5283, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
[PlatformSpecific(PlatformID.Linux | PlatformID.OSX)]
public void NegotiateStream_Ctor_Throws()
{
Assert.Throws<PlatformNotSupportedException>(() => new NegotiateStream(new VirtualNetworkStream(null, isServer: false)));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Practices.ServiceLocation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Logging;
using Prism.Modularity;
using Prism.Wpf.Tests.Mocks;
namespace Prism.Wpf.Tests.Modularity
{
/// <summary>
/// Summary description for ModuleInitializerFixture
/// </summary>
[TestClass]
public class ModuleInitializerFixture
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullContainerThrows()
{
ModuleInitializer loader = new ModuleInitializer(null, new MockLogger());
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullLoggerThrows()
{
ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), null);
}
[TestMethod]
[ExpectedException(typeof(ModuleInitializeException))]
public void InitializationExceptionsAreWrapped()
{
var moduleInfo = CreateModuleInfo(typeof(ExceptionThrowingModule));
ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), new MockLogger());
loader.Initialize(moduleInfo);
}
[TestMethod]
public void ShouldResolveModuleAndInitializeSingleModule()
{
IServiceLocator containerFacade = new MockContainerAdapter();
var service = new ModuleInitializer(containerFacade, new MockLogger());
FirstTestModule.wasInitializedOnce = false;
var info = CreateModuleInfo(typeof(FirstTestModule));
service.Initialize(info);
Assert.IsTrue(FirstTestModule.wasInitializedOnce);
}
[TestMethod]
public void ShouldLogModuleInitializeErrorsAndContinueLoading()
{
IServiceLocator containerFacade = new MockContainerAdapter();
var logger = new MockLogger();
var service = new CustomModuleInitializerService(containerFacade, logger);
var invalidModule = CreateModuleInfo(typeof(InvalidModule));
Assert.IsFalse(service.HandleModuleInitializerrorCalled);
service.Initialize(invalidModule);
Assert.IsTrue(service.HandleModuleInitializerrorCalled);
}
[TestMethod]
public void ShouldLogModuleInitializationError()
{
IServiceLocator containerFacade = new MockContainerAdapter();
var logger = new MockLogger();
var service = new ModuleInitializer(containerFacade, logger);
ExceptionThrowingModule.wasInitializedOnce = false;
var exceptionModule = CreateModuleInfo(typeof(ExceptionThrowingModule));
try
{
service.Initialize(exceptionModule);
}
catch (ModuleInitializeException)
{
}
Assert.IsNotNull(logger.LastMessage);
StringAssert.Contains(logger.LastMessage, "ExceptionThrowingModule");
}
[TestMethod]
public void ShouldThrowExceptionIfBogusType()
{
var moduleInfo = new ModuleInfo("TestModule", "BadAssembly.BadType");
ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), new MockLogger());
try
{
loader.Initialize(moduleInfo);
Assert.Fail("Did not throw exception");
}
catch (ModuleInitializeException ex)
{
StringAssert.Contains(ex.Message, "BadAssembly.BadType");
}
catch(Exception)
{
Assert.Fail();
}
}
private static ModuleInfo CreateModuleInfo(Type type, params string[] dependsOn)
{
ModuleInfo moduleInfo = new ModuleInfo(type.Name, type.AssemblyQualifiedName);
moduleInfo.DependsOn.AddRange(dependsOn);
return moduleInfo;
}
public static class ModuleLoadTracker
{
public static readonly Stack<Type> ModuleLoadStack = new Stack<Type>();
}
public class FirstTestModule : IModule
{
public static bool wasInitializedOnce;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class SecondTestModule : IModule
{
public static bool wasInitializedOnce;
public static long initializedOnTickCount;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class DependantModule : IModule
{
public static bool wasInitializedOnce;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class DependencyModule : IModule
{
public static bool wasInitializedOnce;
public static long initializedOnTickCount;
public void Initialize()
{
wasInitializedOnce = true;
ModuleLoadTracker.ModuleLoadStack.Push(GetType());
}
}
public class ExceptionThrowingModule : IModule
{
public static bool wasInitializedOnce;
public static long initializedOnTickCount;
public void Initialize()
{
throw new InvalidOperationException("Intialization can't be performed");
}
}
public class InvalidModule { }
public class CustomModuleInitializerService : ModuleInitializer
{
public bool HandleModuleInitializerrorCalled;
public CustomModuleInitializerService(IServiceLocator containerFacade, ILoggerFacade logger)
: base(containerFacade, logger)
{
}
public override void HandleModuleInitializationError(ModuleInfo moduleInfo, string assemblyName, Exception exception)
{
HandleModuleInitializerrorCalled = true;
}
}
public class Module1 : IModule { void IModule.Initialize() { } }
public class Module2 : IModule { void IModule.Initialize() { } }
public class Module3 : IModule { void IModule.Initialize() { } }
public class Module4 : IModule { void IModule.Initialize() { } }
}
}
| |
using Avalonia.Collections;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Utilities;
namespace Avalonia.Controls
{
/// <summary>
/// Enum which describes how to position the TickBar.
/// </summary>
public enum TickBarPlacement
{
/// <summary>
/// Position this tick at the left of target element.
/// </summary>
Left,
/// <summary>
/// Position this tick at the top of target element.
/// </summary>
Top,
/// <summary>
/// Position this tick at the right of target element.
/// </summary>
Right,
/// <summary>
/// Position this tick at the bottom of target element.
/// </summary>
Bottom,
}
/// <summary>
/// An element that is used for drawing <see cref="Slider"/>'s Ticks.
/// </summary>
public class TickBar : Control
{
static TickBar()
{
AffectsRender<TickBar>(FillProperty,
IsDirectionReversedProperty,
ReservedSpaceProperty,
MaximumProperty,
MinimumProperty,
OrientationProperty,
PlacementProperty,
TickFrequencyProperty,
TicksProperty);
}
public TickBar() : base()
{
}
/// <summary>
/// Defines the <see cref="Fill"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> FillProperty =
AvaloniaProperty.Register<TickBar, IBrush>(nameof(Fill));
/// <summary>
/// Brush used to fill the TickBar's Ticks.
/// </summary>
public IBrush Fill
{
get { return GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
/// <summary>
/// Defines the <see cref="Minimum"/> property.
/// </summary>
public static readonly StyledProperty<double> MinimumProperty =
AvaloniaProperty.Register<TickBar, double>(nameof(Minimum), 0d);
/// <summary>
/// Logical position where the Minimum Tick will be drawn
/// </summary>
public double Minimum
{
get { return GetValue(MinimumProperty); }
set
{
SetValue(MinimumProperty, value);
}
}
/// <summary>
/// Defines the <see cref="Maximum"/> property.
/// </summary>
public static readonly StyledProperty<double> MaximumProperty =
AvaloniaProperty.Register<TickBar, double>(nameof(Maximum), 0d);
/// <summary>
/// Logical position where the Maximum Tick will be drawn
/// </summary>
public double Maximum
{
get { return GetValue(MaximumProperty); }
set { SetValue(MaximumProperty, value); }
}
/// <summary>
/// Defines the <see cref="TickFrequency"/> property.
/// </summary>
public static readonly StyledProperty<double> TickFrequencyProperty =
AvaloniaProperty.Register<TickBar, double>(nameof(TickFrequency), 0d);
/// <summary>
/// TickFrequency property defines how the tick will be drawn.
/// </summary>
public double TickFrequency
{
get { return GetValue(TickFrequencyProperty); }
set { SetValue(TickFrequencyProperty, value); }
}
/// <summary>
/// Defines the <see cref="Orientation"/> property.
/// </summary>
public static readonly StyledProperty<Orientation> OrientationProperty =
AvaloniaProperty.Register<TickBar, Orientation>(nameof(Orientation));
/// <summary>
/// TickBar parent's orientation.
/// </summary>
public Orientation Orientation
{
get { return GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
/// <summary>
/// Defines the <see cref="Ticks"/> property.
/// </summary>
public static readonly StyledProperty<AvaloniaList<double>> TicksProperty =
AvaloniaProperty.Register<TickBar, AvaloniaList<double>>(nameof(Ticks));
/// <summary>
/// The Ticks property contains collection of value of type Double which
/// are the logical positions use to draw the ticks.
/// The property value is a <see cref="AvaloniaList{T}" />.
/// </summary>
public AvaloniaList<double> Ticks
{
get { return GetValue(TicksProperty); }
set { SetValue(TicksProperty, value); }
}
/// <summary>
/// Defines the <see cref="IsDirectionReversed"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsDirectionReversedProperty =
AvaloniaProperty.Register<TickBar, bool>(nameof(IsDirectionReversed), false);
/// <summary>
/// The IsDirectionReversed property defines the direction of value incrementation.
/// By default, if Tick's orientation is Horizontal, ticks will be drawn from left to right.
/// (And, bottom to top for Vertical orientation).
/// If IsDirectionReversed is 'true' the direction of the drawing will be in opposite direction.
/// </summary>
public bool IsDirectionReversed
{
get { return GetValue(IsDirectionReversedProperty); }
set { SetValue(IsDirectionReversedProperty, value); }
}
/// <summary>
/// Defines the <see cref="Placement"/> property.
/// </summary>
public static readonly StyledProperty<TickBarPlacement> PlacementProperty =
AvaloniaProperty.Register<TickBar, TickBarPlacement>(nameof(Placement), 0d);
/// <summary>
/// Placement property specified how the Tick will be placed.
/// This property affects the way ticks are drawn.
/// This property has type of <see cref="TickBarPlacement" />.
/// </summary>
public TickBarPlacement Placement
{
get { return GetValue(PlacementProperty); }
set { SetValue(PlacementProperty, value); }
}
/// <summary>
/// Defines the <see cref="ReservedSpace"/> property.
/// </summary>
public static readonly StyledProperty<Rect> ReservedSpaceProperty =
AvaloniaProperty.Register<TickBar, Rect>(nameof(ReservedSpace));
/// <summary>
/// TickBar will use ReservedSpaceProperty for left and right spacing (for horizontal orientation) or
/// top and bottom spacing (for vertical orienation).
/// The space on both sides of TickBar is half of specified ReservedSpace.
/// This property has type of <see cref="Rect" />.
/// </summary>
public Rect ReservedSpace
{
get { return GetValue(ReservedSpaceProperty); }
set { SetValue(ReservedSpaceProperty, value); }
}
/// <summary>
/// Draw ticks.
/// Ticks can be draw in 8 different ways depends on Placement property and IsDirectionReversed property.
///
/// This function also draw selection-tick(s) if IsSelectionRangeEnabled is 'true' and
/// SelectionStart and SelectionEnd are valid.
///
/// The primary ticks (for Mininum and Maximum value) height will be 100% of TickBar's render size (use Width or Height
/// depends on Placement property).
///
/// The secondary ticks (all other ticks, including selection-tics) height will be 75% of TickBar's render size.
///
/// Brush that use to fill ticks is specified by Fill property.
/// </summary>
public override void Render(DrawingContext dc)
{
var size = new Size(Bounds.Width, Bounds.Height);
var range = Maximum - Minimum;
var tickLen = 0.0d; // Height for Primary Tick (for Mininum and Maximum value)
var tickLen2 = 0.0d; // Height for Secondary Tick
var logicalToPhysical = 1.0;
var startPoint = new Point();
var endPoint = new Point();
var rSpace = Orientation == Orientation.Horizontal ? ReservedSpace.Width : ReservedSpace.Height;
// Take Thumb size in to account
double halfReservedSpace = rSpace * 0.5;
switch (Placement)
{
case TickBarPlacement.Top:
if (MathUtilities.GreaterThanOrClose(rSpace, size.Width))
{
return;
}
size = new Size(size.Width - rSpace, size.Height);
tickLen = -size.Height;
startPoint = new Point(halfReservedSpace, size.Height);
endPoint = new Point(halfReservedSpace + size.Width, size.Height);
logicalToPhysical = size.Width / range;
break;
case TickBarPlacement.Bottom:
if (MathUtilities.GreaterThanOrClose(rSpace, size.Width))
{
return;
}
size = new Size(size.Width - rSpace, size.Height);
tickLen = size.Height;
startPoint = new Point(halfReservedSpace, 0d);
endPoint = new Point(halfReservedSpace + size.Width, 0d);
logicalToPhysical = size.Width / range;
break;
case TickBarPlacement.Left:
if (MathUtilities.GreaterThanOrClose(rSpace, size.Height))
{
return;
}
size = new Size(size.Width, size.Height - rSpace);
tickLen = -size.Width;
startPoint = new Point(size.Width, size.Height + halfReservedSpace);
endPoint = new Point(size.Width, halfReservedSpace);
logicalToPhysical = size.Height / range * -1;
break;
case TickBarPlacement.Right:
if (MathUtilities.GreaterThanOrClose(rSpace, size.Height))
{
return;
}
size = new Size(size.Width, size.Height - rSpace);
tickLen = size.Width;
startPoint = new Point(0d, size.Height + halfReservedSpace);
endPoint = new Point(0d, halfReservedSpace);
logicalToPhysical = size.Height / range * -1;
break;
};
tickLen2 = tickLen * 0.75;
// Invert direciton of the ticks
if (IsDirectionReversed)
{
logicalToPhysical *= -1;
// swap startPoint & endPoint
var pt = startPoint;
startPoint = endPoint;
endPoint = pt;
}
var pen = new Pen(Fill, 1.0d);
// Is it Vertical?
if (Placement == TickBarPlacement.Left || Placement == TickBarPlacement.Right)
{
// Reduce tick interval if it is more than would be visible on the screen
double interval = TickFrequency;
if (interval > 0.0)
{
double minInterval = (Maximum - Minimum) / size.Height;
if (interval < minInterval)
{
interval = minInterval;
}
}
// Draw Min & Max tick
dc.DrawLine(pen, startPoint, new Point(startPoint.X + tickLen, startPoint.Y));
dc.DrawLine(pen, new Point(startPoint.X, endPoint.Y),
new Point(startPoint.X + tickLen, endPoint.Y));
// This property is rarely set so let's try to avoid the GetValue
// caching of the mutable default value
var ticks = Ticks ?? null;
// Draw ticks using specified Ticks collection
if (ticks?.Count > 0)
{
for (int i = 0; i < ticks.Count; i++)
{
if (MathUtilities.LessThanOrClose(ticks[i], Minimum) || MathUtilities.GreaterThanOrClose(ticks[i], Maximum))
{
continue;
}
double adjustedTick = ticks[i] - Minimum;
double y = adjustedTick * logicalToPhysical + startPoint.Y;
dc.DrawLine(pen,
new Point(startPoint.X, y),
new Point(startPoint.X + tickLen2, y));
}
}
// Draw ticks using specified TickFrequency
else if (interval > 0.0)
{
for (double i = interval; i < range; i += interval)
{
double y = i * logicalToPhysical + startPoint.Y;
dc.DrawLine(pen,
new Point(startPoint.X, y),
new Point(startPoint.X + tickLen2, y));
}
}
}
else // Placement == Top || Placement == Bottom
{
// Reduce tick interval if it is more than would be visible on the screen
double interval = TickFrequency;
if (interval > 0.0)
{
double minInterval = (Maximum - Minimum) / size.Width;
if (interval < minInterval)
{
interval = minInterval;
}
}
// Draw Min & Max tick
dc.DrawLine(pen, startPoint, new Point(startPoint.X, startPoint.Y + tickLen));
dc.DrawLine(pen, new Point(endPoint.X, startPoint.Y),
new Point(endPoint.X, startPoint.Y + tickLen));
// This property is rarely set so let's try to avoid the GetValue
// caching of the mutable default value
var ticks = Ticks ?? null;
// Draw ticks using specified Ticks collection
if (ticks?.Count > 0)
{
for (int i = 0; i < ticks.Count; i++)
{
if (MathUtilities.LessThanOrClose(ticks[i], Minimum) || MathUtilities.GreaterThanOrClose(ticks[i], Maximum))
{
continue;
}
double adjustedTick = ticks[i] - Minimum;
double x = adjustedTick * logicalToPhysical + startPoint.X;
dc.DrawLine(pen,
new Point(x, startPoint.Y),
new Point(x, startPoint.Y + tickLen2));
}
}
// Draw ticks using specified TickFrequency
else if (interval > 0.0)
{
for (double i = interval; i < range; i += interval)
{
double x = i * logicalToPhysical + startPoint.X;
dc.DrawLine(pen,
new Point(x, startPoint.Y),
new Point(x, startPoint.Y + tickLen2));
}
}
}
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
//Added for UNET tutorials
float animSpeed = Mathf.Abs(vertical);
GetComponent<Animator>().SetFloat("Speed", animSpeed);
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using MCEBuddy.Globals;
using MCEBuddy.Util;
namespace MCEBuddy.AppWrapper
{
public class FFmpeg : Base
{
private const string APP_PATH = "ffmpeg\\ffmpeg.exe";
private const string DVRMS_APP_PATH = "ffmpeg\\ffmpeg.dvrms.exe";
private float _Duration = 0;
private double[] _dupArray = new double[0];
private double _lastDup = 0;
private double[] _dropArray = new double[0];
private double _lastDrop = 0;
private bool _muxError = false;
private bool _h264mp4toannexbError = false; // Specific error condition when putting H.264 to MPEGTS format
private bool _aacadtstoascError = false; // Specific error while converting TS to MP4 format
private bool _encodeError = false; // Any critical error
/// <summary>
/// General FFMPEG to convert a file
/// </summary>
/// <param name="Parameters">Parameters to pass to FFMPEG</param>
/// <param name="jobStatus">Reference to JobStatus</param>
/// <param name="jobLog">JobLog</param>
public FFmpeg(string Parameters, JobStatus jobStatus, Log jobLog, bool ignoreSuspend = false)
: base(Parameters, APP_PATH, jobStatus, jobLog, ignoreSuspend)
{
_Parameters = " -probesize 100M -analyzeduration 300M " + _Parameters; // We need to probe deeper into the files to get the correct audio / video track information else it can lead to incorrect channel information and failure
_success = false; //ffmpeg looks for a +ve output so we have a false to begin with
_uiAdminSessionProcess = true; // Assume we are always using ffmpeg build with hardware API's (UI Session 1 process)
}
/// <summary>
/// FFMPEG to convert a DVRMS file
/// </summary>
/// <param name="Parameters">Parameters to pass to FFMPEG</param>
/// <param name="DVRMS">Set to true if converting a DVRMS file</param>
/// <param name="jobStatus">Reference to JobStatus</param>
/// <param name="jobLog">JobLog</param>
public FFmpeg(string Parameters, bool DVRMS, JobStatus jobStatus, Log jobLog, bool ignoreSuspend = false)
: base(Parameters, DVRMS_APP_PATH, jobStatus, jobLog, ignoreSuspend)
{
_success = false; //ffmpeg looks for a +ve output so we have a false to begin with
}
/// <summary>
/// True of there is a Non Monotonically Increasing Muxing error
/// </summary>
public bool MuxError
{ get { return _muxError; } }
/// <summary>
/// True is there is a h264_mp4toannexb bitstream parsing error
/// </summary>
public bool H264MP4ToAnnexBError
{ get { return _h264mp4toannexbError; } }
/// <summary>
/// True is there is a aac_adtstoasc bitstream parsing error
/// </summary>
public bool AACADTSToASCError
{ get { return _aacadtstoascError; } }
/// <summary>
/// Returns true if any of the errors detected are a fatal error
/// </summary>
private bool FatalError
{ get { return (_muxError || _encodeError || _h264mp4toannexbError || _aacadtstoascError); } }
/// <summary>
/// Return the average rate of change in duplicate frames
/// </summary>
public double AverageDupROC
{
get
{
if (_dupArray.Length == 0)
return 0;
else
return _dupArray.Average();
}
}
/// <summary>
/// Return the average rate of change in dropped frames
/// </summary>
public double AverageDropROC
{
get
{
if (_dropArray.Length == 0)
return 0;
else
return _dropArray.Average();
}
}
private float TimeStringToSecs(string timeString)
{
// Cater for different cuilds fo ffmpeg and their varying output
if (timeString.Contains(":"))
{
float secs = 0;
int mult = 1;
string[] timeVals = timeString.Split(':');
for (int i = timeVals.Length - 1; i >= 0; i--)
{
float val = 0;
float.TryParse(timeVals[i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out val);
secs += mult * val;
mult = mult * 60;
}
return secs;
}
else
{
float secs = 0;
float.TryParse(timeString, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out secs);
return secs;
}
}
protected override void OutputHandler(object sendingProcess, System.Diagnostics.DataReceivedEventArgs ConsoleOutput)
{
try
{
string StdOut;
int StartPos, EndPos;
base.OutputHandler(sendingProcess, ConsoleOutput);
if (ConsoleOutput.Data == null) return;
if (!String.IsNullOrEmpty(ConsoleOutput.Data))
{
StdOut = ConsoleOutput.Data;
if (StdOut.Contains("Duration:") && StdOut.Contains(",") && (_Duration < 1))
{
StartPos = StdOut.IndexOf("Duration:") + "Duration:".Length;
EndPos = StdOut.IndexOf(",", StartPos);
_Duration = TimeStringToSecs(StdOut.Substring(StartPos, EndPos - StartPos));
_jobLog.WriteEntry("Video duration=" + _Duration, Log.LogEntryType.Debug);
}
else if (StdOut.Contains("frame=") && StdOut.Contains("time="))
{
StartPos = StdOut.IndexOf("time=") + "time=".Length;
EndPos = StdOut.IndexOf(" ", StartPos);
float timeCoded = TimeStringToSecs(StdOut.Substring(StartPos, EndPos - StartPos));
if (timeCoded > 0)
{
_jobStatus.PercentageComplete = (float)(timeCoded / _Duration * 100);
UpdateETAByPercentageComplete();
}
}
// Capture average rate of change in duplicate frames
if (StdOut.Contains("dup="))
{
StartPos = StdOut.IndexOf("dup=") + "dup=".Length;
EndPos = StdOut.IndexOf(" ", StartPos);
Array.Resize(ref _dupArray, _dupArray.Length + 1); // increase the array size by 1 to store new value
double dup = 0;
double.TryParse(StdOut.Substring(StartPos, EndPos - StartPos), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out dup);
_dupArray[_dupArray.Length - 1] = dup - _lastDup; // We are storing the change in dup value to calcuate the average rate of change in duplicate packets
_lastDup = dup;
}
// Capture average rate of change in dropped frames
if (StdOut.Contains("drop="))
{
StartPos = StdOut.IndexOf("drop=") + "drop=".Length;
EndPos = StdOut.IndexOf(" ", StartPos);
Array.Resize(ref _dropArray, _dropArray.Length + 1); // increase the array size by 1 to store new value
double drop = 0;
double.TryParse(StdOut.Substring(StartPos, EndPos - StartPos), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out drop);
_dropArray[_dropArray.Length - 1] = drop - _lastDrop; // We are storing the change in dup value to calcuate the average rate of change in duplicate packets
_lastDrop = drop;
}
// TODO: We need to track down more errors from av_interleaved_write_frame() and ffmpeg and put them here, newer builds report global headers even if 1 frame is encoded. The only other option is to look at the return value of ffmpeg for an error, but then wtv files are often cut and this may not work with them.
// av_interleaved_write_frame(): Invalid argument
// av_interleaved_write_frame(): Invalid data found when processing input
if (StdOut.Contains(@"av_interleaved_write_frame(): Invalid"))
_encodeError = true;
// use audio bitstream filter 'aac_adtstoasc' to fix it
if (StdOut.Contains("use") && StdOut.Contains("bitstream filter") && StdOut.Contains("aac_adtstoasc"))
_aacadtstoascError = true;
// [wtv @ 0000000003ffab20] H.264 bitstream malformed, no startcode found, use the h264_mp4toannexb bitstream filter (-bsf h264_mp4toannexb)
// [mpegts @ 02bdd680] H.264 bitstream malformed, no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it ('-bsf:v h264_mp4toannexb' option with ffmpeg)
if (StdOut.Contains("use") && StdOut.Contains("bitstream filter") && StdOut.Contains("h264_mp4toannexb"))
_h264mp4toannexbError = true;
if (StdOut.Contains("non monotonically increasing"))
_muxError = true;
if ((StdOut.Contains("global headers")) && (StdOut.Contains("muxing overhead"))) // This is always the last line printed, so any errors happen before this is printed
_success = true && !FatalError;
}
}
catch (Exception e)
{
_jobLog.WriteEntry(this, "ERROR Processing Console Output.\n" + e.ToString(), Log.LogEntryType.Error);
}
}
/// <summary>
/// Generic function to run a FFMPEG command handle common errors related to FFMPEG conversion
/// </summary>
/// <param name="cmdParams">Command parameters to pass to ffmpeg</param>
/// <param name="outputFile">Exact name of the output file as it appears in the command paramters (including quotes if required)</param>
/// <returns>True if successful</returns>
public static bool FFMpegExecuteAndHandleErrors(string cmdParams, JobStatus jobStatus, Log jobLog, string outputFile)
{
return FFMpegExecuteAndHandleErrors(cmdParams, jobStatus, jobLog, outputFile, true);
}
/// <summary>
/// Generic function to run a FFMPEG command handle common errors related to FFMPEG conversion
/// </summary>
/// <param name="cmdParams">Command parameters to pass to ffmpeg</param>
/// <param name="outputFile">Exact name of the output file as it appears in the command paramters (including quotes if required)</param>
/// <param name="checkZeroOutputFileSize">If true, will check output file size and function will return false if the size is 0 or file doesn't exist, false to ignore output filesize and presence</param>
/// <returns>True if successful</returns>
public static bool FFMpegExecuteAndHandleErrors(string cmdParams, JobStatus jobStatus, Log jobLog, string outputFile, bool checkZeroOutputFileSize)
{
FFmpeg retFFMpeg; // Dummy
return FFMpegExecuteAndHandleErrors(cmdParams, jobStatus, jobLog, outputFile, checkZeroOutputFileSize, out retFFMpeg);
}
/// <summary>
/// Generic function to run a FFMPEG command handle common errors related to FFMPEG conversion
/// </summary>
/// <param name="cmdParams">Command parameters to pass to ffmpeg</param>
/// <param name="outputFile">Exact name of the output file as it appears in the command paramters (including quotes if required)</param>
/// <param name="checkZeroOutputFileSize">If true, will check output file size and function will return false if the size is 0 or file doesn't exist, false to ignore output filesize and presence</param>
/// <param name="ffmpegExecutedObject">Returns a pointer to the final executed ffmpeg object</param>
/// <returns>True if successful</returns>
public static bool FFMpegExecuteAndHandleErrors(string cmdParams, JobStatus jobStatus, Log jobLog, string outputFile, bool checkZeroOutputFileSize, out FFmpeg ffmpegExecutedObject)
{
FFmpeg ffmpeg = new FFmpeg(cmdParams, jobStatus, jobLog);
ffmpeg.Run();
// Check if it's a h264_mp4toannexb error, when converting H.264 video to MPEGTS format this can sometimes be an issue
if (!ffmpeg.Success && ffmpeg.H264MP4ToAnnexBError)
{
jobLog.WriteEntry("h264_mp4toannexb error, retying and setting bitstream flag", Log.LogEntryType.Warning);
// -bsf h264_mp4toannexb is required when this error occurs, put it just before the output filename
cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf h264_mp4toannexb ");
ffmpeg = new FFmpeg(cmdParams, jobStatus, jobLog);
ffmpeg.Run();
}
// Check if it's a aac_adtstoasc error, when converting AAC Audio from MPEGTS to MP4 format this can sometimes be an issue
if (!ffmpeg.Success && ffmpeg.AACADTSToASCError)
{
jobLog.WriteEntry("aac_adtstoasc error, retying and setting bitstream flag", Log.LogEntryType.Warning);
// -bsf aac_adtstoasc is required when this error occurs, put it just before the output filename
cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf:a aac_adtstoasc ");
ffmpeg = new FFmpeg(cmdParams, jobStatus, jobLog);
ffmpeg.Run();
}
// Check if we are asked to check for output filesize only here (generic errors)
// Otherwise it might an error related to genpts (check if we ran the previous ffmpeg related to h264_mp4toannexb and it succeded) - genpts is done after trying to fix other issues
if (checkZeroOutputFileSize)
jobLog.WriteEntry("Checking output file size [KB] -> " + (Util.FileIO.FileSize(outputFile) / 1024).ToString("N", System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
if ((!ffmpeg.Success || (checkZeroOutputFileSize ? (FileIO.FileSize(outputFile) <= 0) : false)) && !cmdParams.Contains("genpts")) // Possible that some combinations used prior to calling this already have genpts in the command line
{
jobLog.WriteEntry("Ffmpeg conversion failed, retying using GenPts", Log.LogEntryType.Warning);
// genpt is required sometimes when -ss is specified before the inputs file, see ffmpeg ticket #2054
cmdParams = "-fflags +genpts " + cmdParams;
ffmpeg = new FFmpeg(cmdParams, jobStatus, jobLog);
ffmpeg.Run();
}
// Check again post genpts if it's a h264_mp4toannexb error (if not already done), when converting H.264 video to MPEGTS format this can sometimes be an issue
if (!ffmpeg.Success && ffmpeg.H264MP4ToAnnexBError && !cmdParams.Contains("h264_mp4toannexb"))
{
jobLog.WriteEntry("H264MP4ToAnnexBError error, retying and setting bitstream flag", Log.LogEntryType.Warning);
// -bsf h264_mp4toannexb is required when this error occurs, put it just before the output filename
cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf h264_mp4toannexb ");
ffmpeg = new FFmpeg(cmdParams, jobStatus, jobLog);
ffmpeg.Run();
}
// Check again post genpts if it's a aac_adtstoasc error (if not already done), when converting AAC Audio from MPEGTS to MP4 format this can sometimes be an issue
if (!ffmpeg.Success && ffmpeg.AACADTSToASCError && !cmdParams.Contains("aac_adtstoasc"))
{
jobLog.WriteEntry("aac_adtstoasc error, retying and setting bitstream flag", Log.LogEntryType.Warning);
// -bsf aac_adtstoasc is required when this error occurs, put it just before the output filename
cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf:a aac_adtstoasc ");
ffmpeg = new FFmpeg(cmdParams, jobStatus, jobLog);
ffmpeg.Run();
}
ffmpegExecutedObject = ffmpeg; // Set the return object to the final run ffmpeg object
jobLog.WriteEntry("FFMpeg output file size [KB] -> " + (Util.FileIO.FileSize(outputFile) / 1024).ToString("N", System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
return (ffmpeg.Success && (checkZeroOutputFileSize ? (FileIO.FileSize(outputFile) > 0) : true));
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using System.Reflection;
//test
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
public class LoadingMethods : CSharpTestBase
{
[Fact]
public void Test1()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[]
{
TestReferences.SymbolsTests.MDTestLib1,
TestReferences.SymbolsTests.MDTestLib2,
TestReferences.SymbolsTests.Methods.CSMethods,
TestReferences.SymbolsTests.Methods.VBMethods,
TestReferences.NetFx.v4_0_21006.mscorlib,
TestReferences.SymbolsTests.Methods.ByRefReturn
},
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
var module1 = assemblies[0].Modules[0];
var module2 = assemblies[1].Modules[0];
var module3 = assemblies[2].Modules[0];
var module4 = assemblies[3].Modules[0];
var module5 = assemblies[4].Modules[0];
var byrefReturn = assemblies[5].Modules[0];
var varTC10 = module2.GlobalNamespace.GetTypeMembers("TC10").Single();
Assert.Equal(6, varTC10.GetMembers().Length);
var localM1 = (MethodSymbol)varTC10.GetMembers("M1").Single();
var localM2 = (MethodSymbol)varTC10.GetMembers("M2").Single();
var localM3 = (MethodSymbol)varTC10.GetMembers("M3").Single();
var localM4 = (MethodSymbol)varTC10.GetMembers("M4").Single();
var localM5 = (MethodSymbol)varTC10.GetMembers("M5").Single();
Assert.Equal("void TC10.M1()", localM1.ToTestDisplayString());
Assert.True(localM1.ReturnsVoid);
Assert.Equal(Accessibility.Public, localM1.DeclaredAccessibility);
Assert.Same(module2, localM1.Locations.Single().MetadataModule);
Assert.Equal("void TC10.M2(System.Int32 m1_1)", localM2.ToTestDisplayString());
Assert.True(localM2.ReturnsVoid);
Assert.Equal(Accessibility.Protected, localM2.DeclaredAccessibility);
var localM1_1 = localM2.Parameters[0];
Assert.IsType<PEParameterSymbol>(localM1_1);
Assert.Same(localM1_1.ContainingSymbol, localM2);
Assert.Equal(SymbolKind.Parameter, localM1_1.Kind);
Assert.Equal(Accessibility.NotApplicable, localM1_1.DeclaredAccessibility);
Assert.False(localM1_1.IsAbstract);
Assert.False(localM1_1.IsSealed);
Assert.False(localM1_1.IsVirtual);
Assert.False(localM1_1.IsOverride);
Assert.False(localM1_1.IsStatic);
Assert.False(localM1_1.IsExtern);
Assert.Equal(0, localM1_1.CustomModifiers.Length);
Assert.Equal("TC8 TC10.M3()", localM3.ToTestDisplayString());
Assert.False(localM3.ReturnsVoid);
Assert.Equal(Accessibility.Protected, localM3.DeclaredAccessibility);
Assert.Equal("C1<System.Type> TC10.M4(ref C1<System.Type> x, ref TC8 y)", localM4.ToTestDisplayString());
Assert.False(localM4.ReturnsVoid);
Assert.Equal(Accessibility.Internal, localM4.DeclaredAccessibility);
Assert.Equal("void TC10.M5(ref C1<System.Type>[,,] x, ref TC8[] y)", localM5.ToTestDisplayString());
Assert.True(localM5.ReturnsVoid);
Assert.Equal(Accessibility.ProtectedOrInternal, localM5.DeclaredAccessibility);
var localM6 = varTC10.GetMembers("M6");
Assert.Equal(0, localM6.Length);
var localC107 = module1.GlobalNamespace.GetTypeMembers("C107").Single();
var varC108 = localC107.GetMembers("C108").Single();
Assert.Equal(SymbolKind.NamedType, varC108.Kind);
var csharpC1 = module3.GlobalNamespace.GetTypeMembers("C1").Single();
var sameName1 = csharpC1.GetMembers("SameName").Single();
var sameName2 = csharpC1.GetMembers("sameName").Single();
Assert.Equal(SymbolKind.NamedType, sameName1.Kind);
Assert.Equal("SameName", sameName1.Name);
Assert.Equal(SymbolKind.Method, sameName2.Kind);
Assert.Equal("sameName", sameName2.Name);
Assert.Equal(2, csharpC1.GetMembers("SameName2").Length);
Assert.Equal(1, csharpC1.GetMembers("sameName2").Length);
Assert.Equal(0, csharpC1.GetMembers("DoesntExist").Length);
var basicC1 = module4.GlobalNamespace.GetTypeMembers("C1").Single();
var basicC1_M1 = (MethodSymbol)basicC1.GetMembers("M1").Single();
var basicC1_M2 = (MethodSymbol)basicC1.GetMembers("M2").Single();
var basicC1_M3 = (MethodSymbol)basicC1.GetMembers("M3").Single();
var basicC1_M4 = (MethodSymbol)basicC1.GetMembers("M4").Single();
Assert.False(basicC1_M1.Parameters[0].IsOptional);
Assert.False(basicC1_M1.Parameters[0].HasExplicitDefaultValue);
Assert.Same(module4, basicC1_M1.Parameters[0].Locations.Single().MetadataModule);
Assert.True(basicC1_M2.Parameters[0].IsOptional);
Assert.False(basicC1_M2.Parameters[0].HasExplicitDefaultValue);
Assert.True(basicC1_M3.Parameters[0].IsOptional);
Assert.True(basicC1_M3.Parameters[0].HasExplicitDefaultValue);
Assert.True(basicC1_M4.Parameters[0].IsOptional);
Assert.False(basicC1_M4.Parameters[0].HasExplicitDefaultValue);
var emptyStructure = module4.GlobalNamespace.GetTypeMembers("EmptyStructure").Single();
Assert.Equal(1, emptyStructure.GetMembers().Length); //synthesized parameterless constructor
Assert.Equal(0, emptyStructure.GetMembers("NoMembersOrTypes").Length);
var basicC1_M5 = (MethodSymbol)basicC1.GetMembers("M5").Single();
var basicC1_M6 = (MethodSymbol)basicC1.GetMembers("M6").Single();
var basicC1_M7 = (MethodSymbol)basicC1.GetMembers("M7").Single();
var basicC1_M8 = (MethodSymbol)basicC1.GetMembers("M8").Single();
var basicC1_M9 = basicC1.GetMembers("M9").OfType<MethodSymbol>().ToArray();
Assert.False(basicC1_M5.IsGenericMethod); // Check genericity before cracking signature
Assert.True(basicC1_M6.ReturnsVoid);
Assert.False(basicC1_M6.IsGenericMethod); // Check genericity after cracking signature
Assert.True(basicC1_M7.IsGenericMethod); // Check genericity before cracking signature
Assert.Equal("void C1.M7<T>(System.Int32 x)", basicC1_M7.ToTestDisplayString());
Assert.True(basicC1_M6.ReturnsVoid);
Assert.True(basicC1_M8.IsGenericMethod); // Check genericity after cracking signature
Assert.Equal("void C1.M8<T>(System.Int32 x)", basicC1_M8.ToTestDisplayString());
Assert.Equal(2, basicC1_M9.Count());
Assert.Equal(1, basicC1_M9.Count(m => m.IsGenericMethod));
Assert.Equal(1, basicC1_M9.Count(m => !m.IsGenericMethod));
var basicC1_M10 = (MethodSymbol)basicC1.GetMembers("M10").Single();
Assert.Equal("void C1.M10<T1>(T1 x)", basicC1_M10.ToTestDisplayString());
var basicC1_M11 = (MethodSymbol)basicC1.GetMembers("M11").Single();
Assert.Equal("T3 C1.M11<T2, T3>(T2 x)", basicC1_M11.ToTestDisplayString());
Assert.Equal(0, basicC1_M11.TypeParameters[0].ConstraintTypes.Length);
Assert.Same(basicC1, basicC1_M11.TypeParameters[1].ConstraintTypes.Single());
var basicC1_M12 = (MethodSymbol)basicC1.GetMembers("M12").Single();
Assert.Equal(0, basicC1_M12.TypeArguments.Length);
Assert.False(basicC1_M12.IsVararg);
Assert.False(basicC1_M12.IsExtern);
Assert.False(basicC1_M12.IsStatic);
var loadLibrary = (MethodSymbol)basicC1.GetMembers("LoadLibrary").Single();
Assert.True(loadLibrary.IsExtern);
var basicC2 = module4.GlobalNamespace.GetTypeMembers("C2").Single();
var basicC2_M1 = (MethodSymbol)basicC2.GetMembers("M1").Single();
Assert.Equal("void C2<T4>.M1<T5>(T5 x, T4 y)", basicC2_M1.ToTestDisplayString());
var console = module5.GlobalNamespace.GetMembers("System").OfType<NamespaceSymbol>().Single().
GetTypeMembers("Console").Single();
Assert.Equal(1, console.GetMembers("WriteLine").OfType<MethodSymbol>().Count(m => m.IsVararg));
Assert.True(console.GetMembers("WriteLine").OfType<MethodSymbol>().Single(m => m.IsVararg).IsStatic);
var basicModifiers1 = module4.GlobalNamespace.GetTypeMembers("Modifiers1").Single();
var basicModifiers1_M1 = (MethodSymbol)basicModifiers1.GetMembers("M1").Single();
var basicModifiers1_M2 = (MethodSymbol)basicModifiers1.GetMembers("M2").Single();
var basicModifiers1_M3 = (MethodSymbol)basicModifiers1.GetMembers("M3").Single();
var basicModifiers1_M4 = (MethodSymbol)basicModifiers1.GetMembers("M4").Single();
var basicModifiers1_M5 = (MethodSymbol)basicModifiers1.GetMembers("M5").Single();
var basicModifiers1_M6 = (MethodSymbol)basicModifiers1.GetMembers("M6").Single();
var basicModifiers1_M7 = (MethodSymbol)basicModifiers1.GetMembers("M7").Single();
var basicModifiers1_M8 = (MethodSymbol)basicModifiers1.GetMembers("M8").Single();
var basicModifiers1_M9 = (MethodSymbol)basicModifiers1.GetMembers("M9").Single();
Assert.True(basicModifiers1_M1.IsAbstract);
Assert.False(basicModifiers1_M1.IsVirtual);
Assert.False(basicModifiers1_M1.IsSealed);
Assert.True(basicModifiers1_M1.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M1.IsOverride);
Assert.False(basicModifiers1_M2.IsAbstract);
Assert.True(basicModifiers1_M2.IsVirtual);
Assert.False(basicModifiers1_M2.IsSealed);
Assert.True(basicModifiers1_M2.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M2.IsOverride);
Assert.False(basicModifiers1_M3.IsAbstract);
Assert.False(basicModifiers1_M3.IsVirtual);
Assert.False(basicModifiers1_M3.IsSealed);
Assert.False(basicModifiers1_M3.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M3.IsOverride);
Assert.False(basicModifiers1_M4.IsAbstract);
Assert.False(basicModifiers1_M4.IsVirtual);
Assert.False(basicModifiers1_M4.IsSealed);
Assert.True(basicModifiers1_M4.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M4.IsOverride);
Assert.False(basicModifiers1_M5.IsAbstract);
Assert.False(basicModifiers1_M5.IsVirtual);
Assert.False(basicModifiers1_M5.IsSealed);
Assert.True(basicModifiers1_M5.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M5.IsOverride);
Assert.True(basicModifiers1_M6.IsAbstract);
Assert.False(basicModifiers1_M6.IsVirtual);
Assert.False(basicModifiers1_M6.IsSealed);
Assert.False(basicModifiers1_M6.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M6.IsOverride);
Assert.False(basicModifiers1_M7.IsAbstract);
Assert.True(basicModifiers1_M7.IsVirtual);
Assert.False(basicModifiers1_M7.IsSealed);
Assert.False(basicModifiers1_M7.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M7.IsOverride);
Assert.True(basicModifiers1_M8.IsAbstract);
Assert.False(basicModifiers1_M8.IsVirtual);
Assert.False(basicModifiers1_M8.IsSealed);
Assert.True(basicModifiers1_M8.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M8.IsOverride);
Assert.False(basicModifiers1_M9.IsAbstract);
Assert.True(basicModifiers1_M9.IsVirtual);
Assert.False(basicModifiers1_M9.IsSealed);
Assert.True(basicModifiers1_M9.HidesBaseMethodsByName);
Assert.False(basicModifiers1_M9.IsOverride);
var basicModifiers2 = module4.GlobalNamespace.GetTypeMembers("Modifiers2").Single();
var basicModifiers2_M1 = (MethodSymbol)basicModifiers2.GetMembers("M1").Single();
var basicModifiers2_M2 = (MethodSymbol)basicModifiers2.GetMembers("M2").Single();
var basicModifiers2_M6 = (MethodSymbol)basicModifiers2.GetMembers("M6").Single();
var basicModifiers2_M7 = (MethodSymbol)basicModifiers2.GetMembers("M7").Single();
Assert.True(basicModifiers2_M1.IsAbstract);
Assert.False(basicModifiers2_M1.IsVirtual);
Assert.False(basicModifiers2_M1.IsSealed);
Assert.True(basicModifiers2_M1.HidesBaseMethodsByName);
Assert.True(basicModifiers2_M1.IsOverride);
Assert.False(basicModifiers2_M2.IsAbstract);
Assert.False(basicModifiers2_M2.IsVirtual);
Assert.True(basicModifiers2_M2.IsSealed);
Assert.True(basicModifiers2_M2.HidesBaseMethodsByName);
Assert.True(basicModifiers2_M2.IsOverride);
Assert.True(basicModifiers2_M6.IsAbstract);
Assert.False(basicModifiers2_M6.IsVirtual);
Assert.False(basicModifiers2_M6.IsSealed);
Assert.False(basicModifiers2_M6.HidesBaseMethodsByName);
Assert.True(basicModifiers2_M6.IsOverride);
Assert.False(basicModifiers2_M7.IsAbstract);
Assert.False(basicModifiers2_M7.IsVirtual);
Assert.True(basicModifiers2_M7.IsSealed);
Assert.False(basicModifiers2_M7.HidesBaseMethodsByName);
Assert.True(basicModifiers2_M7.IsOverride);
var basicModifiers3 = module4.GlobalNamespace.GetTypeMembers("Modifiers3").Single();
var basicModifiers3_M1 = (MethodSymbol)basicModifiers3.GetMembers("M1").Single();
var basicModifiers3_M6 = (MethodSymbol)basicModifiers3.GetMembers("M6").Single();
Assert.False(basicModifiers3_M1.IsAbstract);
Assert.False(basicModifiers3_M1.IsVirtual);
Assert.False(basicModifiers3_M1.IsSealed);
Assert.True(basicModifiers3_M1.HidesBaseMethodsByName);
Assert.True(basicModifiers3_M1.IsOverride);
Assert.False(basicModifiers3_M6.IsAbstract);
Assert.False(basicModifiers3_M6.IsVirtual);
Assert.False(basicModifiers3_M6.IsSealed);
Assert.False(basicModifiers3_M6.HidesBaseMethodsByName);
Assert.True(basicModifiers3_M6.IsOverride);
var csharpModifiers1 = module3.GlobalNamespace.GetTypeMembers("Modifiers1").Single();
var csharpModifiers1_M1 = (MethodSymbol)csharpModifiers1.GetMembers("M1").Single();
var csharpModifiers1_M2 = (MethodSymbol)csharpModifiers1.GetMembers("M2").Single();
var csharpModifiers1_M3 = (MethodSymbol)csharpModifiers1.GetMembers("M3").Single();
var csharpModifiers1_M4 = (MethodSymbol)csharpModifiers1.GetMembers("M4").Single();
Assert.True(csharpModifiers1_M1.IsAbstract);
Assert.False(csharpModifiers1_M1.IsVirtual);
Assert.False(csharpModifiers1_M1.IsSealed);
Assert.False(csharpModifiers1_M1.HidesBaseMethodsByName);
Assert.False(csharpModifiers1_M1.IsOverride);
Assert.False(csharpModifiers1_M2.IsAbstract);
Assert.True(csharpModifiers1_M2.IsVirtual);
Assert.False(csharpModifiers1_M2.IsSealed);
Assert.False(csharpModifiers1_M2.HidesBaseMethodsByName);
Assert.False(csharpModifiers1_M2.IsOverride);
Assert.False(csharpModifiers1_M3.IsAbstract);
Assert.False(csharpModifiers1_M3.IsVirtual);
Assert.False(csharpModifiers1_M3.IsSealed);
Assert.False(csharpModifiers1_M3.HidesBaseMethodsByName);
Assert.False(csharpModifiers1_M3.IsOverride);
Assert.False(csharpModifiers1_M4.IsAbstract);
Assert.True(csharpModifiers1_M4.IsVirtual);
Assert.False(csharpModifiers1_M4.IsSealed);
Assert.False(csharpModifiers1_M4.HidesBaseMethodsByName);
Assert.False(csharpModifiers1_M4.IsOverride);
var csharpModifiers2 = module3.GlobalNamespace.GetTypeMembers("Modifiers2").Single();
var csharpModifiers2_M1 = (MethodSymbol)csharpModifiers2.GetMembers("M1").Single();
var csharpModifiers2_M2 = (MethodSymbol)csharpModifiers2.GetMembers("M2").Single();
var csharpModifiers2_M3 = (MethodSymbol)csharpModifiers2.GetMembers("M3").Single();
Assert.False(csharpModifiers2_M1.IsAbstract);
Assert.False(csharpModifiers2_M1.IsVirtual);
Assert.True(csharpModifiers2_M1.IsSealed);
Assert.False(csharpModifiers2_M1.HidesBaseMethodsByName);
Assert.True(csharpModifiers2_M1.IsOverride);
Assert.True(csharpModifiers2_M2.IsAbstract);
Assert.False(csharpModifiers2_M2.IsVirtual);
Assert.False(csharpModifiers2_M2.IsSealed);
Assert.False(csharpModifiers2_M2.HidesBaseMethodsByName);
Assert.True(csharpModifiers2_M2.IsOverride);
Assert.False(csharpModifiers2_M3.IsAbstract);
Assert.True(csharpModifiers2_M3.IsVirtual);
Assert.False(csharpModifiers2_M3.IsSealed);
Assert.False(csharpModifiers2_M3.HidesBaseMethodsByName);
Assert.False(csharpModifiers2_M3.IsOverride);
var csharpModifiers3 = module3.GlobalNamespace.GetTypeMembers("Modifiers3").Single();
var csharpModifiers3_M1 = (MethodSymbol)csharpModifiers3.GetMembers("M1").Single();
var csharpModifiers3_M3 = (MethodSymbol)csharpModifiers3.GetMembers("M3").Single();
var csharpModifiers3_M4 = (MethodSymbol)csharpModifiers3.GetMembers("M4").Single();
Assert.False(csharpModifiers3_M1.IsAbstract);
Assert.False(csharpModifiers3_M1.IsVirtual);
Assert.False(csharpModifiers3_M1.IsSealed);
Assert.False(csharpModifiers3_M1.HidesBaseMethodsByName);
Assert.True(csharpModifiers3_M1.IsOverride);
Assert.False(csharpModifiers3_M3.IsAbstract);
Assert.False(csharpModifiers3_M3.IsVirtual);
Assert.False(csharpModifiers3_M3.IsSealed);
Assert.False(csharpModifiers3_M3.HidesBaseMethodsByName);
Assert.False(csharpModifiers3_M3.IsOverride);
Assert.True(csharpModifiers3_M4.IsAbstract);
Assert.False(csharpModifiers3_M4.IsVirtual);
Assert.False(csharpModifiers3_M4.IsSealed);
Assert.False(csharpModifiers3_M4.HidesBaseMethodsByName);
Assert.False(csharpModifiers3_M4.IsOverride);
var byrefReturnMethod = byrefReturn.GlobalNamespace.GetTypeMembers("ByRefReturn").Single().GetMembers("M").OfType<MethodSymbol>().Single();
Assert.Equal(TypeKind.Error, byrefReturnMethod.ReturnType.TypeKind);
Assert.IsType<ByRefReturnErrorTypeSymbol>(byrefReturnMethod.ReturnType);
}
[Fact]
public void TestExplicitImplementationSimple()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp);
var globalNamespace = assembly.GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Class").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces.Contains(@interface));
var classMethod = (MethodSymbol)@class.GetMembers("Interface.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, explicitImpl);
}
[Fact]
public void TestExplicitImplementationMultiple()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL);
var globalNamespace = assembly.GlobalNamespace;
var interface1 = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I1").Single();
Assert.Equal(TypeKind.Interface, interface1.TypeKind);
var interface1Method = (MethodSymbol)interface1.GetMembers("Method1").Single();
var interface2 = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I2").Single();
Assert.Equal(TypeKind.Interface, interface2.TypeKind);
var interface2Method = (MethodSymbol)interface2.GetMembers("Method2").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces.Contains(interface1));
Assert.True(@class.Interfaces.Contains(interface2));
var classMethod = (MethodSymbol)@class.GetMembers("Method").Single(); // the method is considered to be Ordinary
Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind); // becasue it has name without '.'
var explicitImpls = classMethod.ExplicitInterfaceImplementations;
Assert.Equal(2, explicitImpls.Length);
Assert.Equal(interface1Method, explicitImpls[0]);
Assert.Equal(interface2Method, explicitImpls[1]);
}
[Fact]
public void TestExplicitImplementationGeneric()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
mrefs: new[]
{
TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Last(); //this assumes decl order
Assert.Equal("void IGeneric<T>.Method<U>(T t, U u)", interfaceMethod.ToTestDisplayString()); //make sure we got the one we expected
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Generic").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces.Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Last(); //this assumes decl order
Assert.Equal("void IGeneric<S>.Method<U>(S t, U u)", substitutedInterfaceMethod.ToTestDisplayString()); //make sure we got the one we expected
Assert.Equal(interfaceMethod, substitutedInterfaceMethod.OriginalDefinition);
var classMethod = (MethodSymbol)@class.GetMembers("IGeneric<S>.Method").Last(); //this assumes decl order
Assert.Equal("void Generic<S>.IGeneric<S>.Method<V>(S s, V v)", classMethod.ToTestDisplayString()); //make sure we got the one we expected
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceMethod, explicitImpl);
}
[Fact]
public void TestExplicitImplementationConstructed()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Last(); //this assumes decl order
Assert.Equal("void IGeneric<T>.Method<U>(T t, U u)", interfaceMethod.ToTestDisplayString()); //make sure we got the one we expected
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Constructed").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces.Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Last(); //this assumes decl order
Assert.Equal("void IGeneric<System.Int32>.Method<U>(System.Int32 t, U u)", substitutedInterfaceMethod.ToTestDisplayString()); //make sure we got the one we expected
Assert.Equal(interfaceMethod, substitutedInterfaceMethod.OriginalDefinition);
var classMethod = (MethodSymbol)@class.GetMembers("IGeneric<System.Int32>.Method").Last(); //this assumes decl order
Assert.Equal("void Constructed.IGeneric<System.Int32>.Method<W>(System.Int32 i, W w)", classMethod.ToTestDisplayString()); //make sure we got the one we expected
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceMethod, explicitImpl);
}
[Fact]
public void TestExplicitImplementationInterfaceCycleSuccess()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL);
var globalNamespace = assembly.GlobalNamespace;
var cyclicInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ImplementsSelf").Single();
Assert.Equal(TypeKind.Interface, cyclicInterface.TypeKind);
var implementedInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I1").Single();
Assert.Equal(TypeKind.Interface, implementedInterface.TypeKind);
var interface2Method = (MethodSymbol)implementedInterface.GetMembers("Method1").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("InterfaceCycleSuccess").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces.Contains(cyclicInterface));
Assert.True(@class.Interfaces.Contains(implementedInterface));
var classMethod = (MethodSymbol)@class.GetMembers("Method").Single(); // the method is considered to be Ordinary
Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind); // becasue it has name without '.'
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interface2Method, explicitImpl);
}
[Fact]
public void TestExplicitImplementationInterfaceCycleFailure()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL);
var globalNamespace = assembly.GlobalNamespace;
var cyclicInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ImplementsSelf").Single();
Assert.Equal(TypeKind.Interface, cyclicInterface.TypeKind);
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("InterfaceCycleFailure").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces.Contains(cyclicInterface));
var classMethod = (MethodSymbol)@class.GetMembers("Method").Single();
//we couldn't find an interface method that's explicitly implemented, so we have no reason to believe the method isn't ordinary
Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind);
var explicitImpls = classMethod.ExplicitInterfaceImplementations;
Assert.False(explicitImpls.Any());
}
/// <summary>
/// A type def explicitly implements an interface, also a type def, but only
/// indirectly, via a type ref.
/// </summary>
[Fact]
public void TestExplicitImplementationDefRefDef()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var defInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
var defInterfaceMethod = (MethodSymbol)defInterface.GetMembers("Method").Single();
var refInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGenericInterface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
Assert.True(refInterface.Interfaces.Contains(defInterface));
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IndirectImplementation").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var classInterfacesConstructedFrom = @class.Interfaces.Select(i => i.ConstructedFrom);
Assert.Equal(2, classInterfacesConstructedFrom.Count());
Assert.Contains(defInterface, classInterfacesConstructedFrom);
Assert.Contains(refInterface, classInterfacesConstructedFrom);
var classMethod = (MethodSymbol)@class.GetMembers("Interface.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(defInterfaceMethod, explicitImpl);
}
/// <summary>
/// IL type explicitly overrides a class (vs interface) method.
/// ExplicitInterfaceImplementations should be empty.
/// </summary>
[Fact]
public void TestExplicitImplementationOfClassMethod()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL);
var globalNamespace = assembly.GlobalNamespace;
var baseClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementedClass").Single();
Assert.Equal(TypeKind.Class, baseClass.TypeKind);
var derivedClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementsAClass").Single();
Assert.Equal(TypeKind.Class, derivedClass.TypeKind);
Assert.Equal(baseClass, derivedClass.BaseType);
var derivedClassMethod = (MethodSymbol)derivedClass.GetMembers("Method").Single();
Assert.Equal(MethodKind.Ordinary, derivedClassMethod.MethodKind);
Assert.Equal(0, derivedClassMethod.ExplicitInterfaceImplementations.Length);
}
/// <summary>
/// IL type explicitly overrides an interface method on an unrelated interface.
/// ExplicitInterfaceImplementations should be empty.
/// </summary>
[Fact]
public void TestExplicitImplementationOfUnrelatedInterfaceMethod()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL);
var globalNamespace = assembly.GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IUnrelated").First(); //decl order
Assert.Equal(0, @interface.Arity);
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementsUnrelatedInterfaceMethods").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.Equal(0, @class.AllInterfaces.Length);
var classMethod = (MethodSymbol)@class.GetMembers("Method1").Single();
Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind);
Assert.Equal(0, classMethod.ExplicitInterfaceImplementations.Length);
var classGenericMethod = (MethodSymbol)@class.GetMembers("Method1").Single();
Assert.Equal(MethodKind.Ordinary, classGenericMethod.MethodKind);
Assert.Equal(0, classGenericMethod.ExplicitInterfaceImplementations.Length);
}
/// <summary>
/// IL type explicitly overrides an interface method on an unrelated generic interface.
/// ExplicitInterfaceImplementations should be empty.
/// </summary>
[Fact]
public void TestExplicitImplementationOfUnrelatedGenericInterfaceMethod()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IUnrelated").Last(); //decl order
Assert.Equal(1, @interface.Arity);
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementsUnrelatedInterfaceMethods").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.Equal(0, @class.AllInterfaces.Length);
var classMethod = (MethodSymbol)@class.GetMembers("Method2").Single();
Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind);
Assert.Equal(0, classMethod.ExplicitInterfaceImplementations.Length);
var classGenericMethod = (MethodSymbol)@class.GetMembers("Method2").Single();
Assert.Equal(MethodKind.Ordinary, classGenericMethod.MethodKind);
Assert.Equal(0, classGenericMethod.ExplicitInterfaceImplementations.Length);
}
/// <summary>
/// In metadata, nested types implicitly share all type parameters of their containing types.
/// This results in some extra computations when mapping a type parameter position to a type
/// parameter symbol.
/// </summary>
[Fact]
public void TestTypeParameterPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var outerInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric2").Single();
Assert.Equal(1, outerInterface.Arity);
Assert.Equal(TypeKind.Interface, outerInterface.TypeKind);
var outerInterfaceMethod = outerInterface.GetMembers().Single();
var outerClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Outer").Single();
Assert.Equal(1, outerClass.Arity);
Assert.Equal(TypeKind.Class, outerClass.TypeKind);
var innerInterface = (NamedTypeSymbol)outerClass.GetTypeMembers("IInner").Single();
Assert.Equal(1, innerInterface.Arity);
Assert.Equal(TypeKind.Interface, innerInterface.TypeKind);
var innerInterfaceMethod = innerInterface.GetMembers().Single();
var innerClass1 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner1").Single();
CheckInnerClassHelper(innerClass1, "IGeneric2<A>.Method", outerInterfaceMethod);
var innerClass2 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner2").Single();
CheckInnerClassHelper(innerClass2, "IGeneric2<T>.Method", outerInterfaceMethod);
var innerClass3 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner3").Single();
CheckInnerClassHelper(innerClass3, "Outer<T>.IInner<C>.Method", innerInterfaceMethod);
var innerClass4 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner4").Single();
CheckInnerClassHelper(innerClass4, "Outer<T>.IInner<T>.Method", innerInterfaceMethod);
}
private static void CheckInnerClassHelper(NamedTypeSymbol innerClass, string methodName, Symbol interfaceMethod)
{
var @interface = interfaceMethod.ContainingType;
Assert.Equal(1, innerClass.Arity);
Assert.Equal(TypeKind.Class, innerClass.TypeKind);
Assert.Equal(@interface, innerClass.Interfaces.Single().ConstructedFrom);
var innerClassMethod = (MethodSymbol)innerClass.GetMembers(methodName).Single();
var innerClassImplementingMethod = innerClassMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, innerClassImplementingMethod.OriginalDefinition);
Assert.Equal(@interface, innerClassImplementingMethod.ContainingType.ConstructedFrom);
}
[Fact]
public void TestVirtualnessFlags_Invoke()
{
var source = @"
class Invoke
{
void Foo(MetadataModifiers m)
{
m.M00();
m.M01();
m.M02();
m.M03();
m.M04();
m.M05();
m.M06();
m.M07();
m.M08();
m.M09();
m.M10();
m.M11();
m.M12();
m.M13();
m.M14();
m.M15();
}
}
";
var compilation = CreateCompilationWithMscorlib(source, new[] { TestReferences.SymbolsTests.Methods.ILMethods });
compilation.VerifyDiagnostics(); // No errors, as in Dev10
}
[Fact]
public void TestVirtualnessFlags_NoOverride()
{
var source = @"
class Abstract : MetadataModifiers
{
//CS0534 for methods 2, 5, 8, 9, 11, 12, 14, 15
}
";
var compilation = CreateCompilationWithMscorlib(source, new[] { TestReferences.SymbolsTests.Methods.ILMethods });
compilation.VerifyDiagnostics(
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M02()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M02()"),
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M05()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M05()"),
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M08()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M08()"),
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M09()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M09()"),
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M11()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M11()"),
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M12()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M12()"),
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M14()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M14()"),
// (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M15()'
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M15()"));
}
[Fact]
public void TestVirtualnessFlags_Override()
{
var source = @"
class Override : MetadataModifiers
{
public override void M00() { } //CS0506
public override void M01() { } //CS0506
public override void M02() { }
public override void M03() { }
public override void M04() { } //CS0506
public override void M05() { }
public override void M06() { }
public override void M07() { } //CS0506
public override void M08() { }
public override void M09() { }
public override void M10() { } //CS0239 (Dev10 reports CS0506, presumably because MetadataModifiers.M10 isn't overriding anything)
public override void M11() { }
public override void M12() { }
public override void M13() { } //CS0506
public override void M14() { }
public override void M15() { }
}
";
var compilation = CreateCompilationWithMscorlib(source, new[] { TestReferences.SymbolsTests.Methods.ILMethods });
compilation.VerifyDiagnostics(
// (4,26): error CS0506: 'Override.M00()': cannot override inherited member 'MetadataModifiers.M00()' because it is not marked virtual, abstract, or override
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M00").WithArguments("Override.M00()", "MetadataModifiers.M00()"),
// (5,26): error CS0506: 'Override.M01()': cannot override inherited member 'MetadataModifiers.M01()' because it is not marked virtual, abstract, or override
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M01").WithArguments("Override.M01()", "MetadataModifiers.M01()"),
// (8,26): error CS0506: 'Override.M04()': cannot override inherited member 'MetadataModifiers.M04()' because it is not marked virtual, abstract, or override
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M04").WithArguments("Override.M04()", "MetadataModifiers.M04()"),
// (11,26): error CS0506: 'Override.M07()': cannot override inherited member 'MetadataModifiers.M07()' because it is not marked virtual, abstract, or override
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M07").WithArguments("Override.M07()", "MetadataModifiers.M07()"),
// (14,26): error CS0239: 'Override.M10()': cannot override inherited member 'MetadataModifiers.M10()' because it is sealed
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "M10").WithArguments("Override.M10()", "MetadataModifiers.M10()"),
// (17,26): error CS0506: 'Override.M13()': cannot override inherited member 'MetadataModifiers.M13()' because it is not marked virtual, abstract, or override
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M13").WithArguments("Override.M13()", "MetadataModifiers.M13()"));
}
[ClrOnlyFact]
public void TestVirtualnessFlags_CSharpRepresentation()
{
// All combinations of VirtualContract, NewSlotVTable, AbstractImpl, and FinalContract - without explicit overriding
// NOTE: some won't peverify (newslot/final/abstract without virtual, abstract with final)
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, 0, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Override, MethodAttributes.Virtual, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.Final, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Virtual, MethodAttributes.Virtual | MethodAttributes.NewSlot, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.SealedOverride, MethodAttributes.Virtual | MethodAttributes.Final, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: false);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false);
// All combinations of VirtualContract, NewSlotVTable, AbstractImpl, and FinalContract - with explicit overriding
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, 0, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Override, MethodAttributes.Virtual, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.Final, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Override, MethodAttributes.Virtual | MethodAttributes.NewSlot, isExplicitOverride: true); //differs from above
CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.SealedOverride, MethodAttributes.Virtual | MethodAttributes.Final, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true);
CheckLoadingVirtualnessFlags(SymbolVirtualness.SealedOverride, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: true); //differs from above
CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: true); //differs from above
CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true); //differs from above
}
private void CheckLoadingVirtualnessFlags(SymbolVirtualness expectedVirtualness, MethodAttributes flags, bool isExplicitOverride)
{
const string ilTemplate = @"
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{{
.method public hidebysig newslot virtual
instance void M() cil managed
{{
ret
}}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}}
}} // end of class Base
.class public abstract auto ansi beforefieldinit Derived
extends Base
{{
.method public hidebysig{0} instance void
M() cil managed
{{
{1}
{2}
}}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}}
}} // end of class Derived
";
string modifiers = "";
if ((flags & MethodAttributes.NewSlot) != 0)
{
modifiers += " newslot";
}
if ((flags & MethodAttributes.Abstract) != 0)
{
modifiers += " abstract";
}
if ((flags & MethodAttributes.Virtual) != 0)
{
modifiers += " virtual";
}
if ((flags & MethodAttributes.Final) != 0)
{
modifiers += " final";
}
string explicitOverride = isExplicitOverride ? ".override Base::M" : "";
string body = ((flags & MethodAttributes.Abstract) != 0) ? "" : "ret";
CompileWithCustomILSource("", string.Format(ilTemplate, modifiers, explicitOverride, body), compilation =>
{
var derivedClass = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("Derived");
var method = derivedClass.GetMember<MethodSymbol>("M");
switch (expectedVirtualness)
{
case SymbolVirtualness.NonVirtual:
Assert.False(method.IsVirtual);
Assert.False(method.IsOverride);
Assert.False(method.IsAbstract);
Assert.False(method.IsSealed);
break;
case SymbolVirtualness.Virtual:
Assert.True(method.IsVirtual);
Assert.False(method.IsOverride);
Assert.False(method.IsAbstract);
Assert.False(method.IsSealed);
break;
case SymbolVirtualness.Override:
Assert.False(method.IsVirtual);
Assert.True(method.IsOverride);
Assert.False(method.IsAbstract);
Assert.False(method.IsSealed);
break;
case SymbolVirtualness.SealedOverride:
Assert.False(method.IsVirtual);
Assert.True(method.IsOverride);
Assert.False(method.IsAbstract);
Assert.True(method.IsSealed);
break;
case SymbolVirtualness.Abstract:
Assert.False(method.IsVirtual);
Assert.False(method.IsOverride);
Assert.True(method.IsAbstract);
Assert.False(method.IsSealed);
break;
case SymbolVirtualness.AbstractOverride:
Assert.False(method.IsVirtual);
Assert.True(method.IsOverride);
Assert.True(method.IsAbstract);
Assert.False(method.IsSealed);
break;
default:
Assert.False(true, "Unexpected enum value " + expectedVirtualness);
break;
}
},
emitOptions: TestEmitters.RefEmitBug);
}
// Note that not all combinations are possible.
private enum SymbolVirtualness
{
NonVirtual,
Virtual,
Override,
SealedOverride,
Abstract,
AbstractOverride,
}
[Fact]
public void Constructors1()
{
string ilSource = @"
.class private auto ansi cls1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method public specialname rtspecialname static
void .cctor() cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
}
}
.class private auto ansi Instance_vs_Static
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
static void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method public specialname rtspecialname instance
void .cctor() cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
}
}
.class private auto ansi ReturnAValue1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance int32 .ctor(int32 x) cil managed
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int32 V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_0004
IL_0004: ldloc.0
IL_0005: ret
}
.method private specialname rtspecialname static
int32 .cctor() cil managed
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int32 V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_0004
IL_0004: ldloc.0
IL_0005: ret
}
}
.class private auto ansi ReturnAValue2
extends [mscorlib]System.Object
{
.method public specialname rtspecialname static
int32 .cctor() cil managed
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int32 V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_0004
IL_0004: ldloc.0
IL_0005: ret
}
}
.class private auto ansi Generic1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor<T>() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method private specialname rtspecialname static
void .cctor<T>() cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
}
}
.class private auto ansi Generic2
extends [mscorlib]System.Object
{
.method public specialname rtspecialname static
void .cctor<T>() cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
}
}
.class private auto ansi HasParameter
extends [mscorlib]System.Object
{
.method public specialname rtspecialname static
void .cctor(int32 x) cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
}
}
.class private auto ansi Virtual
extends [mscorlib]System.Object
{
.method public newslot strict virtual specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
";
var compilation = CreateCompilationWithCustomILSource("", ilSource);
foreach (var m in compilation.GetTypeByMetadataName("cls1").GetMembers())
{
Assert.Equal(m.Name == ".cctor" ? MethodKind.StaticConstructor : MethodKind.Constructor, ((MethodSymbol)m).MethodKind);
}
foreach (var m in compilation.GetTypeByMetadataName("Instance_vs_Static").GetMembers())
{
Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind);
}
foreach (var m in compilation.GetTypeByMetadataName("ReturnAValue1").GetMembers())
{
Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind);
}
foreach (var m in compilation.GetTypeByMetadataName("ReturnAValue2").GetMembers())
{
Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind);
}
foreach (var m in compilation.GetTypeByMetadataName("Generic1").GetMembers())
{
Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind);
}
foreach (var m in compilation.GetTypeByMetadataName("Generic2").GetMembers())
{
Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind);
}
foreach (var m in compilation.GetTypeByMetadataName("HasParameter").GetMembers())
{
Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind);
}
foreach (var m in compilation.GetTypeByMetadataName("Virtual").GetMembers())
{
Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind);
}
}
[Fact]
public void OverridesAndLackOfNewSlot()
{
string ilSource = @"
.class interface public abstract auto ansi serializable Microsoft.FSharp.Control.IDelegateEvent`1<([mscorlib]System.Delegate) TDelegate>
{
.method public hidebysig abstract virtual
instance void AddHandler(!TDelegate 'handler') cil managed
{
} // end of method IDelegateEvent`1::AddHandler
.method public hidebysig abstract virtual
instance void RemoveHandler(!TDelegate 'handler') cil managed
{
} // end of method IDelegateEvent`1::RemoveHandler
} // end of class Microsoft.FSharp.Control.IDelegateEvent`1
";
var compilation = CreateCompilationWithCustomILSource("", ilSource);
foreach (var m in compilation.GetTypeByMetadataName("Microsoft.FSharp.Control.IDelegateEvent`1").GetMembers())
{
Assert.False(((MethodSymbol)m).IsVirtual);
Assert.True(((MethodSymbol)m).IsAbstract);
Assert.False(((MethodSymbol)m).IsOverride);
}
}
[Fact]
public void MemberSignature_LongFormType()
{
string source = @"
public class D
{
public static void Main()
{
string s = C.RT();
double d = C.VT();
}
}
";
var longFormRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.LongTypeFormInSignature.AsImmutableOrNull());
var c = CreateCompilationWithMscorlib(source, new[] { longFormRef });
c.VerifyDiagnostics(
// (6,20): error CS0570: 'C.RT()' is not supported by the language
Diagnostic(ErrorCode.ERR_BindToBogus, "RT").WithArguments("C.RT()"),
// (7,20): error CS0570: 'C.VT()' is not supported by the language
Diagnostic(ErrorCode.ERR_BindToBogus, "VT").WithArguments("C.VT()"));
}
[WorkItem(666162, "DevDiv")]
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void Repro666162()
{
var il = @"
.assembly extern mscorlib { }
.assembly extern Missing { }
.assembly Lib { }
.class public auto ansi beforefieldinit Test
extends [mscorlib]System.Object
{
.method public hidebysig instance class Test modreq (bool)&
M() cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class Test
";
var ilRef = CompileIL(il, appendDefaultHeader: false);
var comp = CreateCompilation("", new[] { ilRef });
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var method = type.GetMember<MethodSymbol>("M");
Assert.NotNull(method.ReturnType);
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace SocketHttpListener.Net
{
class ChunkStream
{
enum State
{
None,
PartialSize,
Body,
BodyFinished,
Trailer
}
class Chunk
{
public byte[] Bytes;
public int Offset;
public Chunk(byte[] chunk)
{
this.Bytes = chunk;
}
public int Read(byte[] buffer, int offset, int size)
{
int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
Buffer.BlockCopy(Bytes, Offset, buffer, offset, nread);
Offset += nread;
return nread;
}
}
internal WebHeaderCollection headers;
int chunkSize;
int chunkRead;
int totalWritten;
State state;
//byte [] waitBuffer;
StringBuilder saved;
bool sawCR;
bool gotit;
int trailerState;
ArrayList chunks;
public ChunkStream(byte[] buffer, int offset, int size, WebHeaderCollection headers)
: this(headers)
{
Write(buffer, offset, size);
}
public ChunkStream(WebHeaderCollection headers)
{
this.headers = headers;
saved = new StringBuilder();
chunks = new ArrayList();
chunkSize = -1;
totalWritten = 0;
}
public void ResetBuffer()
{
chunkSize = -1;
chunkRead = 0;
totalWritten = 0;
chunks.Clear();
}
public void WriteAndReadBack(byte[] buffer, int offset, int size, ref int read)
{
if (offset + read > 0)
Write(buffer, offset, offset + read);
read = Read(buffer, offset, size);
}
public int Read(byte[] buffer, int offset, int size)
{
return ReadFromChunks(buffer, offset, size);
}
int ReadFromChunks(byte[] buffer, int offset, int size)
{
int count = chunks.Count;
int nread = 0;
for (int i = 0; i < count; i++)
{
Chunk chunk = (Chunk)chunks[i];
if (chunk == null)
continue;
if (chunk.Offset == chunk.Bytes.Length)
{
chunks[i] = null;
continue;
}
nread += chunk.Read(buffer, offset + nread, size - nread);
if (nread == size)
break;
}
return nread;
}
public void Write(byte[] buffer, int offset, int size)
{
if (offset < size)
InternalWrite(buffer, ref offset, size);
}
void InternalWrite(byte[] buffer, ref int offset, int size)
{
if (state == State.None || state == State.PartialSize)
{
state = GetChunkSize(buffer, ref offset, size);
if (state == State.PartialSize)
return;
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (state == State.Body && offset < size)
{
state = ReadBody(buffer, ref offset, size);
if (state == State.Body)
return;
}
if (state == State.BodyFinished && offset < size)
{
state = ReadCRLF(buffer, ref offset, size);
if (state == State.BodyFinished)
return;
sawCR = false;
}
if (state == State.Trailer && offset < size)
{
state = ReadTrailer(buffer, ref offset, size);
if (state == State.Trailer)
return;
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (offset < size)
InternalWrite(buffer, ref offset, size);
}
public bool WantMore
{
get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); }
}
public bool DataAvailable
{
get
{
int count = chunks.Count;
for (int i = 0; i < count; i++)
{
Chunk ch = (Chunk)chunks[i];
if (ch == null || ch.Bytes == null)
continue;
if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
return (state != State.Body);
}
return false;
}
}
public int TotalDataSize
{
get { return totalWritten; }
}
public int ChunkLeft
{
get { return chunkSize - chunkRead; }
}
State ReadBody(byte[] buffer, ref int offset, int size)
{
if (chunkSize == 0)
return State.BodyFinished;
int diff = size - offset;
if (diff + chunkRead > chunkSize)
diff = chunkSize - chunkRead;
byte[] chunk = new byte[diff];
Buffer.BlockCopy(buffer, offset, chunk, 0, diff);
chunks.Add(new Chunk(chunk));
offset += diff;
chunkRead += diff;
totalWritten += diff;
return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
}
State GetChunkSize(byte[] buffer, ref int offset, int size)
{
chunkRead = 0;
chunkSize = 0;
char c = '\0';
while (offset < size)
{
c = (char)buffer[offset++];
if (c == '\r')
{
if (sawCR)
ThrowProtocolViolation("2 CR found");
sawCR = true;
continue;
}
if (sawCR && c == '\n')
break;
if (c == ' ')
gotit = true;
if (!gotit)
saved.Append(c);
if (saved.Length > 20)
ThrowProtocolViolation("chunk size too long.");
}
if (!sawCR || c != '\n')
{
if (offset < size)
ThrowProtocolViolation("Missing \\n");
try
{
if (saved.Length > 0)
{
chunkSize = Int32.Parse(RemoveChunkExtension(saved.ToString()), NumberStyles.HexNumber);
}
}
catch (Exception)
{
ThrowProtocolViolation("Cannot parse chunk size.");
}
return State.PartialSize;
}
chunkRead = 0;
try
{
chunkSize = Int32.Parse(RemoveChunkExtension(saved.ToString()), NumberStyles.HexNumber);
}
catch (Exception)
{
ThrowProtocolViolation("Cannot parse chunk size.");
}
if (chunkSize == 0)
{
trailerState = 2;
return State.Trailer;
}
return State.Body;
}
static string RemoveChunkExtension(string input)
{
int idx = input.IndexOf(';');
if (idx == -1)
return input;
return input.Substring(0, idx);
}
State ReadCRLF(byte[] buffer, ref int offset, int size)
{
if (!sawCR)
{
if ((char)buffer[offset++] != '\r')
ThrowProtocolViolation("Expecting \\r");
sawCR = true;
if (offset == size)
return State.BodyFinished;
}
if (sawCR && (char)buffer[offset++] != '\n')
ThrowProtocolViolation("Expecting \\n");
return State.None;
}
State ReadTrailer(byte[] buffer, ref int offset, int size)
{
char c = '\0';
// short path
if (trailerState == 2 && (char)buffer[offset] == '\r' && saved.Length == 0)
{
offset++;
if (offset < size && (char)buffer[offset] == '\n')
{
offset++;
return State.None;
}
offset--;
}
int st = trailerState;
string stString = "\r\n\r";
while (offset < size && st < 4)
{
c = (char)buffer[offset++];
if ((st == 0 || st == 2) && c == '\r')
{
st++;
continue;
}
if ((st == 1 || st == 3) && c == '\n')
{
st++;
continue;
}
if (st > 0)
{
saved.Append(stString.Substring(0, saved.Length == 0 ? st - 2 : st));
st = 0;
if (saved.Length > 4196)
ThrowProtocolViolation("Error reading trailer (too long).");
}
}
if (st < 4)
{
trailerState = st;
if (offset < size)
ThrowProtocolViolation("Error reading trailer.");
return State.Trailer;
}
StringReader reader = new StringReader(saved.ToString());
string line;
while ((line = reader.ReadLine()) != null && line != "")
headers.Add(line);
return State.None;
}
static void ThrowProtocolViolation(string message)
{
WebException we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null);
throw we;
}
}
}
| |
namespace Ocelot.UnitTests.Configuration
{
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
using Newtonsoft.Json;
using System.IO;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
using Ocelot.Configuration.Repository;
public class DiskFileConfigurationRepositoryTests : IDisposable
{
private readonly Mock<IHostingEnvironment> _hostingEnvironment;
private IFileConfigurationRepository _repo;
private string _environmentSpecificPath;
private string _ocelotJsonPath;
private FileConfiguration _result;
private FileConfiguration _fileConfiguration;
// This is a bit dirty and it is dev.dev so that the ConfigurationBuilderExtensionsTests
// cant pick it up if they run in parralel..and the semaphore stops them running at the same time...sigh
// these are not really unit tests but whatever...
private string _environmentName = "DEV.DEV";
private static SemaphoreSlim _semaphore;
public DiskFileConfigurationRepositoryTests()
{
_semaphore = new SemaphoreSlim(1, 1);
_semaphore.Wait();
_hostingEnvironment = new Mock<IHostingEnvironment>();
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new DiskFileConfigurationRepository(_hostingEnvironment.Object);
}
[Fact]
public void should_return_file_configuration()
{
var config = FakeFileConfigurationForGet();
this.Given(_ => GivenTheConfigurationIs(config))
.When(_ => WhenIGetTheReRoutes())
.Then(_ => ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_return_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForGet();
this.Given(_ => GivenTheEnvironmentNameIsUnavailable())
.And(_ => GivenTheConfigurationIs(config))
.When(_ => WhenIGetTheReRoutes())
.Then(_ => ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration()
{
var config = FakeFileConfigurationForSet();
this.Given(_ => GivenIHaveAConfiguration(config))
.When(_ => WhenISetTheConfiguration())
.Then(_ => ThenTheConfigurationIsStoredAs(config))
.And(_ => ThenTheConfigurationJsonIsIndented(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForSet();
this.Given(_ => GivenIHaveAConfiguration(config))
.And(_ => GivenTheEnvironmentNameIsUnavailable())
.When(_ => WhenISetTheConfiguration())
.Then(_ => ThenTheConfigurationIsStoredAs(config))
.And(_ => ThenTheConfigurationJsonIsIndented(config))
.BDDfy();
}
[Fact]
public void should_set_environment_file_configuration_and_ocelot_file_configuration()
{
var config = FakeFileConfigurationForSet();
this.Given(_ => GivenIHaveAConfiguration(config))
.And(_ => GivenTheConfigurationIs(config))
.And(_ => GivenTheUserAddedOcelotJson())
.When(_ => WhenISetTheConfiguration())
.Then(_ => ThenTheConfigurationIsStoredAs(config))
.And(_ => ThenTheConfigurationJsonIsIndented(config))
.Then(_ => ThenTheOcelotJsonIsStoredAs(config))
.BDDfy();
}
private void GivenTheUserAddedOcelotJson()
{
_ocelotJsonPath = $"{AppContext.BaseDirectory}/ocelot.json";
if (File.Exists(_ocelotJsonPath))
{
File.Delete(_ocelotJsonPath);
}
File.WriteAllText(_ocelotJsonPath, "Doesnt matter");
}
private void GivenTheEnvironmentNameIsUnavailable()
{
_environmentName = null;
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new DiskFileConfigurationRepository(_hostingEnvironment.Object);
}
private void GivenIHaveAConfiguration(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
}
private void WhenISetTheConfiguration()
{
_repo.Set(_fileConfiguration);
_result = _repo.Get().Result.Data;
}
private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for(var i = 0; i < _result.ReRoutes.Count; i++)
{
for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++)
{
var result = _result.ReRoutes[i].DownstreamHostAndPorts[j];
var expected = expecteds.ReRoutes[i].DownstreamHostAndPorts[j];
result.Host.ShouldBe(expected.Host);
result.Port.ShouldBe(expected.Port);
}
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expecteds.ReRoutes[i].DownstreamScheme);
}
}
private void ThenTheOcelotJsonIsStoredAs(FileConfiguration expecteds)
{
var resultText = File.ReadAllText(_ocelotJsonPath);
var expectedText = JsonConvert.SerializeObject(expecteds, Formatting.Indented);
resultText.ShouldBe(expectedText);
}
private void GivenTheConfigurationIs(FileConfiguration fileConfiguration)
{
_environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot{(string.IsNullOrEmpty(_environmentName) ? string.Empty : ".")}{_environmentName}.json";
var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented);
if (File.Exists(_environmentSpecificPath))
{
File.Delete(_environmentSpecificPath);
}
File.WriteAllText(_environmentSpecificPath, jsonConfiguration);
}
private void ThenTheConfigurationJsonIsIndented(FileConfiguration expecteds)
{
var path = !string.IsNullOrEmpty(_environmentSpecificPath) ? _environmentSpecificPath : _environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot{(string.IsNullOrEmpty(_environmentName) ? string.Empty : ".")}{_environmentName}.json";
var resultText = File.ReadAllText(path);
var expectedText = JsonConvert.SerializeObject(expecteds, Formatting.Indented);
resultText.ShouldBe(expectedText);
}
private void WhenIGetTheReRoutes()
{
_result = _repo.Get().Result.Data;
}
private void ThenTheFollowingIsReturned(FileConfiguration expecteds)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for(var i = 0; i < _result.ReRoutes.Count; i++)
{
for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++)
{
var result = _result.ReRoutes[i].DownstreamHostAndPorts[j];
var expected = expecteds.ReRoutes[i].DownstreamHostAndPorts[j];
result.Host.ShouldBe(expected.Host);
result.Port.ShouldBe(expected.Port);
}
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expecteds.ReRoutes[i].DownstreamScheme);
}
}
private FileConfiguration FakeFileConfigurationForSet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "123.12.12.12",
Port = 80,
}
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/asdfs/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
private FileConfiguration FakeFileConfigurationForGet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 80,
}
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/test/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
public void Dispose()
{
_semaphore.Release();
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.DynamicProxy.Generators
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
#if !SILVERLIGHT
using System.Xml.Serialization;
#endif
using Castle.DynamicProxy.Contributors;
using Castle.DynamicProxy.Generators.Emitters;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Castle.DynamicProxy.Serialization;
public class InterfaceProxyWithTargetGenerator : BaseProxyGenerator
{
protected FieldReference targetField;
public InterfaceProxyWithTargetGenerator(ModuleScope scope, Type @interface)
: base(scope, @interface)
{
CheckNotGenericTypeDefinition(@interface, "@interface");
}
protected virtual bool AllowChangeTarget
{
get { return false; }
}
protected virtual string GeneratorType
{
get { return ProxyTypeConstants.InterfaceWithTarget; }
}
public Type GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options)
{
// make sure ProxyGenerationOptions is initialized
options.Initialize();
CheckNotGenericTypeDefinition(proxyTargetType, "proxyTargetType");
CheckNotGenericTypeDefinitions(interfaces, "interfaces");
EnsureValidBaseType(options.BaseTypeForInterfaceProxy);
ProxyGenerationOptions = options;
interfaces = TypeUtil.GetAllInterfaces(interfaces).ToArray();
var cacheKey = new CacheKey(proxyTargetType, targetType, interfaces, options);
return ObtainProxyType(cacheKey, (n, s) => GenerateType(n, proxyTargetType, interfaces, s));
}
protected virtual ITypeContributor AddMappingForTargetType(IDictionary<Type, ITypeContributor> typeImplementerMapping,
Type proxyTargetType, ICollection<Type> targetInterfaces,
ICollection<Type> additionalInterfaces,
INamingScope namingScope)
{
var contributor = new InterfaceProxyTargetContributor(proxyTargetType, AllowChangeTarget, namingScope)
{ Logger = Logger };
var proxiedInterfaces = targetType.GetAllInterfaces();
foreach (var @interface in proxiedInterfaces)
{
contributor.AddInterfaceToProxy(@interface);
AddMappingNoCheck(@interface, contributor, typeImplementerMapping);
}
foreach (var @interface in additionalInterfaces)
{
if (!ImplementedByTarget(targetInterfaces, @interface) || proxiedInterfaces.Contains(@interface))
{
continue;
}
contributor.AddInterfaceToProxy(@interface);
AddMappingNoCheck(@interface, contributor, typeImplementerMapping);
}
return contributor;
}
#if (!SILVERLIGHT)
protected override void CreateTypeAttributes(ClassEmitter emitter)
{
base.CreateTypeAttributes(emitter);
emitter.DefineCustomAttribute<SerializableAttribute>();
}
#endif
protected virtual Type GenerateType(string typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope)
{
IEnumerable<ITypeContributor> contributors;
var allInterfaces = GetTypeImplementerMapping(interfaces, proxyTargetType, out contributors, namingScope);
ClassEmitter emitter;
FieldReference interceptorsField;
var baseType = Init(typeName, out emitter, proxyTargetType, out interceptorsField, allInterfaces);
var model = new MetaType();
// Collect methods
foreach (var contributor in contributors)
{
contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model);
}
ProxyGenerationOptions.Hook.MethodsInspected();
// Constructor
var cctor = GenerateStaticConstructor(emitter);
var ctorArguments = new List<FieldReference>();
foreach (var contributor in contributors)
{
contributor.Generate(emitter, ProxyGenerationOptions);
// TODO: redo it
if (contributor is MixinContributor)
{
ctorArguments.AddRange((contributor as MixinContributor).Fields);
}
}
ctorArguments.Add(interceptorsField);
ctorArguments.Add(targetField);
var selector = emitter.GetField("__selector");
if (selector != null)
{
ctorArguments.Add(selector);
}
GenerateConstructors(emitter, baseType, ctorArguments.ToArray());
// Complete type initializer code body
CompleteInitCacheMethod(cctor.CodeBuilder);
// Crosses fingers and build type
var generatedType = emitter.BuildType();
InitializeStaticFields(generatedType);
return generatedType;
}
protected virtual InterfaceProxyWithoutTargetContributor GetContributorForAdditionalInterfaces(
INamingScope namingScope)
{
return new InterfaceProxyWithoutTargetContributor(namingScope, (c, m) => NullExpression.Instance) { Logger = Logger };
}
protected virtual IEnumerable<Type> GetTypeImplementerMapping(Type[] interfaces, Type proxyTargetType,
out IEnumerable<ITypeContributor> contributors,
INamingScope namingScope)
{
IDictionary<Type, ITypeContributor> typeImplementerMapping = new Dictionary<Type, ITypeContributor>();
var mixins = new MixinContributor(namingScope, AllowChangeTarget) { Logger = Logger };
// Order of interface precedence:
// 1. first target
var targetInterfaces = proxyTargetType.GetAllInterfaces();
var additionalInterfaces = TypeUtil.GetAllInterfaces(interfaces);
var target = AddMappingForTargetType(typeImplementerMapping, proxyTargetType, targetInterfaces, additionalInterfaces,
namingScope);
// 2. then mixins
if (ProxyGenerationOptions.HasMixins)
{
foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces)
{
if (targetInterfaces.Contains(mixinInterface))
{
// OK, so the target implements this interface. We now do one of two things:
if (additionalInterfaces.Contains(mixinInterface))
{
// we intercept the interface, and forward calls to the target type
AddMapping(mixinInterface, target, typeImplementerMapping);
}
// we do not intercept the interface
mixins.AddEmptyInterface(mixinInterface);
}
else
{
if (!typeImplementerMapping.ContainsKey(mixinInterface))
{
mixins.AddInterfaceToProxy(mixinInterface);
typeImplementerMapping.Add(mixinInterface, mixins);
}
}
}
}
var additionalInterfacesContributor = GetContributorForAdditionalInterfaces(namingScope);
// 3. then additional interfaces
foreach (var @interface in additionalInterfaces)
{
if (typeImplementerMapping.ContainsKey(@interface))
{
continue;
}
if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface))
{
continue;
}
additionalInterfacesContributor.AddInterfaceToProxy(@interface);
AddMappingNoCheck(@interface, additionalInterfacesContributor, typeImplementerMapping);
}
// 4. plus special interfaces
var instance = new InterfaceProxyInstanceContributor(targetType, GeneratorType, interfaces);
AddMappingForISerializable(typeImplementerMapping, instance);
try
{
AddMappingNoCheck(typeof(IProxyTargetAccessor), instance, typeImplementerMapping);
}
catch (ArgumentException)
{
HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces, additionalInterfaces);
}
contributors = new List<ITypeContributor>
{
target,
additionalInterfacesContributor,
mixins,
instance
};
return typeImplementerMapping.Keys;
}
protected virtual Type Init(string typeName, out ClassEmitter emitter, Type proxyTargetType,
out FieldReference interceptorsField, IEnumerable<Type> interfaces)
{
var baseType = ProxyGenerationOptions.BaseTypeForInterfaceProxy;
emitter = BuildClassEmitter(typeName, baseType, interfaces);
CreateFields(emitter, proxyTargetType);
CreateTypeAttributes(emitter);
interceptorsField = emitter.GetField("__interceptors");
return baseType;
}
private void CreateFields(ClassEmitter emitter, Type proxyTargetType)
{
base.CreateFields(emitter);
targetField = emitter.CreateField("__target", proxyTargetType);
#if !SILVERLIGHT
emitter.DefineCustomAttributeFor<XmlIgnoreAttribute>(targetField);
#endif
}
private void EnsureValidBaseType(Type type)
{
if (type == null)
{
throw new ArgumentException(
"Base type for proxy is null reference. Please set it to System.Object or some other valid type.");
}
if (!type.IsClass())
{
ThrowInvalidBaseType(type, "it is not a class type");
}
if (type.IsSealed())
{
ThrowInvalidBaseType(type, "it is sealed");
}
var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, TypeExtender.EmptyTypes, null);
if (constructor == null || constructor.IsPrivate)
{
ThrowInvalidBaseType(type, "it does not have accessible parameterless constructor");
}
}
private bool ImplementedByTarget(ICollection<Type> targetInterfaces, Type @interface)
{
return targetInterfaces.Contains(@interface);
}
private void ThrowInvalidBaseType(Type type, string doesNotHaveAccessibleParameterlessConstructor)
{
var format =
"Type {0} is not valid base type for interface proxy, because {1}. Only a non-sealed class with non-private default constructor can be used as base type for interface proxy. Please use some other valid type.";
throw new ArgumentException(string.Format(format, type, doesNotHaveAccessibleParameterlessConstructor));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Xml;
using System.Xml.Xsl;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Web.WebServices;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.template;
using umbraco.cms.businesslogic.web;
using System.Net;
using System.Collections;
using umbraco.NodeFactory;
namespace umbraco.presentation.webservices
{
/// <summary>
/// Summary description for codeEditorSave
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class codeEditorSave : UmbracoAuthorizedWebService
{
[WebMethod]
public string SaveCss(string fileName, string oldName, string fileContents, int fileID)
{
if (AuthorizeRequest(DefaultApps.settings.ToString()))
{
var stylesheet = Services.FileService.GetStylesheetByName(oldName.EnsureEndsWith(".css"));
if (stylesheet == null) throw new InvalidOperationException("No stylesheet found with name " + oldName);
stylesheet.Content = fileContents;
if (fileName.InvariantEquals(oldName) == false)
{
//it's changed which means we need to change the path
stylesheet.Path = stylesheet.Path.TrimEnd(oldName.EnsureEndsWith(".css")) + fileName.EnsureEndsWith(".css");
}
Services.FileService.SaveStylesheet(stylesheet, Security.CurrentUser.Id);
return "true";
}
return "false";
}
[WebMethod]
public string SaveXslt(string fileName, string oldName, string fileContents, bool ignoreDebugging)
{
if (AuthorizeRequest(DefaultApps.developer.ToString()))
{
IOHelper.EnsurePathExists(SystemDirectories.Xslt);
// validate file
IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName),
SystemDirectories.Xslt);
// validate extension
IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName),
new List<string>() { "xsl", "xslt" });
StreamWriter SW;
string tempFileName = IOHelper.MapPath(SystemDirectories.Xslt + "/" + DateTime.Now.Ticks + "_temp.xslt");
SW = File.CreateText(tempFileName);
SW.Write(fileContents);
SW.Close();
// Test the xslt
string errorMessage = "";
if (!ignoreDebugging)
{
try
{
// Check if there's any documents yet
string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/root/node" : "/root/*";
if (content.Instance.XmlContent.SelectNodes(xpath).Count > 0)
{
var macroXML = new XmlDocument();
macroXML.LoadXml("<macro/>");
var macroXSLT = new XslCompiledTransform();
var umbPage = new page(content.Instance.XmlContent.SelectSingleNode("//* [@parentID = -1]"));
var xslArgs = macro.AddMacroXsltExtensions();
var lib = new library(umbPage);
xslArgs.AddExtensionObject("urn:umbraco.library", lib);
HttpContext.Current.Trace.Write("umbracoMacro", "After adding extensions");
// Add the current node
xslArgs.AddParam("currentPage", "", library.GetXmlNodeById(umbPage.PageID.ToString()));
HttpContext.Current.Trace.Write("umbracoMacro", "Before performing transformation");
// Create reader and load XSL file
// We need to allow custom DTD's, useful for defining an ENTITY
var readerSettings = new XmlReaderSettings();
readerSettings.ProhibitDtd = false;
using (var xmlReader = XmlReader.Create(tempFileName, readerSettings))
{
var xslResolver = new XmlUrlResolver();
xslResolver.Credentials = CredentialCache.DefaultCredentials;
macroXSLT.Load(xmlReader, XsltSettings.TrustedXslt, xslResolver);
xmlReader.Close();
// Try to execute the transformation
var macroResult = new HtmlTextWriter(new StringWriter());
macroXSLT.Transform(macroXML, xslArgs, macroResult);
macroResult.Close();
File.Delete(tempFileName);
}
}
else
{
//errorMessage = ui.Text("developer", "xsltErrorNoNodesPublished");
File.Delete(tempFileName);
//base.speechBubble(speechBubbleIcon.info, ui.Text("errors", "xsltErrorHeader", base.getUser()), "Unable to validate xslt as no published content nodes exist.");
}
}
catch (Exception errorXslt)
{
File.Delete(tempFileName);
errorMessage = (errorXslt.InnerException ?? errorXslt).ToString();
// Full error message
errorMessage = errorMessage.Replace("\n", "<br/>\n");
//closeErrorMessage.Visible = true;
// Find error
var m = Regex.Matches(errorMessage, @"\d*[^,],\d[^\)]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match mm in m)
{
string[] errorLine = mm.Value.Split(',');
if (errorLine.Length > 0)
{
var theErrorLine = int.Parse(errorLine[0]);
var theErrorChar = int.Parse(errorLine[1]);
errorMessage = "Error in XSLT at line " + errorLine[0] + ", char " + errorLine[1] +
"<br/>";
errorMessage += "<span style=\"font-family: courier; font-size: 11px;\">";
var xsltText = fileContents.Split("\n".ToCharArray());
for (var i = 0; i < xsltText.Length; i++)
{
if (i >= theErrorLine - 3 && i <= theErrorLine + 1)
if (i + 1 == theErrorLine)
{
errorMessage += "<b>" + (i + 1) + ": >>> " +
Server.HtmlEncode(xsltText[i].Substring(0, theErrorChar));
errorMessage +=
"<span style=\"text-decoration: underline; border-bottom: 1px solid red\">" +
Server.HtmlEncode(
xsltText[i].Substring(theErrorChar,
xsltText[i].Length - theErrorChar)).
Trim() + "</span>";
errorMessage += " <<<</b><br/>";
}
else
errorMessage += (i + 1) + ": " +
Server.HtmlEncode(xsltText[i]) + "<br/>";
}
errorMessage += "</span>";
}
}
}
}
if (errorMessage == "" && fileName.ToLower().EndsWith(".xslt"))
{
//Hardcoded security-check... only allow saving files in xslt directory...
var savePath = IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName);
if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Xslt + "/")))
{
//deletes the old xslt file
if (fileName != oldName)
{
var p = IOHelper.MapPath(SystemDirectories.Xslt + "/" + oldName);
if (File.Exists(p))
File.Delete(p);
}
SW = File.CreateText(savePath);
SW.Write(fileContents);
SW.Close();
errorMessage = "true";
}
else
{
errorMessage = "Illegal path";
}
}
File.Delete(tempFileName);
return errorMessage;
}
return "false";
}
[WebMethod]
public string SaveDLRScript(string fileName, string oldName, string fileContents, bool ignoreDebugging)
{
if (AuthorizeRequest(DefaultApps.developer.ToString()))
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException("fileName");
var allowedExtensions = new List<string>();
foreach (var lang in MacroEngineFactory.GetSupportedUILanguages())
{
if (!allowedExtensions.Contains(lang.Extension))
allowedExtensions.Add(lang.Extension);
}
// validate file
IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName),
SystemDirectories.MacroScripts);
// validate extension
IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName),
allowedExtensions);
//As Files Can Be Stored In Sub Directories, So We Need To Get The Exeuction Directory Correct
var lastOccurance = fileName.LastIndexOf('/') + 1;
var directory = fileName.Substring(0, lastOccurance);
var fileNameWithExt = fileName.Substring(lastOccurance);
var tempFileName =
IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + directory + DateTime.Now.Ticks + "_" +
fileNameWithExt);
using (var sw = new StreamWriter(tempFileName, false, Encoding.UTF8))
{
sw.Write(fileContents);
sw.Close();
}
var errorMessage = "";
if (!ignoreDebugging)
{
var root = Document.GetRootDocuments().FirstOrDefault();
if (root != null)
{
var args = new Hashtable();
var n = new Node(root.Id);
args.Add("currentPage", n);
try
{
var engine = MacroEngineFactory.GetByFilename(tempFileName);
var tempErrorMessage = "";
var xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/root/node" : "/root/*";
if (
!engine.Validate(fileContents, tempFileName, Node.GetNodeByXpath(xpath),
out tempErrorMessage))
errorMessage = tempErrorMessage;
}
catch (Exception err)
{
errorMessage = err.ToString();
}
}
}
if (errorMessage == "")
{
var savePath = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName);
//deletes the file
if (fileName != oldName)
{
var p = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + oldName);
if (File.Exists(p))
File.Delete(p);
}
using (var sw = new StreamWriter(savePath, false, Encoding.UTF8))
{
sw.Write(fileContents);
sw.Close();
}
errorMessage = "true";
}
File.Delete(tempFileName);
return errorMessage.Replace("\n", "<br/>\n");
}
return "false";
}
//[WebMethod]
//public string SavePartialView(string filename, string oldName, string contents)
//{
// if (BasePage.ValidateUserContextID(BasePage.umbracoUserContextID))
// {
// var folderPath = SystemDirectories.MvcViews + "/Partials/";
// // validate file
// IOHelper.ValidateEditPath(IOHelper.MapPath(folderPath + filename), folderPath);
// // validate extension
// IOHelper.ValidateFileExtension(IOHelper.MapPath(folderPath + filename), new[] {"cshtml"}.ToList());
// var val = contents;
// string returnValue;
// var saveOldPath = oldName.StartsWith("~/") ? IOHelper.MapPath(oldName) : IOHelper.MapPath(folderPath + oldName);
// var savePath = filename.StartsWith("~/") ? IOHelper.MapPath(filename) : IOHelper.MapPath(folderPath + filename);
// //Directory check.. only allow files in script dir and below to be edited
// if (savePath.StartsWith(IOHelper.MapPath(folderPath)))
// {
// //deletes the old file
// if (savePath != saveOldPath)
// {
// if (File.Exists(saveOldPath))
// File.Delete(saveOldPath);
// }
// using (var sw = File.CreateText(savePath))
// {
// sw.Write(val);
// }
// returnValue = "true";
// }
// else
// {
// returnValue = "illegalPath";
// }
// return returnValue;
// }
// return "false";
//}
[WebMethod]
public string SaveScript(string filename, string oldName, string contents)
{
if (AuthorizeRequest(DefaultApps.settings.ToString()))
{
// validate file
IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename),
SystemDirectories.Scripts);
// validate extension
IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename),
UmbracoConfig.For.UmbracoSettings().Content.ScriptFileTypes.ToList());
var val = contents;
string returnValue;
try
{
var saveOldPath = "";
saveOldPath = oldName.StartsWith("~/")
? IOHelper.MapPath(oldName)
: IOHelper.MapPath(SystemDirectories.Scripts + "/" + oldName);
var savePath = "";
savePath = filename.StartsWith("~/")
? IOHelper.MapPath(filename)
: IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename);
//Directory check.. only allow files in script dir and below to be edited
if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Scripts + "/")) || savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Masterpages + "/")))
{
//deletes the old file
if (savePath != saveOldPath)
{
if (File.Exists(saveOldPath))
File.Delete(saveOldPath);
}
//ensure the folder exists before saving
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
using (var sw = File.CreateText(savePath))
{
sw.Write(val);
sw.Close();
}
returnValue = "true";
}
else
{
returnValue = "illegalPath";
}
}
catch
{
returnValue = "false";
}
return returnValue;
}
return "false";
}
[Obsolete("This method has been superceded by the REST service /Umbraco/RestServices/SaveFile/SaveTemplate which is powered by the SaveFileController.")]
[WebMethod]
public string SaveTemplate(string templateName, string templateAlias, string templateContents, int templateID, int masterTemplateID)
{
if (AuthorizeRequest(DefaultApps.settings.ToString()))
{
var _template = new Template(templateID);
string retVal = "false";
if (_template != null)
{
_template.Text = templateName;
_template.Alias = templateAlias;
_template.MasterTemplate = masterTemplateID;
_template.Design = templateContents;
_template.Save();
retVal = "true";
}
return retVal;
}
return "false";
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace swagger
{
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>
/// ServicesOperations operations.
/// </summary>
internal partial class ServicesOperations : IServiceOperations<SearchManagementClient>, IServicesOperations
{
/// <summary>
/// Initializes a new instance of the ServicesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ServicesOperations(SearchManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SearchManagementClient
/// </summary>
public SearchManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a Search service in the given resource group.
/// If the Search service already exists, all properties will be updated with
/// the given values.
/// <see href="https://msdn.microsoft.com/library/azure/dn832687.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription.
/// </param>
/// <param name='serviceName'>
/// The name of the Search service to operate on.
/// </param>
/// <param name='parameters'>
/// #parameter-parameters
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// 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<SearchServiceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, SearchServiceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{serviceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SearchServiceResource>();
_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<SearchServiceResource>(_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<SearchServiceResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a Search service in the given resource group, along with its
/// associated resources.
/// <see href="https://msdn.microsoft.com/library/azure/dn832692.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription.
/// </param>
/// <param name='serviceName'>
/// The name of the Search service to operate on.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// 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> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{serviceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new 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>
/// Returns a list of all Search services in the given resource group.
/// <see href="https://msdn.microsoft.com/library/azure/dn832688.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// 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<SearchServiceListResult>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "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.Search/searchServices").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SearchServiceListResult>();
_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<SearchServiceListResult>(_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;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2006 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PARALLEL
using System;
using System.Threading;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// The EventPumpState enum represents the state of an
/// EventPump.
/// </summary>
public enum EventPumpState
{
/// <summary>
/// The pump is stopped
/// </summary>
Stopped,
/// <summary>
/// The pump is pumping events with no stop requested
/// </summary>
Pumping,
/// <summary>
/// The pump is pumping events but a stop has been requested
/// </summary>
Stopping
}
/// <summary>
/// EventPump pulls events out of an EventQueue and sends
/// them to a listener. It is used to send events back to
/// the client without using the CallContext of the test
/// runner thread.
/// </summary>
public class EventPump : IDisposable
{
static Logger log = InternalTrace.GetLogger("EventPump");
#region Instance Variables
/// <summary>
/// The handle on which a thread enqueuing an event with <see cref="Event.IsSynchronous"/> == <c>true</c>
/// waits, until the EventPump has sent the event to its listeners.
/// </summary>
private readonly AutoResetEvent synchronousEventSent = new AutoResetEvent(false);
/// <summary>
/// The downstream listener to which we send events
/// </summary>
private ITestListener eventListener;
/// <summary>
/// The queue that holds our events
/// </summary>
EventQueue events;
/// <summary>
/// Thread to do the pumping
/// </summary>
Thread pumpThread;
/// <summary>
/// The current state of the eventpump
/// </summary>
private volatile EventPumpState pumpState = EventPumpState.Stopped;
private string name;
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="eventListener">The EventListener to receive events</param>
/// <param name="events">The event queue to pull events from</param>
public EventPump( ITestListener eventListener, EventQueue events)
{
this.eventListener = eventListener;
this.events = events;
this.events.SetWaitHandleForSynchronizedEvents(this.synchronousEventSent);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the current state of the pump
/// </summary>
/// <remarks>
/// On <c>volatile</c> and <see cref="Thread.MemoryBarrier"/>, see
/// "http://www.albahari.com/threading/part4.aspx".
/// </remarks>
public EventPumpState PumpState
{
get
{
Thread.MemoryBarrier();
return pumpState;
}
set
{
this.pumpState = value;
Thread.MemoryBarrier();
}
}
/// <summary>
/// Gets or sets the name of this EventPump
/// (used only internally and for testing).
/// </summary>
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
#endregion
#region Public Methods
/// <summary>
/// Dispose stops the pump
/// Disposes the used WaitHandle, too.
/// </summary>
public void Dispose()
{
Stop();
((IDisposable)this.synchronousEventSent).Dispose();
}
/// <summary>
/// Start the pump
/// </summary>
public void Start()
{
if ( this.PumpState == EventPumpState.Stopped ) // Ignore if already started
{
this.pumpThread = new Thread( new ThreadStart( PumpThreadProc ) );
this.pumpThread.Name = "EventPumpThread" + this.Name;
this.pumpThread.Priority = ThreadPriority.Highest;
pumpState = EventPumpState.Pumping;
this.pumpThread.Start();
}
}
/// <summary>
/// Tell the pump to stop after emptying the queue.
/// </summary>
public void Stop()
{
if ( pumpState == EventPumpState.Pumping ) // Ignore extra calls
{
this.PumpState = EventPumpState.Stopping;
this.events.Stop();
this.pumpThread.Join();
}
}
#endregion
#region PumpThreadProc
/// <summary>
/// Our thread proc for removing items from the event
/// queue and sending them on. Note that this would
/// need to do more locking if any other thread were
/// removing events from the queue.
/// </summary>
private void PumpThreadProc()
{
//ITestListener hostListeners = CoreExtensions.Host.Listeners;
try
{
while (true)
{
Event e = this.events.Dequeue( this.PumpState == EventPumpState.Pumping );
if ( e == null )
break;
try
{
e.Send(this.eventListener);
//e.Send(hostListeners);
}
catch (Exception ex)
{
log.Error( "Exception in event handler\r\n {0}", ex );
}
finally
{
if ( e.IsSynchronous )
this.synchronousEventSent.Set();
}
}
}
catch (Exception ex)
{
log.Error( "Exception in pump thread", ex );
}
finally
{
this.PumpState = EventPumpState.Stopped;
//pumpThread = null;
if (this.events.Count > 0)
log.Error("Event pump thread exiting with {0} events remaining");
}
}
#endregion
}
}
#endif
| |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl.Events
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Portable.IO;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Portable;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Ignite events.
/// </summary>
internal class Events : PlatformTarget, IEvents
{
/// <summary>
/// Opcodes.
/// </summary>
protected enum Op
{
RemoteQuery = 1,
RemoteListen = 2,
StopRemoteListen = 3,
WaitForLocal = 4,
LocalQuery = 5,
RecordLocal = 6,
EnableLocal = 8,
DisableLocal = 9,
GetEnabledEvents = 10
}
/** Map from user func to local wrapper, needed for invoke/unsubscribe. */
private readonly Dictionary<object, Dictionary<int, LocalHandledEventFilter>> _localFilters
= new Dictionary<object, Dictionary<int, LocalHandledEventFilter>>();
/** Grid. */
protected readonly Ignite Ignite;
/// <summary>
/// Initializes a new instance of the <see cref="Events"/> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="clusterGroup">Cluster group.</param>
public Events(IUnmanagedTarget target, PortableMarshaller marsh, IClusterGroup clusterGroup)
: base(target, marsh)
{
Debug.Assert(clusterGroup != null);
ClusterGroup = clusterGroup;
Ignite = (Ignite) clusterGroup.Ignite;
}
/** <inheritDoc /> */
public virtual IEvents WithAsync()
{
return new EventsAsync(UU.EventsWithAsync(Target), Marshaller, ClusterGroup);
}
/** <inheritDoc /> */
public virtual bool IsAsync
{
get { return false; }
}
/** <inheritDoc /> */
public virtual IFuture GetFuture()
{
throw IgniteUtils.GetAsyncModeDisabledException();
}
/** <inheritDoc /> */
public virtual IFuture<TResult> GetFuture<TResult>()
{
throw IgniteUtils.GetAsyncModeDisabledException();
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup { get; private set; }
/** <inheritDoc /> */
public virtual List<T> RemoteQuery<T>(IEventFilter<T> filter, TimeSpan? timeout = null, params int[] types)
where T : IEvent
{
IgniteArgumentCheck.NotNull(filter, "filter");
return DoOutInOp((int) Op.RemoteQuery,
writer =>
{
writer.Write(new PortableOrSerializableObjectHolder(filter));
writer.WriteLong((long) (timeout == null ? 0 : timeout.Value.TotalMilliseconds));
WriteEventTypes(types, writer);
},
reader => ReadEvents<T>(reader));
}
/** <inheritDoc /> */
public virtual Guid RemoteListen<T>(int bufSize = 1, TimeSpan? interval = null, bool autoUnsubscribe = true,
IEventFilter<T> localListener = null, IEventFilter<T> remoteFilter = null, params int[] types)
where T : IEvent
{
IgniteArgumentCheck.Ensure(bufSize > 0, "bufSize", "should be > 0");
IgniteArgumentCheck.Ensure(interval == null || interval.Value.TotalMilliseconds > 0, "interval", "should be null or >= 0");
return DoOutInOp((int) Op.RemoteListen,
writer =>
{
writer.WriteInt(bufSize);
writer.WriteLong((long) (interval == null ? 0 : interval.Value.TotalMilliseconds));
writer.WriteBoolean(autoUnsubscribe);
writer.WriteBoolean(localListener != null);
if (localListener != null)
{
var listener = new RemoteListenEventFilter(Ignite, (id, e) => localListener.Invoke(id, (T) e));
writer.WriteLong(Ignite.HandleRegistry.Allocate(listener));
}
writer.WriteBoolean(remoteFilter != null);
if (remoteFilter != null)
writer.Write(new PortableOrSerializableObjectHolder(remoteFilter));
WriteEventTypes(types, writer);
},
reader => Marshaller.StartUnmarshal(reader).ReadGuid() ?? Guid.Empty);
}
/** <inheritDoc /> */
public virtual void StopRemoteListen(Guid opId)
{
DoOutOp((int) Op.StopRemoteListen, writer =>
{
Marshaller.StartMarshal(writer).WriteGuid(opId);
});
}
/** <inheritDoc /> */
public IEvent WaitForLocal(params int[] types)
{
return WaitForLocal<IEvent>(null, types);
}
/** <inheritDoc /> */
public virtual T WaitForLocal<T>(IEventFilter<T> filter, params int[] types) where T : IEvent
{
long hnd = 0;
try
{
return WaitForLocal0(filter, ref hnd, types);
}
finally
{
if (filter != null)
Ignite.HandleRegistry.Release(hnd);
}
}
/** <inheritDoc /> */
public List<IEvent> LocalQuery(params int[] types)
{
return DoOutInOp((int) Op.LocalQuery,
writer => WriteEventTypes(types, writer),
reader => ReadEvents<IEvent>(reader));
}
/** <inheritDoc /> */
public void RecordLocal(IEvent evt)
{
throw new NotImplementedException("GG-10244");
}
/** <inheritDoc /> */
public void LocalListen<T>(IEventFilter<T> listener, params int[] types) where T : IEvent
{
IgniteArgumentCheck.NotNull(listener, "listener");
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
foreach (var type in types)
LocalListen(listener, type);
}
/** <inheritDoc /> */
public bool StopLocalListen<T>(IEventFilter<T> listener, params int[] types) where T : IEvent
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
return false;
var success = false;
// Should do this inside lock to avoid race with subscription
// ToArray is required because we are going to modify underlying dictionary during enumeration
foreach (var filter in GetLocalFilters(listener, types).ToArray())
success |= UU.EventsStopLocalListen(Target, filter.Handle);
return success;
}
}
/** <inheritDoc /> */
public void EnableLocal(params int[] types)
{
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
DoOutOp((int)Op.EnableLocal, writer => WriteEventTypes(types, writer));
}
/** <inheritDoc /> */
public void DisableLocal(params int[] types)
{
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
DoOutOp((int)Op.DisableLocal, writer => WriteEventTypes(types, writer));
}
/** <inheritDoc /> */
public int[] GetEnabledEvents()
{
return DoInOp((int)Op.GetEnabledEvents, reader => ReadEventTypes(reader));
}
/** <inheritDoc /> */
public bool IsEnabled(int type)
{
return UU.EventsIsEnabled(Target, type);
}
/// <summary>
/// Waits for the specified events.
/// </summary>
/// <typeparam name="T">Type of events.</typeparam>
/// <param name="filter">Optional filtering predicate. Event wait will end as soon as it returns false.</param>
/// <param name="handle">The filter handle, if applicable.</param>
/// <param name="types">Types of the events to wait for.
/// If not provided, all events will be passed to the filter.</param>
/// <returns>Ignite event.</returns>
protected T WaitForLocal0<T>(IEventFilter<T> filter, ref long handle, params int[] types) where T : IEvent
{
if (filter != null)
handle = Ignite.HandleRegistry.Allocate(new LocalEventFilter
{
InvokeFunc = stream => InvokeLocalFilter(stream, filter)
});
var hnd = handle;
return DoOutInOp((int)Op.WaitForLocal,
writer =>
{
if (filter != null)
{
writer.WriteBoolean(true);
writer.WriteLong(hnd);
}
else
writer.WriteBoolean(false);
WriteEventTypes(types, writer);
},
reader => EventReader.Read<T>(Marshaller.StartUnmarshal(reader)));
}
/// <summary>
/// Reads events from a portable stream.
/// </summary>
/// <typeparam name="T">Event type.</typeparam>
/// <param name="reader">Reader.</param>
/// <returns>Resulting list or null.</returns>
private List<T> ReadEvents<T>(IPortableStream reader) where T : IEvent
{
return ReadEvents<T>(Marshaller.StartUnmarshal(reader));
}
/// <summary>
/// Reads events from a portable reader.
/// </summary>
/// <typeparam name="T">Event type.</typeparam>
/// <param name="portableReader">Reader.</param>
/// <returns>Resulting list or null.</returns>
protected static List<T> ReadEvents<T>(PortableReaderImpl portableReader) where T : IEvent
{
var count = portableReader.RawReader().ReadInt();
if (count == -1)
return null;
var result = new List<T>(count);
for (var i = 0; i < count; i++)
result.Add(EventReader.Read<T>(portableReader));
return result;
}
/// <summary>
/// Gets local filters by user listener and event type.
/// </summary>
/// <param name="listener">Listener.</param>
/// <param name="types">Types.</param>
/// <returns>Collection of local listener wrappers.</returns>
[SuppressMessage("ReSharper", "InconsistentlySynchronizedField",
Justification = "This private method should be always called within a lock on localFilters")]
private IEnumerable<LocalHandledEventFilter> GetLocalFilters(object listener, int[] types)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
return Enumerable.Empty<LocalHandledEventFilter>();
if (types.Length == 0)
return filters.Values;
return types.Select(type =>
{
LocalHandledEventFilter filter;
return filters.TryGetValue(type, out filter) ? filter : null;
}).Where(x => x != null);
}
/// <summary>
/// Adds an event listener for local events.
/// </summary>
/// <typeparam name="T">Type of events.</typeparam>
/// <param name="listener">Predicate that is called on each received event.</param>
/// <param name="type">Event type for which this listener will be notified</param>
private void LocalListen<T>(IEventFilter<T> listener, int type) where T : IEvent
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
{
filters = new Dictionary<int, LocalHandledEventFilter>();
_localFilters[listener] = filters;
}
LocalHandledEventFilter localFilter;
if (!filters.TryGetValue(type, out localFilter))
{
localFilter = CreateLocalFilter(listener, type);
filters[type] = localFilter;
}
UU.EventsLocalListen(Target, localFilter.Handle, type);
}
}
/// <summary>
/// Creates a user filter wrapper.
/// </summary>
/// <typeparam name="T">Event object type.</typeparam>
/// <param name="listener">Listener.</param>
/// <param name="type">Event type.</param>
/// <returns>Created wrapper.</returns>
private LocalHandledEventFilter CreateLocalFilter<T>(IEventFilter<T> listener, int type) where T : IEvent
{
var result = new LocalHandledEventFilter(
stream => InvokeLocalFilter(stream, listener),
unused =>
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (_localFilters.TryGetValue(listener, out filters))
{
filters.Remove(type);
if (filters.Count == 0)
_localFilters.Remove(listener);
}
}
});
result.Handle = Ignite.HandleRegistry.Allocate(result);
return result;
}
/// <summary>
/// Invokes local filter using data from specified stream.
/// </summary>
/// <typeparam name="T">Event object type.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="listener">The listener.</param>
/// <returns>Filter invocation result.</returns>
private bool InvokeLocalFilter<T>(IPortableStream stream, IEventFilter<T> listener) where T : IEvent
{
var evt = EventReader.Read<T>(Marshaller.StartUnmarshal(stream));
// No guid in local mode
return listener.Invoke(Guid.Empty, evt);
}
/// <summary>
/// Writes the event types.
/// </summary>
/// <param name="types">Types.</param>
/// <param name="writer">Writer.</param>
private static void WriteEventTypes(int[] types, IPortableRawWriter writer)
{
if (types.Length == 0)
types = null; // empty array means no type filtering
writer.WriteIntArray(types);
}
/// <summary>
/// Writes the event types.
/// </summary>
/// <param name="reader">Reader.</param>
private int[] ReadEventTypes(IPortableStream reader)
{
return Marshaller.StartUnmarshal(reader).ReadIntArray();
}
/// <summary>
/// Local user filter wrapper.
/// </summary>
private class LocalEventFilter : IInteropCallback
{
/** */
public Func<IPortableStream, bool> InvokeFunc;
/** <inheritdoc /> */
public int Invoke(IPortableStream stream)
{
return InvokeFunc(stream) ? 1 : 0;
}
}
/// <summary>
/// Local user filter wrapper with handle.
/// </summary>
private class LocalHandledEventFilter : Handle<Func<IPortableStream, bool>>, IInteropCallback
{
/** */
public long Handle;
/** <inheritdoc /> */
public int Invoke(IPortableStream stream)
{
return Target(stream) ? 1 : 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalHandledEventFilter"/> class.
/// </summary>
/// <param name="invokeFunc">The invoke function.</param>
/// <param name="releaseAction">The release action.</param>
public LocalHandledEventFilter(
Func<IPortableStream, bool> invokeFunc, Action<Func<IPortableStream, bool>> releaseAction)
: base(invokeFunc, releaseAction)
{
// No-op.
}
}
}
}
| |
// 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.IO;
using System.Xml;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization; // For SR
using System.Security;
using System.Text;
using System.Globalization;
namespace System.Xml
{
public interface IXmlTextReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
}
internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderInitializer
{
private const int MaxTextChunk = 2048;
private PrefixHandle _prefix;
private StringHandle _localName;
private int[] _rowOffsets;
private OnXmlDictionaryReaderClose _onClose;
private bool _buffered;
private int _maxBytesPerRead;
private static byte[] s_charType = new byte[256]
{
/* 0 (.) */
CharType.None,
/* 1 (.) */
CharType.None,
/* 2 (.) */
CharType.None,
/* 3 (.) */
CharType.None,
/* 4 (.) */
CharType.None,
/* 5 (.) */
CharType.None,
/* 6 (.) */
CharType.None,
/* 7 (.) */
CharType.None,
/* 8 (.) */
CharType.None,
/* 9 (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace,
/* A (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace,
/* B (.) */
CharType.None,
/* C (.) */
CharType.None,
/* D (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace,
/* E (.) */
CharType.None,
/* F (.) */
CharType.None,
/* 10 (.) */
CharType.None,
/* 11 (.) */
CharType.None,
/* 12 (.) */
CharType.None,
/* 13 (.) */
CharType.None,
/* 14 (.) */
CharType.None,
/* 15 (.) */
CharType.None,
/* 16 (.) */
CharType.None,
/* 17 (.) */
CharType.None,
/* 18 (.) */
CharType.None,
/* 19 (.) */
CharType.None,
/* 1A (.) */
CharType.None,
/* 1B (.) */
CharType.None,
/* 1C (.) */
CharType.None,
/* 1D (.) */
CharType.None,
/* 1E (.) */
CharType.None,
/* 1F (.) */
CharType.None,
/* 20 ( ) */
CharType.None|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.AttributeText|CharType.SpecialWhitespace,
/* 21 (!) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 22 (") */
CharType.None|CharType.Comment|CharType.Text,
/* 23 (#) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 24 ($) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 25 (%) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 26 (&) */
CharType.None|CharType.Comment,
/* 27 (') */
CharType.None|CharType.Comment|CharType.Text,
/* 28 (() */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 29 ()) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2A (*) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2B (+) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2C (,) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2D (-) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 2E (.) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 2F (/) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 30 (0) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 31 (1) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 32 (2) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 33 (3) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 34 (4) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 35 (5) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 36 (6) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 37 (7) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 38 (8) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 39 (9) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 3A (:) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3B (;) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3C (<) */
CharType.None|CharType.Comment,
/* 3D (=) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3E (>) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3F (?) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 40 (@) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 41 (A) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 42 (B) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 43 (C) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 44 (D) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 45 (E) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 46 (F) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 47 (G) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 48 (H) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 49 (I) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4A (J) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4B (K) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4C (L) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4D (M) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4E (N) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4F (O) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 50 (P) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 51 (Q) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 52 (R) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 53 (S) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 54 (T) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 55 (U) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 56 (V) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 57 (W) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 58 (X) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 59 (Y) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 5A (Z) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 5B ([) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5C (\) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5D (]) */
CharType.None|CharType.Comment|CharType.AttributeText,
/* 5E (^) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5F (_) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 60 (`) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 61 (a) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 62 (b) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 63 (c) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 64 (d) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 65 (e) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 66 (f) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 67 (g) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 68 (h) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 69 (i) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6A (j) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6B (k) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6C (l) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6D (m) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6E (n) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6F (o) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 70 (p) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 71 (q) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 72 (r) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 73 (s) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 74 (t) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 75 (u) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 76 (v) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 77 (w) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 78 (x) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 79 (y) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 7A (z) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 7B ({) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7C (|) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7D (}) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7E (~) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7F (.) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 80 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 81 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 82 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 83 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 84 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 85 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 86 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 87 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 88 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 89 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8A (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8B (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8C (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8D (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8E (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8F (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 90 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 91 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 92 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 93 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 94 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 95 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 96 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 97 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 98 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 99 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9A (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9B (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9C (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9D (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9E (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9F (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A0 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AD (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* ED (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EF (?) */
CharType.None|CharType.FirstName|CharType.Name,
/* F0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
};
public XmlUTF8TextReader()
{
_prefix = new PrefixHandle(BufferReader);
_localName = new StringHandle(BufferReader);
}
public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, onClose);
ArraySegment<byte> seg = EncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding);
BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null);
_buffered = true;
}
public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
MoveToInitial(quotas, onClose);
stream = new EncodingStreamWrapper(stream, encoding);
BufferReader.SetBuffer(stream, null, null);
_buffered = false;
}
private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
MoveToInitial(quotas);
_maxBytesPerRead = quotas.MaxBytesPerRead;
_onClose = onClose;
}
public override void Close()
{
_rowOffsets = null;
base.Close();
OnXmlDictionaryReaderClose onClose = _onClose;
_onClose = null;
if (onClose != null)
{
try
{
onClose(this);
}
catch (Exception e)
{
if (DiagnosticUtility.IsFatal(e)) throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
}
private void SkipWhitespace()
{
while (!BufferReader.EndOfFile && (s_charType[BufferReader.GetByte()] & CharType.Whitespace) != 0)
BufferReader.SkipByte();
}
private void ReadDeclaration()
{
if (!_buffered)
BufferElement();
int offset;
byte[] buffer = BufferReader.GetBuffer(5, out offset);
if (buffer[offset + 0] != (byte)'?' ||
buffer[offset + 1] != (byte)'x' ||
buffer[offset + 2] != (byte)'m' ||
buffer[offset + 3] != (byte)'l' ||
(s_charType[buffer[offset + 4]] & CharType.Whitespace) == 0)
{
XmlExceptionHelper.ThrowProcessingInstructionNotSupported(this);
}
// If anything came before the "<?xml ?>" it's an error.
if (this.Node.ReadState != ReadState.Initial)
{
XmlExceptionHelper.ThrowDeclarationNotFirst(this);
}
BufferReader.Advance(5);
int localNameOffset = offset + 1;
int localNameLength = 3;
int valueOffset = BufferReader.Offset;
SkipWhitespace();
ReadAttributes();
int valueLength = BufferReader.Offset - valueOffset;
// Backoff the spaces
while (valueLength > 0)
{
byte ch = BufferReader.GetByte(valueOffset + valueLength - 1);
if ((s_charType[ch] & CharType.Whitespace) == 0)
break;
valueLength--;
}
buffer = BufferReader.GetBuffer(2, out offset);
if (buffer[offset + 0] != (byte)'?' ||
buffer[offset + 1] != (byte)'>')
{
XmlExceptionHelper.ThrowTokenExpected(this, "?>", Encoding.UTF8.GetString(buffer, offset, 2));
}
BufferReader.Advance(2);
XmlDeclarationNode declarationNode = MoveToDeclaration();
declarationNode.LocalName.SetValue(localNameOffset, localNameLength);
declarationNode.Value.SetValue(ValueHandleType.UTF8, valueOffset, valueLength);
}
private void VerifyNCName(string s)
{
try
{
XmlConvert.VerifyNCName(s);
}
catch (XmlException exception)
{
XmlExceptionHelper.ThrowXmlException(this, exception);
}
}
private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName)
{
int offset;
int offsetMax;
byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax);
int ch = 0;
int anyChar = 0;
int prefixChar = 0;
int prefixOffset = offset;
if (offset < offsetMax)
{
ch = buffer[offset];
prefixChar = ch;
if ((s_charType[ch] & CharType.FirstName) == 0)
anyChar |= 0x80;
anyChar |= ch;
offset++;
while (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.Name) == 0)
break;
anyChar |= ch;
offset++;
}
}
else
{
anyChar |= 0x80;
ch = 0;
}
if (ch == ':')
{
int prefixLength = offset - prefixOffset;
if (prefixLength == 1 && prefixChar >= 'a' && prefixChar <= 'z')
prefix.SetValue(PrefixHandle.GetAlphaPrefix(prefixChar - 'a'));
else
prefix.SetValue(prefixOffset, prefixLength);
offset++;
int localNameOffset = offset;
if (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.FirstName) == 0)
anyChar |= 0x80;
anyChar |= ch;
offset++;
while (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.Name) == 0)
break;
anyChar |= ch;
offset++;
}
}
else
{
anyChar |= 0x80;
ch = 0;
}
localName.SetValue(localNameOffset, offset - localNameOffset);
if (anyChar >= 0x80)
{
VerifyNCName(prefix.GetString());
VerifyNCName(localName.GetString());
}
}
else
{
prefix.SetValue(PrefixHandleType.Empty);
localName.SetValue(prefixOffset, offset - prefixOffset);
if (anyChar >= 0x80)
{
VerifyNCName(localName.GetString());
}
}
BufferReader.Advance(offset - prefixOffset);
}
private int ReadAttributeText(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.AttributeText) != 0)
offset++;
return offset - textOffset;
}
private void ReadAttributes()
{
int startOffset = 0;
if (_buffered)
startOffset = BufferReader.Offset;
while (true)
{
byte ch;
ReadQualifiedName(_prefix, _localName);
if (BufferReader.GetByte() != '=')
{
SkipWhitespace();
if (BufferReader.GetByte() != '=')
XmlExceptionHelper.ThrowTokenExpected(this, "=", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
byte quoteChar = BufferReader.GetByte();
if (quoteChar != '"' && quoteChar != '\'')
{
SkipWhitespace();
quoteChar = BufferReader.GetByte();
if (quoteChar != '"' && quoteChar != '\'')
XmlExceptionHelper.ThrowTokenExpected(this, "\"", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
bool escaped = false;
int valueOffset = BufferReader.Offset;
while (true)
{
int offset, offsetMax;
byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax);
int length = ReadAttributeText(buffer, offset, offsetMax);
BufferReader.Advance(length);
ch = BufferReader.GetByte();
if (ch == quoteChar)
break;
if (ch == '&')
{
ReadCharRef();
escaped = true;
}
else if (ch == '\'' || ch == '"')
{
BufferReader.SkipByte();
}
else if (ch == '\n' || ch == '\r' || ch == '\t')
{
BufferReader.SkipByte();
escaped = true;
}
else if (ch == 0xEF)
{
ReadNonFFFE();
}
else
{
XmlExceptionHelper.ThrowTokenExpected(this, ((char)quoteChar).ToString(), (char)ch);
}
}
int valueLength = BufferReader.Offset - valueOffset;
XmlAttributeNode attributeNode;
if (_prefix.IsXmlns)
{
Namespace ns = AddNamespace();
_localName.ToPrefixHandle(ns.Prefix);
ns.Uri.SetValue(valueOffset, valueLength, escaped);
attributeNode = AddXmlnsAttribute(ns);
}
else if (_prefix.IsEmpty && _localName.IsXmlns)
{
Namespace ns = AddNamespace();
ns.Prefix.SetValue(PrefixHandleType.Empty);
ns.Uri.SetValue(valueOffset, valueLength, escaped);
attributeNode = AddXmlnsAttribute(ns);
}
else if (_prefix.IsXml)
{
attributeNode = AddXmlAttribute();
attributeNode.Prefix.SetValue(_prefix);
attributeNode.LocalName.SetValue(_localName);
attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength);
FixXmlAttribute(attributeNode);
}
else
{
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(_prefix);
attributeNode.LocalName.SetValue(_localName);
attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength);
}
attributeNode.QuoteChar = (char)quoteChar;
BufferReader.SkipByte();
ch = BufferReader.GetByte();
bool space = false;
while ((s_charType[ch] & CharType.Whitespace) != 0)
{
space = true;
BufferReader.SkipByte();
ch = BufferReader.GetByte();
}
if (ch == '>' || ch == '/' || ch == '?')
break;
if (!space)
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlSpaceBetweenAttributes)));
}
if (_buffered && (BufferReader.Offset - startOffset) > _maxBytesPerRead)
XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(this, _maxBytesPerRead);
ProcessAttributes();
}
// NOTE: Call only if 0xEF has been seen in the stream AND there are three valid bytes to check (buffer[offset], buffer[offset + 1], buffer[offset + 2]).
// 0xFFFE and 0xFFFF are not valid characters per Unicode specification. The first byte in the UTF8 representation is 0xEF.
private bool IsNextCharacterNonFFFE(byte[] buffer, int offset)
{
Fx.Assert(buffer[offset] == 0xEF, "buffer[offset] MUST be 0xEF.");
if (buffer[offset + 1] == 0xBF && (buffer[offset + 2] == 0xBE || buffer[offset + 2] == 0xBF))
{
// 0xFFFE : 0xEF 0xBF 0xBE
// 0xFFFF : 0xEF 0xBF 0xBF
// we know that buffer[offset] is already 0xEF, don't bother checking it.
return false;
}
// no bad characters
return true;
}
private void ReadNonFFFE()
{
int off;
byte[] buff = BufferReader.GetBuffer(3, out off);
if (buff[off + 1] == 0xBF && (buff[off + 2] == 0xBE || buff[off + 2] == 0xBF))
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE)));
}
BufferReader.Advance(3);
}
private void BufferElement()
{
int elementOffset = BufferReader.Offset;
const int byteCount = 128;
bool done = false;
byte quoteChar = 0;
while (!done)
{
int offset;
int offsetMax;
byte[] buffer = BufferReader.GetBuffer(byteCount, out offset, out offsetMax);
if (offset + byteCount != offsetMax)
break;
for (int i = offset; i < offsetMax && !done; i++)
{
byte b = buffer[i];
if (quoteChar == 0)
{
if (b == '\'' || b == '"')
quoteChar = b;
if (b == '>')
done = true;
}
else
{
if (b == quoteChar)
{
quoteChar = 0;
}
}
}
BufferReader.Advance(byteCount);
}
BufferReader.Offset = elementOffset;
}
private new void ReadStartElement()
{
if (!_buffered)
BufferElement();
XmlElementNode elementNode = EnterScope();
elementNode.NameOffset = BufferReader.Offset;
ReadQualifiedName(elementNode.Prefix, elementNode.LocalName);
elementNode.NameLength = BufferReader.Offset - elementNode.NameOffset;
byte ch = BufferReader.GetByte();
while ((s_charType[ch] & CharType.Whitespace) != 0)
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
}
if (ch != '>' && ch != '/')
{
ReadAttributes();
ch = BufferReader.GetByte();
}
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
bool isEmptyElement = false;
if (ch == '/')
{
isEmptyElement = true;
BufferReader.SkipByte();
}
elementNode.IsEmptyElement = isEmptyElement;
elementNode.ExitScope = isEmptyElement;
if (BufferReader.GetByte() != '>')
XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte());
BufferReader.SkipByte();
elementNode.BufferOffset = BufferReader.Offset;
}
private new void ReadEndElement()
{
BufferReader.SkipByte();
XmlElementNode elementNode = this.ElementNode;
int nameOffset = elementNode.NameOffset;
int nameLength = elementNode.NameLength;
int offset;
byte[] buffer = BufferReader.GetBuffer(nameLength, out offset);
for (int i = 0; i < nameLength; i++)
{
if (buffer[offset + i] != buffer[nameOffset + i])
{
ReadQualifiedName(_prefix, _localName);
XmlExceptionHelper.ThrowTagMismatch(this, elementNode.Prefix.GetString(), elementNode.LocalName.GetString(), _prefix.GetString(), _localName.GetString());
}
}
BufferReader.Advance(nameLength);
if (BufferReader.GetByte() != '>')
{
SkipWhitespace();
if (BufferReader.GetByte() != '>')
XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
MoveToEndElement();
}
private void ReadComment()
{
BufferReader.SkipByte();
if (BufferReader.GetByte() != '-')
XmlExceptionHelper.ThrowTokenExpected(this, "--", (char)BufferReader.GetByte());
BufferReader.SkipByte();
int commentOffset = BufferReader.Offset;
while (true)
{
while (true)
{
byte b = BufferReader.GetByte();
if (b == '-')
break;
if ((s_charType[b] & CharType.Comment) == 0)
{
if (b == 0xEF)
ReadNonFFFE();
else
XmlExceptionHelper.ThrowInvalidXml(this, b);
}
else
{
BufferReader.SkipByte();
}
}
int offset;
byte[] buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)'-' &&
buffer[offset + 1] == (byte)'-')
{
if (buffer[offset + 2] == (byte)'>')
break;
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidCommentChars)));
}
BufferReader.SkipByte();
}
int commentLength = BufferReader.Offset - commentOffset;
MoveToComment().Value.SetValue(ValueHandleType.UTF8, commentOffset, commentLength);
BufferReader.Advance(3);
}
private void ReadCData()
{
int offset;
byte[] buffer = BufferReader.GetBuffer(7, out offset);
if (buffer[offset + 0] != (byte)'[' ||
buffer[offset + 1] != (byte)'C' ||
buffer[offset + 2] != (byte)'D' ||
buffer[offset + 3] != (byte)'A' ||
buffer[offset + 4] != (byte)'T' ||
buffer[offset + 5] != (byte)'A' ||
buffer[offset + 6] != (byte)'[')
{
XmlExceptionHelper.ThrowTokenExpected(this, "[CDATA[", Encoding.UTF8.GetString(buffer, offset, 7));
}
BufferReader.Advance(7);
int cdataOffset = BufferReader.Offset;
while (true)
{
byte b;
while (true)
{
b = BufferReader.GetByte();
if (b == ']')
break;
if (b == 0xEF)
ReadNonFFFE();
else
BufferReader.SkipByte();
}
buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)']' &&
buffer[offset + 1] == (byte)']' &&
buffer[offset + 2] == (byte)'>')
break;
BufferReader.SkipByte();
}
int cdataLength = BufferReader.Offset - cdataOffset;
MoveToCData().Value.SetValue(ValueHandleType.UTF8, cdataOffset, cdataLength);
BufferReader.Advance(3);
}
private int ReadCharRef()
{
DiagnosticUtility.DebugAssert(BufferReader.GetByte() == '&', "");
int charEntityOffset = BufferReader.Offset;
BufferReader.SkipByte();
while (BufferReader.GetByte() != ';')
BufferReader.SkipByte();
BufferReader.SkipByte();
int charEntityLength = BufferReader.Offset - charEntityOffset;
BufferReader.Offset = charEntityOffset;
int ch = BufferReader.GetCharEntity(charEntityOffset, charEntityLength);
BufferReader.Advance(charEntityLength);
return ch;
}
private void ReadWhitespace()
{
byte[] buffer;
int offset;
int offsetMax;
int length;
if (_buffered)
{
buffer = BufferReader.GetBuffer(out offset, out offsetMax);
length = ReadWhitespace(buffer, offset, offsetMax);
}
else
{
buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax);
length = ReadWhitespace(buffer, offset, offsetMax);
length = BreakText(buffer, offset, length);
}
BufferReader.Advance(length);
MoveToWhitespaceText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
private int ReadWhitespace(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int wsOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.SpecialWhitespace) != 0)
offset++;
return offset - wsOffset;
}
private int ReadText(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.Text) != 0)
offset++;
return offset - textOffset;
}
// Read Unicode codepoints 0xFvvv
private int ReadTextAndWatchForInvalidCharacters(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && ((charType[buffer[offset]] & CharType.Text) != 0 || buffer[offset] == 0xEF))
{
if (buffer[offset] != 0xEF)
{
offset++;
}
else
{
// Ensure that we have three bytes (buffer[offset], buffer[offset + 1], buffer[offset + 2])
// available for IsNextCharacterNonFFFE to check.
if (offset + 2 < offsetMax)
{
if (IsNextCharacterNonFFFE(buffer, offset))
{
// if first byte is 0xEF, UTF8 mandates a 3-byte character representation of this Unicode code point
offset += 3;
}
else
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE)));
}
}
else
{
if (BufferReader.Offset < offset)
{
// We have read some characters already
// Let the outer ReadText advance the bufferReader and return text node to caller
break;
}
else
{
// Get enough bytes for us to process next character, then go back to top of while loop
int dummy;
BufferReader.GetBuffer(3, out dummy);
}
}
}
}
return offset - textOffset;
}
// bytes bits UTF-8 representation
// ----- ---- -----------------------------------
// 1 7 0vvvvvvv
// 2 11 110vvvvv 10vvvvvv
// 3 16 1110vvvv 10vvvvvv 10vvvvvv
// 4 21 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
// ----- ---- -----------------------------------
private int BreakText(byte[] buffer, int offset, int length)
{
// See if we might be breaking a utf8 sequence
if (length > 0 && (buffer[offset + length - 1] & 0x80) == 0x80)
{
// Find the lead char of the utf8 sequence (0x11xxxxxx)
int originalLength = length;
do
{
length--;
}
while (length > 0 && (buffer[offset + length] & 0xC0) != 0xC0);
// Couldn't find the lead char
if (length == 0)
return originalLength; // Invalid utf8 sequence - can't break
// Count how many bytes follow the lead char
byte b = unchecked((byte)(buffer[offset + length] << 2));
int byteCount = 2;
while ((b & 0x80) == 0x80)
{
b = unchecked((byte)(b << 1));
byteCount++;
// There shouldn't be more than 3 bytes following the lead char
if (byteCount > 4)
return originalLength; // Invalid utf8 sequence - can't break
}
if (length + byteCount == originalLength)
return originalLength; // sequence fits exactly
}
return length;
}
private void ReadText(bool hasLeadingByteOf0xEF)
{
byte[] buffer;
int offset;
int offsetMax;
int length;
if (_buffered)
{
buffer = BufferReader.GetBuffer(out offset, out offsetMax);
if (hasLeadingByteOf0xEF)
{
length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax);
}
else
{
length = ReadText(buffer, offset, offsetMax);
}
}
else
{
buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax);
if (hasLeadingByteOf0xEF)
{
length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax);
}
else
{
length = ReadText(buffer, offset, offsetMax);
}
length = BreakText(buffer, offset, length);
}
BufferReader.Advance(length);
if (offset < offsetMax - 1 - length && (buffer[offset + length] == (byte)'<' && buffer[offset + length + 1] != (byte)'!'))
{
MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
else
{
MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
}
private void ReadEscapedText()
{
int ch = ReadCharRef();
if (ch < 256 && (s_charType[ch] & CharType.Whitespace) != 0)
MoveToWhitespaceText().Value.SetCharValue(ch);
else
MoveToComplexText().Value.SetCharValue(ch);
}
public override bool Read()
{
if (this.Node.ReadState == ReadState.Closed)
return false;
if (this.Node.CanMoveToElement)
{
// If we're positioned on an attribute or attribute text on an empty element, we need to move back
// to the element in order to get the correct setting of ExitScope
MoveToElement();
}
SignNode();
if (this.Node.ExitScope)
{
ExitScope();
}
if (!_buffered)
BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead);
if (BufferReader.EndOfFile)
{
MoveToEndOfFile();
return false;
}
byte ch = BufferReader.GetByte();
if (ch == (byte)'<')
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
if (ch == (byte)'/')
ReadEndElement();
else if (ch == (byte)'!')
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
if (ch == '-')
{
ReadComment();
}
else
{
if (OutsideRootElement)
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCDATAInvalidAtTopLevel)));
ReadCData();
}
}
else if (ch == (byte)'?')
ReadDeclaration();
else
ReadStartElement();
}
else if ((s_charType[ch] & CharType.SpecialWhitespace) != 0)
{
ReadWhitespace();
}
else if (OutsideRootElement && ch != '\r')
{
XmlExceptionHelper.ThrowInvalidRootData(this);
}
else if ((s_charType[ch] & CharType.Text) != 0)
{
ReadText(false);
}
else if (ch == '&')
{
ReadEscapedText();
}
else if (ch == '\r')
{
BufferReader.SkipByte();
if (!BufferReader.EndOfFile && BufferReader.GetByte() == '\n')
ReadWhitespace();
else
MoveToComplexText().Value.SetCharValue('\n');
}
else if (ch == ']')
{
int offset;
byte[] buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)']' &&
buffer[offset + 1] == (byte)']' &&
buffer[offset + 2] == (byte)'>')
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCloseCData)));
}
BufferReader.SkipByte();
MoveToComplexText().Value.SetCharValue(']'); // Need to get past the ']' and keep going.
}
else if (ch == 0xEF) // Watch for invalid characters 0xfffe and 0xffff
{
ReadText(true);
}
else
{
XmlExceptionHelper.ThrowInvalidXml(this, ch);
}
return true;
}
protected override XmlSigningNodeWriter CreateSigningNodeWriter()
{
return new XmlSigningNodeWriter(true);
}
public bool HasLineInfo()
{
return true;
}
public int LineNumber
{
get
{
int row, column;
GetPosition(out row, out column);
return row;
}
}
public int LinePosition
{
get
{
int row, column;
GetPosition(out row, out column);
return column;
}
}
private void GetPosition(out int row, out int column)
{
if (_rowOffsets == null)
{
_rowOffsets = BufferReader.GetRows();
}
int offset = BufferReader.Offset;
int j = 0;
while (j < _rowOffsets.Length - 1 && _rowOffsets[j + 1] < offset)
j++;
row = j + 1;
column = offset - _rowOffsets[j] + 1;
}
private static class CharType
{
public const byte None = 0x00;
public const byte FirstName = 0x01;
public const byte Name = 0x02;
public const byte Whitespace = 0x04;
public const byte Text = 0x08;
public const byte AttributeText = 0x10;
public const byte SpecialWhitespace = 0x20;
public const byte Comment = 0x40;
}
}
}
| |
// 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 gagvc = Google.Ads.GoogleAds.V8.Common;
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCampaignSimulationServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCampaignSimulationRequestObject()
{
moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient> mockGrpcClient = new moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient>(moq::MockBehavior.Strict);
GetCampaignSimulationRequest request = new GetCampaignSimulationRequest
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::CampaignSimulation expectedResponse = new gagvr::CampaignSimulation
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
CampaignId = -3743237468908008719L,
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
TargetImpressionSharePointList = new gagvc::TargetImpressionShareSimulationPointList(),
BudgetPointList = new gagvc::BudgetSimulationPointList(),
};
mockGrpcClient.Setup(x => x.GetCampaignSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSimulationServiceClient client = new CampaignSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSimulation response = client.GetCampaignSimulation(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignSimulationRequestObjectAsync()
{
moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient> mockGrpcClient = new moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient>(moq::MockBehavior.Strict);
GetCampaignSimulationRequest request = new GetCampaignSimulationRequest
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::CampaignSimulation expectedResponse = new gagvr::CampaignSimulation
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
CampaignId = -3743237468908008719L,
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
TargetImpressionSharePointList = new gagvc::TargetImpressionShareSimulationPointList(),
BudgetPointList = new gagvc::BudgetSimulationPointList(),
};
mockGrpcClient.Setup(x => x.GetCampaignSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSimulationServiceClient client = new CampaignSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSimulation responseCallSettings = await client.GetCampaignSimulationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignSimulation responseCancellationToken = await client.GetCampaignSimulationAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignSimulation()
{
moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient> mockGrpcClient = new moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient>(moq::MockBehavior.Strict);
GetCampaignSimulationRequest request = new GetCampaignSimulationRequest
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::CampaignSimulation expectedResponse = new gagvr::CampaignSimulation
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
CampaignId = -3743237468908008719L,
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
TargetImpressionSharePointList = new gagvc::TargetImpressionShareSimulationPointList(),
BudgetPointList = new gagvc::BudgetSimulationPointList(),
};
mockGrpcClient.Setup(x => x.GetCampaignSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSimulationServiceClient client = new CampaignSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSimulation response = client.GetCampaignSimulation(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignSimulationAsync()
{
moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient> mockGrpcClient = new moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient>(moq::MockBehavior.Strict);
GetCampaignSimulationRequest request = new GetCampaignSimulationRequest
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::CampaignSimulation expectedResponse = new gagvr::CampaignSimulation
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
CampaignId = -3743237468908008719L,
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
TargetImpressionSharePointList = new gagvc::TargetImpressionShareSimulationPointList(),
BudgetPointList = new gagvc::BudgetSimulationPointList(),
};
mockGrpcClient.Setup(x => x.GetCampaignSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSimulationServiceClient client = new CampaignSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSimulation responseCallSettings = await client.GetCampaignSimulationAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignSimulation responseCancellationToken = await client.GetCampaignSimulationAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignSimulationResourceNames()
{
moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient> mockGrpcClient = new moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient>(moq::MockBehavior.Strict);
GetCampaignSimulationRequest request = new GetCampaignSimulationRequest
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::CampaignSimulation expectedResponse = new gagvr::CampaignSimulation
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
CampaignId = -3743237468908008719L,
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
TargetImpressionSharePointList = new gagvc::TargetImpressionShareSimulationPointList(),
BudgetPointList = new gagvc::BudgetSimulationPointList(),
};
mockGrpcClient.Setup(x => x.GetCampaignSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSimulationServiceClient client = new CampaignSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSimulation response = client.GetCampaignSimulation(request.ResourceNameAsCampaignSimulationName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignSimulationResourceNamesAsync()
{
moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient> mockGrpcClient = new moq::Mock<CampaignSimulationService.CampaignSimulationServiceClient>(moq::MockBehavior.Strict);
GetCampaignSimulationRequest request = new GetCampaignSimulationRequest
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::CampaignSimulation expectedResponse = new gagvr::CampaignSimulation
{
ResourceNameAsCampaignSimulationName = gagvr::CampaignSimulationName.FromCustomerCampaignTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
CampaignId = -3743237468908008719L,
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
TargetImpressionSharePointList = new gagvc::TargetImpressionShareSimulationPointList(),
BudgetPointList = new gagvc::BudgetSimulationPointList(),
};
mockGrpcClient.Setup(x => x.GetCampaignSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSimulationServiceClient client = new CampaignSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSimulation responseCallSettings = await client.GetCampaignSimulationAsync(request.ResourceNameAsCampaignSimulationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignSimulation responseCancellationToken = await client.GetCampaignSimulationAsync(request.ResourceNameAsCampaignSimulationName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Globalization
{
internal partial class CultureData
{
/// <summary>
/// Check with the OS to see if this is a valid culture.
/// If so we populate a limited number of fields. If its not valid we return false.
///
/// The fields we populate:
///
/// sWindowsName -- The name that windows thinks this culture is, ie:
/// en-US if you pass in en-US
/// de-DE_phoneb if you pass in de-DE_phoneb
/// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine)
/// fj if you pass in fj (neutral, post-Windows 7 machine)
///
/// sRealName -- The name you used to construct the culture, in pretty form
/// en-US if you pass in EN-us
/// en if you pass in en
/// de-DE_phoneb if you pass in de-DE_phoneb
///
/// sSpecificCulture -- The specific culture for this culture
/// en-US for en-US
/// en-US for en
/// de-DE_phoneb for alt sort
/// fj-FJ for fj (neutral)
///
/// sName -- The IETF name of this culture (ie: no sort info, could be neutral)
/// en-US if you pass in en-US
/// en if you pass in en
/// de-DE if you pass in de-DE_phoneb
///
/// bNeutral -- TRUE if it is a neutral locale
///
/// For a neutral we just populate the neutral name, but we leave the windows name pointing to the
/// windows locale that's going to provide data for us.
/// </summary>
private unsafe bool InitCultureData()
{
// TODO: Implement this fully.
// For now, just use all of the Invariant's data
CultureData invariant = CultureData.Invariant;
this.sRealName = invariant.sRealName;
this.sWindowsName = invariant.sWindowsName;
// Identity
this.sName = invariant.sName;
this.sParent = invariant.sParent;
this.bNeutral = invariant.bNeutral;
this.sEnglishDisplayName = invariant.sEnglishDisplayName;
this.sNativeDisplayName = invariant.sNativeDisplayName;
this.sSpecificCulture = invariant.sSpecificCulture;
// Language
this.sISO639Language = invariant.sISO639Language;
this.sLocalizedLanguage = invariant.sLocalizedLanguage;
this.sEnglishLanguage = invariant.sEnglishLanguage;
this.sNativeLanguage = invariant.sNativeLanguage;
// Region
this.sRegionName = invariant.sRegionName;
this.sEnglishCountry = invariant.sEnglishCountry;
this.sNativeCountry = invariant.sNativeCountry;
this.sISO3166CountryName = invariant.sISO3166CountryName;
// Numbers
this.sPositiveSign = invariant.sPositiveSign;
this.sNegativeSign = invariant.sNegativeSign;
this.saNativeDigits = invariant.saNativeDigits;
this.iDigits = invariant.iDigits;
this.iNegativeNumber = invariant.iNegativeNumber;
this.waGrouping = invariant.waGrouping;
this.sDecimalSeparator = invariant.sDecimalSeparator;
this.sThousandSeparator = invariant.sThousandSeparator;
this.sNaN = invariant.sNaN;
this.sPositiveInfinity = invariant.sPositiveInfinity;
this.sNegativeInfinity = invariant.sNegativeInfinity;
// Percent
this.iNegativePercent = invariant.iNegativePercent;
this.iPositivePercent = invariant.iPositivePercent;
this.sPercent = invariant.sPercent;
this.sPerMille = invariant.sPerMille;
// Currency
this.sCurrency = invariant.sCurrency;
this.sIntlMonetarySymbol = invariant.sIntlMonetarySymbol;
this.iCurrencyDigits = invariant.iCurrencyDigits;
this.iCurrency = invariant.iCurrency;
this.iNegativeCurrency = invariant.iNegativeCurrency;
this.waMonetaryGrouping = invariant.waMonetaryGrouping;
this.sMonetaryDecimal = invariant.sMonetaryDecimal;
this.sMonetaryThousand = invariant.sMonetaryThousand;
// Misc
this.iMeasure = invariant.iMeasure;
this.sListSeparator = invariant.sListSeparator;
// Time
this.sAM1159 = invariant.sAM1159;
this.sPM2359 = invariant.sPM2359;
this.saLongTimes = invariant.saLongTimes;
this.saShortTimes = invariant.saShortTimes;
this.saDurationFormats = invariant.saDurationFormats;
// Calendar specific data
this.iFirstDayOfWeek = invariant.iFirstDayOfWeek;
this.iFirstWeekOfYear = invariant.iFirstWeekOfYear;
this.waCalendars = invariant.waCalendars;
// Store for specific data about each calendar
this.calendars = invariant.calendars;
// Text information
this.iReadingLayout = invariant.iReadingLayout;
return true;
}
private string GetLocaleInfo(LocaleStringData type)
{
// TODO: Implement this fully.
return GetLocaleInfo("", type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
// TODO: Implement this fully.
switch(type)
{
case LocaleStringData.LocalizedDisplayName:
return "Invariant Language (Invariant Country)";
case LocaleStringData.EnglishDisplayName:
return "Invariant Language (Invariant Country)";
case LocaleStringData.NativeDisplayName:
return "Invariant Language (Invariant Country)";
case LocaleStringData.LocalizedLanguageName:
return "Invariant Language";
case LocaleStringData.EnglishLanguageName:
return "Invariant Language";
case LocaleStringData.NativeLanguageName:
return "Invariant Language";
case LocaleStringData.EnglishCountryName:
return "Invariant Country";
case LocaleStringData.NativeCountryName:
return "Invariant Country";
case LocaleStringData.ListSeparator:
return ",";
case LocaleStringData.DecimalSeparator:
return ".";
case LocaleStringData.ThousandSeparator:
return ",";
case LocaleStringData.Digits:
return "3;0";
case LocaleStringData.MonetarySymbol:
return "\u00A4";
case LocaleStringData.Iso4217MonetarySymbol:
return "XDR";
case LocaleStringData.MonetaryDecimalSeparator:
return ".";
case LocaleStringData.MonetaryThousandSeparator:
return ",";
case LocaleStringData.AMDesignator:
return "AM";
case LocaleStringData.PMDesignator:
return "PM";
case LocaleStringData.PositiveSign:
return "+";
case LocaleStringData.NegativeSign:
return "-";
case LocaleStringData.Iso639LanguageName:
return "iv";
case LocaleStringData.Iso3166CountryName:
return "IV";
case LocaleStringData.NaNSymbol:
return "NaN";
case LocaleStringData.PositiveInfinitySymbol:
return "Infinity";
case LocaleStringData.NegativeInfinitySymbol:
return "-Infinity";
case LocaleStringData.ParentName:
return "";
case LocaleStringData.PercentSymbol:
return "%";
case LocaleStringData.PerMilleSymbol:
return "\u2030";
default:
Contract.Assert(false, "Unmatched case in GetLocaleInfo(LocaleStringData)");
throw new NotImplementedException();
}
}
private int GetLocaleInfo(LocaleNumberData type)
{
// TODO: Implement this fully.
switch (type)
{
case LocaleNumberData.LanguageId:
return 127;
case LocaleNumberData.MeasurementSystem:
return 0;
case LocaleNumberData.FractionalDigitsCount:
return 2;
case LocaleNumberData.NegativeNumberFormat:
return 1;
case LocaleNumberData.MonetaryFractionalDigitsCount:
return 2;
case LocaleNumberData.PositiveMonetaryNumberFormat:
return 0;
case LocaleNumberData.NegativeMonetaryNumberFormat:
return 0;
case LocaleNumberData.CalendarType:
return 1;
case LocaleNumberData.FirstWeekOfYear:
return 0;
case LocaleNumberData.ReadingLayout:
return 0;
case LocaleNumberData.NegativePercentFormat:
return 0;
case LocaleNumberData.PositivePercentFormat:
return 0;
default:
Contract.Assert(false, "Unmatched case in GetLocaleInfo(LocaleNumberData)");
throw new NotImplementedException();
}
}
private int[] GetLocaleInfo(LocaleGroupingData type)
{
// TODO: Implement this fully.
switch (type)
{
case LocaleGroupingData.Digit:
return new int[] { 3 };
case LocaleGroupingData.Monetary:
return new int[] { 3 };
default:
Contract.Assert(false, "Unmatched case in GetLocaleInfo(LocaleGroupingData)");
throw new NotImplementedException();
}
}
private string GetTimeFormatString()
{
// TODO: Implement this fully.
return "HH:mm:ss";
}
private int GetFirstDayOfWeek()
{
// TODO: Implement this fully.
return 0;
}
private String[] GetTimeFormats()
{
// TODO: Implement this fully.
return new string[] { "HH:mm:ss" };
}
private String[] GetShortTimeFormats()
{
// TODO: Implement this fully.
return new string[] { "HH:mm", "hh:mm tt", "H:mm", "h:mm tt" };
}
// Enumerate all system cultures and then try to find out which culture has
// region name match the requested region name
private static CultureData GetCultureDataFromRegionName(String regionName)
{
// TODO: Implement this fully.
if (regionName == "")
{
return CultureInfo.InvariantCulture.m_cultureData;
}
throw new NotImplementedException();
}
private static string GetLanguageDisplayName(string cultureName)
{
// TODO: Implement this fully.
if (cultureName == "")
{
return "Invariant Language";
}
throw new NotImplementedException();
}
private static string GetRegionDisplayName(string isoCountryCode)
{
// TODO: Implement this fully.
return "";
}
private static CultureInfo GetUserDefaultCulture()
{
// TODO: Implement this fully.
return CultureInfo.InvariantCulture;
}
private static bool IsCustomCultureId(int cultureId)
{
// TODO: Implement this fully.
return false;
}
// PAL methods end here.
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.