context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
namespace XenAdmin.ConsoleView
{
partial class VNCTabView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
Program.AssertOnEventThread();
UnregisterEventListeners();
if (disposing && (components != null))
{
components.Dispose();
}
if (disposing && vncScreen != null && !vncScreen.IsDisposed)
{
vncScreen.GpuStatusChanged -= ShowGpuWarningIfRequired;
vncScreen.Dispose();
}
if (this.fullscreenForm != null)
{
fullscreenForm.Hide();
fullscreenForm.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VNCTabView));
this.sendCAD = new System.Windows.Forms.Button();
this.contentPanel = new System.Windows.Forms.Panel();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelGeneralInformationMessage = new System.Windows.Forms.Label();
this.pictureBoxGeneralInformationMessage = new System.Windows.Forms.PictureBox();
this.scaleCheckBox = new System.Windows.Forms.CheckBox();
this.fullscreenButton = new System.Windows.Forms.Button();
this.dockButton = new System.Windows.Forms.Button();
this.tip = new System.Windows.Forms.ToolTip(this.components);
this.LifeCycleMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.powerStateLabel = new System.Windows.Forms.Label();
this.dedicatedGpuWarning = new System.Windows.Forms.Label();
this.gradientPanel1 = new XenAdmin.Controls.GradientPanel.GradientPanel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.HostLabel = new System.Windows.Forms.Label();
this.buttonSSH = new System.Windows.Forms.Button();
this.toggleConsoleButton = new System.Windows.Forms.Button();
this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxGeneralInformationMessage)).BeginInit();
this.gradientPanel1.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// sendCAD
//
resources.ApplyResources(this.sendCAD, "sendCAD");
this.sendCAD.Name = "sendCAD";
this.sendCAD.UseVisualStyleBackColor = true;
this.sendCAD.Click += new System.EventHandler(this.sendCAD_Click);
//
// contentPanel
//
resources.ApplyResources(this.contentPanel, "contentPanel");
this.contentPanel.Name = "contentPanel";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.labelGeneralInformationMessage, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.pictureBoxGeneralInformationMessage, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.sendCAD, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.scaleCheckBox, 3, 0);
this.tableLayoutPanel1.Controls.Add(this.fullscreenButton, 5, 0);
this.tableLayoutPanel1.Controls.Add(this.dockButton, 4, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// labelGeneralInformationMessage
//
resources.ApplyResources(this.labelGeneralInformationMessage, "labelGeneralInformationMessage");
this.labelGeneralInformationMessage.AutoEllipsis = true;
this.labelGeneralInformationMessage.Name = "labelGeneralInformationMessage";
//
// pictureBoxGeneralInformationMessage
//
resources.ApplyResources(this.pictureBoxGeneralInformationMessage, "pictureBoxGeneralInformationMessage");
this.pictureBoxGeneralInformationMessage.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16;
this.pictureBoxGeneralInformationMessage.Name = "pictureBoxGeneralInformationMessage";
this.pictureBoxGeneralInformationMessage.TabStop = false;
//
// scaleCheckBox
//
resources.ApplyResources(this.scaleCheckBox, "scaleCheckBox");
this.scaleCheckBox.Name = "scaleCheckBox";
this.scaleCheckBox.UseVisualStyleBackColor = true;
this.scaleCheckBox.CheckedChanged += new System.EventHandler(this.scaleCheckBox_CheckedChanged);
//
// fullscreenButton
//
resources.ApplyResources(this.fullscreenButton, "fullscreenButton");
this.fullscreenButton.Name = "fullscreenButton";
this.fullscreenButton.UseVisualStyleBackColor = true;
this.fullscreenButton.Click += new System.EventHandler(this.fullscreenButton_Click);
//
// dockButton
//
resources.ApplyResources(this.dockButton, "dockButton");
this.dockButton.Image = global::XenAdmin.Properties.Resources.detach_24;
this.dockButton.Name = "dockButton";
this.dockButton.UseVisualStyleBackColor = true;
this.dockButton.Click += new System.EventHandler(this.dockButton_Click);
//
// tip
//
this.tip.ShowAlways = true;
//
// LifeCycleMenuStrip
//
this.LifeCycleMenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.LifeCycleMenuStrip.Name = "LifeCycleMenuStrip";
resources.ApplyResources(this.LifeCycleMenuStrip, "LifeCycleMenuStrip");
this.LifeCycleMenuStrip.Closing += new System.Windows.Forms.ToolStripDropDownClosingEventHandler(this.LifeCycleMenuStrip_Closing);
this.LifeCycleMenuStrip.Opened += new System.EventHandler(this.LifeCycleMenuStrip_Opened);
//
// powerStateLabel
//
this.powerStateLabel.AutoEllipsis = true;
this.powerStateLabel.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.powerStateLabel, "powerStateLabel");
this.powerStateLabel.ForeColor = System.Drawing.SystemColors.ControlText;
this.powerStateLabel.Name = "powerStateLabel";
this.powerStateLabel.Click += new System.EventHandler(this.powerStateLabel_Click);
//
// dedicatedGpuWarning
//
this.dedicatedGpuWarning.AutoEllipsis = true;
this.dedicatedGpuWarning.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.dedicatedGpuWarning, "dedicatedGpuWarning");
this.dedicatedGpuWarning.ForeColor = System.Drawing.SystemColors.ControlText;
this.dedicatedGpuWarning.Name = "dedicatedGpuWarning";
//
// gradientPanel1
//
this.gradientPanel1.Controls.Add(this.tableLayoutPanel2);
resources.ApplyResources(this.gradientPanel1, "gradientPanel1");
this.gradientPanel1.Name = "gradientPanel1";
this.gradientPanel1.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Tab;
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.HostLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.buttonSSH, 3, 0);
this.tableLayoutPanel2.Controls.Add(this.toggleConsoleButton, 5, 0);
this.tableLayoutPanel2.Controls.Add(this.multipleDvdIsoList1, 2, 0);
this.tableLayoutPanel2.Controls.Add(this.pictureBox1, 1, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// HostLabel
//
this.HostLabel.AutoEllipsis = true;
resources.ApplyResources(this.HostLabel, "HostLabel");
this.HostLabel.ForeColor = System.Drawing.Color.White;
this.HostLabel.Name = "HostLabel";
//
// buttonSSH
//
resources.ApplyResources(this.buttonSSH, "buttonSSH");
this.buttonSSH.Name = "buttonSSH";
this.buttonSSH.UseVisualStyleBackColor = true;
this.buttonSSH.Click += new System.EventHandler(this.buttonSSH_Click);
//
// toggleConsoleButton
//
resources.ApplyResources(this.toggleConsoleButton, "toggleConsoleButton");
this.toggleConsoleButton.Name = "toggleConsoleButton";
this.tip.SetToolTip(this.toggleConsoleButton, resources.GetString("toggleConsoleButton.ToolTip"));
this.toggleConsoleButton.UseVisualStyleBackColor = true;
this.toggleConsoleButton.Click += new System.EventHandler(this.toggleConsoleButton_Click);
//
// multipleDvdIsoList1
//
resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1");
this.multipleDvdIsoList1.LabelNewCdForeColor = System.Drawing.SystemColors.HotTrack;
this.multipleDvdIsoList1.LabelSingleDvdForeColor = System.Drawing.SystemColors.ControlText;
this.multipleDvdIsoList1.LinkLabelLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(255)))));
this.multipleDvdIsoList1.Name = "multipleDvdIsoList1";
this.multipleDvdIsoList1.VM = null;
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::XenAdmin.Properties.Resources._001_LifeCycle_h32bit_24;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.LifeCycleButton_MouseClick);
this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
this.pictureBox1.MouseEnter += new System.EventHandler(this.pictureBox1_MouseEnter);
this.pictureBox1.MouseLeave += new System.EventHandler(this.pictureBox1_MouseLeave);
this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
//
// VNCTabView
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.contentPanel);
this.Controls.Add(this.dedicatedGpuWarning);
this.Controls.Add(this.powerStateLabel);
this.Controls.Add(this.gradientPanel1);
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "VNCTabView";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxGeneralInformationMessage)).EndInit();
this.gradientPanel1.ResumeLayout(false);
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button dockButton;
private System.Windows.Forms.Button sendCAD;
private System.Windows.Forms.Panel contentPanel;
private System.Windows.Forms.CheckBox scaleCheckBox;
private System.Windows.Forms.Button fullscreenButton;
private System.Windows.Forms.ToolTip tip;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.ContextMenuStrip LifeCycleMenuStrip;
private System.Windows.Forms.PictureBox pictureBox1;
private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel1;
private System.Windows.Forms.Label HostLabel;
private System.Windows.Forms.Button toggleConsoleButton;
private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1;
private System.Windows.Forms.Label powerStateLabel;
private System.Windows.Forms.Label dedicatedGpuWarning;
private System.Windows.Forms.Button buttonSSH;
private System.Windows.Forms.PictureBox pictureBoxGeneralInformationMessage;
private System.Windows.Forms.Label labelGeneralInformationMessage;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
namespace System.Net.Http.Headers
{
public class ContentDispositionHeaderValue : ICloneable
{
#region Fields
private const string fileName = "filename";
private const string name = "name";
private const string fileNameStar = "filename*";
private const string creationDate = "creation-date";
private const string modificationDate = "modification-date";
private const string readDate = "read-date";
private const string size = "size";
// Use ICollection<T> since we may have multiple parameters with the same name.
private ICollection<NameValueHeaderValue> _parameters;
private string _dispositionType;
#endregion Fields
#region Properties
public string DispositionType
{
get { return _dispositionType; }
set
{
CheckDispositionTypeFormat(value, "value");
_dispositionType = value;
}
}
public ICollection<NameValueHeaderValue> Parameters
{
get
{
if (_parameters == null)
{
_parameters = new ObjectCollection<NameValueHeaderValue>();
}
return _parameters;
}
}
public string Name
{
get { return GetName(name); }
set { SetName(name, value); }
}
public string FileName
{
get { return GetName(fileName); }
set { SetName(fileName, value); }
}
public string FileNameStar
{
get { return GetName(fileNameStar); }
set { SetName(fileNameStar, value); }
}
public DateTimeOffset? CreationDate
{
get { return GetDate(creationDate); }
set { SetDate(creationDate, value); }
}
public DateTimeOffset? ModificationDate
{
get { return GetDate(modificationDate); }
set { SetDate(modificationDate, value); }
}
public DateTimeOffset? ReadDate
{
get { return GetDate(readDate); }
set { SetDate(readDate, value); }
}
public long? Size
{
get
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
ulong value;
if (sizeParameter != null)
{
string sizeString = sizeParameter.Value;
if (UInt64.TryParse(sizeString, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
{
return (long)value;
}
}
return null;
}
set
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
if (value == null)
{
// Remove parameter.
if (sizeParameter != null)
{
_parameters.Remove(sizeParameter);
}
}
else if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
else if (sizeParameter != null)
{
sizeParameter.Value = value.Value.ToString(CultureInfo.InvariantCulture);
}
else
{
string sizeString = value.Value.ToString(CultureInfo.InvariantCulture);
_parameters.Add(new NameValueHeaderValue(size, sizeString));
}
}
}
#endregion Properties
#region Constructors
internal ContentDispositionHeaderValue()
{
// Used by the parser to create a new instance of this type.
}
protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
{
Contract.Requires(source != null);
_dispositionType = source._dispositionType;
if (source._parameters != null)
{
foreach (var parameter in source._parameters)
{
this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone());
}
}
}
public ContentDispositionHeaderValue(string dispositionType)
{
CheckDispositionTypeFormat(dispositionType, "dispositionType");
_dispositionType = dispositionType;
}
#endregion Constructors
#region Overloads
public override string ToString()
{
return _dispositionType + NameValueHeaderValue.ToString(_parameters, ';', true);
}
public override bool Equals(object obj)
{
ContentDispositionHeaderValue other = obj as ContentDispositionHeaderValue;
if (other == null)
{
return false;
}
return string.Equals(_dispositionType, other._dispositionType, StringComparison.OrdinalIgnoreCase) &&
HeaderUtilities.AreEqualCollections(_parameters, other._parameters);
}
public override int GetHashCode()
{
// The dispositionType string is case-insensitive.
return StringComparer.OrdinalIgnoreCase.GetHashCode(_dispositionType) ^ NameValueHeaderValue.GetHashCode(_parameters);
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new ContentDispositionHeaderValue(this);
}
#endregion Overloads
#region Parsing
public static ContentDispositionHeaderValue Parse(string input)
{
int index = 0;
return (ContentDispositionHeaderValue)GenericHeaderParser.ContentDispositionParser.ParseValue(input,
null, ref index);
}
public static bool TryParse(string input, out ContentDispositionHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.ContentDispositionParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (ContentDispositionHeaderValue)output;
return true;
}
return false;
}
internal static int GetDispositionTypeLength(string input, int startIndex, out object parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespaces. If not, we'll return 0.
string dispositionType = null;
int dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out dispositionType);
if (dispositionTypeLength == 0)
{
return 0;
}
int current = startIndex + dispositionTypeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
ContentDispositionHeaderValue contentDispositionHeader = new ContentDispositionHeaderValue();
contentDispositionHeader._dispositionType = dispositionType;
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
if ((current < input.Length) && (input[current] == ';'))
{
current++; // Skip delimiter.
int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
contentDispositionHeader.Parameters);
if (parameterLength == 0)
{
return 0;
}
parsedValue = contentDispositionHeader;
return current + parameterLength - startIndex;
}
// We have a ContentDisposition header without parameters.
parsedValue = contentDispositionHeader;
return current - startIndex;
}
private static int GetDispositionTypeExpressionLength(string input, int startIndex, out string dispositionType)
{
Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length));
// This method just parses the disposition type string, it does not parse parameters.
dispositionType = null;
// Parse the disposition type, i.e. <dispositiontype> in content-disposition string
// "<dispositiontype>; param1=value1; param2=value2".
int typeLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (typeLength == 0)
{
return 0;
}
dispositionType = input.Substring(startIndex, typeLength);
return typeLength;
}
private static void CheckDispositionTypeFormat(string dispositionType, string parameterName)
{
if (string.IsNullOrEmpty(dispositionType))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
// When adding values using strongly typed objects, no leading/trailing LWS (whitespaces) are allowed.
string tempDispositionType;
int dispositionTypeLength = GetDispositionTypeExpressionLength(dispositionType, 0, out tempDispositionType);
if ((dispositionTypeLength == 0) || (tempDispositionType.Length != dispositionType.Length))
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, dispositionType));
}
}
#endregion Parsing
#region Helpers
// Gets a parameter of the given name and attempts to extract a date.
// Returns null if the parameter is not present or the format is incorrect.
private DateTimeOffset? GetDate(string parameter)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
DateTimeOffset date;
if (dateParameter != null)
{
string dateString = dateParameter.Value;
// Should have quotes, remove them.
if (IsQuoted(dateString))
{
dateString = dateString.Substring(1, dateString.Length - 2);
}
if (HttpRuleParser.TryStringToDate(dateString, out date))
{
return date;
}
}
return null;
}
// Add the given parameter to the list. Remove if date is null.
private void SetDate(string parameter, DateTimeOffset? date)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (date == null)
{
// Remove parameter.
if (dateParameter != null)
{
_parameters.Remove(dateParameter);
}
}
else
{
// Must always be quoted.
string dateString = string.Format(CultureInfo.InvariantCulture, "\"{0}\"",
HttpRuleParser.DateToString(date.Value));
if (dateParameter != null)
{
dateParameter.Value = dateString;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, dateString));
}
}
}
// Gets a parameter of the given name and attempts to decode it if nessisary.
// Returns null if the parameter is not present or the raw value if the encoding is incorrect.
private string GetName(string parameter)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (nameParameter != null)
{
string result;
// filename*=utf-8'lang'%7FMyString
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
if (TryDecode5987(nameParameter.Value, out result))
{
return result;
}
return null; // Unrecognized encoding.
}
// filename="=?utf-8?B?BDFSDFasdfasdc==?="
if (TryDecodeMime(nameParameter.Value, out result))
{
return result;
}
// May not have been encoded.
return nameParameter.Value;
}
return null;
}
// Add/update the given parameter in the list, encoding if necessary.
// Remove if value is null/Empty
private void SetName(string parameter, string value)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (string.IsNullOrEmpty(value))
{
// Remove parameter.
if (nameParameter != null)
{
_parameters.Remove(nameParameter);
}
}
else
{
string processedValue = string.Empty;
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
processedValue = Encode5987(value);
}
else
{
processedValue = EncodeAndQuoteMime(value);
}
if (nameParameter != null)
{
nameParameter.Value = processedValue;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, processedValue));
}
}
}
// Returns input for decoding failures, as the content might not be encoded.
private string EncodeAndQuoteMime(string input)
{
string result = input;
bool needsQuotes = false;
// Remove bounding quotes, they'll get re-added later.
if (IsQuoted(result))
{
result = result.Substring(1, result.Length - 2);
needsQuotes = true;
}
if (result.IndexOf("\"", 0, StringComparison.Ordinal) >= 0) // Only bounding quotes are allowed.
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, input));
}
else if (RequiresEncoding(result))
{
needsQuotes = true; // Encoded data must always be quoted, the equals signs are invalid in tokens.
result = EncodeMime(result); // =?utf-8?B?asdfasdfaesdf?=
}
else if (!needsQuotes && HttpRuleParser.GetTokenLength(result, 0) != result.Length)
{
needsQuotes = true;
}
if (needsQuotes)
{
// Re-add quotes "value".
result = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", result);
}
return result;
}
// Returns true if the value starts and ends with a quote.
private bool IsQuoted(string value)
{
Debug.Assert(value != null);
return value.Length > 1 && value.StartsWith("\"", StringComparison.Ordinal)
&& value.EndsWith("\"", StringComparison.Ordinal);
}
// tspecials are required to be in a quoted string. Only non-ascii needs to be encoded.
private bool RequiresEncoding(string input)
{
Debug.Assert(input != null);
foreach (char c in input)
{
if ((int)c > 0x7f)
{
return true;
}
}
return false;
}
// Encode using MIME encoding.
private string EncodeMime(string input)
{
byte[] buffer = Encoding.UTF8.GetBytes(input);
string encodedName = Convert.ToBase64String(buffer);
return string.Format(CultureInfo.InvariantCulture, "=?utf-8?B?{0}?=", encodedName);
}
// Attempt to decode MIME encoded strings.
private bool TryDecodeMime(string input, out string output)
{
Debug.Assert(input != null);
output = null;
string processedInput = input;
// Require quotes, min of "=?e?b??="
if (!IsQuoted(processedInput) || processedInput.Length < 10)
{
return false;
}
string[] parts = processedInput.Split('?');
// "=, encodingName, encodingType, encodedData, ="
if (parts.Length != 5 || parts[0] != "\"=" || parts[4] != "=\"" || parts[2].ToLowerInvariant() != "b")
{
// Not encoded.
// This does not support multi-line encoding.
// Only base64 encoding is supported, not quoted printable.
return false;
}
try
{
Encoding encoding = Encoding.GetEncoding(parts[1]);
byte[] bytes = Convert.FromBase64String(parts[3]);
output = encoding.GetString(bytes, 0, bytes.Length);
return true;
}
catch (ArgumentException)
{
// Unknown encoding or bad characters.
}
catch (FormatException)
{
// Bad base64 decoding.
}
return false;
}
// Encode a string using RFC 5987 encoding.
// encoding'lang'PercentEncodedSpecials
private string Encode5987(string input)
{
StringBuilder builder = new StringBuilder("utf-8\'\'");
foreach (char c in input)
{
// attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
// ; token except ( "*" / "'" / "%" )
if (c > 0x7F) // Encodes as multiple utf-8 bytes
{
byte[] bytes = Encoding.UTF8.GetBytes(c.ToString());
foreach (byte b in bytes)
{
builder.Append(UriShim.HexEscape((char)b));
}
}
else if (!HttpRuleParser.IsTokenChar(c) || c == '*' || c == '\'' || c == '%')
{
// ASCII - Only one encoded byte.
builder.Append(UriShim.HexEscape(c));
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
// Attempt to decode using RFC 5987 encoding.
// encoding'language'my%20string
private bool TryDecode5987(string input, out string output)
{
output = null;
string[] parts = input.Split('\'');
if (parts.Length != 3)
{
return false;
}
StringBuilder decoded = new StringBuilder();
try
{
Encoding encoding = Encoding.GetEncoding(parts[0]);
string dataString = parts[2];
byte[] unescapedBytes = new byte[dataString.Length];
int unescapedBytesCount = 0;
for (int index = 0; index < dataString.Length; index++)
{
if (UriShim.IsHexEncoding(dataString, index)) // %FF
{
// Unescape and cache bytes, multi-byte characters must be decoded all at once.
unescapedBytes[unescapedBytesCount++] = (byte)UriShim.HexUnescape(dataString, ref index);
index--; // HexUnescape did +=3; Offset the for loop's ++
}
else
{
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
unescapedBytesCount = 0;
}
decoded.Append(dataString[index]); // Normal safe character.
}
}
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
}
}
catch (ArgumentException)
{
return false; // Unknown encoding or bad characters.
}
output = decoded.ToString();
return true;
}
#endregion Helpers
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Network Management API includes operations for managing the virtual
/// networks for your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for
/// more information)
/// </summary>
internal partial class NetworkOperations : IServiceOperations<NetworkManagementClient>, INetworkOperations
{
/// <summary>
/// Initializes a new instance of the NetworkOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal NetworkOperations(NetworkManagementClient client)
{
this._client = client;
}
private NetworkManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient.
/// </summary>
public NetworkManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Abort Virtual Network migration api validates and aborts the given
/// virtual network for IaaS Classic to ARM migration.
/// </summary>
/// <param name='virtualNetworkName'>
/// Required. Name of the Virtual Network to be migrated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> AbortMigrationAsync(string virtualNetworkName, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
TracingAdapter.Enter(invocationId, this, "AbortMigrationAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
AzureOperationResponse response = await client.Networks.BeginAbortMigrationAsync(virtualNetworkName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Abort Virtual Network migration api validates and aborts the given
/// virtual network for IaaS Classic to ARM migration.
/// </summary>
/// <param name='virtualNetworkName'>
/// Required. Name of the Virtual Network to be migrated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> BeginAbortMigrationAsync(string virtualNetworkName, CancellationToken cancellationToken)
{
// Validate
if (virtualNetworkName == null)
{
throw new ArgumentNullException("virtualNetworkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
TracingAdapter.Enter(invocationId, this, "BeginAbortMigrationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/virtualnetwork/";
url = url + Uri.EscapeDataString(virtualNetworkName);
url = url + "/migration";
List<string> queryParameters = new List<string>();
queryParameters.Add("comp=abort");
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2017-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.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Commit Virtual Network migration api validates and commits the
/// given virtual network for IaaS Classic to ARM migration.
/// </summary>
/// <param name='virtualNetworkName'>
/// Required. Name of the Virtual Network to be migrated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> BeginCommitMigrationAsync(string virtualNetworkName, CancellationToken cancellationToken)
{
// Validate
if (virtualNetworkName == null)
{
throw new ArgumentNullException("virtualNetworkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
TracingAdapter.Enter(invocationId, this, "BeginCommitMigrationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/virtualnetwork/";
url = url + Uri.EscapeDataString(virtualNetworkName);
url = url + "/migration";
List<string> queryParameters = new List<string>();
queryParameters.Add("comp=commit");
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2017-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.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Prepare Virtual Network migration api validates and prepare the
/// given virtual network for IaaS Classic to ARM migration.
/// </summary>
/// <param name='virtualNetworkName'>
/// Required. Name of the Virtual Network to be migrated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> BeginPrepareMigrationAsync(string virtualNetworkName, CancellationToken cancellationToken)
{
// Validate
if (virtualNetworkName == null)
{
throw new ArgumentNullException("virtualNetworkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
TracingAdapter.Enter(invocationId, this, "BeginPrepareMigrationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/virtualnetwork/";
url = url + Uri.EscapeDataString(virtualNetworkName);
url = url + "/migration";
List<string> queryParameters = new List<string>();
queryParameters.Add("comp=prepare");
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2017-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.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Begin Setting Network Configuration operation asynchronously
/// configures the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> BeginSettingConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Configuration == null)
{
throw new ArgumentNullException("parameters.Configuration");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginSettingConfigurationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/media";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2017-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Configuration;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
// 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.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Commit Virtual Network migration api validates and commits the
/// given virtual network for IaaS Classic to ARM migration.
/// </summary>
/// <param name='virtualNetworkName'>
/// Required. Name of the Virtual Network to be migrated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> CommitMigrationAsync(string virtualNetworkName, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
TracingAdapter.Enter(invocationId, this, "CommitMigrationAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
AzureOperationResponse response = await client.Networks.BeginCommitMigrationAsync(virtualNetworkName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Get Network Configuration operation retrieves the network
/// configuration file for the given subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Network Configuration operation response.
/// </returns>
public async Task<NetworkGetConfigurationResponse> GetConfigurationAsync(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>();
TracingAdapter.Enter(invocationId, this, "GetConfigurationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/media";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2017-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
NetworkGetConfigurationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkGetConfigurationResponse();
result.Configuration = responseContent;
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Virtual network sites operation retrieves the virtual
/// networks configured for the subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response structure for the Network Operations List operation.
/// </returns>
public async Task<NetworkListResponse> ListAsync(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>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/virtualnetwork";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2017-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
NetworkListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement virtualNetworkSitesSequenceElement = responseDoc.Element(XName.Get("VirtualNetworkSites", "http://schemas.microsoft.com/windowsazure"));
if (virtualNetworkSitesSequenceElement != null)
{
foreach (XElement virtualNetworkSitesElement in virtualNetworkSitesSequenceElement.Elements(XName.Get("VirtualNetworkSite", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.VirtualNetworkSite virtualNetworkSiteInstance = new NetworkListResponse.VirtualNetworkSite();
result.VirtualNetworkSites.Add(virtualNetworkSiteInstance);
XElement nameElement = virtualNetworkSitesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
virtualNetworkSiteInstance.Name = nameInstance;
}
XElement labelElement = virtualNetworkSitesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = labelElement.Value;
virtualNetworkSiteInstance.Label = labelInstance;
}
XElement idElement = virtualNetworkSitesElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
virtualNetworkSiteInstance.Id = idInstance;
}
XElement affinityGroupElement = virtualNetworkSitesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure"));
if (affinityGroupElement != null)
{
string affinityGroupInstance = affinityGroupElement.Value;
virtualNetworkSiteInstance.AffinityGroup = affinityGroupInstance;
}
XElement locationElement = virtualNetworkSitesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
virtualNetworkSiteInstance.Location = locationInstance;
}
XElement stateElement = virtualNetworkSitesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
virtualNetworkSiteInstance.State = stateInstance;
}
XElement addressSpaceElement = virtualNetworkSitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure"));
if (addressSpaceElement != null)
{
NetworkListResponse.AddressSpace addressSpaceInstance = new NetworkListResponse.AddressSpace();
virtualNetworkSiteInstance.AddressSpace = addressSpaceInstance;
XElement addressPrefixesSequenceElement = addressSpaceElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixesSequenceElement != null)
{
foreach (XElement addressPrefixesElement in addressPrefixesSequenceElement.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
{
addressSpaceInstance.AddressPrefixes.Add(addressPrefixesElement.Value);
}
}
}
XElement subnetsSequenceElement = virtualNetworkSitesElement.Element(XName.Get("Subnets", "http://schemas.microsoft.com/windowsazure"));
if (subnetsSequenceElement != null)
{
foreach (XElement subnetsElement in subnetsSequenceElement.Elements(XName.Get("Subnet", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.Subnet subnetInstance = new NetworkListResponse.Subnet();
virtualNetworkSiteInstance.Subnets.Add(subnetInstance);
XElement nameElement2 = subnetsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
subnetInstance.Name = nameInstance2;
}
XElement addressPrefixElement = subnetsElement.Element(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixElement != null)
{
string addressPrefixInstance = addressPrefixElement.Value;
subnetInstance.AddressPrefix = addressPrefixInstance;
}
XElement networkSecurityGroupElement = subnetsElement.Element(XName.Get("NetworkSecurityGroup", "http://schemas.microsoft.com/windowsazure"));
if (networkSecurityGroupElement != null)
{
string networkSecurityGroupInstance = networkSecurityGroupElement.Value;
subnetInstance.NetworkSecurityGroup = networkSecurityGroupInstance;
}
}
}
XElement dnsElement = virtualNetworkSitesElement.Element(XName.Get("Dns", "http://schemas.microsoft.com/windowsazure"));
if (dnsElement != null)
{
XElement dnsServersSequenceElement = dnsElement.Element(XName.Get("DnsServers", "http://schemas.microsoft.com/windowsazure"));
if (dnsServersSequenceElement != null)
{
foreach (XElement dnsServersElement in dnsServersSequenceElement.Elements(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.DnsServer dnsServerInstance = new NetworkListResponse.DnsServer();
virtualNetworkSiteInstance.DnsServers.Add(dnsServerInstance);
XElement nameElement3 = dnsServersElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement3 != null)
{
string nameInstance3 = nameElement3.Value;
dnsServerInstance.Name = nameInstance3;
}
XElement addressElement = dnsServersElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
if (addressElement != null)
{
string addressInstance = addressElement.Value;
dnsServerInstance.Address = addressInstance;
}
}
}
}
XElement gatewayElement = virtualNetworkSitesElement.Element(XName.Get("Gateway", "http://schemas.microsoft.com/windowsazure"));
if (gatewayElement != null)
{
NetworkListResponse.Gateway gatewayInstance = new NetworkListResponse.Gateway();
virtualNetworkSiteInstance.Gateway = gatewayInstance;
XElement profileElement = gatewayElement.Element(XName.Get("Profile", "http://schemas.microsoft.com/windowsazure"));
if (profileElement != null)
{
string profileInstance = profileElement.Value;
gatewayInstance.Profile = profileInstance;
}
XElement sitesSequenceElement = gatewayElement.Element(XName.Get("Sites", "http://schemas.microsoft.com/windowsazure"));
if (sitesSequenceElement != null)
{
foreach (XElement sitesElement in sitesSequenceElement.Elements(XName.Get("LocalNetworkSite", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.LocalNetworkSite localNetworkSiteInstance = new NetworkListResponse.LocalNetworkSite();
gatewayInstance.Sites.Add(localNetworkSiteInstance);
XElement nameElement4 = sitesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement4 != null)
{
string nameInstance4 = nameElement4.Value;
localNetworkSiteInstance.Name = nameInstance4;
}
XElement vpnGatewayAddressElement = sitesElement.Element(XName.Get("VpnGatewayAddress", "http://schemas.microsoft.com/windowsazure"));
if (vpnGatewayAddressElement != null)
{
string vpnGatewayAddressInstance = vpnGatewayAddressElement.Value;
localNetworkSiteInstance.VpnGatewayAddress = vpnGatewayAddressInstance;
}
XElement addressSpaceElement2 = sitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure"));
if (addressSpaceElement2 != null)
{
NetworkListResponse.AddressSpace addressSpaceInstance2 = new NetworkListResponse.AddressSpace();
localNetworkSiteInstance.AddressSpace = addressSpaceInstance2;
XElement addressPrefixesSequenceElement2 = addressSpaceElement2.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixesSequenceElement2 != null)
{
foreach (XElement addressPrefixesElement2 in addressPrefixesSequenceElement2.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
{
addressSpaceInstance2.AddressPrefixes.Add(addressPrefixesElement2.Value);
}
}
}
XElement connectionsSequenceElement = sitesElement.Element(XName.Get("Connections", "http://schemas.microsoft.com/windowsazure"));
if (connectionsSequenceElement != null)
{
foreach (XElement connectionsElement in connectionsSequenceElement.Elements(XName.Get("Connection", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.Connection connectionInstance = new NetworkListResponse.Connection();
localNetworkSiteInstance.Connections.Add(connectionInstance);
XElement typeElement = connectionsElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
connectionInstance.Type = typeInstance;
}
}
}
}
}
XElement vPNClientAddressPoolElement = gatewayElement.Element(XName.Get("VPNClientAddressPool", "http://schemas.microsoft.com/windowsazure"));
if (vPNClientAddressPoolElement != null)
{
NetworkListResponse.VPNClientAddressPool vPNClientAddressPoolInstance = new NetworkListResponse.VPNClientAddressPool();
gatewayInstance.VPNClientAddressPool = vPNClientAddressPoolInstance;
XElement addressPrefixesSequenceElement3 = vPNClientAddressPoolElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixesSequenceElement3 != null)
{
foreach (XElement addressPrefixesElement3 in addressPrefixesSequenceElement3.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
{
vPNClientAddressPoolInstance.AddressPrefixes.Add(addressPrefixesElement3.Value);
}
}
}
}
XElement migrationStateElement = virtualNetworkSitesElement.Element(XName.Get("MigrationState", "http://schemas.microsoft.com/windowsazure"));
if (migrationStateElement != null)
{
string migrationStateInstance = migrationStateElement.Value;
virtualNetworkSiteInstance.MigrationState = migrationStateInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Prepare Virtual Network migration api validates and prepare the
/// given virtual network for IaaS Classic to ARM migration.
/// </summary>
/// <param name='virtualNetworkName'>
/// Required. Name of the Virtual Network to be migrated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> PrepareMigrationAsync(string virtualNetworkName, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
TracingAdapter.Enter(invocationId, this, "PrepareMigrationAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
AzureOperationResponse response = await client.Networks.BeginPrepareMigrationAsync(virtualNetworkName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Set Network Configuration operation asynchronously configures
/// the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> SetConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "SetConfigurationAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
AzureOperationResponse response = await client.Networks.BeginSettingConfigurationAsync(parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Prepare Virtual Network migration api validates the given virtual
/// network for IaaS Classic to ARM migration.
/// </summary>
/// <param name='virtualNetworkName'>
/// Required. Name of the Virtual Network to be migrated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Validate Network Migration operation response.
/// </returns>
public async Task<NetworkMigrationValidationResponse> ValidateMigrationAsync(string virtualNetworkName, CancellationToken cancellationToken)
{
// Validate
if (virtualNetworkName == null)
{
throw new ArgumentNullException("virtualNetworkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
TracingAdapter.Enter(invocationId, this, "ValidateMigrationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/virtualnetwork/";
url = url + Uri.EscapeDataString(virtualNetworkName);
url = url + "/migration";
List<string> queryParameters = new List<string>();
queryParameters.Add("comp=validate");
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2017-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
NetworkMigrationValidationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkMigrationValidationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement validationMessagesSequenceElement = responseDoc.Element(XName.Get("ValidationMessages", "http://schemas.microsoft.com/windowsazure"));
if (validationMessagesSequenceElement != null)
{
foreach (XElement validationMessagesElement in validationMessagesSequenceElement.Elements(XName.Get("ValidationMessage", "http://schemas.microsoft.com/windowsazure")))
{
NetworkMigrationValidationMessage validationMessageInstance = new NetworkMigrationValidationMessage();
result.ValidationMessages.Add(validationMessageInstance);
XElement resourceTypeElement = validationMessagesElement.Element(XName.Get("ResourceType", "http://schemas.microsoft.com/windowsazure"));
if (resourceTypeElement != null)
{
string resourceTypeInstance = resourceTypeElement.Value;
validationMessageInstance.ResourceType = resourceTypeInstance;
}
XElement resourceNameElement = validationMessagesElement.Element(XName.Get("ResourceName", "http://schemas.microsoft.com/windowsazure"));
if (resourceNameElement != null)
{
string resourceNameInstance = resourceNameElement.Value;
validationMessageInstance.ResourceName = resourceNameInstance;
}
XElement categoryElement = validationMessagesElement.Element(XName.Get("Category", "http://schemas.microsoft.com/windowsazure"));
if (categoryElement != null)
{
string categoryInstance = categoryElement.Value;
validationMessageInstance.Category = categoryInstance;
}
XElement messageElement = validationMessagesElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
validationMessageInstance.Message = messageInstance;
}
XElement virtualMachineElement = validationMessagesElement.Element(XName.Get("VirtualMachine", "http://schemas.microsoft.com/windowsazure"));
if (virtualMachineElement != null)
{
string virtualMachineInstance = virtualMachineElement.Value;
validationMessageInstance.VirtualMachineName = virtualMachineInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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 ASC.Mail.Net.SIP.Stack
{
#region usings
using System;
using Message;
#endregion
/// <summary>
/// This class is base class for SIP dialogs. Defined in RFC 3261 12.
/// </summary>
public class SIP_Dialog
{
#region Events
/// <summary>
/// This event is raised when Dialog state has changed.
/// </summary>
public event EventHandler StateChanged = null;
/// <summary>
/// This event is raised when remote-party terminates dialog with BYE request.
/// </summary>
/// <remarks>This event is useful only if the application is interested in processing the headers in the BYE message.</remarks>
public event EventHandler<SIP_RequestReceivedEventArgs> TerminatedByRemoteParty = null;
#endregion
#region Members
private readonly DateTime m_CreateTime;
private string m_CallID = "";
private bool m_IsSecure;
private bool m_IsTerminatedByRemoteParty;
private int m_LocalSeqNo;
private string m_LocalTag = "";
private SIP_Flow m_pFlow;
private SIP_Uri m_pLocalContact;
private AbsoluteUri m_pLocalUri;
private object m_pLock = new object();
private SIP_Uri m_pRemoteTarget;
private AbsoluteUri m_pRemoteUri;
private SIP_t_AddressParam[] m_pRouteSet;
private SIP_Stack m_pStack;
private int m_RemoteSeqNo;
private string m_RemoteTag = "";
private SIP_DialogState m_State = SIP_DialogState.Early;
#endregion
#region Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the dialog.
/// </summary>
public object SyncRoot
{
get { return m_pLock; }
}
/// <summary>
/// Gets dialog state.
/// </summary>
public SIP_DialogState State
{
get { return m_State; }
}
/// <summary>
/// Gets owner stack.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Stack Stack
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pStack;
}
}
/// <summary>
/// Gets dialog creation time.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public DateTime CreateTime
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_CreateTime;
}
}
/// <summary>
/// Gets dialog ID.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public string ID
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return CallID + "-" + LocalTag + "-" + RemoteTag;
}
}
/// <summary>
/// Get call ID.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public string CallID
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_CallID;
}
}
/// <summary>
/// Gets local-tag.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public string LocalTag
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_LocalTag;
}
}
/// <summary>
/// Gets remote-tag.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public string RemoteTag
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_RemoteTag;
}
}
/// <summary>
/// Gets local sequence number.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public int LocalSeqNo
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_LocalSeqNo;
}
}
/// <summary>
/// Gets remote sequence number.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public int RemoteSeqNo
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_RemoteSeqNo;
}
}
/// <summary>
/// Gets local URI.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public AbsoluteUri LocalUri
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pLocalUri;
}
}
/// <summary>
/// Gets remote URI.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public AbsoluteUri RemoteUri
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pRemoteUri;
}
}
/// <summary>
/// Gets local contact URI.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Uri LocalContact
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pLocalContact;
}
}
/// <summary>
/// Gets remote target URI.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Uri RemoteTarget
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pRemoteTarget;
}
}
/// <summary>
/// Gets if dialog uses secure transport.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public bool IsSecure
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_IsSecure;
}
}
/// <summary>
/// Gets route set.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_t_AddressParam[] RouteSet
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pRouteSet;
}
}
/// <summary>
/// Gets if dialog was terminated by remote-party.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public bool IsTerminatedByRemoteParty
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_IsTerminatedByRemoteParty;
}
}
/// <summary>
/// Gets data flow used to send or receive last SIP message.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Flow Flow
{
get
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pFlow;
}
}
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
public SIP_Dialog()
{
m_CreateTime = DateTime.Now;
m_pRouteSet = new SIP_t_AddressParam[0];
}
#endregion
#region Methods
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public virtual void Dispose()
{
lock (m_pLock)
{
if (State == SIP_DialogState.Disposed)
{
return;
}
SetState(SIP_DialogState.Disposed, true);
m_pStack = null;
m_CallID = null;
m_LocalTag = null;
m_RemoteTag = null;
m_pLocalUri = null;
m_pRemoteUri = null;
m_pLocalContact = null;
m_pRemoteTarget = null;
m_pRouteSet = null;
m_pFlow = null;
m_pLock = null;
}
}
/// <summary>
/// Terminates dialog.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
public void Terminate()
{
Terminate(null, true);
}
/// <summary>
/// Terminates dialog.
/// </summary>
/// <param name="reason">Termination reason. This value may be null.</param>
/// <param name="sendBye">If true BYE is sent to remote party.</param>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
public virtual void Terminate(string reason, bool sendBye)
{
lock (m_pLock)
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (State == SIP_DialogState.Terminating || State == SIP_DialogState.Terminated)
{
return;
}
/* RFC 3261 15.
The caller's UA MAY send a BYE for either confirmed or early dialogs, and the callee's UA MAY send a BYE on
confirmed dialogs, but MUST NOT send a BYE on early dialogs.
RFC 3261 15.1.
Once the BYE is constructed, the UAC core creates a new non-INVITE client transaction, and passes it the BYE request.
The UAC MUST consider the session terminated (and therefore stop sending or listening for media) as soon as the BYE
request is passed to the client transaction. If the response for the BYE is a 481 (Call/Transaction Does Not Exist)
or a 408 (Request Timeout) or no response at all is received for the BYE (that is, a timeout is returned by the
client transaction), the UAC MUST consider the session and the dialog terminated.
*/
SetState(SIP_DialogState.Terminating, true);
if (sendBye)
{
// TODO: UAS early
if (State == SIP_DialogState.Confirmed)
{
SIP_Request bye = CreateRequest(SIP_Methods.BYE);
if (!string.IsNullOrEmpty(reason))
{
SIP_t_ReasonValue r = new SIP_t_ReasonValue();
r.Protocol = "SIP";
r.Text = reason;
bye.Reason.Add(r.ToStringValue());
}
// Send BYE, just wait BYE to complete, we don't care about response code.
SIP_RequestSender sender = CreateRequestSender(bye);
sender.Completed += delegate { SetState(SIP_DialogState.Terminated, true); };
sender.Start();
}
}
else
{
SetState(SIP_DialogState.Terminated, true);
}
}
}
/// <summary>
/// Creates new SIP request using this dialog info.
/// </summary>
/// <param name="method">SIP method.</param>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>method</b> is null reference.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
/// <returns>Returns created request.</returns>
public SIP_Request CreateRequest(string method)
{
if (State == SIP_DialogState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (method == null)
{
throw new ArgumentNullException("method");
}
if (method == string.Empty)
{
throw new ArgumentException("Argument 'method' value must be specified.");
}
/* RFC 3261 12.2.1.1.
A request within a dialog is constructed by using many of the
components of the state stored as part of the dialog.
The URI in the To field of the request MUST be set to the remote URI
from the dialog state. The tag in the To header field of the request
MUST be set to the remote tag of the dialog ID. The From URI of the
request MUST be set to the local URI from the dialog state. The tag
in the From header field of the request MUST be set to the local tag
of the dialog ID. If the value of the remote or local tags is null,
the tag parameter MUST be omitted from the To or From header fields,
respectively.
The Call-ID of the request MUST be set to the Call-ID of the dialog.
Requests within a dialog MUST contain strictly monotonically
increasing and contiguous CSeq sequence numbers (increasing-by-one)
in each direction (excepting ACK and CANCEL of course, whose numbers
equal the requests being acknowledged or cancelled). Therefore, if
the local sequence number is not empty, the value of the local
sequence number MUST be incremented by one, and this value MUST be
placed into the CSeq header field. If the local sequence number is
empty, an initial value MUST be chosen using the guidelines of
Section 8.1.1.5. The method field in the CSeq header field value
MUST match the method of the request.
With a length of 32 bits, a client could generate, within a single
call, one request a second for about 136 years before needing to
wrap around. The initial value of the sequence number is chosen
so that subsequent requests within the same call will not wrap
around. A non-zero initial value allows clients to use a time-
based initial sequence number. A client could, for example,
choose the 31 most significant bits of a 32-bit second clock as an
initial sequence number.
The UAC uses the remote target and route set to build the Request-URI
and Route header field of the request.
If the route set is empty, the UAC MUST place the remote target URI
into the Request-URI. The UAC MUST NOT add a Route header field to
the request.
If the route set is not empty, and the first URI in the route set
contains the lr parameter (see Section 19.1.1), the UAC MUST place
the remote target URI into the Request-URI and MUST include a Route
header field containing the route set values in order, including all
parameters.
If the route set is not empty, and its first URI does not contain the
lr parameter, the UAC MUST place the first URI from the route set
into the Request-URI, stripping any parameters that are not allowed
in a Request-URI. The UAC MUST add a Route header field containing
the remainder of the route set values in order, including all
parameters. The UAC MUST then place the remote target URI into the
Route header field as the last value.
For example, if the remote target is sip:user@remoteua and the route
set contains:
<sip:proxy1>,<sip:proxy2>,<sip:proxy3;lr>,<sip:proxy4>
The request will be formed with the following Request-URI and Route
header field:
METHOD sip:proxy1
Route: <sip:proxy2>,<sip:proxy3;lr>,<sip:proxy4>,<sip:user@remoteua>
If the first URI of the route set does not contain the lr
parameter, the proxy indicated does not understand the routing
mechanisms described in this document and will act as specified in
RFC 2543, replacing the Request-URI with the first Route header
field value it receives while forwarding the message. Placing the
Request-URI at the end of the Route header field preserves the
information in that Request-URI across the strict router (it will
be returned to the Request-URI when the request reaches a loose-
router).
A UAC SHOULD include a Contact header field in any target refresh
requests within a dialog, and unless there is a need to change it,
the URI SHOULD be the same as used in previous requests within the
dialog. If the "secure" flag is true, that URI MUST be a SIPS URI.
As discussed in Section 12.2.2, a Contact header field in a target
refresh request updates the remote target URI. This allows a UA to
provide a new contact address, should its address change during the
duration of the dialog.
However, requests that are not target refresh requests do not affect
the remote target URI for the dialog.
The rest of the request is formed as described in Section 8.1.1.
*/
lock (m_pLock)
{
SIP_Request request = m_pStack.CreateRequest(method,
new SIP_t_NameAddress("", m_pRemoteUri),
new SIP_t_NameAddress("", m_pLocalUri));
if (m_pRouteSet.Length == 0)
{
request.RequestLine.Uri = m_pRemoteTarget;
}
else
{
SIP_Uri topmostRoute = ((SIP_Uri) m_pRouteSet[0].Address.Uri);
if (topmostRoute.Param_Lr)
{
request.RequestLine.Uri = m_pRemoteTarget;
for (int i = 0; i < m_pRouteSet.Length; i++)
{
request.Route.Add(m_pRouteSet[i].ToStringValue());
}
}
else
{
request.RequestLine.Uri = SIP_Utils.UriToRequestUri(topmostRoute);
for (int i = 1; i < m_pRouteSet.Length; i++)
{
request.Route.Add(m_pRouteSet[i].ToStringValue());
}
}
}
request.To.Tag = m_RemoteTag;
request.From.Tag = m_LocalTag;
request.CallID = m_CallID;
request.CSeq.SequenceNumber = ++m_LocalSeqNo;
request.Contact.Add(m_pLocalContact.ToString());
return request;
}
}
/// <summary>
/// Creates SIP request sender for the specified request.
/// </summary>
/// <remarks>All requests sent through this dialog SHOULD use this request sender to send out requests.</remarks>
/// <param name="request">SIP request.</param>
/// <returns>Returns created sender.</returns>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null.</exception>
public SIP_RequestSender CreateRequestSender(SIP_Request request)
{
lock (m_pLock)
{
if (State == SIP_DialogState.Terminated)
{
throw new ObjectDisposedException(GetType().Name);
}
if (request == null)
{
throw new ArgumentNullException("request");
}
SIP_RequestSender sender = m_pStack.CreateRequestSender(request, Flow);
return sender;
}
}
#endregion
#region Virtual methods
/// <summary>
/// Initializes dialog.
/// </summary>
/// <param name="stack">Owner stack.</param>
/// <param name="transaction">Owner transaction.</param>
/// <param name="response">SIP response what caused dialog creation.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>transaction</b> or <b>response</b>.</exception>
protected internal virtual void Init(SIP_Stack stack,
SIP_Transaction transaction,
SIP_Response response)
{
if (stack == null)
{
throw new ArgumentNullException("stack");
}
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if (response == null)
{
throw new ArgumentNullException("response");
}
m_pStack = stack;
#region UAS
/* RFC 3261 12.1.1.
The UAS then constructs the state of the dialog. This state MUST be
maintained for the duration of the dialog.
If the request arrived over TLS, and the Request-URI contained a SIPS
URI, the "secure" flag is set to TRUE.
The route set MUST be set to the list of URIs in the Record-Route
header field from the request, taken in order and preserving all URI
parameters. If no Record-Route header field is present in the
request, the route set MUST be set to the empty set. This route set,
even if empty, overrides any pre-existing route set for future
requests in this dialog. The remote target MUST be set to the URI
from the Contact header field of the request.
The remote sequence number MUST be set to the value of the sequence
number in the CSeq header field of the request. The local sequence
number MUST be empty. The call identifier component of the dialog ID
MUST be set to the value of the Call-ID in the request. The local
tag component of the dialog ID MUST be set to the tag in the To field
in the response to the request (which always includes a tag), and the
remote tag component of the dialog ID MUST be set to the tag from the
From field in the request. A UAS MUST be prepared to receive a
request without a tag in the From field, in which case the tag is
considered to have a value of null.
This is to maintain backwards compatibility with RFC 2543, which
did not mandate From tags.
The remote URI MUST be set to the URI in the From field, and the
local URI MUST be set to the URI in the To field.
*/
if (transaction is SIP_ServerTransaction)
{
// TODO: Validate request or client transaction must do it ?
m_IsSecure = ((SIP_Uri) transaction.Request.RequestLine.Uri).IsSecure;
m_pRouteSet =
(SIP_t_AddressParam[]) Core.ReverseArray(transaction.Request.RecordRoute.GetAllValues());
m_pRemoteTarget = (SIP_Uri) transaction.Request.Contact.GetTopMostValue().Address.Uri;
m_RemoteSeqNo = transaction.Request.CSeq.SequenceNumber;
m_LocalSeqNo = 0;
m_CallID = transaction.Request.CallID;
m_LocalTag = response.To.Tag;
m_RemoteTag = transaction.Request.From.Tag;
m_pRemoteUri = transaction.Request.From.Address.Uri;
m_pLocalUri = transaction.Request.To.Address.Uri;
m_pLocalContact = (SIP_Uri) response.Contact.GetTopMostValue().Address.Uri;
}
#endregion
#region UAC
/* RFC 3261 12.1.2.
When a UAC receives a response that establishes a dialog, it
constructs the state of the dialog. This state MUST be maintained
for the duration of the dialog.
If the request was sent over TLS, and the Request-URI contained a
SIPS URI, the "secure" flag is set to TRUE.
The route set MUST be set to the list of URIs in the Record-Route
header field from the response, taken in reverse order and preserving
all URI parameters. If no Record-Route header field is present in
the response, the route set MUST be set to the empty set. This route
set, even if empty, overrides any pre-existing route set for future
requests in this dialog. The remote target MUST be set to the URI
from the Contact header field of the response.
The local sequence number MUST be set to the value of the sequence
number in the CSeq header field of the request. The remote sequence
number MUST be empty (it is established when the remote UA sends a
request within the dialog). The call identifier component of the
dialog ID MUST be set to the value of the Call-ID in the request.
The local tag component of the dialog ID MUST be set to the tag in
the From field in the request, and the remote tag component of the
dialog ID MUST be set to the tag in the To field of the response. A
UAC MUST be prepared to receive a response without a tag in the To
field, in which case the tag is considered to have a value of null.
This is to maintain backwards compatibility with RFC 2543, which
did not mandate To tags.
The remote URI MUST be set to the URI in the To field, and the local
URI MUST be set to the URI in the From field.
*/
else
{
// TODO: Validate request or client transaction must do it ?
m_IsSecure = ((SIP_Uri) transaction.Request.RequestLine.Uri).IsSecure;
m_pRouteSet = (SIP_t_AddressParam[]) Core.ReverseArray(response.RecordRoute.GetAllValues());
m_pRemoteTarget = (SIP_Uri) response.Contact.GetTopMostValue().Address.Uri;
m_LocalSeqNo = transaction.Request.CSeq.SequenceNumber;
m_RemoteSeqNo = 0;
m_CallID = transaction.Request.CallID;
m_LocalTag = transaction.Request.From.Tag;
m_RemoteTag = response.To.Tag;
m_pRemoteUri = transaction.Request.To.Address.Uri;
m_pLocalUri = transaction.Request.From.Address.Uri;
m_pLocalContact = (SIP_Uri) transaction.Request.Contact.GetTopMostValue().Address.Uri;
}
#endregion
m_pFlow = transaction.Flow;
}
/// <summary>
/// Processes specified request through this dialog.
/// </summary>
/// <param name="e">Method arguments.</param>
/// <returns>Returns true if this dialog processed specified response, otherwise false.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>e</b> is null reference.</exception>
protected internal virtual bool ProcessRequest(SIP_RequestReceivedEventArgs e)
{
if (e == null)
{
throw new ArgumentNullException("e");
}
if (e.Request.RequestLine.Method == SIP_Methods.BYE)
{
e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, e.Request));
m_IsTerminatedByRemoteParty = true;
OnTerminatedByRemoteParty(e);
SetState(SIP_DialogState.Terminated, true);
return true;
}
return false;
}
/// <summary>
/// Processes specified response through this dialog.
/// </summary>
/// <param name="response">SIP response to process.</param>
/// <returns>Returns true if this dialog processed specified response, otherwise false.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null.</exception>
protected internal virtual bool ProcessResponse(SIP_Response response)
{
if (response == null)
{
throw new ArgumentNullException("response");
}
return false;
}
#endregion
#region Utility methods
/// <summary>
/// Raises <b>StateChanged</b> event.
/// </summary>
private void OnStateChanged()
{
if (StateChanged != null)
{
StateChanged(this, new EventArgs());
}
}
/// <summary>
/// Raises <b>TerminatedByRemoteParty</b> event.
/// </summary>
/// <param name="bye">BYE request.</param>
private void OnTerminatedByRemoteParty(SIP_RequestReceivedEventArgs bye)
{
if (TerminatedByRemoteParty != null)
{
TerminatedByRemoteParty(this, bye);
}
}
#endregion
/// <summary>
/// Gets if sepcified request method is target-refresh method.
/// </summary>
/// <param name="method">SIP request method.</param>
/// <returns>Returns true if specified method is target-refresh method.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>method</b> is null reference.</exception>
protected bool IsTargetRefresh(string method)
{
if (method == null)
{
throw new ArgumentNullException("method");
}
method = method.ToUpper();
// RFC 5057 5.4. Target Refresh Requests.
if (method == SIP_Methods.INVITE)
{
return true;
}
else if (method == SIP_Methods.UPDATE)
{
return true;
}
else if (method == SIP_Methods.SUBSCRIBE)
{
return true;
}
else if (method == SIP_Methods.NOTIFY)
{
return true;
}
else if (method == SIP_Methods.REFER)
{
return true;
}
return false;
}
/// <summary>
/// Sets dialog state.
/// </summary>
/// <param name="state">New dialog state,</param>
/// <param name="raiseEvent">If true, StateChanged event is raised after state change.</param>
protected void SetState(SIP_DialogState state, bool raiseEvent)
{
m_State = state;
if (raiseEvent)
{
OnStateChanged();
}
if (m_State == SIP_DialogState.Terminated)
{
Dispose();
}
}
}
}
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <kintaro@think-in-co.de>
*/
namespace Pictor
{
public interface ISpanInterpolator
{
void Begin(double x, double y, uint len);
void Coordinates(out int x, out int y);
void Next();
Transform.ITransform Transformer
{
get;
set;
}
void ReSynchronize(double xe, double ye, uint len);
void LocalScale(out int x, out int y);
};
//================================================LinearSpanInterpolator
public sealed class LinearSpanInterpolator : ISpanInterpolator
{
private Transform.ITransform m_trans;
private Dda2LineInterpolator m_li_x;
private Dda2LineInterpolator m_li_y;
public enum ESubpixelScale
{
SubpixelShift = 8,
subpixel_shift = SubpixelShift,
Scale = 1 << subpixel_shift
};
//--------------------------------------------------------------------
public LinearSpanInterpolator()
{
}
public LinearSpanInterpolator(Transform.ITransform trans)
{
m_trans = trans;
}
public LinearSpanInterpolator(Transform.ITransform trans, double x, double y, uint len)
{
m_trans = trans;
Begin(x, y, len);
}
//----------------------------------------------------------------
public Transform.ITransform Transformer
{
get
{
return m_trans;
}
set
{
m_trans = value;
}
}
public void LocalScale(out int x, out int y)
{
throw new System.NotImplementedException();
}
//----------------------------------------------------------------
public void Begin(double x, double y, uint len)
{
double tx;
double ty;
tx = x;
ty = y;
m_trans.Transform(ref tx, ref ty);
int x1 = Basics.Round(tx * (double)ESubpixelScale.Scale);
int y1 = Basics.Round(ty * (double)ESubpixelScale.Scale);
tx = x + len;
ty = y;
m_trans.Transform(ref tx, ref ty);
int x2 = Basics.Round(tx * (double)ESubpixelScale.Scale);
int y2 = Basics.Round(ty * (double)ESubpixelScale.Scale);
m_li_x = new Dda2LineInterpolator(x1, x2, (int)len);
m_li_y = new Dda2LineInterpolator(y1, y2, (int)len);
}
//----------------------------------------------------------------
public void ReSynchronize(double xe, double ye, uint len)
{
m_trans.Transform(ref xe, ref ye);
m_li_x = new Dda2LineInterpolator(m_li_x.y(), Basics.Round(xe * (double)ESubpixelScale.Scale), (int)len);
m_li_y = new Dda2LineInterpolator(m_li_y.y(), Basics.Round(ye * (double)ESubpixelScale.Scale), (int)len);
}
//----------------------------------------------------------------
//public void operator++()
public void Next()
{
m_li_x.Next();
m_li_y.Next();
}
//----------------------------------------------------------------
public void Coordinates(out int x, out int y)
{
x = m_li_x.y();
y = m_li_y.y();
}
};
/*
//=====================================span_interpolator_linear_subdiv
template<class Transformer = ITransformer, uint SubpixelShift = 8>
class span_interpolator_linear_subdiv
{
public:
typedef Transformer trans_type;
enum ESubpixelScale
{
subpixel_shift = SubpixelShift,
Scale = 1 << subpixel_shift
};
//----------------------------------------------------------------
span_interpolator_linear_subdiv() :
m_subdiv_shift(4),
m_subdiv_size(1 << m_subdiv_shift),
m_subdiv_mask(m_subdiv_size - 1) {}
span_interpolator_linear_subdiv(const trans_type& trans,
uint SubdivisionShift = 4) :
m_subdiv_shift(SubdivisionShift),
m_subdiv_size(1 << m_subdiv_shift),
m_subdiv_mask(m_subdiv_size - 1),
m_trans(&trans) {}
span_interpolator_linear_subdiv(const trans_type& trans,
double x, double y, uint len,
uint SubdivisionShift = 4) :
m_subdiv_shift(SubdivisionShift),
m_subdiv_size(1 << m_subdiv_shift),
m_subdiv_mask(m_subdiv_size - 1),
m_trans(&trans)
{
Begin(x, y, len);
}
//----------------------------------------------------------------
const trans_type& Transformer() const { return *m_trans; }
void Transformer(const trans_type& trans) { m_trans = &trans; }
//----------------------------------------------------------------
uint SubdivisionShift() const { return m_subdiv_shift; }
void SubdivisionShift(uint shift)
{
m_subdiv_shift = shift;
m_subdiv_size = 1 << m_subdiv_shift;
m_subdiv_mask = m_subdiv_size - 1;
}
//----------------------------------------------------------------
void Begin(double x, double y, uint len)
{
double tx;
double ty;
m_pos = 1;
m_src_x = Round(x * Scale) + Scale;
m_src_y = y;
m_len = len;
if(len > m_subdiv_size) len = m_subdiv_size;
tx = x;
ty = y;
m_trans->Transform(&tx, &ty);
int x1 = Round(tx * Scale);
int y1 = Round(ty * Scale);
tx = x + len;
ty = y;
m_trans->Transform(&tx, &ty);
m_li_x = Dda2LineInterpolator(x1, Round(tx * Scale), len);
m_li_y = Dda2LineInterpolator(y1, Round(ty * Scale), len);
}
//----------------------------------------------------------------
void operator++()
{
++m_li_x;
++m_li_y;
if(m_pos >= m_subdiv_size)
{
uint len = m_len;
if(len > m_subdiv_size) len = m_subdiv_size;
double tx = double(m_src_x) / double(Scale) + len;
double ty = m_src_y;
m_trans->Transform(&tx, &ty);
m_li_x = Dda2LineInterpolator(m_li_x.y(), Round(tx * Scale), len);
m_li_y = Dda2LineInterpolator(m_li_y.y(), Round(ty * Scale), len);
m_pos = 0;
}
m_src_x += Scale;
++m_pos;
--m_len;
}
//----------------------------------------------------------------
void Coordinates(int* x, int* y) const
{
*x = m_li_x.y();
*y = m_li_y.y();
}
private:
uint m_subdiv_shift;
uint m_subdiv_size;
uint m_subdiv_mask;
const trans_type* m_trans;
Dda2LineInterpolator m_li_x;
Dda2LineInterpolator m_li_y;
int m_src_x;
double m_src_y;
uint m_pos;
uint m_len;
};
*/
}
| |
/*
* 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.Cache.Query.Continuous
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Resource;
using CQU = ContinuousQueryUtils;
/// <summary>
/// Continuous query handle interface.
/// </summary>
internal interface IContinuousQueryHandleImpl : IDisposable
{
/// <summary>
/// Process callback.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Result.</returns>
void Apply(IBinaryStream stream);
}
/// <summary>
/// Continuous query handle.
/// </summary>
internal class ContinuousQueryHandleImpl<TK, TV> : IContinuousQueryHandleImpl, IContinuousQueryFilter,
IContinuousQueryHandle<ICacheEntry<TK, TV>>
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Keep binary flag. */
private readonly bool _keepBinary;
/** Real listener. */
private readonly ICacheEntryEventListener<TK, TV> _lsnr;
/** Real filter. */
private readonly ICacheEntryEventFilter<TK, TV> _filter;
/** GC handle. */
private readonly long _hnd;
/** Native query. */
private readonly IPlatformTargetInternal _nativeQry;
/** Initial query cursor. */
private volatile IQueryCursor<ICacheEntry<TK, TV>> _initialQueryCursor;
/** Disposed flag. */
private bool _disposed;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="qry">Query.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="keepBinary">Keep binary flag.</param>
/// <param name="createTargetCb">The initialization callback.</param>
/// <param name="initialQry">The initial query.</param>
public ContinuousQueryHandleImpl(ContinuousQuery<TK, TV> qry, Marshaller marsh, bool keepBinary,
Func<Action<BinaryWriter>, IPlatformTargetInternal> createTargetCb, QueryBase initialQry)
{
_marsh = marsh;
_keepBinary = keepBinary;
_lsnr = qry.Listener;
_filter = qry.Filter;
// 1. Inject resources.
ResourceProcessor.Inject(_lsnr, _marsh.Ignite);
ResourceProcessor.Inject(_filter, _marsh.Ignite);
try
{
// 2. Allocate handle.
_hnd = _marsh.Ignite.HandleRegistry.Allocate(this);
// 3. Call Java.
_nativeQry = createTargetCb(writer =>
{
writer.WriteLong(_hnd);
writer.WriteBoolean(qry.Local);
writer.WriteBoolean(_filter != null);
var javaFilter = _filter as PlatformJavaObjectFactoryProxy;
if (javaFilter != null)
{
writer.WriteObject(javaFilter.GetRawProxy());
}
else
{
var filterHolder = _filter == null || qry.Local
? null
: new ContinuousQueryFilterHolder(_filter, _keepBinary);
writer.WriteObject(filterHolder);
}
writer.WriteInt(qry.BufferSize);
writer.WriteLong((long)qry.TimeInterval.TotalMilliseconds);
writer.WriteBoolean(qry.AutoUnsubscribe);
if (initialQry != null)
{
writer.WriteInt((int)initialQry.OpId);
initialQry.Write(writer, _keepBinary);
}
else
writer.WriteInt(-1); // no initial query
});
// 4. Initial query.
var nativeInitialQryCur = _nativeQry.OutObjectInternal(0);
_initialQueryCursor = nativeInitialQryCur == null
? null
: new QueryCursor<TK, TV>(nativeInitialQryCur, _keepBinary);
}
catch (Exception)
{
if (_hnd > 0)
_marsh.Ignite.HandleRegistry.Release(_hnd);
if (_nativeQry != null)
_nativeQry.Dispose();
if (_initialQueryCursor != null)
_initialQueryCursor.Dispose();
throw;
}
}
/** <inheritdoc /> */
public void Apply(IBinaryStream stream)
{
ICacheEntryEvent<TK, TV>[] evts = CQU.ReadEvents<TK, TV>(stream, _marsh, _keepBinary);
_lsnr.OnEvent(evts);
}
/** <inheritdoc /> */
public bool Evaluate(IBinaryStream stream)
{
Debug.Assert(_filter != null, "Evaluate should not be called if filter is not set.");
ICacheEntryEvent<TK, TV> evt = CQU.ReadEvent<TK, TV>(stream, _marsh, _keepBinary);
return _filter.Evaluate(evt);
}
/** <inheritdoc /> */
public void Inject(Ignite grid)
{
throw new NotSupportedException("Should not be called.");
}
/** <inheritdoc /> */
public long Allocate()
{
throw new NotSupportedException("Should not be called.");
}
/** <inheritdoc /> */
public void Release()
{
_marsh.Ignite.HandleRegistry.Release(_hnd);
}
/** <inheritdoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> GetInitialQueryCursor()
{
lock (this)
{
if (_disposed)
throw new ObjectDisposedException("Continuous query handle has been disposed.");
var cur = _initialQueryCursor;
if (cur == null)
throw new InvalidOperationException("GetInitialQueryCursor() can be called only once.");
_initialQueryCursor = null;
return cur;
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "There is no finalizer.")]
public void Dispose()
{
lock (this)
{
if (_disposed || _nativeQry == null)
return;
try
{
_nativeQry.InLongOutLong(0, 0);
}
finally
{
_nativeQry.Dispose();
_disposed = true;
}
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: MarketDataMessage.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Ecng.Common;
using StockSharp.Localization;
/// <summary>
/// Market-data types.
/// </summary>
[DataContract]
[Serializable]
public enum MarketDataTypes
{
/// <summary>
/// Level 1.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Level1Key)]
Level1,
/// <summary>
/// Market depth (order book).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.MarketDepthKey)]
MarketDepth,
/// <summary>
/// Tick trades.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.TicksKey)]
Trades,
/// <summary>
/// Order log.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.OrderLogKey)]
OrderLog,
/// <summary>
/// News.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.NewsKey)]
News,
/// <summary>
/// Candles (time-frame).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.TimeFrameCandleKey)]
CandleTimeFrame,
/// <summary>
/// Candle (tick).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.TickCandleKey)]
CandleTick,
/// <summary>
/// Candle (volume).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.VolumeCandleKey)]
CandleVolume,
/// <summary>
/// Candle (range).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.RangeCandleKey)]
CandleRange,
/// <summary>
/// Candle (X&0).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.PnFCandleKey)]
CandlePnF,
/// <summary>
/// Candle (renko).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.RenkoCandleKey)]
CandleRenko,
/// <summary>
/// Board info.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BoardInfoKey)]
Board,
/// <summary>
/// Heikin Ashi.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.HeikinAshiKey)]
CandleHeikinAshi
}
/// <summary>
/// Build modes.
/// </summary>
[DataContract]
[Serializable]
public enum MarketDataBuildModes
{
/// <summary>
/// Request built data and build the missing data from trades, depths etc.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LoadAndBuildKey)]
LoadAndBuild,
/// <summary>
/// Request only built data.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LoadKey)]
Load,
/// <summary>
/// Build from trades, depths etc.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BuildKey)]
Build
}
/// <summary>
/// Market-data message (uses as a subscribe/unsubscribe in outgoing case, confirmation event in incoming case).
/// </summary>
[DataContract]
[Serializable]
public class MarketDataMessage : SecurityMessage, ISubscriptionMessage, IGeneratedMessage
{
/// <inheritdoc />
[DataMember]
[DisplayNameLoc(LocalizedStrings.Str343Key)]
[DescriptionLoc(LocalizedStrings.Str344Key)]
[MainCategory]
public DateTimeOffset? From { get; set; }
/// <inheritdoc />
[DataMember]
[DisplayNameLoc(LocalizedStrings.Str345Key)]
[DescriptionLoc(LocalizedStrings.Str346Key)]
[MainCategory]
public DateTimeOffset? To { get; set; }
DataType ISubscriptionMessage.DataType => DataType2;
private DataType _dataType2 = Messages.DataType.Level1;
/// <summary>
/// Market data type.
/// </summary>
[DataMember]
public DataType DataType2
{
get => _dataType2;
set => _dataType2 = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Market data type.
/// </summary>
[Browsable(false)]
[DataMember]
//[Obsolete("Use DataType2 property.")]
public new MarketDataTypes DataType
{
#pragma warning disable CS0618 // Type or member is obsolete
#pragma warning disable CS0612 // Type or member is obsolete
get => DataType2.ToMarketDataType();
set => DataType2 = value.ToDataType(Arg);
#pragma warning restore CS0612 // Type or member is obsolete
#pragma warning restore CS0618 // Type or member is obsolete
}
/// <summary>
/// Additional argument for market data request.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.Str347Key)]
[DescriptionLoc(LocalizedStrings.Str348Key)]
[MainCategory]
[Obsolete("Use DataType2 property.")]
public object Arg
{
get => DataType2.Arg;
set => DataType2 = Messages.DataType.Create(DataType2.MessageType, value);
}
/// <inheritdoc />
[DataMember]
public bool IsSubscribe { get; set; }
/// <inheritdoc />
[DataMember]
public long TransactionId { get; set; }
/// <inheritdoc />
[DataMember]
public long? Skip { get; set; }
/// <inheritdoc />
[DataMember]
public long? Count { get; set; }
/// <summary>
/// Max depth of requested order book. Uses in case <see cref="DataType2"/> = <see cref="DataType.MarketDepth"/>.
/// </summary>
[DataMember]
public int? MaxDepth { get; set; }
/// <summary>
/// News id. Uses in case of request news text.
/// </summary>
[DataMember]
public string NewsId { get; set; }
/// <summary>
/// To perform the calculation <see cref="CandleMessage.PriceLevels"/>. By default, it is disabled.
/// </summary>
[DataMember]
public bool IsCalcVolumeProfile { get; set; }
/// <summary>
/// Build mode.
/// </summary>
[DataMember]
public MarketDataBuildModes BuildMode { get; set; }
/// <inheritdoc />
[DataMember]
public DataType BuildFrom { get; set; }
/// <summary>
/// Extra info for the <see cref="BuildFrom"/>.
/// </summary>
[DataMember]
public Level1Fields? BuildField { get; set; }
/// <summary>
/// Allow build candles from smaller timeframe.
/// </summary>
/// <remarks>
/// Available only for <see cref="TimeFrameCandleMessage"/>.
/// </remarks>
[DataMember]
public bool AllowBuildFromSmallerTimeFrame { get; set; } = true;
/// <summary>
/// Use only the regular trading hours for which data will be requested.
/// </summary>
[DataMember]
public bool IsRegularTradingHours { get; set; }
/// <summary>
/// Request <see cref="CandleStates.Finished"/> only candles.
/// </summary>
[DataMember]
public bool IsFinishedOnly { get; set; }
/// <summary>
/// Board code.
/// </summary>
[DataMember]
public string BoardCode { get; set; }
/// <summary>
/// Interval for data refresh.
/// </summary>
[DataMember]
public TimeSpan? RefreshSpeed { get; set; }
/// <summary>
/// Order log to market depth builder.
/// </summary>
public IOrderLogMarketDepthBuilder DepthBuilder { get; set; }
/// <summary>
/// Try fill gaps.
/// </summary>
[DataMember]
public bool FillGaps { get; set; }
/// <summary>
/// Pass through incremental <see cref="QuoteChangeMessage"/>.
/// </summary>
[DataMember]
public bool DoNotBuildOrderBookInrement { get; set; }
bool ISubscriptionMessage.FilterEnabled => false;
/// <summary>
/// Initializes a new instance of the <see cref="MarketDataMessage"/>.
/// </summary>
public MarketDataMessage()
: base(MessageTypes.MarketData)
{
}
/// <summary>
/// Initialize <see cref="MarketDataMessage"/>.
/// </summary>
/// <param name="type">Message type.</param>
protected MarketDataMessage(MessageTypes type)
: base(type)
{
}
/// <summary>
/// Create a copy of <see cref="MarketDataMessage"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Message Clone()
{
var clone = new MarketDataMessage();
CopyTo(clone);
return clone;
}
/// <summary>
/// Copy the message into the <paramref name="destination" />.
/// </summary>
/// <param name="destination">The object, to which copied information.</param>
public void CopyTo(MarketDataMessage destination)
{
base.CopyTo(destination);
destination.DataType2 = DataType2.TypedClone();
destination.From = From;
destination.To = To;
destination.IsSubscribe = IsSubscribe;
destination.TransactionId = TransactionId;
destination.Skip = Skip;
destination.Count = Count;
destination.MaxDepth = MaxDepth;
destination.NewsId = NewsId;
destination.BuildMode = BuildMode;
destination.BuildFrom = BuildFrom?.TypedClone();
destination.BuildField = BuildField;
destination.IsCalcVolumeProfile = IsCalcVolumeProfile;
destination.AllowBuildFromSmallerTimeFrame = AllowBuildFromSmallerTimeFrame;
destination.IsRegularTradingHours = IsRegularTradingHours;
destination.IsFinishedOnly = IsFinishedOnly;
destination.BoardCode = BoardCode;
destination.RefreshSpeed = RefreshSpeed;
destination.DepthBuilder = DepthBuilder;
destination.FillGaps = FillGaps;
destination.DoNotBuildOrderBookInrement = DoNotBuildOrderBookInrement;
}
/// <inheritdoc />
public override string ToString()
{
var str = base.ToString() + $",DataType={DataType2},IsSubscribe={IsSubscribe}";
if (TransactionId != default)
str += $",TransId={TransactionId}";
if (OriginalTransactionId != default)
str += $",OrigId={OriginalTransactionId}";
if (MaxDepth != default)
str += $",MaxDepth={MaxDepth}";
if (Skip != default)
str += $",Skip={Skip}";
if (Count != default)
str += $",Cnt={Count}";
if (From != default)
str += $",From={From}";
if (To != default)
str += $",To={To}";
if (BuildMode == MarketDataBuildModes.Build)
str += $",Build={BuildMode}/{BuildFrom}/{BuildField}";
if (AllowBuildFromSmallerTimeFrame)
str += $",SmallTF={AllowBuildFromSmallerTimeFrame}";
if (IsRegularTradingHours)
str += $",RTH={IsRegularTradingHours}";
if (IsFinishedOnly)
str += $",FinOnly={IsFinishedOnly}";
if (IsCalcVolumeProfile)
str += $",Profile={IsCalcVolumeProfile}";
if (!BoardCode.IsEmpty())
str += $",BoardCode={BoardCode}";
if (RefreshSpeed != null)
str += $",Speed={RefreshSpeed}";
if (FillGaps)
str += $",Gaps={FillGaps}";
if (DoNotBuildOrderBookInrement)
str += $",NotBuildInc={DoNotBuildOrderBookInrement}";
return str;
}
}
}
| |
using System;
using Microsoft.SPOT;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using Microsoft.SPOT.Hardware;
namespace HttpLibrary
{
/// <summary>
/// HttpResponse Class for handeling Http responses
/// </summary>
public class HttpResponse
{
public enum FileType
{
/// <summary>
/// Image jpeg
/// </summary>
JPEG = 1,
/// <summary>
/// Image gif
/// </summary>
GIF = 2,
/// <summary>
/// Html text
/// </summary>
Html = 3,
/// <summary>
/// CSS text
/// </summary>
CSS = 4,
/// <summary>
/// Image png
/// </summary>
PNG = 5,
/// <summary>
/// Java script
/// </summary>
JAVASCRIPT = 6
};
private Socket connection;
private FileStream file_stream;
private const string HtmlPageHeader = "HTTP/1.0 200 OK\r\nContent-Type: ";
private byte[] send_buffer;
private string files_path;
/// <summary>
/// Class constructor
/// </summary>
/// <param name="buffer">Send buffer</param>
/// <param name="FilesPath">Server files Location</param>
/// <param name="Connection">Current active socket</param>
public HttpResponse(byte[] buffer, string FilesPath, Socket Connection)
{
this.send_buffer = buffer;
this.files_path = FilesPath;
this.connection = Connection;
}
/// <summary>
/// Gets the current active socket
/// </summary>
public Socket Connection { get { return this.connection; } }
/// <summary>
/// Gets where server files are located
/// </summary>
public string FilesPath { get { return this.files_path; } }
/// <summary>
/// Gets the response buffer
/// </summary>
public string Buffer { get { return new string(UTF8Encoding.UTF8.GetChars(this.send_buffer)); } }
/// <summary>
/// Send a data byte array
/// </summary>
/// <param name="Data">Data to send</param>
public void Write(byte[] Data)
{
int datalength = Data.Length;
int i = 0;
while (datalength > 256)
{
this.connection.Send(Data, i, 256, SocketFlags.None);
i += 256;
datalength -= 256;
}
this.connection.Send(Data, i, datalength, SocketFlags.None);
}
/// <summary>
/// Send Data String
/// </summary>
/// <param name="Str">String to send</param>
public void Write(string Str)
{
byte[] Data = UTF8Encoding.UTF8.GetBytes(Str);
int datalength = Data.Length;
int i = 0;
while (datalength > 256)
{
this.connection.Send(Data, i, 256, SocketFlags.None);
i += 256;
datalength -= 256;
}
this.connection.Send(Data, i, datalength, SocketFlags.None);
}
/// <summary>
/// Sends a byte array (header) followed by the data array
/// </summary>
/// <param name="Data">Data array</param>
/// <param name="Header">Header Array</param>
public void Write(byte[] Data, byte[] Header)
{
int datalength = Data.Length;
int i = 0;
connection.Send(Header, 0, Header.Length, SocketFlags.None);
while (datalength > send_buffer.Length)
{
this.connection.Send(Data, i, send_buffer.Length, SocketFlags.None);
i += send_buffer.Length;
datalength -= send_buffer.Length;
}
this.connection.Send(Data, i, datalength, SocketFlags.None);
}
/// <summary>
/// Send a header string followed by a data string
/// </summary>
/// <param name="Str">Data string</param>
/// <param name="Header">Header string</param>
public void Write(string Str, string Header)
{
byte[] Data = UTF8Encoding.UTF8.GetBytes(Str);
byte[] header = UTF8Encoding.UTF8.GetBytes(Header);
int datalength = Data.Length;
int i = 0;
connection.Send(header, 0, header.Length, SocketFlags.None);
while (datalength > send_buffer.Length)
{
this.connection.Send(Data, i, send_buffer.Length, SocketFlags.None);
i += send_buffer.Length;
datalength -= send_buffer.Length;
}
this.connection.Send(Data, i, datalength, SocketFlags.None);
}
/// <summary>
/// Sends a file
/// </summary>
/// <param name="FileName">Full file path</param>
public void WriteFile(string FileName)
{
string FILE_EXTENTION = GetFileExtention(FileName.ToLower());
switch (FILE_EXTENTION)
{
case "gif":
FragmentateAndSend(FileName, FileType.GIF);
break;
case "txt":
FragmentateAndSend(FileName, FileType.Html);
break;
case "jpg":
FragmentateAndSend(FileName, FileType.JPEG);
break;
case "jpeg":
FragmentateAndSend(FileName, FileType.JPEG);
break;
case "htm":
FragmentateAndSend(FileName, FileType.Html);
break;
case "html":
FragmentateAndSend(FileName, FileType.Html);
break;
case "css":
FragmentateAndSend(FileName, FileType.CSS);
break;
case "png":
FragmentateAndSend(FileName, FileType.PNG);
break;
case "js":
FragmentateAndSend(FileName, FileType.JAVASCRIPT);
break;
default:
FragmentateAndSend(FileName, FileType.Html);
break;
}
}
/// <summary>
/// Redirects client to a specified url
/// </summary>
/// <param name="Url">Url</param>
public void Redirect(string Url)
{
string rs = "<meta http-equiv=\"refresh\" content=\"0; url=" + Url + "\">";
byte[] header = UTF8Encoding.UTF8.GetBytes(HtmlPageHeader + "; charset=utf-8\r\nContent-Length: " + rs.Length.ToString() + "\r\n\r\n");
byte[] databytes = UTF8Encoding.UTF8.GetBytes(rs);
connection.Send(header, 0, header.Length, SocketFlags.None);
connection.Send(databytes, 0, databytes.Length, SocketFlags.None);
}
private void FragmentateAndSend(string file_name, FileType Type)
{
byte[] HEADER;
long FILE_LENGTH;
file_stream= new FileStream(file_name, FileMode.Open, FileAccess.Read);
FILE_LENGTH = file_stream.Length;
HEADER = GenerateHeaderBytes(Type, FILE_LENGTH);
this.connection.Send(HEADER, 0, HEADER.Length, SocketFlags.None);
while (FILE_LENGTH > send_buffer.Length)
{
file_stream.Read(send_buffer, 0, send_buffer.Length);
this.connection.Send(send_buffer, 0, send_buffer.Length, SocketFlags.None);
FILE_LENGTH -= send_buffer.Length;
}
file_stream.Read(send_buffer, 0, (int)FILE_LENGTH);
this.connection.Send(send_buffer, 0, (int)FILE_LENGTH, SocketFlags.None);
file_stream.Close();
}
private string GetFileExtention(string file_name)
{
string x = file_name;
x = x.Substring(x.LastIndexOf('.') + 1);
return x;
}
/// <summary>
/// Writes a not found page
/// </summary>
public void WriteNotFound()
{
string page = "<html><head><title>Page Not Found</title><body><h1 align=center>Page Not Found</h1></body></html>";
byte[] pagebytes = UTF8Encoding.UTF8.GetBytes(page);
byte[] headerbytes = GenerateHeaderBytes(FileType.Html, page.Length);
this.connection.Send(headerbytes, 0, headerbytes.Length, SocketFlags.None);
this.connection.Send(pagebytes, 0, pagebytes.Length, SocketFlags.None);
}
/// <summary>
/// Sends all the files in the memory card as an index page
/// </summary>
public void WriteFilesList(string answer)
{
string[] files = Directory.GetFiles(@"\SD");
StringBuilder page = new StringBuilder();
string file_name = "";
page.Append("<html><head><title>File Directory</title></head>");
page.Append("<script type=\"text/JavaScript\">\n");
page.Append("<!--\n");
page.Append("function timedRefresh(timeoutPeriod) {setTimeout(\"location.reload(true);\",timeoutPeriod); }\n");
page.Append("// -->\n");
page.Append("</script>\n");
page.Append("</head>");
page.Append("<body>");
page.Append("<h3 align=\"left\">" + "Local Time: " + DateTime.Now.ToString() + "</h3>");
page.Append("<h3 align=\"left\">" + "System Time: " + Utility.GetMachineTime().ToString() + "</h3>");
page.Append("<h3 align=\"left\">" + answer + "</h3>");
page.Append("<h2 align=\"center\">File Directory</h2>");
page.Append("<hr>");
foreach (string f in files)
{
file_name = f.Split('\\')[2];
page.Append("<a href=\"/" + file_name + "\">" + file_name + "</a><br><hr>");
}
page.Append("</body>");
page.Append("</html>");
Write(page.ToString(), GenerateHeaderString(FileType.Html, page.Length));
}
/// <summary>
/// Generates a mime type header string based on the file length and type
/// </summary>
/// <param name="Type">File type</param>
/// <param name="FileLength">File length</param>
/// <returns></returns>
public static string GenerateHeaderString(FileType Type, long FileLength)
{
if (Type == FileType.Html)
return "HTTP/1.0 200 OK\r\nContent-Type: " + "text/html" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n";
else if (Type == FileType.JPEG)
return "HTTP/1.0 200 OK\r\nContent-Type: " + "image/jpeg" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n";
else if (Type == FileType.GIF)
return "HTTP/1.0 200 OK\r\nContent-Type: " + "image/gif" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n";
else if (Type == FileType.CSS)
return "HTTP/1.0 200 OK\r\nContent-Type: " + "text/css" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n";
else if (Type == FileType.PNG)
return "HTTP/1.0 200 OK\r\nContent-Type: " + "image/png" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n";
else if (Type == FileType.JAVASCRIPT)
return "HTTP/1.0 200 OK\r\nContent-Type: " + "text/javascript" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n";
else
return "HTTP/1.0 200 OK\r\nContent-Type: " + "text/html" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n";
}
/// <summary>
/// Generates a mime type header byte array based on the file length and type
/// </summary>
/// <param name="Type">File type</param>
/// <param name="FileLength">File length</param>
/// <returns></returns>
public static byte[] GenerateHeaderBytes(FileType Type, long FileLength)
{
if (Type == FileType.Html)
return System.Text.UTF8Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: " + "text/html" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n");
else if (Type == FileType.JPEG)
return System.Text.UTF8Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: " + "image/jpeg" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n");
else if (Type == FileType.GIF)
return System.Text.UTF8Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: " + "image/gif" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n");
else if (Type == FileType.CSS)
return System.Text.UTF8Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: " + "text/css" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n");
else if (Type == FileType.PNG)
return System.Text.UTF8Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: " + "image/png" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n");
else if (Type == FileType.JAVASCRIPT)
return System.Text.UTF8Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: " + "text/javascript" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n");
else
return System.Text.UTF8Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: " + "text/html" + "; charset=utf-8\r\nContent-Length: " + FileLength.ToString() + "\r\n\r\n");
}
}
}
| |
// 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.
/*============================================================
**
**
**
**
**
** Purpose: CultureInfo-specific collection of resources.
**
**
===========================================================*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Resources
{
// A RuntimeResourceSet stores all the resources defined in one
// particular CultureInfo, with some loading optimizations.
//
// It is expected that nearly all the runtime's users will be satisfied with the
// default resource file format, and it will be more efficient than most simple
// implementations. Users who would consider creating their own ResourceSets and/or
// ResourceReaders and ResourceWriters are people who have to interop with a
// legacy resource file format, are creating their own resource file format
// (using XML, for instance), or require doing resource lookups at runtime over
// the network. This group will hopefully be small, but all the infrastructure
// should be in place to let these users write & plug in their own tools.
//
// The Default Resource File Format
//
// The fundamental problems addressed by the resource file format are:
//
// * Versioning - A ResourceReader could in theory support many different
// file format revisions.
// * Storing intrinsic datatypes (ie, ints, Strings, DateTimes, etc) in a compact
// format
// * Support for user-defined classes - Accomplished using Serialization
// * Resource lookups should not require loading an entire resource file - If you
// look up a resource, we only load the value for that resource, minimizing working set.
//
//
// There are four sections to the default file format. The first
// is the Resource Manager header, which consists of a magic number
// that identifies this as a Resource file, and a ResourceSet class name.
// The class name is written here to allow users to provide their own
// implementation of a ResourceSet (and a matching ResourceReader) to
// control policy. If objects greater than a certain size or matching a
// certain naming scheme shouldn't be stored in memory, users can tweak that
// with their own subclass of ResourceSet.
//
// The second section in the system default file format is the
// RuntimeResourceSet specific header. This contains a version number for
// the .resources file, the number of resources in this file, the number of
// different types contained in the file, followed by a list of fully
// qualified type names. After this, we include an array of hash values for
// each resource name, then an array of virtual offsets into the name section
// of the file. The hashes allow us to do a binary search on an array of
// integers to find a resource name very quickly without doing many string
// compares (except for once we find the real type, of course). If a hash
// matches, the index into the array of hash values is used as the index
// into the name position array to find the name of the resource. The type
// table allows us to read multiple different classes from the same file,
// including user-defined types, in a more efficient way than using
// Serialization, at least when your .resources file contains a reasonable
// proportion of base data types such as Strings or ints. We use
// Serialization for all the non-instrinsic types.
//
// The third section of the file is the name section. It contains a
// series of resource names, written out as byte-length prefixed little
// endian Unicode strings (UTF-16). After each name is a four byte virtual
// offset into the data section of the file, pointing to the relevant
// string or serialized blob for this resource name.
//
// The fourth section in the file is the data section, which consists
// of a type and a blob of bytes for each item in the file. The type is
// an integer index into the type table. The data is specific to that type,
// but may be a number written in binary format, a String, or a serialized
// Object.
//
// The system default file format (V1) is as follows:
//
// What Type of Data
// ==================================================== ===========
//
// Resource Manager header
// Magic Number (0xBEEFCACE) Int32
// Resource Manager header version Int32
// Num bytes to skip from here to get past this header Int32
// Class name of IResourceReader to parse this file String
// Class name of ResourceSet to parse this file String
//
// RuntimeResourceReader header
// ResourceReader version number Int32
// [Only in debug V2 builds - "***DEBUG***"] String
// Number of resources in the file Int32
// Number of types in the type table Int32
// Name of each type Set of Strings
// Padding bytes for 8-byte alignment (use PAD) Bytes (0-7)
// Hash values for each resource name Int32 array, sorted
// Virtual offset of each resource name Int32 array, coupled with hash values
// Absolute location of Data section Int32
//
// RuntimeResourceReader Name Section
// Name & virtual offset of each resource Set of (UTF-16 String, Int32) pairs
//
// RuntimeResourceReader Data Section
// Type and Value of each resource Set of (Int32, blob of bytes) pairs
//
// This implementation, when used with the default ResourceReader class,
// loads only the strings that you look up for. It can do string comparisons
// without having to create a new String instance due to some memory mapped
// file optimizations in the ResourceReader and FastResourceComparer
// classes. This keeps the memory we touch to a minimum when loading
// resources.
//
// If you use a different IResourceReader class to read a file, or if you
// do case-insensitive lookups (and the case-sensitive lookup fails) then
// we will load all the names of each resource and each resource value.
// This could probably use some optimization.
//
// In addition, this supports object serialization in a similar fashion.
// We build an array of class types contained in this file, and write it
// to RuntimeResourceReader header section of the file. Every resource
// will contain its type (as an index into the array of classes) with the data
// for that resource. We will use the Runtime's serialization support for this.
//
// All strings in the file format are written with BinaryReader and
// BinaryWriter, which writes out the length of the String in bytes as an
// Int32 then the contents as Unicode chars encoded in UTF-8. In the name
// table though, each resource name is written in UTF-16 so we can do a
// string compare byte by byte against the contents of the file, without
// allocating objects. Ideally we'd have a way of comparing UTF-8 bytes
// directly against a String object, but that may be a lot of work.
//
// The offsets of each resource string are relative to the beginning
// of the Data section of the file. This way, if a tool decided to add
// one resource to a file, it would only need to increment the number of
// resources, add the hash & location of last byte in the name section
// to the array of resource hashes and resource name positions (carefully
// keeping these arrays sorted), add the name to the end of the name &
// offset list, possibly add the type list of types types (and increase
// the number of items in the type table), and add the resource value at
// the end of the file. The other offsets wouldn't need to be updated to
// reflect the longer header section.
//
// Resource files are currently limited to 2 gigabytes due to these
// design parameters. A future version may raise the limit to 4 gigabytes
// by using unsigned integers, or may use negative numbers to load items
// out of an assembly manifest. Also, we may try sectioning the resource names
// into smaller chunks, each of size sqrt(n), would be substantially better for
// resource files containing thousands of resources.
//
internal sealed class RuntimeResourceSet : ResourceSet, IEnumerable
{
internal const int Version = 2; // File format version number
// Cache for resources. Key is the resource name, which can be cached
// for arbitrarily long times, since the object is usually a string
// literal that will live for the lifetime of the appdomain. The
// value is a ResourceLocator instance, which might cache the object.
private Dictionary<String, ResourceLocator> _resCache;
// For our special load-on-demand reader, cache the cast. The
// RuntimeResourceSet's implementation knows how to treat this reader specially.
private ResourceReader _defaultReader;
// This is a lookup table for case-insensitive lookups, and may be null.
// Consider always using a case-insensitive resource cache, as we don't
// want to fill this out if we can avoid it. The problem is resource
// fallback will somewhat regularly cause us to look up resources that
// don't exist.
private Dictionary<String, ResourceLocator> _caseInsensitiveTable;
// If we're not using our custom reader, then enumerate through all
// the resources once, adding them into the table.
private bool _haveReadFromReader;
internal RuntimeResourceSet(String fileName) : base(false)
{
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
_defaultReader = new ResourceReader(stream, _resCache);
Reader = _defaultReader;
}
internal RuntimeResourceSet(Stream stream) : base(false)
{
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
_defaultReader = new ResourceReader(stream, _resCache);
Reader = _defaultReader;
}
protected override void Dispose(bool disposing)
{
if (Reader == null)
return;
if (disposing)
{
lock (Reader)
{
_resCache = null;
if (_defaultReader != null)
{
_defaultReader.Close();
_defaultReader = null;
}
_caseInsensitiveTable = null;
// Set Reader to null to avoid a race in GetObject.
base.Dispose(disposing);
}
}
else
{
// Just to make sure we always clear these fields in the future...
_resCache = null;
_caseInsensitiveTable = null;
_defaultReader = null;
base.Dispose(disposing);
}
}
public override IDictionaryEnumerator GetEnumerator()
{
return GetEnumeratorHelper();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumeratorHelper();
}
private IDictionaryEnumerator GetEnumeratorHelper()
{
IResourceReader copyOfReader = Reader;
if (copyOfReader == null || _resCache == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
return copyOfReader.GetEnumerator();
}
public override String GetString(String key)
{
Object o = GetObject(key, false, true);
return (String)o;
}
public override String GetString(String key, bool ignoreCase)
{
Object o = GetObject(key, ignoreCase, true);
return (String)o;
}
public override Object GetObject(String key)
{
return GetObject(key, false, false);
}
public override Object GetObject(String key, bool ignoreCase)
{
return GetObject(key, ignoreCase, false);
}
private Object GetObject(String key, bool ignoreCase, bool isString)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (Reader == null || _resCache == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
Contract.EndContractBlock();
Object value = null;
ResourceLocator resLocation;
lock (Reader)
{
if (Reader == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
if (_defaultReader != null)
{
// Find the offset within the data section
int dataPos = -1;
if (_resCache.TryGetValue(key, out resLocation))
{
value = resLocation.Value;
dataPos = resLocation.DataPosition;
}
if (dataPos == -1 && value == null)
{
dataPos = _defaultReader.FindPosForResource(key);
}
if (dataPos != -1 && value == null)
{
Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
// Normally calling LoadString or LoadObject requires
// taking a lock. Note that in this case, we took a
// lock on the entire RuntimeResourceSet, which is
// sufficient since we never pass this ResourceReader
// to anyone else.
ResourceTypeCode typeCode;
if (isString)
{
value = _defaultReader.LoadString(dataPos);
typeCode = ResourceTypeCode.String;
}
else
{
value = _defaultReader.LoadObject(dataPos, out typeCode);
}
resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null);
lock (_resCache)
{
_resCache[key] = resLocation;
}
}
if (value != null || !ignoreCase)
{
return value; // may be null
}
} // if (_defaultReader != null)
// At this point, we either don't have our default resource reader
// or we haven't found the particular resource we're looking for
// and may have to search for it in a case-insensitive way.
if (!_haveReadFromReader)
{
// If necessary, init our case insensitive hash table.
if (ignoreCase && _caseInsensitiveTable == null)
{
_caseInsensitiveTable = new Dictionary<String, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
}
if (_defaultReader == null)
{
IDictionaryEnumerator en = Reader.GetEnumerator();
while (en.MoveNext())
{
DictionaryEntry entry = en.Entry;
String readKey = (String)entry.Key;
ResourceLocator resLoc = new ResourceLocator(-1, entry.Value);
_resCache.Add(readKey, resLoc);
if (ignoreCase)
_caseInsensitiveTable.Add(readKey, resLoc);
}
// Only close the reader if it is NOT our default one,
// since we need it around to resolve ResourceLocators.
if (!ignoreCase)
Reader.Close();
}
else
{
Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
while (en.MoveNext())
{
// Note: Always ask for the resource key before the data position.
String currentKey = (String)en.Key;
int dataPos = en.DataPosition;
ResourceLocator resLoc = new ResourceLocator(dataPos, null);
_caseInsensitiveTable.Add(currentKey, resLoc);
}
}
_haveReadFromReader = true;
}
Object obj = null;
bool found = false;
bool keyInWrongCase = false;
if (_defaultReader != null)
{
if (_resCache.TryGetValue(key, out resLocation))
{
found = true;
obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
}
if (!found && ignoreCase)
{
if (_caseInsensitiveTable.TryGetValue(key, out resLocation))
{
found = true;
keyInWrongCase = true;
obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
}
return obj;
} // lock(Reader)
}
// The last parameter indicates whether the lookup required a
// case-insensitive lookup to succeed, indicating we shouldn't add
// the ResourceLocation to our case-sensitive cache.
private Object ResolveResourceLocator(ResourceLocator resLocation, String key, Dictionary<String, ResourceLocator> copyOfCache, bool keyInWrongCase)
{
// We need to explicitly resolve loosely linked manifest
// resources, and we need to resolve ResourceLocators with null objects.
Object value = resLocation.Value;
if (value == null)
{
ResourceTypeCode typeCode;
lock (Reader)
{
value = _defaultReader.LoadObject(resLocation.DataPosition, out typeCode);
}
if (!keyInWrongCase && ResourceLocator.CanCache(typeCode))
{
resLocation.Value = value;
copyOfCache[key] = resLocation;
}
}
return value;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*=============================================================================
**
**
** Purpose: A circular-array implementation of a generic queue.
**
**
=============================================================================*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Collections.Generic
{
// A simple Queue of generic objects. Internally it is implemented as a
// circular buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(QueueDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Queue<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array;
private int _head; // First valid element in the queue
private int _tail; // Last valid element in the queue
private int _size; // Number of elements.
private int _version;
private Object _syncRoot;
private const int MinimumGrow = 4;
private const int GrowFactor = 200; // double each time
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue"]/*' />
public Queue()
{
_array = Array.Empty<T>();
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue1"]/*' />
public Queue(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedNonNegNumRequired);
_array = new T[capacity];
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue3"]/*' />
public Queue(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
_array = EnumerableHelpers.ToArray(collection, out _size);
_tail = (_size == _array.Length) ? 0 : _size;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Count"]/*' />
public int Count
{
get { return _size; }
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IsSynchronized"]/*' />
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
Object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Clear"]/*' />
public void Clear()
{
if (_size != 0)
{
if (_head < _tail)
Array.Clear(_array, _head, _size);
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_size = 0;
}
_head = 0;
_tail = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.CopyTo"]/*' />
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_Index);
}
int arrayLen = array.Length;
if (arrayLen - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = (arrayLen - arrayIndex < _size) ? (arrayLen - arrayIndex) : _size;
if (numToCopy == 0) return;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, arrayIndex, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy);
}
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound);
}
int arrayLen = array.Length;
if (index < 0 || index > arrayLen)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
if (arrayLen - index < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = (arrayLen - index < _size) ? arrayLen - index : _size;
if (numToCopy == 0) return;
try
{
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
// Adds item to the tail of the queue.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Enqueue"]/*' />
public void Enqueue(T item)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100);
if (newcapacity < _array.Length + MinimumGrow)
{
newcapacity = _array.Length + MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = item;
MoveNext(ref _tail);
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.GetEnumerator"]/*' />
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IEnumerable.GetEnumerator"]/*' />
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method simply returns null.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Dequeue"]/*' />
public T Dequeue()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
T removed = _array[_head];
_array[_head] = default(T);
MoveNext(ref _head);
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Peek"]/*' />
public T Peek()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
return _array[_head];
}
// Returns true if the queue contains at least one object equal to item.
// Equality is determined using item.Equals().
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Contains"]/*' />
public bool Contains(T item)
{
int index = _head;
int count = _size;
EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > 0)
{
if (c.Equals(_array[index], item))
{
return true;
}
MoveNext(ref index);
}
return false;
}
private T GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.ToArray"]/*' />
public T[] ToArray()
{
T[] arr = new T[_size];
if (_size == 0)
return arr; // consider replacing with Array.Empty<T>() to be consistent with non-generic Queue
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
T[] newarray = new T[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
// Increments the index wrapping it if necessary.
private void MoveNext(ref int index)
{
// It is tempting to use the remainder operator here but it is actually much slower
// than a simple comparison and a rarely taken branch.
int tmp = index + 1;
index = (tmp == _array.Length) ? 0 : tmp;
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
SetCapacity(_size);
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator"]/*' />
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>,
System.Collections.IEnumerator
{
private Queue<T> _q;
private int _index; // -1 = not started, -2 = ended/disposed
private int _version;
private T _currentElement;
internal Enumerator(Queue<T> q)
{
_q = q;
_version = _q._version;
_index = -1;
_currentElement = default(T);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Dispose"]/*' />
public void Dispose()
{
_index = -2;
_currentElement = default(T);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.MoveNext"]/*' />
public bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
return false;
_index++;
if (_index == _q._size)
{
_index = -2;
_currentElement = default(T);
return false;
}
_currentElement = _q.GetElement(_index);
return true;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Current"]/*' />
public T Current
{
get
{
if (_index < 0)
{
if (_index == -1)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
else
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
return _currentElement;
}
}
Object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -1;
_currentElement = default(T);
}
}
}
}
| |
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 resume.interface.rest.Areas.HelpPage.ModelDescriptions;
using resume.interface.rest.Areas.HelpPage.Models;
namespace resume.interface.rest.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.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 WeddingPlanner.CommunicationBus.Areas.HelpPage.ModelDescriptions;
using WeddingPlanner.CommunicationBus.Areas.HelpPage.Models;
using WeddingPlanner.CommunicationBus.Areas.HelpPage.SampleGeneration;
namespace WeddingPlanner.CommunicationBus.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Ooui
{
public abstract class Node : EventTarget
{
readonly List<Node> children = new List<Node> ();
public IReadOnlyList<Node> Children {
get {
lock (children) {
return new ReadOnlyList<Node> (children);
}
}
}
public Node FirstChild {
get {
lock (children) {
if (children.Count > 0)
return children[0];
return null;
}
}
}
public virtual string Text {
get {
var sb = new System.Text.StringBuilder ();
foreach (var c in Children) {
sb.Append (c.Text);
}
return sb.ToString ();
}
set {
if (Children.Count == 1) {
var textNode = Children[0] as TextNode;
if (textNode != null) {
textNode.Text = value;
return;
}
}
ReplaceAll (new TextNode (value ?? ""));
}
}
protected Node (string tagName)
: base (tagName)
{
}
public override EventTarget GetElementById (string id)
{
if (id == Id) return this;
foreach (var c in Children) {
if (c is Element e) {
var r = e.GetElementById (id);
if (r != null)
return r;
}
}
return null;
}
public Node AppendChild (Node newChild)
{
return InsertBefore (newChild, null);
}
public Node InsertBefore (Node newChild, Node referenceChild)
{
if (newChild == null)
return null;
lock (children) {
if (referenceChild == null) {
children.Add (newChild);
}
else {
var index = children.IndexOf (referenceChild);
if (index < 0) {
throw new ArgumentException ("Reference must be a child of this element", nameof (referenceChild));
}
children.Insert (index, newChild);
}
}
newChild.MessageSent += HandleChildMessageSent;
Call ("insertBefore", newChild, referenceChild);
OnChildInsertedBefore (newChild, referenceChild);
return newChild;
}
public Node RemoveChild (Node child)
{
if (child == null)
return null;
lock (children) {
if (!children.Remove (child)) {
throw new ArgumentException ("Child not contained in this element", nameof (child));
}
}
child.MessageSent -= HandleChildMessageSent;
Call ("removeChild", child);
OnChildRemoved (child);
return child;
}
protected virtual void OnChildInsertedBefore (Node newChild, Node referenceChild)
{
}
protected virtual void OnChildRemoved (Node child)
{
}
protected void ReplaceAll (Node newNode)
{
var toRemove = new List<Node> ();
lock (children) {
toRemove.AddRange (children);
children.Clear ();
}
foreach (var child in toRemove) {
child.MessageSent -= HandleChildMessageSent;
Call ("removeChild", child);
}
InsertBefore (newNode, null);
}
void HandleChildMessageSent (Message message)
{
Send (message);
}
protected override bool SaveStateMessageIfNeeded (Message message)
{
if (message.TargetId == Id) {
var handled = false;
switch (message.MessageType) {
case MessageType.Call when message.Key == "insertBefore":
AddStateMessage (message);
break;
case MessageType.Call when message.Key == "removeChild" && message.Value is Array ma && ma.Length == 1:
UpdateStateMessages (state => {
var mchild = ma.GetValue (0);
Node nextChild = null;
for (var i = 0; i < state.Count;) {
var x = state[i];
if (x.Key == "insertBefore" && x.Value is Array xa && xa.Length == 2 && ReferenceEquals (xa.GetValue (0), mchild)) {
// Remove any inserts for this node
nextChild = xa.GetValue (1) as Node;
state.RemoveAt (i);
}
else if (x.Key == "insertBefore" && x.Value is Array ya && ya.Length == 2 && ReferenceEquals (ya.GetValue (1), mchild)) {
// Replace inserts that reference this node
state[i] = Message.Call (Id, "insertBefore", ya.GetValue (0), nextChild);
i++;
}
else {
i++;
}
}
});
break;
}
if (!handled) {
base.SaveStateMessageIfNeeded (message);
}
return true;
}
else {
var ch = Children;
for (var i = 0; i < ch.Count; i++) {
if (ch[i].SaveStateMessageIfNeeded (message))
return true;
}
return false;
}
}
protected override bool TriggerEventFromMessage (Message message)
{
if (message.TargetId == Id) {
if (base.TriggerEventFromMessage (message))
return true;
}
else {
var ch = Children;
for (var i = 0; i < ch.Count; i++) {
if (ch[i].TriggerEventFromMessage (message))
return true;
}
}
return false;
}
#if !NO_XML
public virtual string OuterHtml {
get {
using (var stream = new System.IO.MemoryStream ()) {
var settings = new System.Xml.XmlWriterSettings {
OmitXmlDeclaration = true,
ConformanceLevel = System.Xml.ConformanceLevel.Fragment,
CloseOutput = false,
};
using (var w = System.Xml.XmlWriter.Create (stream, settings)) {
WriteOuterHtml (w);
}
stream.Position = 0;
return new System.IO.StreamReader (stream).ReadToEnd ();
}
}
}
public abstract void WriteOuterHtml (System.Xml.XmlWriter w);
#endif
}
class ReadOnlyList<T> : IReadOnlyList<T>
{
readonly List<T> list;
public ReadOnlyList (List<T> items)
{
list = new List<T> (items);
}
T IReadOnlyList<T>.this[int index] => list[index];
int IReadOnlyCollection<T>.Count => list.Count;
IEnumerator<T> IEnumerable<T>.GetEnumerator ()
{
return ((IEnumerable<T>)list).GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return ((IEnumerable)list).GetEnumerator ();
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: MbpInfo.cs
//
// Description: Provides paragraph level margin collapsing support.
//
//---------------------------------------------------------------------------
using System;
using System.Windows; // DependencyObject
using System.Windows.Documents; // Block
using MS.Internal.Text; // TextDpi
using System.Windows.Media; // Brush
using MS.Internal.PtsHost.UnsafeNativeMethods; // Pts
namespace MS.Internal.PtsHost
{
/// <summary>
/// Provides services for MBP handling.
/// </summary>
internal sealed class MbpInfo
{
/// <summary>
/// Get MbpInfo from DependencyObject.
/// </summary>
/// <param name="o">DependencyObject for which MBP properties are retrieved.</param>
internal static MbpInfo FromElement(DependencyObject o)
{
if (o is Block || o is AnchoredBlock || o is TableCell || o is ListItem)
{
MbpInfo mbp = new MbpInfo((TextElement)o);
double lineHeight = DynamicPropertyReader.GetLineHeightValue(o);
if (mbp.IsMarginAuto)
{
ResolveAutoMargin(mbp, o, lineHeight);
}
if (mbp.IsPaddingAuto)
{
ResolveAutoPadding(mbp, o, lineHeight);
}
return mbp;
}
return _empty;
}
/// <summary>
/// Mirrors margin
/// </summary>
internal void MirrorMargin()
{
ReverseFlowDirection(ref _margin);
}
/// <summary>
/// Mirrors border and padding
/// </summary>
internal void MirrorBP()
{
ReverseFlowDirection(ref _border);
ReverseFlowDirection(ref _padding);
}
/// <summary>
/// Reverses flow direction for a given thickness
/// </summary>
private static void ReverseFlowDirection(ref Thickness thickness)
{
double temp = thickness.Left;
thickness.Left = thickness.Right;
thickness.Right = temp;
}
/// <summary>
/// Static constructor.
/// </summary>
static MbpInfo()
{
_empty = new MbpInfo();
}
/// <summary>
/// Private constructor.
/// </summary>
private MbpInfo()
{
_margin = new Thickness();
_border = new Thickness();
_padding = new Thickness();
_borderBrush = new SolidColorBrush();
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="block">Block for which MBP properties are retrieved.</param>
private MbpInfo(TextElement block)
{
_margin = (Thickness)block.GetValue(Block.MarginProperty);
_border = (Thickness)block.GetValue(Block.BorderThicknessProperty);
_padding = (Thickness)block.GetValue(Block.PaddingProperty);
_borderBrush = (Brush)block.GetValue(Block.BorderBrushProperty);
}
/// <summary>
/// Resolve Auto values for Margin.
/// </summary>
private static void ResolveAutoMargin(MbpInfo mbp, DependencyObject o, double lineHeight)
{
Thickness defaultMargin;
if (o is Paragraph)
{
DependencyObject parent = ((Paragraph)o).Parent;
if (parent is ListItem || parent is TableCell || parent is AnchoredBlock)
{
defaultMargin = new Thickness(0);
}
else
{
defaultMargin = new Thickness(0, lineHeight, 0, lineHeight);
}
}
else if (o is Table || o is List)
{
defaultMargin = new Thickness(0, lineHeight, 0, lineHeight);
}
else if (o is Figure || o is Floater)
{
defaultMargin = new Thickness(0.5 * lineHeight);
}
else
{
defaultMargin = new Thickness(0);
}
mbp.Margin = new Thickness(
Double.IsNaN(mbp.Margin.Left) ? defaultMargin.Left : mbp.Margin.Left,
Double.IsNaN(mbp.Margin.Top) ? defaultMargin.Top : mbp.Margin.Top,
Double.IsNaN(mbp.Margin.Right) ? defaultMargin.Right : mbp.Margin.Right,
Double.IsNaN(mbp.Margin.Bottom) ? defaultMargin.Bottom : mbp.Margin.Bottom);
}
/// <summary>
/// Resolve Auto values for Padding.
/// </summary>
private static void ResolveAutoPadding(MbpInfo mbp, DependencyObject o, double lineHeight)
{
Thickness defaultPadding;
if (o is Figure || o is Floater)
{
defaultPadding = new Thickness(0.5 * lineHeight);
}
else if (o is List)
{
defaultPadding = ListMarkerSourceInfo.CalculatePadding((List)o, lineHeight);
}
else
{
defaultPadding = new Thickness(0);
}
mbp.Padding = new Thickness(
Double.IsNaN(mbp.Padding.Left) ? defaultPadding.Left : mbp.Padding.Left,
Double.IsNaN(mbp.Padding.Top) ? defaultPadding.Top : mbp.Padding.Top,
Double.IsNaN(mbp.Padding.Right) ? defaultPadding.Right : mbp.Padding.Right,
Double.IsNaN(mbp.Padding.Bottom) ? defaultPadding.Bottom : mbp.Padding.Bottom);
}
/// <value>
/// Combined value of left Margin, Border and Padding.
/// </value>
internal int MBPLeft
{
get { return TextDpi.ToTextDpi(_margin.Left) + TextDpi.ToTextDpi(_border.Left) + TextDpi.ToTextDpi(_padding.Left); }
}
/// <value>
/// Combined value of right Margin, Border and Padding.
/// </value>
internal int MBPRight
{
get { return TextDpi.ToTextDpi(_margin.Right) + TextDpi.ToTextDpi(_border.Right) + TextDpi.ToTextDpi(_padding.Right); }
}
/// <value>
/// Combined value of top Margin, Border and Padding.
/// </value>
internal int MBPTop
{
get { return TextDpi.ToTextDpi(_margin.Top) + TextDpi.ToTextDpi(_border.Top) + TextDpi.ToTextDpi(_padding.Top); }
}
/// <value>
/// Combined value of top Margin, Border and Padding.
/// </value>
internal int MBPBottom
{
get { return TextDpi.ToTextDpi(_margin.Bottom) + TextDpi.ToTextDpi(_border.Bottom) + TextDpi.ToTextDpi(_padding.Bottom); }
}
/// <value>
/// Combined value of left Border and Padding.
/// </value>
internal int BPLeft
{
get { return TextDpi.ToTextDpi(_border.Left) + TextDpi.ToTextDpi(_padding.Left); }
}
/// <value>
/// Combined value of right Border and Padding.
/// </value>
internal int BPRight
{
get { return TextDpi.ToTextDpi(_border.Right) + TextDpi.ToTextDpi(_padding.Right); }
}
/// <value>
/// Combined value of top Border and Padding.
/// </value>
internal int BPTop
{
get { return TextDpi.ToTextDpi(_border.Top) + TextDpi.ToTextDpi(_padding.Top); }
}
/// <value>
/// Combined value of bottom Border and Padding.
/// </value>
internal int BPBottom
{
get { return TextDpi.ToTextDpi(_border.Bottom) + TextDpi.ToTextDpi(_padding.Bottom); }
}
/// <value>
/// Left Border
/// </value>
internal int BorderLeft
{
get { return TextDpi.ToTextDpi(_border.Left); }
}
/// <value>
/// Right Border
/// </value>
internal int BorderRight
{
get { return TextDpi.ToTextDpi(_border.Right); }
}
/// <value>
/// Top Border
/// </value>
internal int BorderTop
{
get { return TextDpi.ToTextDpi(_border.Top); }
}
/// <value>
/// Bottom Border
/// </value>
internal int BorderBottom
{
get { return TextDpi.ToTextDpi(_border.Bottom); }
}
/// <value>
/// Left margin.
/// </value>
internal int MarginLeft
{
get { return TextDpi.ToTextDpi(_margin.Left); }
}
/// <value>
/// Right margin.
/// </value>
internal int MarginRight
{
get { return TextDpi.ToTextDpi(_margin.Right); }
}
/// <value>
/// top margin.
/// </value>
internal int MarginTop
{
get { return TextDpi.ToTextDpi(_margin.Top); }
}
/// <value>
/// Bottom margin.
/// </value>
internal int MarginBottom
{
get { return TextDpi.ToTextDpi(_margin.Bottom); }
}
/// <value>
/// Margin thickness.
/// </value>
internal Thickness Margin
{
get { return _margin; }
set { _margin = value; }
}
/// <value>
/// Border thickness.
/// </value>
internal Thickness Border
{
get { return _border; }
set { _border = value; }
}
internal Thickness Padding
{
get { return _padding; }
set { _padding = value; }
}
/// <value>
/// Border brush.
/// </value>
internal Brush BorderBrush
{
get { return _borderBrush; }
}
/// <summary>
/// Whether any padding value is Auto.
/// </summary>
private bool IsPaddingAuto
{
get
{
return (
Double.IsNaN(_padding.Left) ||
Double.IsNaN(_padding.Right) ||
Double.IsNaN(_padding.Top) ||
Double.IsNaN(_padding.Bottom));
}
}
/// <summary>
/// Whether any margin value is Auto.
/// </summary>
private bool IsMarginAuto
{
get
{
return (
Double.IsNaN(_margin.Left) ||
Double.IsNaN(_margin.Right) ||
Double.IsNaN(_margin.Top) ||
Double.IsNaN(_margin.Bottom));
}
}
/// <value>
/// Margin thickness.
/// </value>
private Thickness _margin;
/// <value>
/// Border thickness.
/// </value>
private Thickness _border;
/// <value>
/// Padding thickness.
/// </value>
private Thickness _padding;
/// <value>
/// Border brush.
/// </value>
private Brush _borderBrush;
/// <value>
/// Empty MBPInfo instance.
/// </value>
private static MbpInfo _empty;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using gView.DataSources.Raster.File;
using gView.Framework.Data;
using gView.Framework.UI;
using gView.Framework.system.UI;
namespace gView.DataSources.Raster.UI
{
/*
public class RasterCatalogExplorerObject : IExplorerFileObject
{
private IExplorerIcon _icon = new RasterIcon();
private string _filename = "";
private ImageCatalogLayer _layer = null;
public RasterCatalogExplorerObject() { }
public RasterCatalogExplorerObject(string filename)
{
_filename = filename;
}
#region IExplorerFileObject Members
public string Filter
{
get { return "*.cat.mdb"; }
}
public IExplorerIcon Icon
{
get
{
return _icon;
}
}
#endregion
#region IExplorerObject Members
public string Name
{
get
{
try
{
FileInfo fi = new FileInfo(_filename);
return fi.Name;
}
catch { return ""; }
}
}
public string FullName
{
get { return _filename; }
}
public string Type
{
get { return "Access Raster Catalog"; }
}
public void Dispose()
{
if (_layer != null)
{
_layer.Dispose();
_layer = null;
}
}
public new object Object
{
get
{
if (_layer == null)
{
try
{
RasterFile dataset = new RasterFile();
_layer = (ImageCatalogLayer)dataset.AddRasterFile(_filename);
if (!_layer.isValid)
{
_layer.Dispose();
_layer = null;
}
}
catch { _layer = null; }
}
return _layer;
}
}
public IExplorerObject CreateInstanceByFullName(string FullName)
{
return CreateInstance(FullName);
}
public IExplorerFileObject CreateInstance(string filename)
{
try
{
if (!(new FileInfo(filename).Exists)) return null;
}
catch { return null; }
return new RasterCatalogExplorerObject(filename);
}
#endregion
}
*/
[gView.Framework.system.RegisterPlugIn("FD8B1495-5D9D-4e97-B640-BFEAC2C4DD4B")]
public class RasterPyramidExplorerObject : ExplorerObjectCls, IExplorerFileObject
{
private IExplorerIcon _icon = new RasterIcon();
private string _filename = "";
private PyramidFileClass _class = null;
public RasterPyramidExplorerObject() : base(null, typeof(PyramidFileClass), 2) { }
public RasterPyramidExplorerObject(IExplorerObject parent, string filename)
: base(parent, typeof(PyramidFileClass), 2)
{
_filename = filename;
}
#region IExplorerFileObject Members
public string Filter
{
get { return "*.jpg.mdb|*.png.mdb|*.tif.mdb"; }
}
public IExplorerIcon Icon
{
get
{
return _icon;
}
}
#endregion
#region IExplorerObject Members
public string Name
{
get
{
try
{
FileInfo fi = new FileInfo(_filename);
return fi.Name;
}
catch { return ""; }
}
}
public string FullName
{
get { return _filename; }
}
public string Type
{
get { return "Raster Pyramid File"; }
}
public void Dispose()
{
if (_class != null)
{
_class.EndPaint(null);
_class = null;
}
}
public new object Object
{
get
{
if (_class == null)
{
try
{
RasterFileDataset dataset = new RasterFileDataset();
IRasterLayer layer = (IRasterLayer)dataset.AddRasterFile(_filename);
if (layer != null && layer.Class is PyramidFileClass)
{
_class = (PyramidFileClass)layer.Class;
if (!_class.isValid)
{
_class.EndPaint(null);
_class = null;
}
}
}
catch { return _class; }
}
return _class;
}
}
public IExplorerObject CreateInstanceByFullName(IExplorerObject parent, string FullName)
{
return CreateInstance(parent, FullName);
}
public IExplorerFileObject CreateInstance(IExplorerObject parent, string filename)
{
try
{
if (!(new FileInfo(filename)).Exists) return null;
}
catch { return null; }
return new RasterPyramidExplorerObject(parent, filename);
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
try
{
FileInfo fi = new FileInfo(FullName);
if (!fi.Exists) return null;
RasterPyramidExplorerObject rObject = new RasterPyramidExplorerObject(null, FullName);
if (rObject.Object is PyramidFileClass)
{
cache.Append(rObject);
return rObject;
}
return null;
}
catch
{
return null;
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("6F0051F0-F3C7-4eee-BE4B-45340F684FAA")]
public class RasterFileExplorerObject : ExplorerObjectCls, IExplorerFileObject
{
private IExplorerIcon _icon = new RasterIcon();
private string _filename = "";
private IRasterClass _class = null;
public RasterFileExplorerObject() : base(null, typeof(IRasterClass), 2) { }
private RasterFileExplorerObject(IExplorerObject parent, string filename)
: base(parent, typeof(IRasterClass), 2)
{
_filename = filename;
}
#region IExplorerFileObject Members
public string Filter
{
get
{
//return "*.jpg|*.png|*.tif|*.tiff|*.pyc|*.sid|*.jp2";
return "*.jpg|*.png|*.pyc|*.sid|*.jp2";
}
}
public IExplorerIcon Icon
{
get
{
return _icon;
}
}
#endregion
#region IExplorerObject Members
public string Name
{
get
{
try
{
FileInfo fi = new FileInfo(_filename);
return fi.Name;
}
catch { return ""; }
}
}
public string FullName
{
get { return _filename; }
}
public string Type
{
get { return "Raster File"; }
}
public void Dispose()
{
if (_class != null)
{
_class.EndPaint(null);
_class = null;
}
}
public new object Object
{
get
{
if (_class == null)
{
try
{
RasterFileDataset dataset = new RasterFileDataset();
IRasterLayer layer = (IRasterLayer)dataset.AddRasterFile(_filename);
if (layer != null && layer.Class is IRasterClass)
{
_class = layer.Class as IRasterClass;
if (_class is RasterFileClass)
{
if (!((RasterFileClass)_class).isValid)
{
_class.EndPaint(null);
_class = null;
}
}
if (_class is PyramidFile)
{
if (!((PyramidFile)_class).isValid)
{
_class.EndPaint(null);
_class = null;
}
}
}
}
catch { return _class; }
}
return _class;
}
}
public IExplorerObject CreateInstanceByFullName(IExplorerObject parent, string FullName)
{
return CreateInstance(parent, FullName);
}
public IExplorerFileObject CreateInstance(IExplorerObject parent, string filename)
{
try
{
if (!(new FileInfo(filename)).Exists) return null;
}
catch { return null; }
return new RasterFileExplorerObject(parent, filename);
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
try
{
FileInfo fi = new FileInfo(FullName);
if (!fi.Exists) return null;
RasterPyramidExplorerObject rObject = new RasterPyramidExplorerObject(null, FullName);
if (rObject.Object is IRasterClass)
{
cache.Append(rObject);
return rObject;
}
return null;
}
catch
{
return null;
}
}
#endregion
}
internal class RasterIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("5D01CC9D-1424-46e3-AA22-7282969B7062"); }
}
public System.Drawing.Image Image
{
get { return (new Icons()).imageList1.Images[0]; }
}
#endregion
}
}
| |
using System;
namespace Library_Project
{
enum Type {Adult, Child, Dvd, Videotape}
public class Book
{
int bookID;
string authorLastName;
string authorFirstName;
string title;
string callNum;
int mediaType;
int userID;
DateTime dueDate;
public Book(int book_ID, string authLastName, string authFirstName, string _Title, string callNumber, int medType)
{
bookID = book_ID;
authorLastName = authLastName;
authorFirstName = authFirstName;
title = _Title;
callNum = callNumber;
mediaType = medType;
userID = -1;
}//end constructor
public void checkIn()
{
if (isCheckedOut())
{
userID = -1;
dueDate = DateTime.MinValue;
}
}//end checkIn
public DateTime checkOut (int user_ID, DateTime today)
{
int days = 0; //days until due date
userID = user_ID;
switch (mediaType)
{
case (int)Type.Adult:
days = 14;
break;
case (int)Type.Child:
days =7;
break;
case (int)Type.Dvd:
days = 2;
break;
case (int)Type.Videotape:
days = 3;
break;
}//end switch
dueDate = today.AddDays(days);
return dueDate;
}//end checkOut
public bool isCheckedOut()
{
if (userID == -1)
{
return false;
}
else
{
return true;
}
}//end isCheckedOut
public bool isOverDue(DateTime today)
{
if(isCheckedOut() && dueDate < today) //if the book is checked out and if we've passed the due date then it is overdue
{
return true;
}
else //if not then it's not overdue
{
return false;
}
}//end isOverDue
public int getBookID()
{
return bookID;
}//end getBookID
public int getUserID()
{
return userID;
}//end getUserID;
public int getMediaType()
{
return mediaType;
}//end getMediaType
public DateTime getDueDate()
{
return dueDate;
}
public string getFirstName()
{
return authorFirstName;
}
public string getLastName()
{
return authorLastName;
}
public string getTitle()
{
return title;
}
public string getCall()
{
return callNum;
}
public override string ToString()
{
string type = null;
switch (mediaType)
{
case 0:
type = "Adult";
break;
case 1:
type = "Childrens";
break;
case 2:
type = "DVD";
break;
case 3:
type = "Videotape";
break;
}
if (isCheckedOut())
{
return (String.Format("{0} {1}, {2} {3} {4} {5} Status: Checked Out {6} {7}\n", bookID, authorLastName, authorFirstName, title, callNum, type, userID, dueDate));
}
else
{
return (String.Format("{0} {1}, {2} {3} {4} {5} Status: Checked In\n", bookID, authorLastName, authorFirstName, title, callNum, type));
}
}// end print override
}//end Book class
public class User
{
int userID;
string lastName;
string firstName;
int userType;
int items;
Book[] books = new Book[6];
public User(int uID, string lName, string fName, int uType)
{
userID = uID;
lastName = lName;
firstName = fName;
userType = uType;
items = 0;
}//end constructor
public bool isChild()
{
if (userType == (int)Type.Child)
{
return true;
}
else
{
return false;
}
}//end isChild
public int getItemCount()
{
return items;
}//end getItemCount
public void addBook(Book book)
{
books[items] = book;
items++;
}//end addBook
public void removeBook(int bookID)
{
bool found = false;
for (int index = 0; index < items; index++)
{
if (!found)//if we haven't located the book in the array then keep looking for it
{
if (bookID == books[index].getBookID())
{
found = true;
if (index < items - 1) //if its not the last book in the list we want to move the books after it up a space, so this starts the process
{
books[index] = books[index + 1];
}
else//if it's the last one in the list we'll just set it to null
{
books[index] = null;
}
}
}
else
{
if (index < items - 1) //if its not the last book in the list we want to move the books after it up a space
{
books[index] = books[index + 1];
}
else//if it's the last one in the list we'll just set it to null
{
books[index] = null;
}
}
}//end for loop
if (!found)
{
//write message book not found***
}
else
{
items--;
}
}//end removeBook
public string[] listBooks()
{
string[] str = new string[items];
if (items == 0)
{
string[] strtemp = new string[1];
strtemp[0] ="No books currently checked out";
return strtemp;
}
else
{
for (int index = 0; index < items; index++)
{
str[index] = books[index].ToString();
}
return str;
}
}//end listBooks
public override string ToString()
{
if(isChild())
return (String.Format("{0} {1}, {2} {3}", userID, lastName, firstName, "CHILD", items));
else
return (String.Format("{0} {1}, {2} {3}", userID, lastName, firstName, "ADULT", items));
}//end ToString overrider
public int getUserID()
{
return userID;
}//end getUserID
public int getUserType()
{
return userType;
}//end getType
public string getUserLastName()
{
return lastName;
}
public string getUserFirstName()
{
return firstName;
}
}//end user class
public class Library
{
const int CHILD_MAX = 3;
const int ADULT_MAX = 6;
const int ARRAY_MAX = 100;
Book[] books;
User[] users;
DateTime today;
User currentUser;
int bookCap;
int userCap;
public Library()
{
books = new Book[ARRAY_MAX];
users = new User[ARRAY_MAX];
today = DateTime.Now;
bookCap = 0;
userCap = 0;
}//end constructor
public DateTime getToday()
{
return today;
}
public string checkIn(int bookID)
{
string name;
name = "";
bool found = false;
for (int index = 0; index < bookCap; index++)
{
if (bookID == books[index].getBookID()) //if we find the book ID in the list of books then check it in
{
found = true;
if (books[index].isCheckedOut()) //if the book is checked out then checkit back in
{
for (int userIndex = 0; userIndex < userCap; userIndex++)//find the user that has the book
{
if (books[index].getUserID() == users[userIndex].getUserID())
{
name = users[userIndex].getUserLastName();
users[userIndex].removeBook(bookID); //remove book from users list
break;
}
}
books[index].checkIn();
return "Checked In, From User:" + name;
}//end if checked out
else//if it's not checked out then relay message that it is not checked out
{
return "Book Never Checked Out";
}//end else
break;
}//end if
}//end for loop
if (!found) //if we went through the list and didn't find the bookID then it's not in our system, and not checked in
{
return "Book does not belong to library";
}
return "Book Error";
}//end checkIn
public string checkOut(int bookID, int userID, DateTime date)
{
int bookIndex = 0;
int userIndex = 0;
bool bookFound = false;
bool userFound = false;
for (int b = 0; b < bookCap; b++)
{
if (bookID == books[b].getBookID())
{
bookIndex = b;
bookFound = true;
break;//if found break and keep the index
}
}//end book for loop
if (!bookFound)
{
//write message book not found***
return "Book Not Found";
}//end if book not found
if (books[bookIndex].isCheckedOut())
{
//write message book checked out already***
return "Book Already Checked Out";
}//end is checked out test
for (int u = 0; u < userCap; u++)
{
if (userID == users[u].getUserID())
{
userFound = true;
userIndex = u;
break;//if found break and keep the index
}
}//end book for loop
if (!userFound)
{
//write message user not found***
return "User Not Found";
}//end user not found
if (users[userIndex].getUserType() == (int)Type.Child && books[bookIndex].getMediaType() != (int)Type.Child) //if the patron is a child and the book is not a children's book they can't check it out
{
//write message that user is a child and this is not a children's book***
return "User Is a child, this book is not a childrens book";
}//end child checking out non-children's media test
if (users[userIndex].getUserType() == (int)Type.Child && users[userIndex].getItemCount() >= CHILD_MAX)
{
//write message that user has reached check out limit***
return "User has reached max allowed books";
}//end child max test
if (users[userIndex].getItemCount() >= ADULT_MAX)
{
//write message that user has reached check out limit ***
return "User has reached max allowed books";
}//end adult max test
//if all checks pass then we can check out the book
users[userIndex].addBook(books[bookIndex]);
return "Book checked out, you have until: "+books[bookIndex].checkOut(userID, date).ToString()+" to return";
}//end checkOut
public void incrementDate()
{
today = today.AddDays(1);
}//end incrementDate
public string[] listAllBooks()
{
string[] str = new string[bookCap];
//str[0]= bookCap.ToString();
for(int b = 0; b < bookCap; b++)
{
str[b] = books[b].ToString();
}//end for loop
return str;
}//end listAllBooks
public string[] listOverdueBooks()
{
int i=0;
string[] str = new string[bookCap];
for (int b = 0; b < bookCap; b++)
{
if (books[b].isOverDue(today))
{
str[i] = books[b].ToString();
i++;
}
}//end for loop
return str;
}//end listOverdueBooks
public string[] listPatrons()
{
string[] str = new string[userCap];
//str[0]= bookCap.ToString();
for(int b = 0; b < userCap; b++)
{
str[b] = users[b].ToString();
}//end for loop
return str;
}//end listPartons
public string[] listPatronBooks(int userID)
{
bool found = false;
int uIndex = 0;
string[] str = new string[ADULT_MAX];
for (int u = 0; u < userCap; u++)
{
if(users[u].getUserID() == userID)
{
uIndex = u;
found = true;
break;
}
}//end for loop
if (found)
{
return users[uIndex].listBooks();
}// if found print out the users books
else
{
str[0] = "Patron not found";
return str;
}//if not found return string saying it wasn't found
}//end listPatronBooks
/// <summary>
/// Function checks to see if there is a duplicate in the system, if there is it returns error, else creates a new book object and returns success message
/// </summary>
/// <param name="bookID"></param>
/// <param name="lastName"></param>
/// <param name="firstName"></param>
/// <param name="title"></param>
/// <param name="callNumber"></param>
/// <param name="medType"></param>
/// <returns></returns>
public string addBook(int bookID, string lastName, string firstName, string title, string callNumber, int medType)
{
for (int index = 0; index < bookCap; index++)
{
if (bookID == books[index].getBookID())
{
return "Book ID already in use, please pick another";
}
}
Book newBook = new Book(bookID, lastName,firstName,title,callNumber,medType);
books[bookCap] = newBook;
bookCap++;
return "Book Added";
}//end addbook
public void removeBook(int bookID)
{
bool found = false;
for (int index = 0; index < bookCap; index++)
{
if (!found)//if we haven't located the book in the array then keep looking for it
{
if (bookID == books[index].getBookID())
{
found = true;
if (index < bookCap - 1) //if its not the last book in the list we want to move the books after it up a space, so this starts the process
{
books[index] = books[index + 1];
}
else//if it's the last one in the list we'll just set it to null
{
books[index] = null;
}
}
}
else
{
if (index < bookCap - 1) //if its not the last book in the list we want to move the books after it up a space
{
books[index] = books[index + 1];
}
else//if it's the last one in the list we'll just set it to null
{
books[index] = null;
}
}
}//end for loop
if (!found)
{
//write message book not found***
}
else
{
bookCap--;
}
}//end removeBook
/// <summary>
/// Function checks to see if there is a duplicate in the system, if there is it returns error, else creates a new user object and returns success message
/// </summary>
/// <param name="userID"></param>
/// <param name="lastName"></param>
/// <param name="firstName"></param>
/// <param name="uType"></param>
/// <returns></returns>
public string addUser(int userID, string lastName, string firstName, int uType)
{
for (int index = 0; index < userCap; index++)
{
if (userID == users[index].getUserID())
{
return "User ID already in use, please pick another";
}
}
User newUser = new User(userID, lastName, firstName, uType);
users[userCap] = newUser;
userCap++;
return "User Added";
}//end addUser
public void removeUser(int userID)
{
bool found = false;
for (int index = 0; index < userCap; index++)
{
if (!found)//if we haven't located the user in the array then keep looking for it
{
if (userID == users[index].getUserID())
{
found = true;
if (index < userCap - 1) //if its not the last user in the list we want to move the users after it up a space, so this starts the process
{
users[index] = users[index + 1];
}
else//if it's the last one in the list we'll just set it to null
{
users[index] = null;
}
}
}
else
{
if (index < userCap - 1) //if its not the last user in the list we want to move the users after it up a space
{
users[index] = users[index + 1];
}
else//if it's the last one in the list we'll just set it to null
{
users[index] = null;
}
}
}//end for loop
if (!found)
{
//write message user not found***
}
else
{
userCap--;
}
}//end remove user
public void quit()
{
}//end quit
public void advanceToDate(DateTime date)
{
today = date;
}//end advanceToDate
/// <summary>
/// uses the lastname and firstname fields to find a users id in the list of users.
/// </summary>
/// <param name="lastName"></param>
/// <param name="firstName"></param>
/// <returns></returns>
public int lookUpId(string lastName, string firstName)
{
for (int index = 0; index < userCap; index++)
{
if (users[index].getUserLastName() == lastName)
{
if (users[index].getUserFirstName() == firstName)
return users[index].getUserID();
}
}
return 0;
}
/// <summary>
/// uses title to find book id
/// </summary>
/// <param name="title"></param>
/// <returns></returns>
public int lookUpBook(string title)
{
for (int index = 0; index < bookCap; index++)
{
if (books[index].getTitle() == title)
return books[index].getBookID();
}
return 0;
}
public int getBookCap()
{
return bookCap;
}
public int getUserCap()
{
return userCap;
}
/// <summary>
/// creates a string array of all the media items and their characteristics in order to save them to a file.
/// </summary>
/// <returns></returns>
public string[] saveMedia()
{
string[] data = new string[bookCap];
for (int index = 0; index < bookCap; index++)
{
string bookId = books[index].getBookID().ToString();
string lastName = books[index].getLastName();
string firstName = books[index].getFirstName();
string title = books[index].getTitle();
string call = books[index].getCall();
string type = books[index].getMediaType().ToString();
if (books[index].getUserID() != -1)
{
string userId = books[index].getUserID().ToString();
string date = books[index].getDueDate().ToString();
data[index] = (String.Format("{0};{1};{2};{3};{4};{5};{6};{7}", bookId, lastName, firstName, title, call, type,userId,date));
}
else
{
data[index] = String.Format("{0};{1};{2};{3};{4};{5}", bookId, lastName, firstName, title, call,type);
}
}
return data;
}
/// <summary>
/// Creates a string array of all the media items and their characteristics in order to save them to a file.
/// </summary>
/// <returns></returns>
public string[] saveUsers()
{
string[] data = new string[userCap];
for (int index = 0; index<userCap; index++)
{
string userId = users[index].getUserID().ToString();
string lastName = users[index].getUserLastName();
string firstName = users[index].getUserFirstName();
string type;
if (users[index].isChild())
type = "1";
else
type = "0";
data[index] = String.Format("{0};{1};{2};{3}", userId, lastName, firstName, type);
}
return data;
}
}
}//end namespace Library
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using OSGeo.GDAL;
namespace DotSpatial.Data.Rasters.GdalExtension
{
/// <summary>
/// GDAL Image Source
/// </summary>
public class GdalImageSource
{
#region Fields
private Band _alpha;
private Band _blue;
private Dataset _dataset;
private string _fileName;
private Band _green;
private Band _red;
#endregion
#region Constructors
static GdalImageSource()
{
GdalConfiguration.ConfigureGdal();
}
/// <summary>
/// Initializes a new instance of the <see cref="GdalImageSource"/> class, and gets much of the header information without actually
/// reading any values from the file.
/// </summary>
/// <param name="fileName">The file name.</param>
public GdalImageSource(string fileName)
{
Filename = fileName;
ReadHeader();
}
/// <summary>
/// Initializes a new instance of the <see cref="GdalImageSource"/> class.
/// </summary>
public GdalImageSource()
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the bounds
/// </summary>
public RasterBounds Bounds { get; set; }
/// <summary>
/// Gets or sets the file name of the image source. If a relative path gets assigned it is changed to the absolute path including the file extension.
/// </summary>
public string Filename
{
get
{
return _fileName;
}
set
{
_fileName = Path.GetFullPath(value);
}
}
/// <summary>
/// Gets the total number of columns.
/// </summary>
public int NumColumns => Bounds?.NumColumns ?? 0;
/// <summary>
/// Gets the number of overviews, not counting the original image.
/// </summary>
/// <returns>The number of overviews.</returns>
public int NumOverviews { get; private set; }
/// <summary>
/// Gets the number of rows
/// </summary>
public int NumRows => Bounds?.NumRows ?? 0;
#endregion
#region Methods
/// <summary>
/// Closes the data source.
/// </summary>
public void Close()
{
_dataset.Dispose();
_dataset = null;
}
/// <summary>
/// Disposes the dataset.
/// </summary>
public void Dispose()
{
_dataset.Dispose();
_dataset = null;
}
/// <summary>
/// This returns the window of data as a bitmap.
/// </summary>
/// <param name="startRow">The zero based integer index of the first row (Y).</param>
/// <param name="startColumn">The zero based integer index of the first column (X).</param>
/// <param name="numRows">The number of rows to read.</param>
/// <param name="numColumns">The number of columns to read.</param>
/// <param name="overview">The integer overview. 0 for the original image. Each successive index divides the length and height in half. </param>
/// <returns>The bitmap representation for the specified portion of the raster.</returns>
public Bitmap GetBitmap(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
byte[] vals = ReadWindow(startRow, startColumn, numRows, numColumns, overview);
Bitmap bmp = new Bitmap(numRows, numColumns);
BitmapData bData = bmp.LockBits(new Rectangle(0, 0, numColumns, numRows), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
// int stride = bData.Stride;
Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
bmp.UnlockBits(bData);
return bmp;
}
/// <summary>
/// Gets the dimensions of the original (0) plus any overlays.
/// The overlays get smaller as the index gets larger.
/// </summary>
/// <returns>The sizes.</returns>
public Size[] GetSizes()
{
EnsureDatasetOpen();
_red = _dataset.GetRasterBand(1);
int numOverviews = _red.GetOverviewCount();
Debug.WriteLine("Num overviews:" + numOverviews);
if (numOverviews == 0) return null;
Size[] result = new Size[numOverviews + 1];
result[0] = new Size(_red.XSize, _red.YSize);
for (int i = 0; i < numOverviews; i++)
{
Band temp = _red.GetOverview(i);
result[i + 1] = new Size(temp.XSize, temp.YSize);
}
return result;
}
/// <summary>
/// Returns the data from the file in the form of ARGB bytes, regardless of how the image
/// data is actually stored in the file.
/// </summary>
/// <param name="startRow">The zero based integer index of the first row (Y)</param>
/// <param name="startColumn">The zero based integer index of the first column (X)</param>
/// <param name="numRows">The number of rows to read</param>
/// <param name="numColumns">The number of columns to read</param>
/// <param name="overview">The integer overview. 0 for the original image. Each successive index divides the length and height in half. </param>
/// <returns>A Byte of values in ARGB order and in row-major raster-scan sequence</returns>
public byte[] ReadWindow(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
EnsureDatasetOpen();
_red = _dataset.GetRasterBand(1);
byte[] result = null;
switch (_red.GetRasterColorInterpretation())
{
case ColorInterp.GCI_PaletteIndex:
result = ReadPaletteBuffered(startRow, startColumn, numRows, numColumns, overview);
break;
case ColorInterp.GCI_GrayIndex:
result = ReadGrayIndex(startRow, startColumn, numRows, numColumns, overview);
break;
case ColorInterp.GCI_RedBand:
result = ReadRgb(startRow, startColumn, numRows, numColumns, overview);
break;
case ColorInterp.GCI_AlphaBand:
result = ReadArgb(startRow, startColumn, numRows, numColumns, overview);
break;
}
return result;
}
private void EnsureDatasetOpen()
{
if (_dataset == null)
{
_dataset = Helpers.Open(Filename);
}
}
private byte[] ReadArgb(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
if (_dataset.RasterCount < 4)
{
throw new GdalException("ARGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
}
_alpha = _red;
_red = _dataset.GetRasterBand(2);
_green = _dataset.GetRasterBand(3);
_blue = _dataset.GetRasterBand(4);
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
_alpha = _alpha.GetOverview(overview - 1);
_green = _green.GetOverview(overview - 1);
_blue = _blue.GetOverview(overview - 1);
}
int width = numColumns;
int height = numRows;
byte[] a = new byte[width * height];
byte[] r = new byte[width * height];
byte[] g = new byte[width * height];
byte[] b = new byte[width * height];
_alpha.ReadRaster(startColumn, startRow, width, height, a, width, height, 0, 0);
_red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
_green.ReadRaster(startColumn, startRow, width, height, g, width, height, 0, 0);
_blue.ReadRaster(startColumn, startRow, width, height, b, width, height, 0, 0);
byte[] vals = new byte[width * height * 4];
const int Bpp = 4;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
vals[(row * width * Bpp) + (col * Bpp)] = b[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 1] = g[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 2] = r[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 3] = a[(row * width) + col];
}
}
return vals;
}
private byte[] ReadGrayIndex(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
int width = numColumns;
int height = numRows;
byte[] r = new byte[width * height];
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
}
_red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
byte[] vals = new byte[width * height * 4];
const int Bpp = 4;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
vals[(row * width * Bpp) + (col * Bpp)] = r[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 1] = r[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 2] = r[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 3] = 255;
}
}
return vals;
}
/// <summary>
/// Gets the size of the whole image, but doesn't keep the image open unless it was already open.
/// </summary>
private void ReadHeader()
{
EnsureDatasetOpen();
double[] test = new double[6];
_dataset.GetGeoTransform(test);
test = new AffineTransform(test).TransfromToCorner(0.5, 0.5); // shift origin by half a cell
Bounds = new RasterBounds(_dataset.RasterYSize, _dataset.RasterXSize, test);
_red = _dataset.GetRasterBand(1);
NumOverviews = _red.GetOverviewCount();
Close();
}
/// <summary>
/// Returns ARGB 32 bpp regardless of the fact that the original is palette buffered.
/// </summary>
/// <param name="startRow">The start row.</param>
/// <param name="startColumn">The start column.</param>
/// <param name="numRows">The number of rows.</param>
/// <param name="numColumns">The number of columns.</param>
/// <param name="overview">The overview.</param>
/// <returns>The data that was read.</returns>
private byte[] ReadPaletteBuffered(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
ColorTable ct = _red.GetRasterColorTable();
if (ct == null)
{
throw new GdalException("Image was stored with a palette interpretation but has no color table.");
}
if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
{
throw new GdalException("Only RGB palette interpreation is currently supported by this plugin, " + ct.GetPaletteInterpretation() + " is not supported.");
}
int width = numRows;
int height = numColumns;
byte[] r = new byte[width * height];
_red.ReadRaster(startColumn, startRow, numColumns, numRows, r, width, height, 0, 0);
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
}
const int Bpp = 4;
byte[] vals = new byte[width * height * 4];
byte[][] colorTable = new byte[256][];
for (int i = 0; i < 255; i++)
{
ColorEntry ce = ct.GetColorEntry(i);
colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 };
}
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
Array.Copy(colorTable[r[col + (row * width)]], 0, vals, (row * width) + (col * Bpp), 4);
}
}
return vals;
}
private byte[] ReadRgb(int startRow, int startColumn, int numRows, int numColumns, int overview)
{
if (_dataset.RasterCount < 3)
{
throw new GdalException("RGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
}
_green = _dataset.GetRasterBand(2);
_blue = _dataset.GetRasterBand(3);
if (overview > 0)
{
_red = _red.GetOverview(overview - 1);
_green = _green.GetOverview(overview - 1);
_blue = _blue.GetOverview(overview - 1);
}
int width = numColumns;
int height = numRows;
byte[] r = new byte[width * height];
byte[] g = new byte[width * height];
byte[] b = new byte[width * height];
_red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
_green.ReadRaster(startColumn, startRow, width, height, g, width, height, 0, 0);
_blue.ReadRaster(startColumn, startRow, width, height, b, width, height, 0, 0);
byte[] vals = new byte[width * height * 4];
const int Bpp = 4;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
vals[(row * width * Bpp) + (col * Bpp)] = b[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 1] = g[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 2] = r[(row * width) + col];
vals[(row * width * Bpp) + (col * Bpp) + 3] = 255;
}
}
return vals;
}
#endregion
}
}
| |
#region License
// Copyright 2010 John Sheehan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using RestSharp.Serializers;
namespace RestSharp
{
public interface IRestRequest
{
/// <summary>
/// Always send a multipart/form-data request - even when no Files are present.
/// </summary>
bool AlwaysMultipartFormData { get; set; }
/// <summary>
/// Serializer to use when writing JSON request bodies. Used if RequestFormat is Json.
/// By default the included JsonSerializer is used (currently using JSON.NET default serialization).
/// </summary>
ISerializer JsonSerializer { get; set; }
/// <summary>
/// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml.
/// By default the included XmlSerializer is used.
/// </summary>
ISerializer XmlSerializer { get; set; }
/// <summary>
/// Set this to write response to Stream rather than reading into memory.
/// </summary>
Action<Stream> ResponseWriter { get; set; }
/// <summary>
/// Container of all HTTP parameters to be passed with the request.
/// See AddParameter() for explanation of the types of parameters that can be passed
/// </summary>
List<Parameter> Parameters { get; }
/// <summary>
/// Container of all the files to be uploaded with the request.
/// </summary>
List<FileParameter> Files { get; }
/// <summary>
/// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS
/// Default is GET
/// </summary>
Method Method { get; set; }
/// <summary>
/// The Resource URL to make the request against.
/// Tokens are substituted with UrlSegment parameters and match by name.
/// Should not include the scheme or domain. Do not include leading slash.
/// Combined with RestClient.BaseUrl to assemble final URL:
/// {BaseUrl}/{Resource} (BaseUrl is scheme + domain, e.g. http://example.com)
/// </summary>
/// <example>
/// // example for url token replacement
/// request.Resource = "Products/{ProductId}";
/// request.AddParameter("ProductId", 123, ParameterType.UrlSegment);
/// </example>
string Resource { get; set; }
/// <summary>
/// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml.
/// By default XmlSerializer is used.
/// </summary>
DataFormat RequestFormat { get; set; }
/// <summary>
/// Used by the default deserializers to determine where to start deserializing from.
/// Can be used to skip container or root elements that do not have corresponding deserialzation targets.
/// </summary>
string RootElement { get; set; }
/// <summary>
/// Used by the default deserializers to explicitly set which date format string to use when parsing dates.
/// </summary>
string DateFormat { get; set; }
/// <summary>
/// Used by XmlDeserializer. If not specified, XmlDeserializer will flatten response by removing namespaces from element names.
/// </summary>
string XmlNamespace { get; set; }
/// <summary>
/// In general you would not need to set this directly. Used by the NtlmAuthenticator.
/// </summary>
ICredentials Credentials { get; set; }
/// <summary>
/// Timeout in milliseconds to be used for the request. This timeout value overrides a timeout set on the RestClient.
/// </summary>
int Timeout { get; set; }
/// <summary>
/// The number of milliseconds before the writing or reading times out. This timeout value overrides a timeout set on the RestClient.
/// </summary>
int ReadWriteTimeout { get; set; }
/// <summary>
/// How many attempts were made to send this Request?
/// </summary>
/// <remarks>
/// This Number is incremented each time the RestClient sends the request.
/// Useful when using Asynchronous Execution with Callbacks
/// </remarks>
int Attempts { get; }
/// <summary>
/// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running)
/// will be sent along to the server. The default is false.
/// </summary>
bool UseDefaultCredentials { get; set; }
#if FRAMEWORK
/// <summary>
/// Adds a file to the Files collection to be included with a POST or PUT request
/// (other methods do not support file uploads).
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="path">Full path to file to upload</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
IRestRequest AddFile(string name, string path, string contentType = null);
/// <summary>
/// Adds the bytes to the Files collection with the specified file name and content type
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="bytes">The file data</param>
/// <param name="fileName">The file name to use for the uploaded file</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType = null);
/// <summary>
/// Adds the bytes to the Files collection with the specified file name and content type
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="writer">A function that writes directly to the stream. Should NOT close the stream.</param>
/// <param name="fileName">The file name to use for the uploaded file</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
IRestRequest AddFile(string name, Action<Stream> writer, string fileName, string contentType = null);
/// <summary>
/// Add bytes to the Files collection as if it was a file of specific type
/// </summary>
/// <param name="name">A form parameter name</param>
/// <param name="bytes">The file data</param>
/// <param name="filename">The file name to use for the uploaded file</param>
/// <param name="contentType">Specific content type. Es: application/x-gzip </param>
/// <returns></returns>
IRestRequest AddFileBytes(string name, byte[] bytes, string filename, string contentType = "application/x-gzip");
#endif
/// <summary>
/// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer
/// The default format is XML. Change RequestFormat if you wish to use a different serialization format.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <param name="xmlNamespace">The XML namespace to use when serializing</param>
/// <returns>This request</returns>
IRestRequest AddBody(object obj, string xmlNamespace);
/// <summary>
/// Serializes obj to data format specified by RequestFormat and adds it to the request body.
/// The default format is XML. Change RequestFormat if you wish to use a different serialization format.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
IRestRequest AddBody(object obj);
/// <summary>
/// Serializes obj to JSON format and adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
IRestRequest AddJsonBody(object obj);
/// <summary>
/// Serializes obj to XML format and adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
IRestRequest AddXmlBody(object obj);
/// <summary>
/// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer
/// Serializes obj to XML format and passes xmlNamespace then adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <param name="xmlNamespace">The XML namespace to use when serializing</param>
/// <returns>This request</returns>
IRestRequest AddXmlBody(object obj, string xmlNamespace);
/// <summary>
/// Calls AddParameter() for all public, readable properties specified in the includedProperties list
/// </summary>
/// <example>
/// request.AddObject(product, "ProductId", "Price", ...);
/// </example>
/// <param name="obj">The object with properties to add as parameters</param>
/// <param name="includedProperties">The names of the properties to include</param>
/// <returns>This request</returns>
IRestRequest AddObject(object obj, params string[] includedProperties);
/// <summary>
/// Calls AddParameter() for all public, readable properties of obj
/// </summary>
/// <param name="obj">The object with properties to add as parameters</param>
/// <returns>This request</returns>
IRestRequest AddObject(object obj);
/// <summary>
/// Add the parameter to the request
/// </summary>
/// <param name="p">Parameter to add</param>
/// <returns></returns>
IRestRequest AddParameter(Parameter p);
/// <summary>
/// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <returns>This request</returns>
IRestRequest AddParameter(string name, object value);
/// <summary>
/// Adds a parameter to the request. There are five types of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - Cookie: Adds the name/value pair to the HTTP request's Cookies collection
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <param name="type">The type of parameter to add</param>
/// <returns>This request</returns>
IRestRequest AddParameter(string name, object value, ParameterType type);
/// <summary>
/// Adds a parameter to the request. There are five types of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - Cookie: Adds the name/value pair to the HTTP request's Cookies collection
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <param name="contentType">Content-Type of the parameter</param>
/// <param name="type">The type of parameter to add</param>
/// <returns>This request</returns>
IRestRequest AddParameter(string name, object value, string contentType, ParameterType type);
/// <summary>
/// Shortcut to AddParameter(name, value, HttpHeader) overload
/// </summary>
/// <param name="name">Name of the header to add</param>
/// <param name="value">Value of the header to add</param>
/// <returns></returns>
IRestRequest AddHeader(string name, string value);
/// <summary>
/// Shortcut to AddParameter(name, value, Cookie) overload
/// </summary>
/// <param name="name">Name of the cookie to add</param>
/// <param name="value">Value of the cookie to add</param>
/// <returns></returns>
IRestRequest AddCookie(string name, string value);
/// <summary>
/// Shortcut to AddParameter(name, value, UrlSegment) overload
/// </summary>
/// <param name="name">Name of the segment to add</param>
/// <param name="value">Value of the segment to add</param>
/// <returns></returns>
IRestRequest AddUrlSegment(string name, string value);
/// <summary>
/// Shortcut to AddParameter(name, value, QueryString) overload
/// </summary>
/// <param name="name">Name of the parameter to add</param>
/// <param name="value">Value of the parameter to add</param>
/// <returns></returns>
IRestRequest AddQueryParameter(string name, string value);
/// <summary>
/// Shortcut to AddParameter(name, value, Matrix) overload
/// </summary>
/// <param name="name">Name of the parameter to add</param>
/// <param name="value">Value of the parameter to add</param>
/// <returns></returns>
IRestRequest AddMatrixParameter(string name, string value);
Action<IRestResponse> OnBeforeDeserialization { get; set; }
void IncreaseNumAttempts();
}
}
| |
/*******************************************************************************
*
* Copyright (C) 2013-2014 Frozen North Computing
*
* 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.Drawing;
namespace FrozenNorth.OpenGL.FN2D
{
public class FN2DMessage : FN2DControl
{
private const int MARGIN = 20;
private const int PADDING = 20;
private const int TITLE_MARGIN = 4;
private const int TITLE_HEIGHT = 30;
private FN2DLabel titleLabel, messageLabel;
public FN2DMessage(FN2DCanvas canvas, string title, string message, FN2DButton[] buttons)
: base(canvas)
{
Initialize(title, message, buttons);
}
public FN2DMessage(FN2DCanvas canvas, string title, string message, FN2DMessageButtons buttons)
: base(canvas)
{
FN2DButton[] btns = null;
switch (buttons)
{
case FN2DMessageButtons.OK:
btns = new FN2DButton[1];
btns[0] = CreateButton("OK", Color.LightGreen, Color.Green, HandleOKButtonTapped);
break;
case FN2DMessageButtons.Cancel:
btns = new FN2DButton[1];
btns[0] = CreateButton("Cancel", Color.Red, Color.DarkRed, HandleCancelButtonTapped);
break;
case FN2DMessageButtons.OKCancel:
btns = new FN2DButton[2];
btns[0] = CreateButton("OK", Color.LightGreen, Color.Green, HandleOKButtonTapped);
btns[1] = CreateButton("Cancel", Color.Red, Color.DarkRed, HandleCancelButtonTapped);
break;
case FN2DMessageButtons.YesNo:
btns = new FN2DButton[2];
btns[0] = CreateButton("Yes", Color.LightGreen, Color.Green, HandleYesButtonTapped);
btns[1] = CreateButton("No", Color.Red, Color.DarkRed, HandleNoButtonTapped);
break;
case FN2DMessageButtons.YesNoCancel:
btns = new FN2DButton[3];
btns[0] = CreateButton("Yes", Color.LightGreen, Color.Green, HandleYesButtonTapped);
btns[1] = CreateButton("No", Color.DodgerBlue, Color.DarkBlue, HandleNoButtonTapped);
btns[2] = CreateButton("Cancel", Color.Red, Color.DarkRed, HandleCancelButtonTapped);
break;
}
Initialize(title, message, btns);
}
public FN2DMessage(FN2DCanvas canvas, string title, string message)
: this(canvas, title, message, null)
{
}
public FN2DMessage(FN2DCanvas canvas, string message)
: this(canvas, null, message, null)
{
}
/// <summary>
/// Frees unmanaged resources and calls Dispose() on the member objects.
/// </summary>
protected override void Dispose(bool disposing)
{
titleLabel = null;
messageLabel = null;
base.Dispose(disposing);
}
private void Initialize(string title, string message, FN2DButton[] buttons)
{
// check the parameters
if (string.IsNullOrEmpty(title)) title = FN2DCanvas.DefaultMessageTitle;
if (string.IsNullOrEmpty(message)) message = "Message";
if (buttons == null || buttons.Length == 0)
{
buttons = new FN2DButton[] { CreateButton("OK", Color.Blue, Color.DarkBlue, HandleOKButtonTapped) };
}
// configure the background
TopColor = Color.LightGray;
BottomColor = Color.DarkGray;
CornerRadius = 5;
// get the width of the buttons
int buttonsWidth = -PADDING;
foreach (FN2DButton button in buttons)
{
buttonsWidth += button.Width + PADDING;
}
// create the title label
titleLabel = new FN2DLabel(canvas, title);
titleLabel.Font = canvas.GetTitleFont(18, true);
titleLabel.AutoSize = true;
int width = (int)Math.Max(buttonsWidth, titleLabel.Width);
titleLabel.AutoSize = false;
titleLabel.TopColor = Color.DarkGray;
titleLabel.BottomColor = Color.Gray;
titleLabel.CornerRadius = 5;
Add(titleLabel);
// create the message label
messageLabel = new FN2DLabel(canvas, message);
messageLabel.Font = canvas.GetFont(14, false);
messageLabel.TextColor = Color.Black;
messageLabel.AutoSize = true;
Add(messageLabel);
if (messageLabel.Width > width)
{
width = messageLabel.Width;
}
width += MARGIN * 2;
// position the controls
titleLabel.Frame = new Rectangle(TITLE_MARGIN, TITLE_MARGIN, width - TITLE_MARGIN * 2, TITLE_HEIGHT);
int y = TITLE_HEIGHT + TITLE_MARGIN + PADDING;
messageLabel.Frame = new Rectangle(new Point((width - messageLabel.Width) / 2, y), messageLabel.Size);
y += messageLabel.Height + PADDING;
int x = (width - buttonsWidth) / 2;
int height = 0;
foreach (FN2DButton button in buttons)
{
button.Location = new Point(x, y);
Add(button);
x += button.Width + PADDING;
if (button.Height > height)
{
height = button.Height;
}
}
y += height + MARGIN;
Size = new Size(width, y);
}
private FN2DButton CreateButton(string title, Color topColor, Color bottomColor, EventHandler tappedHandler)
{
FN2DButton button = new FN2DButton(canvas, new Rectangle(0, 0, 100, 44), topColor, bottomColor, title);
button.Tapped = tappedHandler;
return button;
}
private void HandleOKButtonTapped(object sender, EventArgs e)
{
canvas.HideModal();
}
private void HandleCancelButtonTapped(object sender, EventArgs e)
{
canvas.HideModal();
}
private void HandleYesButtonTapped(object sender, EventArgs e)
{
canvas.HideModal();
}
private void HandleNoButtonTapped(object sender, EventArgs e)
{
canvas.HideModal();
}
}
/// <summary>
/// Standard buttons supported by FN2DMessage.
/// </summary>
public enum FN2DMessageButtons
{
OK = 0,
Cancel = 1,
OKCancel = 2,
YesNo = 3,
YesNoCancel = 4,
}
}
| |
using nHydrate.Generator.Common.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace nHydrate.DataImport.SqlClient
{
/// <summary>
/// Summary description for DbHelper.
/// </summary>
public class DatabaseHelper : IDatabaseHelper
{
internal DatabaseHelper()
{
}
#region Public Methods
public bool TestConnectionString(string connectString)
{
var valid = false;
var conn = new System.Data.SqlClient.SqlConnection();
try
{
conn.ConnectionString = connectString;
conn.Open();
valid = true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
valid = false;
}
finally
{
conn.Close();
}
return valid;
}
public DataTable GetStaticData(string connectionString, Entity entity)
{
if (entity == null) return null;
var auditFields = new List<SpecialField>();
var importDomain = new ImportDomain();
var dbEntity = importDomain.Import(connectionString, auditFields).EntityList.FirstOrDefault(x => x.Name == entity.Name);
if (dbEntity == null) return null;
//Get the columns that actually exist in the database
var columnList = dbEntity.FieldList;
var fieldList = entity.FieldList.Where(x => !x.DataType.IsBinaryType() && x.DataType != SqlDbType.Timestamp).ToList();
//Load the static data grid
var sb = new StringBuilder();
sb.Append("SELECT ");
foreach (var field in fieldList)
{
if (columnList.Count(x => x.Name.Match(field.Name)) == 1)
{
sb.Append("[" + field.Name + "]");
}
else
{
sb.Append("'' AS [" + field.Name + "]");
}
if (fieldList.ToList().IndexOf(field) < fieldList.Count - 1) sb.Append(",");
}
sb.AppendLine(" FROM [" + entity.Name + "]");
var ds = DatabaseHelper.ExecuteDataset(connectionString, sb.ToString());
if (ds.Tables.Count == 0) return null;
return ds.Tables[0];
}
#endregion
#region SQL
internal static DataSet ExecuteDataset(string connectionString, string sql)
{
var retVal = new DataSet();
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand
{
CommandType = CommandType.Text,
CommandText = sql,
Connection = connection,
CommandTimeout = 300
};
var da = new SqlDataAdapter();
da.SelectCommand = (SqlCommand)command;
try
{
da.Fill(retVal);
connection.Open();
}
catch (Exception /*ignored*/)
{
throw;
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
return retVal;
}
internal static int ExecuteNonQuery(IDbCommand command)
{
var cmd = (SqlCommand)command;
return cmd.ExecuteNonQuery();
}
internal static IDbConnection GetConnection(string connectionString)
{
SqlConnection.ClearAllPools(); //If we do NOT do this, sometimes we get pool errors
var sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = connectionString;
return sqlConnection;
}
internal static SqlDataReader ExecuteReader(IDbConnection connection, CommandType cmdType, string stmt)
{
var cmd = GetCommand();
cmd.CommandText = stmt;
cmd.CommandType = cmdType;
cmd.CommandTimeout = 300;
if (connection.State == ConnectionState.Closed)
connection.Open();
cmd.Connection = connection;
return (SqlDataReader)cmd.ExecuteReader();
}
internal static SqlDataReader ExecuteReader(string connectString, CommandType cmdType, string stmt)
{
try
{
var connection = GetConnection(connectString);
connection.Open();
return ExecuteReader(connection, cmdType, stmt);
}
catch (Exception /*ignored*/)
{
throw;
}
}
internal static IDbCommand GetCommand() => new SqlCommand { CommandType = CommandType.StoredProcedure };
internal static void Fill(IDbDataAdapter da, DataTable dt)
{
var sqlDa = (SqlDataAdapter)da;
sqlDa.Fill(dt);
}
internal static void Update(IDbDataAdapter da, DataTable dt)
{
var sqlDa = (SqlDataAdapter)da;
if (dt != null && dt.Rows.Count > 0)
{
try
{
sqlDa.Update(dt);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
throw;
}
}
}
internal static void Update(IDbDataAdapter da, DataRow[] rows)
{
var sqlDa = (SqlDataAdapter)da;
if (rows.Length > 0)
{
try
{
sqlDa.Update(rows);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
throw;
}
}
}
#endregion
#region Methods
internal static bool IsValidSQLDataType(nHydrate.DataImport.SqlNativeTypes nativeType)
{
switch (nativeType)
{
case SqlNativeTypes.bigint:
case SqlNativeTypes.binary:
case SqlNativeTypes.bit:
case SqlNativeTypes.@char:
case SqlNativeTypes.date:
case SqlNativeTypes.datetime:
case SqlNativeTypes.datetime2:
case SqlNativeTypes.datetimeoffset:
case SqlNativeTypes.@decimal:
case SqlNativeTypes.@float:
//SqlNativeTypes.geography
//SqlNativeTypes.geometry
//SqlNativeTypes.hierarchyid
case SqlNativeTypes.image:
case SqlNativeTypes.@int:
case SqlNativeTypes.money:
case SqlNativeTypes.nchar:
case SqlNativeTypes.ntext:
case SqlNativeTypes.numeric:
case SqlNativeTypes.nvarchar:
case SqlNativeTypes.real:
case SqlNativeTypes.smalldatetime:
case SqlNativeTypes.smallint:
case SqlNativeTypes.smallmoney:
case SqlNativeTypes.sql_variant:
//SqlNativeTypes.sysname
case SqlNativeTypes.text:
case SqlNativeTypes.time:
case SqlNativeTypes.timestamp:
case SqlNativeTypes.tinyint:
//case SqlNativeTypes.:
case SqlNativeTypes.uniqueidentifier:
case SqlNativeTypes.varbinary:
case SqlNativeTypes.varchar:
//case SqlNativeTypes.:
case SqlNativeTypes.xml:
return true;
default:
return false;
}
}
internal static SqlDbType GetSQLDataType(string type, Dictionary<string, string> udtTypes)
{
// NOTE: highly recommended to use Case insensitive dictionary
// example:
// var caseInsensitiveDictionary = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase );
if (null != udtTypes && udtTypes.ContainsKey(type))
{
type = udtTypes[type];
}
if (int.TryParse(type, out var xType))
{
return GetSQLDataType((SqlNativeTypes)xType);
}
else if (Enum.TryParse<SqlNativeTypes>(type, out var sType))
{
return GetSQLDataType(sType);
}
throw new Exception("Unknown native SQL type '" + type + "'!");
}
private static SqlDbType GetSQLDataType(nHydrate.DataImport.SqlNativeTypes nativeType)
{
switch (nativeType)
{
case SqlNativeTypes.bigint: return SqlDbType.BigInt;
case SqlNativeTypes.binary: return SqlDbType.Binary;
case SqlNativeTypes.bit: return SqlDbType.Bit;
case SqlNativeTypes.@char: return SqlDbType.Char;
case SqlNativeTypes.date: return SqlDbType.Date;
case SqlNativeTypes.datetime: return SqlDbType.DateTime;
case SqlNativeTypes.datetime2: return SqlDbType.DateTime2;
case SqlNativeTypes.datetimeoffset: return SqlDbType.DateTimeOffset;
case SqlNativeTypes.@decimal: return SqlDbType.Decimal;
case SqlNativeTypes.@float: return SqlDbType.Float;
//SqlNativeTypes.geography
//SqlNativeTypes.geometry
//SqlNativeTypes.hierarchyid
case SqlNativeTypes.image: return SqlDbType.Image;
case SqlNativeTypes.@int: return SqlDbType.Int;
case SqlNativeTypes.money: return SqlDbType.Money;
case SqlNativeTypes.nchar: return SqlDbType.NChar;
case SqlNativeTypes.ntext: return SqlDbType.NText;
case SqlNativeTypes.numeric: return SqlDbType.Decimal;
case SqlNativeTypes.nvarchar: return SqlDbType.NVarChar;
case SqlNativeTypes.real: return SqlDbType.Real;
case SqlNativeTypes.smalldatetime: return SqlDbType.SmallDateTime;
case SqlNativeTypes.smallint: return SqlDbType.SmallInt;
case SqlNativeTypes.smallmoney: return SqlDbType.SmallMoney;
case SqlNativeTypes.sql_variant: return SqlDbType.Structured;
//SqlNativeTypes.sysname
case SqlNativeTypes.text: return SqlDbType.Text;
case SqlNativeTypes.time: return SqlDbType.Time;
case SqlNativeTypes.timestamp: return SqlDbType.Timestamp;
case SqlNativeTypes.tinyint: return SqlDbType.TinyInt;
//case SqlNativeTypes.: return SqlDbType.Udt;
case SqlNativeTypes.uniqueidentifier: return SqlDbType.UniqueIdentifier;
case SqlNativeTypes.varbinary: return SqlDbType.VarBinary;
case SqlNativeTypes.varchar: return SqlDbType.VarChar;
//case SqlNativeTypes.: return SqlDbType.Variant;
case SqlNativeTypes.xml: return SqlDbType.Xml;
default: throw new Exception("Unknown native SQL type '" + nativeType.ToString() + "'!");
}
}
#endregion
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Objects;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using ESRI.ArcLogistics.DomainObjects;
using ESRI.ArcLogistics.Routing;
namespace ESRI.ArcLogistics.Data
{
/// <summary>
/// Class that manages schedules of the project.
/// </summary>
public class ScheduleManager : DataObjectManager<Schedule>, INotifyPropertyChanged
{
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
internal ScheduleManager(DataObjectContext context, string entitySetName,
SpecFields specFields,
DataService<Route> routeDS)
: base(context, entitySetName, specFields)
{
Debug.Assert(routeDS != null);
_routeDS = routeDS;
}
#endregion constructors
#region INotifyPropertyChanged Members
/// <summary>
/// Fired when property value is changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region public properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets or sets active schedule.
/// </summary>
public Schedule ActiveSchedule
{
get
{
return _activeSchedule;
}
set
{
if (value != _activeSchedule)
{
_activeSchedule = value;
_OnPropertyChanged(
new PropertyChangedEventArgs(ACTIVE_SCHEDULE_PROPERTY_NAME));
}
}
}
/// <summary>
/// Returns overall count of schedules in the project.
/// </summary>
public int Count
{
get
{
return SCHEDULE_COUNT_QUERY(_Context);
}
}
#endregion public properties
#region public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns schedules in specified dates range.
/// </summary>
/// <param name="startDate">Range's start date.</param>
/// <param name="finishDate">Range's finish date.</param>
/// <param name="type">Schedule type, if null then search for all types.</param>
/// <returns>Collection that contains found schedules.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException">Thrown if both
/// <paramref name="startDate"/> and <paramref name="finishDate"/> are null.</exception>
public IDataObjectCollection<Schedule> SearchRange(DateTime? startDate,
DateTime? finishDate, ScheduleType? type)
{
// Dates cannot be simultaneously null.
if (startDate == null && finishDate == null)
throw new ArgumentNullException(Properties.Messages.Error_ArgumentsNullException,
new Exception());
if (type == null)
{
// Find all schedules that are in a given time range.
if (startDate == null)
return _SearchSchedules((DataModel.Schedules schedule) => (
schedule.PlannedDate >= ((DateTime)startDate).Date), false);
else if (finishDate == null)
return _SearchSchedules((DataModel.Schedules schedule) => (
schedule.PlannedDate <= ((DateTime)finishDate).Date), false);
else
return _SearchSchedules((DataModel.Schedules schedule) => (
schedule.PlannedDate >= ((DateTime)startDate).Date &&
schedule.PlannedDate <= ((DateTime)finishDate).Date), false);
}
else
{
// Find all schedules with corresponding type, that are in a given time range.
int scheduleType = (int)type.Value;
if (startDate == null)
return _SearchSchedules((DataModel.Schedules schedule) => (
schedule.PlannedDate <= ((DateTime)finishDate).Date &&
schedule.ScheduleType == scheduleType), false);
else if (finishDate == null)
return _SearchSchedules((DataModel.Schedules schedule) => (
schedule.PlannedDate >= ((DateTime)startDate).Date &&
schedule.ScheduleType == scheduleType), false);
else
return _SearchSchedules((DataModel.Schedules schedule) => (
schedule.PlannedDate >= ((DateTime)startDate).Date &&
schedule.PlannedDate <= ((DateTime)finishDate).Date &&
schedule.ScheduleType == scheduleType), false);
}
}
/// <summary>
/// Returns schedules by specified date.
/// </summary>
/// <param name="day">Date used to query schedules.</param>
/// <param name="asSynchronized">Indicates whether collection remains syncronized when schedules are added or deleted to the project database.</param>
/// <returns>Collection that contains found schedules.</returns>
public IDataObjectCollection<Schedule> Search(DateTime day,
bool asSynchronized)
{
DateTime dayStart = day.Date;
DateTime dayEnd = day.Date.AddDays(1);
return _SearchSchedules((DataModel.Schedules schedule) => (
schedule.PlannedDate >= dayStart && schedule.PlannedDate < dayEnd),
asSynchronized);
}
/// <summary>
/// Returns schedules by specified date.
/// </summary>
/// <param name="day">Date used to query schedules.</param>
/// <returns>Non-syncronized collection that contains selected schedules.</returns>
public IDataObjectCollection<Schedule> Search(DateTime day)
{
return Search(day, false);
}
/// <summary>
/// Returns list of dates from the range that contain at least one schedule with built routes.
/// </summary>
/// <param name="dateFrom">Start date used to query schedules.</param>
/// <param name="dateTo">Finish date used to query schedules.</param>
/// <returns>List of dates from the range that contain at least one schedule with built routes.</returns>
/// <remarks>
/// Schedule with built routes is a schedule where at least one order is assigned.
/// </remarks>
public IList<DateTime> SearchDaysWithBuiltRoutes(DateTime dateFrom,
DateTime dateTo)
{
SqlCeCommand cmd = new SqlCeCommand(
QUERY_DAYS_WITH_BUILT_ROUTES,
_DataService.StoreConnection);
cmd.Parameters.Add(new SqlCeParameter("date_from", dateFrom.Date));
cmd.Parameters.Add(new SqlCeParameter("date_to", dateTo.Date));
List<DateTime> dates = new List<DateTime>();
using (SqlCeDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
dates.Add(reader.GetDateTime(0));
}
return dates;
}
/// <summary>
/// Returns schedules count existent on specified date.
/// </summary>
/// <param name="plannedDate">Any date.</param>
/// <returns>Schedules count existent on specified date.</returns>
public int GetCount(DateTime plannedDate)
{
DateTime dayStart = plannedDate.Date;
DateTime dayEnd = plannedDate.Date.AddDays(1);
ObjectQuery<DataModel.Schedules> schedules = _DataService.CreateDefaultQuery<DataModel.Schedules>();
return (from schedule in schedules
where schedule.PlannedDate >= dayStart && schedule.PlannedDate < dayEnd
select schedule).Count();
}
/// <summary>
/// Returns all schedules available in the project.
/// </summary>
/// <returns>Collection of all project's schedules.</returns>
internal IDataObjectCollection<Schedule> SearchAll(bool asSynchronized)
{
return _SearchAll<DataModel.Schedules>(asSynchronized);
}
/// <summary>
/// Retrieves route by specified id.
/// </summary>
/// <returns><c>Route</c> object if search succeeded or <c>null</c> otherwise.</returns>
public Route SearchRoute(Guid routeId)
{
return _routeDS.FindObjectById(routeId);
}
/// <summary>
/// Updates route results in specified schedule.
/// </summary>
/// <param name="schedule">Schedule object.</param>
/// <param name="routeResults">List of route results to set.</param>
internal void SetRouteResults(Schedule schedule,
IList<RouteResult> routeResults)
{
Debug.Assert(schedule != null);
Debug.Assert(routeResults != null);
foreach (RouteResult result in routeResults)
{
_RemoveStops(result.Route);
_SetResults(result);
if (result.Route.Schedule == null ||
!result.Route.Schedule.Equals(schedule))
{
schedule.Routes.Add(result.Route);
}
}
schedule.CanSave = true;
}
/// <summary>
/// Clears route results for specified route.
/// </summary>
/// <param name="route">Route object.</param>
internal void ClearRouteResults(Route route)
{
Debug.Assert(route != null);
route.Cost = 0.0;
route.StartTime = null;
route.EndTime = null;
route.Overtime = 0.0;
route.TotalTime = 0.0;
route.TotalDistance = 0.0;
route.TravelTime = 0.0;
route.ViolationTime = 0.0;
route.WaitTime = 0.0;
route.CanSave = true;
route.Capacities = null;
_RemoveStops(route);
}
#endregion public methods
#region protected overrides
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
// APIREV: we don't need these protected method in public api
protected override void _Remove(Schedule schedule)
{
Debug.Assert(schedule != null);
// remove stops
foreach (Route route in schedule.Routes)
_RemoveStops(route);
// remove routes
schedule.Routes.Clear(); // removes objects from DB
// remove schedule object itself
base._Remove(schedule);
}
#endregion protected overrides
#region protected methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
protected IDataObjectCollection<Schedule> _SearchSchedules(
Expression<Func<DataModel.Schedules, bool>> whereClause,
bool asSynchronized)
{
return _Search(whereClause, asSynchronized ? whereClause : null);
}
#endregion protected methods
#region private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Raises <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"/>
/// event.
/// </summary>
/// <param name="e">The arguments for the event.</param>
private void _OnPropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, e);
}
private void _RemoveStops(Route route)
{
Debug.Assert(route != null);
if (route.Stops.Count > 0)
{
List<Stop> stops = new List<Stop>(route.Stops);
route.Stops.Clear();
foreach (Stop stop in stops)
_RemoveObject(stop);
}
}
private void _RemoveObject(DataObject obj)
{
ContextHelper.RemoveObject(_Context, obj);
}
private static void _SetResults(RouteResult result)
{
Debug.Assert(result != null);
Route route = result.Route;
route.Cost = result.Cost;
route.StartTime = result.StartTime;
route.EndTime = result.EndTime;
route.Overtime = result.Overtime;
route.TotalTime = result.TotalTime;
route.TotalDistance = result.TotalDistance;
route.TravelTime = result.TravelTime;
route.ViolationTime = result.ViolationTime;
route.WaitTime = result.WaitTime;
route.IsLocked = result.IsLocked;
route.Capacities = result.Capacities;
foreach (StopData stopData in result.Stops)
route.Stops.Add(Stop.CreateFromData(stopData));
}
#endregion private methods
#region Private constants
/// <summary>
/// Query to DataBase.
/// </summary>
private const string QUERY_DAYS_WITH_BUILT_ROUTES = @"select distinct sch.[PlannedDate] from [Schedules] as sch inner join [Routes] as rt on sch.[Id] = rt.[ScheduleId] inner join [Stops] as st on rt.[Id] = st.[RouteId] where sch.[PlannedDate] >= @date_from and sch.[PlannedDate] <= @date_to";
/// <summary>
/// Active schedule property name.
/// </summary>
private const string ACTIVE_SCHEDULE_PROPERTY_NAME = "ActiveSchedule";
/// <summary>
/// Compiled query for finding number of schedules in the project.
/// </summary>
private static readonly Func<DataModel.Entities, int> SCHEDULE_COUNT_QUERY =
CompiledQuery.Compile<DataModel.Entities, int>(context => context.Schedules.Count());
#endregion
#region private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private DataService<Route> _routeDS;
/// <summary>
/// Active schedule.
/// </summary>
private Schedule _activeSchedule;
#endregion private fields
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Tanis.Collections;
namespace Games.Pathfinding
{
/// <summary>
/// Base class for pathfinding nodes, it holds no actual information about the map.
/// An inherited class must be constructed from this class and all virtual methods must be
/// implemented. Note, that calling base() in the overridden methods is not needed.
/// </summary>
public class AStarNode : IComparable
{
#region Properties
private double FGoalEstimate;
private AStarNode FGoalNode;
/// <summary>
/// The parent of the node.
/// </summary>
public AStarNode Parent { get; set; }
/// <summary>
/// The accumulative cost of the path until now.
/// </summary>
public double Cost { set; get; }
/// <summary>
/// The estimated cost to the goal from here.
/// </summary>
public double GoalEstimate
{
set { FGoalEstimate = value; }
get
{
Calculate();
return (FGoalEstimate);
}
}
/// <summary>
/// The cost plus the estimated cost to the goal from here.
/// </summary>
public double TotalCost
{
get { return (Cost + GoalEstimate); }
}
/// <summary>
/// The goal node.
/// </summary>
public AStarNode GoalNode
{
set
{
FGoalNode = value;
Calculate();
}
get { return FGoalNode; }
}
#endregion
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name = "AParent">The node's parent</param>
/// <param name = "AGoalNode">The goal node</param>
/// <param name = "ACost">The accumulative cost until now</param>
public AStarNode(AStarNode AParent, AStarNode AGoalNode, double ACost)
{
Parent = AParent;
Cost = ACost;
GoalNode = AGoalNode;
}
#endregion
#region Public Methods
/// <summary>
/// Determines wheather the current node is the goal.
/// </summary>
/// <returns>Returns true if current node is the goal</returns>
public bool IsGoal()
{
return IsSameState(FGoalNode);
}
#endregion
#region Virtual Methods
/// <summary>
/// Determines wheather the current node is the same state as the on passed.
/// </summary>
/// <param name = "ANode">AStarNode to compare the current node to</param>
/// <returns>Returns true if they are the same state</returns>
public virtual bool IsSameState(AStarNode ANode)
{
return false;
}
/// <summary>
/// Calculates the estimated cost for the remaining trip to the goal.
/// </summary>
public virtual void Calculate()
{
FGoalEstimate = 0.0f;
}
/// <summary>
/// Gets all successors nodes from the current node and adds them to the successor list
/// </summary>
/// <param name = "ASuccessors">List in which the successors will be added</param>
public virtual void GetSuccessors(ArrayList ASuccessors)
{
}
#endregion
#region Overridden Methods
public override bool Equals(object obj)
{
return IsSameState((AStarNode) obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
return (-TotalCost.CompareTo(((AStarNode) obj).TotalCost));
}
#endregion
}
/// <summary>
/// Class for performing A* pathfinding
/// </summary>
public sealed class AStar
{
#region Private Fields
private readonly Heap FClosedList;
private readonly Heap FOpenList;
private readonly ArrayList FSuccessors;
private AStarNode FGoalNode;
private AStarNode FStartNode;
#endregion
#region Properties
private readonly ArrayList FSolution;
private bool m_pathPossible = true;
/// <summary>
/// Holds the solution after pathfinding is done. <see>FindPath()</see>
/// </summary>
public ArrayList Solution
{
get { return FSolution; }
}
public bool pathPossible
{
get { return m_pathPossible; }
}
#endregion
#region Constructors
public AStar()
{
FOpenList = new Heap();
FClosedList = new Heap();
FSuccessors = new ArrayList();
FSolution = new ArrayList();
}
#endregion
#region Private Methods
/// <summary>
/// Prints all the nodes in a list
/// </summary>
/// <param name = "ANodeList">List to print</param>
private void PrintNodeList(object ANodeList)
{
Console.WriteLine("Node list:");
foreach (AStarNode n in (ANodeList as IEnumerable))
{
//n.PrintNodeInfo();
}
Console.WriteLine("=====");
}
#endregion
#region Public Methods
/// <summary>
/// Finds the shortest path from the start node to the goal node
/// </summary>
/// <param name = "AStartNode">Start node</param>
/// <param name = "AGoalNode">Goal node</param>
public void FindPath(AStarNode AStartNode, AStarNode AGoalNode)
{
FStartNode = AStartNode;
FGoalNode = AGoalNode;
FOpenList.Add(FStartNode);
int i = 0;
while (FOpenList.Count > 0 && i < 2000)
{
// Get the node with the lowest TotalCost
AStarNode NodeCurrent = (AStarNode) FOpenList.Pop();
// If the node is the goal copy the path to the solution array
if (NodeCurrent.IsGoal())
{
while (NodeCurrent != null)
{
FSolution.Insert(0, NodeCurrent);
NodeCurrent = NodeCurrent.Parent;
}
break;
}
// Get successors to the current node
NodeCurrent.GetSuccessors(FSuccessors);
foreach (AStarNode NodeSuccessor in FSuccessors)
{
// Test if the currect successor node is on the open list, if it is and
// the TotalCost is higher, we will throw away the current successor.
AStarNode NodeOpen = null;
if (FOpenList.Contains(NodeSuccessor))
NodeOpen = (AStarNode) FOpenList[FOpenList.IndexOf(NodeSuccessor)];
if ((NodeOpen != null) && (NodeSuccessor.TotalCost > NodeOpen.TotalCost))
continue;
// Test if the currect successor node is on the closed list, if it is and
// the TotalCost is higher, we will throw away the current successor.
AStarNode NodeClosed = null;
if (FClosedList.Contains(NodeSuccessor))
NodeClosed = (AStarNode) FClosedList[FClosedList.IndexOf(NodeSuccessor)];
if ((NodeClosed != null) && (NodeSuccessor.TotalCost > NodeClosed.TotalCost))
continue;
// Remove the old successor from the open list
FOpenList.Remove(NodeOpen);
// Remove the old successor from the closed list
FClosedList.Remove(NodeClosed);
// Add the current successor to the open list
FOpenList.Push(NodeSuccessor);
}
// Add the current node to the closed list
FClosedList.Add(NodeCurrent);
i++;
}
if (i == 2000)
{
m_pathPossible = false;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Cosmos.Debug.Common;
using Dapper;
using SQLinq.Dapper;
using SQLinq;
namespace Cosmos.Debug.VSDebugEngine
{
// An implementation of IDebugProperty2
// This interface represents a stack frame property, a program document property, or some other property.
// The property is usually the result of an expression evaluation.
//
// The sample engine only supports locals and parameters for functions that have symbols loaded.
class AD7Property : IDebugProperty2
{
private DebugLocalInfo m_variableInformation;
private AD7Process mProcess;
private AD7StackFrame mStackFrame;
private LOCAL_ARGUMENT_INFO mDebugInfo;
const uint xArrayLengthOffset = 8;
const uint xArrayFirstElementOffset = 16;
private const string NULL = "null";
protected Int32 OFFSET
{
get
{
return mDebugInfo.OFFSET;
}
}
public AD7Property(DebugLocalInfo localInfo, AD7Process process, AD7StackFrame stackFrame)
{
m_variableInformation = localInfo;
mProcess = process;
mStackFrame = stackFrame;
if (localInfo.IsLocal)
{
mDebugInfo = mStackFrame.mLocalInfos[m_variableInformation.Index];
}
else if (localInfo.IsArrayElement)
{
mDebugInfo = new LOCAL_ARGUMENT_INFO()
{
TYPENAME = localInfo.ArrayElementType,
NAME = localInfo.Name,
OFFSET = localInfo.ArrayElementLocation
};
}
else
{
mDebugInfo = mStackFrame.mArgumentInfos[m_variableInformation.Index];
}
}
public void ReadData<T>(ref DEBUG_PROPERTY_INFO propertyInfo, Func<byte[], int, T> ByteToTypeAction)
{
byte[] xData;
if (m_variableInformation.IsArrayElement)
{
xData = mProcess.mDbgConnector.GetMemoryData((uint)OFFSET, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)));
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
return;
}
var xTypedIntValue = ByteToTypeAction(xData, 0);
propertyInfo.bstrValue = String.Format("{0}", xTypedIntValue);
}
else
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)));
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
return;
}
var xTypedIntValue = ByteToTypeAction(xData, 0);
propertyInfo.bstrValue = String.Format("{0}", xTypedIntValue);
}
}
public void ReadDataArray<T>(ref DEBUG_PROPERTY_INFO propertyInfo, string typeAsString)
{
byte[] xData;
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xArrayPointer = BitConverter.ToUInt32(xData, 0);
if (xArrayPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xArrayPointer + xArrayLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xDataLength = BitConverter.ToUInt32(xData, 0);
bool xIsTooLong = xDataLength > 512;
if (xIsTooLong)
{
xDataLength = 512;
}
if (xDataLength > 0)
{
if (this.m_variableInformation.Children.Count == 0)
{
for (int i = 0; i < xDataLength; i++)
{
DebugLocalInfo inf = new DebugLocalInfo();
inf.IsArrayElement = true;
inf.ArrayElementType = typeof(T).AssemblyQualifiedName;
inf.ArrayElementLocation = (int)(xArrayPointer + xArrayFirstElementOffset + (System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) * i));
inf.Name = "[" + i.ToString() + "]";
this.m_variableInformation.Children.Add(new AD7Property(inf, this.mProcess, this.mStackFrame));
}
}
}
propertyInfo.bstrValue = String.Format(typeAsString + "[{0}] at 0x{1} ", xDataLength, xArrayPointer.ToString("X"));
}
}
}
}
// Construct a DEBUG_PROPERTY_INFO representing this local or parameter.
public DEBUG_PROPERTY_INFO ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields)
{
DEBUG_PROPERTY_INFO propertyInfo = new DEBUG_PROPERTY_INFO();
try
{
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME))
{
propertyInfo.bstrFullName = m_variableInformation.Name;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME))
{
propertyInfo.bstrName = m_variableInformation.Name;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE))
{
propertyInfo.bstrType = mDebugInfo.TYPENAME;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE))
{
byte[] xData;
#region String
if (mDebugInfo.TYPENAME == typeof(string).AssemblyQualifiedName)
{
const uint xStringLengthOffset = 12;
const uint xStringFirstCharOffset = 16;
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xStrPointer = BitConverter.ToUInt32(xData, 0);
if (xStrPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xStrPointer + xStringLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xStringLength = BitConverter.ToUInt32(xData, 0);
propertyInfo.bstrValue = "String of length: " + xStringLength;
if (xStringLength > 100)
{
propertyInfo.bstrValue = "For now, strings larger than 100 chars are not supported..";
}
else if (xStringLength == 0)
{
propertyInfo.bstrValue = "\"\"";
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xStrPointer + xStringFirstCharOffset, xStringLength * 2, 2);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
propertyInfo.bstrValue = "\"" + Encoding.Unicode.GetString(xData) + "\"";
}
}
}
}
}
}
#warning TODO: String[]
#endregion
// Byte
else if (mDebugInfo.TYPENAME == typeof(byte).AssemblyQualifiedName)
{
ReadData<byte>(ref propertyInfo, new Func<byte[], int, byte>(delegate(byte[] barr, int ind) { return barr[ind]; }));
}
else if (mDebugInfo.TYPENAME == typeof(byte[]).AssemblyQualifiedName)
{
ReadDataArray<byte>(ref propertyInfo, "byte");
}
// SByte
else if (mDebugInfo.TYPENAME == typeof(sbyte).AssemblyQualifiedName)
{
ReadData<sbyte>(ref propertyInfo, new Func<byte[], int, sbyte>(delegate(byte[] barr, int ind) { return unchecked((sbyte)barr[ind]); }));
}
else if (mDebugInfo.TYPENAME == typeof(sbyte[]).AssemblyQualifiedName)
{
ReadDataArray<sbyte>(ref propertyInfo, "sbyte");
}
#region Char
else if (mDebugInfo.TYPENAME == typeof(char).AssemblyQualifiedName)
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 2);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
var xTypedCharValue = BitConverter.ToChar(xData, 0);
propertyInfo.bstrValue = String.Format("{0} '{1}'", (ushort)xTypedCharValue, xTypedCharValue);
}
}
else if (mDebugInfo.TYPENAME == typeof(char[]).AssemblyQualifiedName)
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xArrayPointer = BitConverter.ToUInt32(xData, 0);
if (xArrayPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xArrayPointer + xArrayLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xDataLength = BitConverter.ToUInt32(xData, 0);
bool xIsTooLong = xDataLength > 512;
var xSB = new StringBuilder();
xSB.AppendFormat("Char[{0}] at 0x{1} {{ ", xDataLength, xArrayPointer.ToString("X"));
if (xIsTooLong)
{
xDataLength = 512;
}
if (xDataLength > 0)
{
xData = mProcess.mDbgConnector.GetMemoryData(xArrayPointer + xArrayFirstElementOffset, xDataLength * 2);
if (xData == null)
{
xSB.Append(String.Format("Error! Memory data received was null!"));
}
else
{
bool first = true;
for (int i = 0; (i / 2) < xDataLength; i += 2)
{
if (!first)
xSB.Append(", ");
char c = BitConverter.ToChar(xData, i);
xSB.Append('\'');
if (c == '\0')
{
xSB.Append("\\0");
}
else
{
xSB.Append(c);
}
xSB.Append('\'');
first = false;
}
}
}
if (xIsTooLong)
{
xSB.Append(", ..");
}
xSB.Append(" }");
propertyInfo.bstrValue = xSB.ToString();
}
}
}
}
#endregion
// Short
else if (mDebugInfo.TYPENAME == typeof(short).AssemblyQualifiedName)
{
ReadData<short>(ref propertyInfo, new Func<byte[], int, short>(BitConverter.ToInt16));
}
else if (mDebugInfo.TYPENAME == typeof(short[]).AssemblyQualifiedName)
{
ReadDataArray<short>(ref propertyInfo, "short");
}
// UShort
else if (mDebugInfo.TYPENAME == typeof(ushort).AssemblyQualifiedName)
{
ReadData<ushort>(ref propertyInfo, new Func<byte[], int, ushort>(BitConverter.ToUInt16));
}
else if (mDebugInfo.TYPENAME == typeof(ushort[]).AssemblyQualifiedName)
{
ReadDataArray<ushort>(ref propertyInfo, "ushort");
}
// Int32
else if (mDebugInfo.TYPENAME == typeof(int).AssemblyQualifiedName)
{
ReadData<int>(ref propertyInfo, new Func<byte[], int, int>(BitConverter.ToInt32));
}
else if (mDebugInfo.TYPENAME == typeof(int[]).AssemblyQualifiedName)
{
ReadDataArray<int>(ref propertyInfo, "int");
}
// UInt32
else if (mDebugInfo.TYPENAME == typeof(uint).AssemblyQualifiedName)
{
ReadData<uint>(ref propertyInfo, new Func<byte[], int, uint>(BitConverter.ToUInt32));
}
else if (mDebugInfo.TYPENAME == typeof(uint[]).AssemblyQualifiedName)
{
ReadDataArray<uint>(ref propertyInfo, "uint");
}
// Long
else if (mDebugInfo.TYPENAME == typeof(long).AssemblyQualifiedName)
{
ReadData<long>(ref propertyInfo, new Func<byte[], int, long>(BitConverter.ToInt64));
}
else if (mDebugInfo.TYPENAME == typeof(long[]).AssemblyQualifiedName)
{
ReadDataArray<long>(ref propertyInfo, "long");
}
// ULong
else if (mDebugInfo.TYPENAME == typeof(ulong).AssemblyQualifiedName)
{
ReadData<ulong>(ref propertyInfo, new Func<byte[], int, ulong>(BitConverter.ToUInt64));
}
else if (mDebugInfo.TYPENAME == typeof(ulong[]).AssemblyQualifiedName)
{
ReadDataArray<ulong>(ref propertyInfo, "ulong");
}
// Float
else if (mDebugInfo.TYPENAME == typeof(float).AssemblyQualifiedName)
{
ReadData<float>(ref propertyInfo, new Func<byte[], int, float>(BitConverter.ToSingle));
}
else if (mDebugInfo.TYPENAME == typeof(float[]).AssemblyQualifiedName)
{
ReadDataArray<float>(ref propertyInfo, "float");
}
// Double
else if (mDebugInfo.TYPENAME == typeof(double).AssemblyQualifiedName)
{
ReadData<double>(ref propertyInfo, new Func<byte[], int, double>(BitConverter.ToDouble));
}
else if (mDebugInfo.TYPENAME == typeof(double[]).AssemblyQualifiedName)
{
ReadDataArray<double>(ref propertyInfo, "double");
}
// Bool
else if (mDebugInfo.TYPENAME == typeof(bool).AssemblyQualifiedName)
{
ReadData<bool>(ref propertyInfo, new Func<byte[], int, bool>(BitConverter.ToBoolean));
}
else if (mDebugInfo.TYPENAME == typeof(bool[]).AssemblyQualifiedName)
{
ReadDataArray<bool>(ref propertyInfo, "bool");
}
else
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
var xPointer = BitConverter.ToUInt32(xData, 0);
if (xPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
try
{
var mp = mProcess.mDebugInfoDb.GetFieldMap(mDebugInfo.TYPENAME);
foreach (string str in mp.FieldNames)
{
Cosmos.Debug.Common.FIELD_INFO xFieldInfo;
xFieldInfo = mProcess.mDebugInfoDb.Connection.Query(new SQLinq<Cosmos.Debug.Common.FIELD_INFO>().Where(q => q.NAME == str)).First();
var inf = new DebugLocalInfo();
inf.IsArrayElement = true;
inf.ArrayElementType = xFieldInfo.TYPE;
inf.ArrayElementLocation = (int)(xPointer + xFieldInfo.OFFSET + 12);
inf.Name = GetFieldName(xFieldInfo);
this.m_variableInformation.Children.Add(new AD7Property(inf, this.mProcess, this.mStackFrame));
}
propertyInfo.bstrValue = String.Format("{0} (0x{1})", xPointer, xPointer.ToString("X").ToUpper());
}
catch (Exception ex)
{
if (ex.GetType().Name == "SQLiteException")
{
//Ignore but warn user
propertyInfo.bstrValue = "SQLiteException. Could not get type information for " + mDebugInfo.TYPENAME;
}
else
{
throw new Exception("Unexpected error in AD7Property.cs:459", ex);
}
}
}
}
}
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_ATTRIB))
{
// The sample does not support writing of values displayed in the debugger, so mark them all as read-only.
propertyInfo.dwAttrib = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_VALUE_READONLY;
if (this.m_variableInformation.Children.Count > 0)
{
propertyInfo.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_OBJ_IS_EXPANDABLE;
}
}
propertyInfo.pProperty = (IDebugProperty2)this;
propertyInfo.dwFields |= (enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP);
// If the debugger has asked for the property, or the property has children (meaning it is a pointer in the sample)
// then set the pProperty field so the debugger can call back when the children are enumerated.
//if (((dwFields & (uint)enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP) != 0)
//|| (this.m_variableInformation.child != null))
//{
// propertyInfo.pProperty = (IDebugProperty2)this;
// propertyInfo.dwFields |= (enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP);
//}
}
catch
{
}
return propertyInfo;
}
private static string GetFieldName(Cosmos.Debug.Common.FIELD_INFO fInf)
{
string s = fInf.NAME;
int i = s.LastIndexOf('.');
if (i > 0)
{
s = s.Substring(i + 1, s.Length - i - 1);
return s;
}
return s;
}
#region IDebugProperty2 Members
// Enumerates the children of a property. This provides support for dereferencing pointers, displaying members of an array, or fields of a class or struct.
// The sample debugger only supports pointer dereferencing as children. This means there is only ever one child.
public int EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref System.Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum)
{
ppEnum = null;
if (this.m_variableInformation.Children.Count > 0)
{
List<DEBUG_PROPERTY_INFO> infs = new List<DEBUG_PROPERTY_INFO>();
foreach (AD7Property dp in m_variableInformation.Children)
{
infs.Add(dp.ConstructDebugPropertyInfo(dwFields));
}
ppEnum = new AD7PropertyEnum(infs.ToArray());
return VSConstants.S_OK;
}
//if (this.m_variableInformation.child != null)
//{
// DEBUG_PROPERTY_INFO[] properties = new DEBUG_PROPERTY_INFO[1];
// properties[0] = (new AD7Property(this.m_variableInformation.child)).ConstructDebugPropertyInfo(dwFields);
// ppEnum = new AD7PropertyEnum(properties);
// return VSConstants.S_OK;
//}
return VSConstants.S_FALSE;
}
// Returns the property that describes the most-derived property of a property
// This is called to support object oriented languages. It allows the debug engine to return an IDebugProperty2 for the most-derived
// object in a hierarchy. This engine does not support this.
public int GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost)
{
throw new Exception("The method or operation is not implemented.");
}
// This method exists for the purpose of retrieving information that does not lend itself to being retrieved by calling the IDebugProperty2::GetPropertyInfo
// method. This includes information about custom viewers, managed type slots and other information.
// The sample engine does not support this.
public int GetExtendedInfo(ref System.Guid guidExtendedInfo, out object pExtendedInfo)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the memory bytes for a property value.
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the memory context for a property value.
public int GetMemoryContext(out IDebugMemoryContext2 ppMemory)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the parent of a property.
// The sample engine does not support obtaining the parent of properties.
public int GetParent(out IDebugProperty2 ppParent)
{
throw new Exception("The method or operation is not implemented.");
}
// Fills in a DEBUG_PROPERTY_INFO structure that describes a property.
public int GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo)
{
pPropertyInfo[0] = new DEBUG_PROPERTY_INFO();
rgpArgs = null;
pPropertyInfo[0] = ConstructDebugPropertyInfo(dwFields);
return VSConstants.S_OK;
}
// Return an IDebugReference2 for this property. An IDebugReference2 can be thought of as a type and an address.
public int GetReference(out IDebugReference2 ppReference)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the size, in bytes, of the property value.
public int GetSize(out uint pdwSize)
{
throw new Exception("The method or operation is not implemented.");
}
// The debugger will call this when the user tries to edit the property's values
// the sample has set the read-only flag on its properties, so this should not be called.
public int SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout)
{
throw new Exception("The method or operation is not implemented.");
}
// The debugger will call this when the user tries to edit the property's values in one of the debugger windows.
// the sample has set the read-only flag on its properties, so this should not be called.
public int SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Archichect.Markers;
using Archichect.Matching;
namespace Archichect.Transforming.Modifying {
public class MarkDeps : TransformerWithOptions<Ignore, MarkDeps.TransformOptions> {
public class TransformOptions {
[NotNull, ItemNotNull]
public List<DependencyMatch> Matches = new List<DependencyMatch>();
[NotNull, ItemNotNull]
public List<DependencyMatch> Excludes = new List<DependencyMatch>();
public bool ClearLeft;
public bool ClearDependency;
public bool ClearRight;
[NotNull, ItemNotNull]
public List<string> MarkersToAddOnLeft = new List<string>();
[NotNull]
public Dictionary<string, int> MarkersToAddOnDep = new Dictionary<string, int>();
[NotNull, ItemNotNull]
public List<string> MarkersToAddOnRight = new List<string>();
[NotNull, ItemNotNull]
public List<string> MarkerPatternsToRemoveOnLeft = new List<string>();
[NotNull, ItemNotNull]
public List<string> MarkersToRemoveOnDep = new List<string>();
[NotNull, ItemNotNull]
public List<string> MarkerPatternsToRemoveOnRight = new List<string>();
public bool ResetBad;
public bool ResetQuestionable;
}
public static readonly DependencyMatchOptions DependencyMatchOptions = new DependencyMatchOptions("mark");
public static readonly Option MarkLeftItemOption = new Option("ml", "mark-left", "marker", "Marker to add to item on left", @default: "", multiple: true);
public static readonly Option MarkDependencyItemOption = new Option("md", "mark-dependency", "marker", "Marker to add to dependency", @default: "", multiple: true);
public static readonly Option MarkRightItemOption = new Option("mr", "mark-right", "marker", "Marker to add to item on right", @default: "", multiple: true);
public static readonly Option UnmarkLeftItemOption = new Option("ul", "unmark-left", "marker", "Marker to be removed from item on left", @default: "", multiple: true);
public static readonly Option UnmarkDependencyItemOption = new Option("ud", "unmark-dependency", "marker", "Marker to be removed from dependency", @default: "", multiple: true);
public static readonly Option UnmarkRightItemOption = new Option("ur", "unmark-right", "marker", "Marker to be removed from item on right", @default: "", multiple: true);
public static readonly Option ClearLeftItemOption = new Option("cl", "clear-left", "", "Remove all markers from item on left", @default: false);
public static readonly Option ClearDependencyItemOption = new Option("cd", "clear-dependency", "", "Remove all markers from dependency", @default: false);
public static readonly Option ClearRightItemOption = new Option("cr", "clear-right", "", "Remove all markers from item on right", @default: false);
public static readonly Option ResetQuestionableCountOption = new Option("rq", "reset-questionable", "", "Reset questionable count on dependencies", @default: false);
public static readonly Option ResetBadCountOption = new Option("rb", "reset-bad", "", "Reset bad count on dependencies", @default: false);
private static readonly Option[] _configOptions = DependencyMatchOptions.WithOptions(
MarkLeftItemOption, MarkDependencyItemOption, MarkRightItemOption,
UnmarkLeftItemOption, UnmarkDependencyItemOption, UnmarkRightItemOption,
ClearLeftItemOption, ClearDependencyItemOption, ClearRightItemOption,
ResetBadCountOption, ResetQuestionableCountOption
);
public override string GetHelp(bool detailedHelp, string filter) {
string result = $@"Modify counts and markers on dependencies, delete or keep dependencies.
Configuration options: None
Transformer options: {Option.CreateHelp(_configOptions, detailedHelp, filter)}";
if (detailedHelp) {
result += @"
A dependency match has the format
usingItemMatch -- dependencyMatch -> usedItemMatch
Each part can be empty, therefore the simplest match (which matches every
dependency) is -- -> or, equivalently, --->.
A dependency is modified if all three matches match it; empty matches
match always.
The three parts have the following syntax:
usingItemMatch, usedItemMatch
item pattern (see -help itempattern)
dependencyMatch
dependency pattern (see -help dependency)
Examples:
'From -- -> 'To Match dependencies where using item
has marker From and used item has marker To
-- 'OnCycle -> Match all dependencies with marker OnCycle
// TODO: add .Net examples
"; // TODO: add .Net examples
}
return result;
}
protected override Ignore CreateConfigureOptions([NotNull] GlobalContext globalContext,
[CanBeNull] string configureOptionsString, bool forceReload) {
return Ignore.Om;
}
protected override TransformOptions CreateTransformOptions([NotNull] GlobalContext globalContext,
[CanBeNull] string transformOptionsString, Func<string, IEnumerable<Dependency>> findOtherWorkingGraph) {
var transformOptions = new TransformOptions();
DependencyMatchOptions.Parse(globalContext, transformOptionsString, globalContext.IgnoreCase, transformOptions.Matches, transformOptions.Excludes,
MarkLeftItemOption.Action((args, j) => {
string marker = Option.ExtractRequiredOptionValue(args, ref j, "missing marker name");
transformOptions.MarkersToAddOnLeft.Add(marker.TrimStart('\''));
return j;
}),
MarkDependencyItemOption.Action((args, j) => {
string marker = Option.ExtractRequiredOptionValue(args, ref j, "missing marker name");
transformOptions.MarkersToAddOnDep[marker.TrimStart('\'')] = 1;
return j;
}),
MarkRightItemOption.Action((args, j) => {
string marker = Option.ExtractRequiredOptionValue(args, ref j, "missing marker name");
transformOptions.MarkersToAddOnRight.Add(marker.TrimStart('\''));
return j;
}),
UnmarkLeftItemOption.Action((args, j) => {
string marker = Option.ExtractRequiredOptionValue(args, ref j, "missing marker name");
transformOptions.MarkerPatternsToRemoveOnLeft.Add(marker.TrimStart('\''));
return j;
}),
UnmarkDependencyItemOption.Action((args, j) => {
string marker = Option.ExtractRequiredOptionValue(args, ref j, "missing marker name");
transformOptions.MarkersToRemoveOnDep.Add(marker.TrimStart('\''));
return j;
}),
UnmarkRightItemOption.Action((args, j) => {
string marker = Option.ExtractRequiredOptionValue(args, ref j, "missing marker");
transformOptions.MarkerPatternsToRemoveOnRight.Add(marker.TrimStart('\''));
return j;
}),
ClearLeftItemOption.Action((args, j) => {
transformOptions.ClearLeft = true;
return j;
}),
ClearDependencyItemOption.Action((args, j) => {
transformOptions.ClearDependency = true;
return j;
}),
ClearRightItemOption.Action((args, j) => {
transformOptions.ClearRight = true;
return j;
}),
ResetBadCountOption.Action((args, j) => {
transformOptions.ResetBad = true;
return j;
}),
ResetQuestionableCountOption.Action((args, j) => {
transformOptions.ResetQuestionable = true;
return j;
})
);
return transformOptions;
}
public override int Transform([NotNull] GlobalContext globalContext, Ignore Ignore,
[NotNull] TransformOptions transformOptions, [NotNull] [ItemNotNull] IEnumerable<Dependency> dependencies,
[NotNull] List<Dependency> transformedDependencies) {
var leftMatches = new HashSet<Item>();
var rightMatches = new HashSet<Item>();
int n = 0;
bool ignoreCase = globalContext.IgnoreCase;
foreach (var d in dependencies.Where(d => d.IsMarkerMatch(transformOptions.Matches, transformOptions.Excludes))) {
leftMatches.Add(d.UsingItem);
rightMatches.Add(d.UsedItem);
if (transformOptions.ClearDependency) {
d.ClearMarkers();
} else {
d.UnionWithMarkers(transformOptions.MarkersToAddOnDep);
d.RemoveMarkers(transformOptions.MarkersToRemoveOnDep, ignoreCase);
}
if (transformOptions.ResetBad) {
d.ResetBad();
}
if (transformOptions.ResetQuestionable) {
d.ResetQuestionable();
}
n++;
}
Log.WriteInfo($"Marked {n} dependencies");
ReadOnlyMarkerSet markersToAddOnLeftMarkerSet = new ReadOnlyMarkerSet(ignoreCase, transformOptions.MarkersToAddOnLeft);
ReadOnlyMarkerSet markersToAddOnRightMarkerSet = new ReadOnlyMarkerSet(ignoreCase, transformOptions.MarkersToAddOnRight);
// Items are modified afterwards - match loop above uses unchanged values
foreach (var left in leftMatches) {
MarkItem(transformOptions.ClearLeft, left, markersToAddOnLeftMarkerSet, transformOptions.MarkerPatternsToRemoveOnLeft, ignoreCase);
}
foreach (var right in rightMatches) {
MarkItem(transformOptions.ClearRight, right, markersToAddOnRightMarkerSet, transformOptions.MarkerPatternsToRemoveOnRight, ignoreCase);
}
transformedDependencies.AddRange(dependencies);
return Program.OK_RESULT;
}
private static void MarkItem(bool clear, Item item, IMarkerSet markersToAdd,
List<string> markerPatternsToRemove, bool ignoreCase) {
if (clear) {
item.ClearMarkers();
} else {
item.MergeWithMarkers(markersToAdd);
item.RemoveMarkers(markerPatternsToRemove, ignoreCase);
}
}
public override IEnumerable<Dependency> CreateSomeTestDependencies(WorkingGraph transformingGraph) {
Item am = transformingGraph.CreateItem(ItemType.SIMPLE, new[] { "A" }, new[] { "M" });
Item bm = transformingGraph.CreateItem(ItemType.SIMPLE, new[] { "B" }, new[] { "M" });
Item cn = transformingGraph.CreateItem(ItemType.SIMPLE, new[] { "C" }, new[] { "N" });
return new[] {
transformingGraph.CreateDependency(am, am, source: null, markers: "", ct:10, questionableCt:5, badCt:3, notOkReason: "test"),
transformingGraph.CreateDependency(am, bm, source: null, markers: "use+define", ct:1, questionableCt:0,badCt: 0),
transformingGraph.CreateDependency(am, cn, source: null, markers: "define", ct:5, questionableCt:0, badCt:2, notOkReason: "test"),
transformingGraph.CreateDependency(bm, am, source: null, markers: "define", ct:5, questionableCt:0, badCt:2, notOkReason: "test"),
};
}
}
}
| |
using System;
using System.Collections.Generic;
using De.Osthus.Ambeth.Collections;
using De.Osthus.Ambeth.Ioc.Annotation;
using De.Osthus.Ambeth.Log;
using De.Osthus.Ambeth.Merge;
using De.Osthus.Ambeth.Merge.Model;
using De.Osthus.Ambeth.Merge.Transfer;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using De.Osthus.Ambeth.Metadata;
using De.Osthus.Ambeth.Cache;
namespace De.Osthus.Ambeth.Converter.Merge
{
public class EntityMetaDataConverter : IDedicatedConverter
{
[LogInstance]
public ILogger Log { private get; set; }
[Autowired]
public ICacheModification CacheModification { protected get; set; }
[Autowired]
public IEntityFactory EntityFactory { protected get; set; }
[Autowired]
public IIntermediateMemberTypeProvider IntermediateMemberTypeProvider { protected get; set; }
[Autowired]
public IProxyHelper ProxyHelper { protected get; set; }
public Object ConvertValueToType(Type expectedType, Type sourceType, Object value, Object additionalInformation)
{
if (sourceType.IsAssignableFrom(typeof(EntityMetaData)))
{
EntityMetaData source = (EntityMetaData) value;
EntityMetaDataTransfer target = new EntityMetaDataTransfer();
target.EntityType = source.EntityType;
target.IdMemberName = GetNameOfMember(source.IdMember);
target.VersionMemberName = GetNameOfMember(source.VersionMember);
target.CreatedByMemberName = GetNameOfMember(source.CreatedByMember);
target.CreatedOnMemberName = GetNameOfMember(source.CreatedOnMember);
target.UpdatedByMemberName = GetNameOfMember(source.UpdatedByMember);
target.UpdatedOnMemberName = GetNameOfMember(source.UpdatedOnMember);
target.AlternateIdMemberNames = GetNamesOfMembers(source.AlternateIdMembers);
target.PrimitiveMemberNames = GetNamesOfMembers(source.PrimitiveMembers);
target.RelationMemberNames = GetNamesOfMembers(source.RelationMembers);
target.AlternateIdMemberIndicesInPrimitives = source.AlternateIdMemberIndicesInPrimitives;
target.TypesRelatingToThis = source.TypesRelatingToThis;
target.TypesToCascadeDelete = ListUtil.ToArray(source.CascadeDeleteTypes);
PrimitiveMember[] primitiveMembers = source.PrimitiveMembers;
RelationMember[] relationMembers = source.RelationMembers;
IList<String> mergeRelevantNames = new List<String>();
for (int a = primitiveMembers.Length; a-- > 0;)
{
PrimitiveMember member = primitiveMembers[a];
if (source.IsMergeRelevant(member))
{
mergeRelevantNames.Add(GetNameOfMember(member));
}
}
for (int a = relationMembers.Length; a-- > 0;)
{
RelationMember member = relationMembers[a];
if (source.IsMergeRelevant(member))
{
mergeRelevantNames.Add(GetNameOfMember(member));
}
}
target.MergeRelevantNames = ListUtil.ToArray<String>(mergeRelevantNames);
return target;
}
else if (sourceType.IsAssignableFrom(typeof(EntityMetaDataTransfer)))
{
EntityMetaDataTransfer source = (EntityMetaDataTransfer) value;
HashMap<String, Member> nameToMemberDict = new HashMap<String, Member>();
EntityMetaData target = new EntityMetaData();
Type entityType = source.EntityType;
Type realType = ProxyHelper.GetRealType(entityType);
target.EntityType = entityType;
target.RealType = realType;
target.IdMember = GetPrimitiveMember(entityType, source.IdMemberName, nameToMemberDict);
target.VersionMember = GetPrimitiveMember(entityType, source.VersionMemberName, nameToMemberDict);
target.CreatedByMember = GetPrimitiveMember(entityType, source.CreatedByMemberName, nameToMemberDict);
target.CreatedOnMember = GetPrimitiveMember(entityType, source.CreatedOnMemberName, nameToMemberDict);
target.UpdatedByMember = GetPrimitiveMember(entityType, source.UpdatedByMemberName, nameToMemberDict);
target.UpdatedOnMember = GetPrimitiveMember(entityType, source.UpdatedOnMemberName, nameToMemberDict);
target.AlternateIdMembers = GetPrimitiveMembers(entityType, source.AlternateIdMemberNames, nameToMemberDict);
target.PrimitiveMembers = GetPrimitiveMembers(entityType, source.PrimitiveMemberNames, nameToMemberDict);
target.RelationMembers = GetRelationMembers(entityType, source.RelationMemberNames, nameToMemberDict);
target.AlternateIdMemberIndicesInPrimitives = source.AlternateIdMemberIndicesInPrimitives;
target.TypesRelatingToThis = source.TypesRelatingToThis;
Type[] typesToCascadeDelete = source.TypesToCascadeDelete;
for (int a = 0, size = typesToCascadeDelete.Length; a < size; a++)
{
target.CascadeDeleteTypes.Add(typesToCascadeDelete[a]);
}
String[] mergeRelevantNames = source.MergeRelevantNames;
if (mergeRelevantNames != null)
{
for (int a = mergeRelevantNames.Length; a-- > 0; )
{
Member resolvedMember = nameToMemberDict.Get(mergeRelevantNames[a]);
target.SetMergeRelevant(resolvedMember, true);
}
}
SetMergeRelevant(target, target.CreatedByMember, false);
SetMergeRelevant(target, target.CreatedOnMember, false);
SetMergeRelevant(target, target.UpdatedByMember, false);
SetMergeRelevant(target, target.UpdatedOnMember, false);
SetMergeRelevant(target, target.IdMember, false);
SetMergeRelevant(target, target.VersionMember, false);
//target.Initialize(CacheModification, EntityFactory);
return target;
}
throw new Exception("Source of type " + sourceType.Name + " not supported");
}
protected void SetMergeRelevant(EntityMetaData metaData, Member member, bool value)
{
if (member != null)
{
metaData.SetMergeRelevant(member, value);
}
}
protected IntermediatePrimitiveMember GetPrimitiveMember(Type entityType, String memberName, IMap<String, Member> nameToMemberDict)
{
if (memberName == null)
{
return null;
}
IntermediatePrimitiveMember member = (IntermediatePrimitiveMember)nameToMemberDict.Get(memberName);
if (member != null)
{
return member;
}
member = IntermediateMemberTypeProvider.GetIntermediatePrimitiveMember(entityType, memberName);
if (member == null)
{
throw new Exception("No member with name '" + memberName + "' found on entity type '" + entityType.FullName + "'");
}
nameToMemberDict.Put(memberName, member);
return member;
}
protected RelationMember GetRelationMember(Type entityType, String memberName, IMap<String, Member> nameToMemberDict)
{
RelationMember member = (RelationMember) nameToMemberDict.Get(memberName);
if (member != null)
{
return member;
}
member = IntermediateMemberTypeProvider.GetIntermediateRelationMember(entityType, memberName);
if (member == null)
{
throw new Exception("No member with name '" + memberName + "' found on entity type '" + entityType.FullName + "'");
}
nameToMemberDict.Put(memberName, member);
return member;
}
protected PrimitiveMember[] GetPrimitiveMembers(Type entityType, String[] memberNames, IMap<String, Member> nameToMemberDict)
{
if (memberNames == null)
{
return EntityMetaData.EmptyPrimitiveMembers;
}
PrimitiveMember[] members = new PrimitiveMember[memberNames.Length];
for (int a = memberNames.Length; a-- > 0;)
{
members[a] = GetPrimitiveMember(entityType, memberNames[a], nameToMemberDict);
}
return members;
}
protected RelationMember[] GetRelationMembers(Type entityType, String[] memberNames, IMap<String, Member> nameToMemberDict)
{
if (memberNames == null)
{
return EntityMetaData.EmptyRelationMembers;
}
RelationMember[] members = new RelationMember[memberNames.Length];
for (int a = memberNames.Length; a-- > 0;)
{
members[a] = GetRelationMember(entityType, memberNames[a], nameToMemberDict);
}
return members;
}
protected String GetNameOfMember(Member member)
{
if (member == null)
{
return null;
}
return member.Name;
}
protected String[] GetNamesOfMembers(Member[] members)
{
if (members == null)
{
return null;
}
String[] names = new String[members.Length];
for (int a = members.Length; a-- > 0;)
{
names[a] = GetNameOfMember(members[a]);
}
return names;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// InheritanceOperations operations.
/// </summary>
internal partial class InheritanceOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IInheritanceOperations
{
/// <summary>
/// Initializes a new instance of the InheritanceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal InheritanceOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that extend others
/// </summary>
/// <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="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SiameseInner>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// 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("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + 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 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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_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<SiameseInner>();
_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<SiameseInner>(_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>
/// Put complex types that extend others
/// </summary>
/// <param name='complexBody'>
/// Please put a siamese with id=2, name="Siameee", color=green,
/// breed=persion, which hates 2 dogs, the 1st one named "Potato" with id=1
/// and food="tomato", and the 2nd one named "Tomato" with id=-1 and
/// food="french fries".
/// </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="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> PutValidWithHttpMessagesAsync(SiameseInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
// 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("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + 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(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, 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 != 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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
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 (_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;
}
}
}
| |
namespace XmlUnit {
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Schema;
public class XmlDiff {
private const string XMLNS_PREFIX = "xmlns";
private readonly XmlInput controlInput;
private readonly XmlInput testInput;
private readonly DiffConfiguration _diffConfiguration;
private DiffResult _diffResult;
public XmlDiff(XmlInput control, XmlInput test,
DiffConfiguration diffConfiguration) {
_diffConfiguration = diffConfiguration;
controlInput = control;
testInput = test;
}
public XmlDiff(XmlInput control, XmlInput test)
: this(control, test, new DiffConfiguration()) {
}
public XmlDiff(TextReader control, TextReader test)
: this(new XmlInput(control), new XmlInput(test)) {
}
public XmlDiff(string control, string test)
: this(new XmlInput(control), new XmlInput(test)) {
}
private XmlReader CreateXmlReader(XmlInput forInput) {
XmlReader xmlReader = forInput.CreateXmlReader();
if (xmlReader is XmlTextReader) {
((XmlTextReader) xmlReader ).WhitespaceHandling = _diffConfiguration.WhitespaceHandling;
}
if (_diffConfiguration.UseValidatingParser) {
var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema | ValidationType.DTD;
var validatingReader = XmlReader.Create(xmlReader, settings);
return validatingReader;
}
return xmlReader;
}
public DiffResult Compare() {
if (_diffResult == null) {
_diffResult = new DiffResult();
XmlReader controlReader, testReader;
controlReader = testReader = null;
try {
controlReader = CreateXmlReader(controlInput);
testReader = CreateXmlReader(testInput);
if (!controlInput.Equals(testInput)) {
Compare(_diffResult, controlReader, testReader);
}
} finally {
try {
if (testReader != null) {
testReader.Close();
}
} finally {
if (controlReader != null) {
controlReader.Close();
}
}
}
}
return _diffResult;
}
private void Compare(DiffResult result, XmlReader controlReader,
XmlReader testReader) {
try {
ReaderWithState control = new ReaderWithState(controlReader);
ReaderWithState test = new ReaderWithState(testReader);
do {
control.Read();
test.Read();
Compare(result, control, test);
} while (control.HasRead && test.HasRead) ;
} catch (FlowControlException e) {
Console.Out.WriteLine(e.Message);
}
}
private void Compare(DiffResult result, ReaderWithState control,
ReaderWithState test) {
if (control.HasRead) {
if (test.HasRead) {
CompareNodes(result, control, test);
CheckEmptyOrAtEndElement(result, control, test);
} else {
DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result);
}
}
}
private void CompareNodes(DiffResult result, ReaderWithState control,
ReaderWithState test) {
XmlNodeType controlNodeType = control.Reader.NodeType;
XmlNodeType testNodeType = test.Reader.NodeType;
if (!controlNodeType.Equals(testNodeType)) {
CheckNodeTypes(controlNodeType, testNodeType, result,
control, test);
} else if (controlNodeType == XmlNodeType.Element) {
CompareElements(result, control, test);
} else if (controlNodeType == XmlNodeType.Text) {
CompareText(result, control, test);
}
}
private void CheckNodeTypes(XmlNodeType controlNodeType,
XmlNodeType testNodeType,
DiffResult result,
ReaderWithState control,
ReaderWithState test) {
ReaderWithState readerToAdvance = null;
if (controlNodeType.Equals(XmlNodeType.XmlDeclaration)) {
readerToAdvance = control;
} else if (testNodeType.Equals(XmlNodeType.XmlDeclaration)) {
readerToAdvance = test;
}
if (readerToAdvance != null) {
DifferenceFound(DifferenceType.HAS_XML_DECLARATION_PREFIX_ID,
controlNodeType, testNodeType, result);
readerToAdvance.Read();
CompareNodes(result, control, test);
} else {
DifferenceFound(DifferenceType.NODE_TYPE_ID, controlNodeType,
testNodeType, result);
}
}
private void CompareElements(DiffResult result, ReaderWithState control,
ReaderWithState test) {
string controlTagName = control.Reader.Name;
string testTagName = test.Reader.Name;
if (!String.Equals(controlTagName, testTagName)) {
DifferenceFound(DifferenceType.ELEMENT_TAG_NAME_ID, result);
} else {
XmlAttribute[] controlAttributes =
GetNonSpecialAttributes(control);
XmlAttribute[] testAttributes = GetNonSpecialAttributes(test);
if (controlAttributes.Length != testAttributes.Length) {
DifferenceFound(DifferenceType.ELEMENT_NUM_ATTRIBUTES_ID, result);
}
CompareAttributes(result, controlAttributes, testAttributes);
}
}
private void CompareAttributes(DiffResult result,
XmlAttribute[] controlAttributes,
XmlAttribute[] testAttributes) {
ArrayList unmatchedTestAttributes = new ArrayList();
unmatchedTestAttributes.AddRange(testAttributes);
for (int i=0; i < controlAttributes.Length; ++i) {
bool controlIsInNs = IsNamespaced(controlAttributes[i]);
string controlAttrName =
GetUnNamespacedNodeName(controlAttributes[i]);
XmlAttribute testAttr = null;
if (!controlIsInNs) {
testAttr = FindAttributeByName(testAttributes,
controlAttrName);
} else {
testAttr = FindAttributeByNameAndNs(testAttributes,
controlAttrName,
controlAttributes[i]
.NamespaceURI);
}
if (testAttr != null) {
unmatchedTestAttributes.Remove(testAttr);
if (!_diffConfiguration.IgnoreAttributeOrder
&& testAttr != testAttributes[i]) {
DifferenceFound(DifferenceType.ATTR_SEQUENCE_ID,
result);
}
if (controlAttributes[i].Value != testAttr.Value) {
DifferenceFound(DifferenceType.ATTR_VALUE_ID, result);
}
} else {
DifferenceFound(DifferenceType.ATTR_NAME_NOT_FOUND_ID,
result);
}
}
foreach (XmlAttribute a in unmatchedTestAttributes) {
DifferenceFound(DifferenceType.ATTR_NAME_NOT_FOUND_ID, result);
}
}
private void CompareText(DiffResult result, ReaderWithState control,
ReaderWithState test) {
string controlText = control.Reader.Value;
string testText = test.Reader.Value;
if (!String.Equals(controlText, testText)) {
DifferenceFound(DifferenceType.TEXT_VALUE_ID, result);
}
}
private void DifferenceFound(DifferenceType differenceType, DiffResult result) {
DifferenceFound(new Difference(differenceType), result);
}
private void DifferenceFound(Difference difference, DiffResult result) {
result.DifferenceFound(this, difference);
if (!ContinueComparison(difference)) {
throw new FlowControlException(difference);
}
}
private void DifferenceFound(DifferenceType differenceType,
XmlNodeType controlNodeType,
XmlNodeType testNodeType,
DiffResult result) {
DifferenceFound(new Difference(differenceType, controlNodeType, testNodeType),
result);
}
private bool ContinueComparison(Difference afterDifference) {
return !afterDifference.MajorDifference;
}
private void CheckEmptyOrAtEndElement(DiffResult result,
ReaderWithState control,
ReaderWithState test) {
if (control.LastElementWasEmpty) {
if (!test.LastElementWasEmpty) {
CheckEndElement(test, result);
}
} else {
if (test.LastElementWasEmpty) {
CheckEndElement(control, result);
}
}
}
private XmlAttribute[] GetNonSpecialAttributes(ReaderWithState r) {
ArrayList l = new ArrayList();
int length = r.Reader.AttributeCount;
if (length > 0) {
XmlDocument doc = new XmlDocument();
r.Reader.MoveToFirstAttribute();
for (int i = 0; i < length; i++) {
XmlAttribute a = doc.CreateAttribute(r.Reader.Name,
r.Reader.NamespaceURI);
if (!IsXMLNSAttribute(a)) {
a.Value = r.Reader.Value;
l.Add(a);
}
r.Reader.MoveToNextAttribute();
}
}
return (XmlAttribute[]) l.ToArray(typeof(XmlAttribute));
}
private bool IsXMLNSAttribute(XmlAttribute attribute) {
return XMLNS_PREFIX == attribute.Prefix ||
XMLNS_PREFIX == attribute.Name;
}
private XmlAttribute FindAttributeByName(XmlAttribute[] attrs,
string name) {
foreach (XmlAttribute a in attrs) {
if (GetUnNamespacedNodeName(a) == name) {
return a;
}
}
return null;
}
private XmlAttribute FindAttributeByNameAndNs(XmlAttribute[] attrs,
string name,
string nsUri) {
foreach (XmlAttribute a in attrs) {
if (GetUnNamespacedNodeName(a) == name
&& a.NamespaceURI == nsUri) {
return a;
}
}
return null;
}
private string GetUnNamespacedNodeName(XmlNode aNode) {
return GetUnNamespacedNodeName(aNode, IsNamespaced(aNode));
}
private string GetUnNamespacedNodeName(XmlNode aNode,
bool isNamespacedNode) {
if (isNamespacedNode) {
return aNode.LocalName;
}
return aNode.Name;
}
private bool IsNamespaced(XmlNode aNode) {
string ns = aNode.NamespaceURI;
return ns != null && ns.Length > 0;
}
private void CheckEndElement(ReaderWithState reader, DiffResult result) {
bool readResult = reader.Read();
if (!readResult
|| reader.Reader.NodeType != XmlNodeType.EndElement) {
DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result);
}
}
public string OptionalDescription {
get {
return _diffConfiguration.Description;
}
}
private class FlowControlException : ApplicationException {
public FlowControlException(Difference cause) : base(cause.ToString()) {
}
}
private class ReaderWithState {
internal ReaderWithState(XmlReader reader) {
Reader = reader;
HasRead = false;
LastElementWasEmpty = false;
}
internal readonly XmlReader Reader;
internal bool HasRead;
internal bool LastElementWasEmpty;
internal bool Read() {
HasRead = Reader.Read();
if (HasRead) {
switch (Reader.NodeType) {
case XmlNodeType.Element:
LastElementWasEmpty = Reader.IsEmptyElement;
break;
case XmlNodeType.EndElement:
LastElementWasEmpty = false;
break;
default:
// don't care
break;
}
}
return HasRead;
}
internal string State {
get {
return string.Format("Name {0}, NodeType {1}, IsEmpty {2},"
+ " HasRead {3}, LastWasEmpty {4}",
Reader.Name,
Reader.NodeType,
Reader.IsEmptyElement,
HasRead, LastElementWasEmpty);
}
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Abstract;
using System.Linq;
using System.Reflection;
using Contoso.Abstract.NServiceBus;
using NServiceBus;
using NServiceBus.Unicast.Transport;
#if CLR45
using NServiceBusBus = NServiceBus.Bus;
#endif
namespace Contoso.Abstract
{
/// <summary>
/// INServiceBus
/// </summary>
public interface INServiceBus : IPublishingServiceBus
{
//int SendWithReturn(int executeTimeout, IServiceBusEndpoint endpoint, params object[] messages);
/// <summary>
/// Returns the specified value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
void Return<T>(T value);
/// <summary>
/// Gets the bus.
/// </summary>
IBus Bus { get; }
}
/// <summary>
/// NServiceBusAbstractor
/// </summary>
public class NServiceBusAbstractor : INServiceBus, ServiceBusManager.ISetupRegistration
{
private IServiceLocator _serviceLocator;
static NServiceBusAbstractor() { ServiceBusManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class.
/// </summary>
/// <param name="assemblies">The assemblies.</param>
public NServiceBusAbstractor(params Assembly[] assemblies)
: this(ServiceLocatorManager.Current, DefaultBusCreator(null, assemblies)) { }
/// <summary>
/// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class.
/// </summary>
/// <param name="serviceLocator">The service locator.</param>
/// <param name="assemblies">The assemblies.</param>
public NServiceBusAbstractor(IServiceLocator serviceLocator, params Assembly[] assemblies)
: this(serviceLocator, DefaultBusCreator(serviceLocator, assemblies)) { }
/// <summary>
/// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class.
/// </summary>
/// <param name="serviceLocator">The service locator.</param>
/// <param name="startableBus">The startable bus.</param>
public NServiceBusAbstractor(IServiceLocator serviceLocator, IStartableBus startableBus)
{
if (serviceLocator == null)
throw new ArgumentNullException("serviceLocator");
if (startableBus == null)
throw new ArgumentNullException("startableBus", "The specified NServiceBus bus cannot be null.");
_serviceLocator = serviceLocator;
Bus = startableBus.Start();
}
/// <summary>
/// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class.
/// </summary>
/// <param name="serviceLocator">The service locator.</param>
/// <param name="bus">The bus.</param>
public NServiceBusAbstractor(IServiceLocator serviceLocator, IBus bus)
{
if (serviceLocator == null)
throw new ArgumentNullException("serviceLocator");
if (bus == null)
throw new ArgumentNullException("bus", "The specified NServiceBus bus cannot be null.");
_serviceLocator = serviceLocator;
Bus = bus;
}
Action<IServiceLocator, string> ServiceBusManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceBusManager.RegisterInstance<INServiceBus>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.-or- null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
/// <summary>
/// Creates the message.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="messageBuilder">The message builder.</param>
/// <returns></returns>
public TMessage CreateMessage<TMessage>(Action<TMessage> messageBuilder)
where TMessage : class
{
#if !CLR45
var message = (TMessage)Bus.CreateInstance(typeof(TMessage));
if (messageBuilder != null)
messageBuilder(message);
return message;
#else
throw new NotImplementedException();
#endif
}
/// <summary>
/// Sends the specified endpoint.
/// </summary>
/// <param name="endpoint">The endpoint.</param>
/// <param name="messages">The messages.</param>
/// <returns></returns>
public virtual IServiceBusCallback Send(IServiceBusEndpoint endpoint, params object[] messages)
{
if (messages == null || messages.Length == 0 || messages[0] == null)
throw new ArgumentNullException("messages", "Please include at least one message.");
try
{
if (endpoint == null) Bus.Send(NServiceBusTransport.Cast(messages));
else if (endpoint != ServiceBus.SelfEndpoint) Bus.Send(NServiceBusTransport.Cast(endpoint), NServiceBusTransport.Cast(messages));
else Bus.SendLocal(NServiceBusTransport.Cast(messages));
}
catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); }
return null;
}
/// <summary>
/// Replies the specified messages.
/// </summary>
/// <param name="messages">The messages.</param>
public virtual void Reply(params object[] messages)
{
if (messages == null || messages.Length == 0 || messages[0] == null)
throw new ArgumentNullException("messages", "Please include at least one message.");
try { Bus.Reply(NServiceBusTransport.Cast(messages)); }
catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); }
}
#region Publishing ServiceBus
/// <summary>
/// Publishes the specified messages.
/// </summary>
/// <param name="messages">The messages.</param>
public virtual void Publish(params object[] messages)
{
if (messages == null || messages.Length == 0 || messages[0] == null)
throw new ArgumentNullException("messages");
try { Bus.Publish(NServiceBusTransport.Cast(messages)); }
catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); }
}
/// <summary>
/// Subscribes the specified message type.
/// </summary>
/// <param name="messageType">Type of the message.</param>
/// <param name="predicate">The predicate.</param>
public virtual void Subscribe(Type messageType, Predicate<object> predicate)
{
if (messageType == null)
throw new ArgumentNullException("messageType");
#if CLR45
if (predicate != null)
throw new ArgumentException("predicate", "Must be null.");
#endif
try
{
if (predicate == null) Bus.Subscribe(messageType);
#if !CLR45
else Bus.Subscribe(messageType,
#if !CLR4
NServiceBusTransport.Cast(predicate)
#else
predicate
#endif
);
#endif
}
catch (Exception ex) { throw new ServiceBusMessageException(messageType, ex); }
}
/// <summary>
/// Unsubscribes the specified message type.
/// </summary>
/// <param name="messageType">Type of the message.</param>
public virtual void Unsubscribe(Type messageType)
{
if (messageType == null)
throw new ArgumentNullException("messageType");
try { Bus.Unsubscribe(messageType); }
catch (Exception ex) { throw new ServiceBusMessageException(messageType, ex); }
}
#endregion
#region Domain-specific
/// <summary>
/// Gets the bus.
/// </summary>
public IBus Bus { get; set; }
/// <summary>
/// Sends the with return.
/// </summary>
/// <param name="executeTimeout">The execute timeout.</param>
/// <param name="endpoint">The endpoint.</param>
/// <param name="messages">The messages.</param>
/// <returns></returns>
public virtual int SendWithReturn(int executeTimeout, IServiceBusEndpoint endpoint, params object[] messages)
{
if (messages == null || messages.Length == 0 || messages[0] == null)
throw new ArgumentNullException("messages", "Please include at least one message.");
IAsyncResult asyncResult;
try
{
if (endpoint == null) asyncResult = Bus.Send(NServiceBusTransport.Cast(messages)).Register(state => { }, null);
if (endpoint != ServiceBus.SelfEndpoint) asyncResult = Bus.Send(NServiceBusTransport.Cast(endpoint), NServiceBusTransport.Cast(messages)).Register(state => { }, null);
else throw new NotSupportedException();
}
catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); }
if (!asyncResult.AsyncWaitHandle.WaitOne(executeTimeout))
throw new TimeoutException();
return ((CompletionResult)asyncResult.AsyncState).ErrorCode;
}
/// <summary>
/// Returns the specified value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
public virtual void Return<T>(T value)
{
if (typeof(T) != typeof(int))
throw new NotSupportedException();
try { Bus.Return(Convert.ToInt32(value)); }
catch (Exception ex) { throw new ServiceBusMessageException(null, ex); }
}
#endregion
/// <summary>
/// Defaults the bus creator.
/// </summary>
/// <param name="serviceLocator">The service locator.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns></returns>
public static IStartableBus DefaultBusCreator(IServiceLocator serviceLocator, params Assembly[] assemblies)
{
if (serviceLocator == null)
serviceLocator = ServiceLocatorManager.Current;
//return Configure.Instance.Builder.Build<IBus>() as IStartableBus;
#if !CLR4
return Configure.With(new[] { typeof(CompletionMessage).Assembly }.Union(assemblies))
.AbstractServiceBuilder() //: .DefaultBuilder()
.XmlSerializer()
.MsmqTransport()
.UnicastBus()
.CreateBus();
#elif !CLR45
return Configure.With(assemblies)
.AbstractServiceBuilder() //: .DefaultBuilder()
.UseTransport<Msmq>()
.UnicastBus()
.CreateBus();
#else
var configuration = new BusConfiguration();
configuration.AssembliesToScan(assemblies);
configuration.AbstractServiceBuilder(); //: .DefaultBuilder()
configuration.UseTransport<MsmqTransport>();
return NServiceBusBus.Create(configuration);
#endif
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Compiler.TypeSystem.Reflection;
using Boo.Lang.Compiler.Util;
using Boo.Lang.Environments;
namespace Boo.Lang.Compiler.Steps.MacroProcessing
{
public sealed class MacroExpander : AbstractNamespaceSensitiveTransformerCompilerStep
{
private int _expanded;
private Set<Node> _visited = new Set<Node>();
private Queue<Statement> _pendingExpansions = new Queue<Statement>();
private DynamicVariable<bool> _ignoringUnknownMacros = new DynamicVariable<bool>(false);
public bool ExpandAll()
{
Reset();
Run();
BubbleUpPendingTypeMembers();
return _expanded > 0;
}
private void Reset()
{
_pendingExpansions.Clear();
_visited.Clear();
_expanded = 0;
}
override public void Run()
{
ExpandModuleGlobalsIgnoringUnknownMacros();
ExpandModules();
}
private void ExpandModules()
{
foreach (Module module in CompileUnit.Modules)
ExpandOnModuleNamespace(module, VisitModule);
}
private void ExpandModuleGlobalsIgnoringUnknownMacros()
{
foreach (Module module in CompileUnit.Modules)
ExpandModuleGlobalsIgnoringUnknownMacros(module);
}
private void ExpandModuleGlobalsIgnoringUnknownMacros(Module current)
{
_ignoringUnknownMacros.With(true, ()=> ExpandOnModuleNamespace(current, VisitGlobalsAllowingCancellation));
}
private void VisitGlobalsAllowingCancellation(Module module)
{
var globals = module.Globals.Statements;
foreach (var stmt in globals.ToArray())
{
Node resultingNode;
if (VisitAllowingCancellation(stmt, out resultingNode) && resultingNode != stmt)
globals.Replace(stmt, (Statement) resultingNode);
BubbleUpPendingTypeMembers();
}
}
private void VisitModule(Module module)
{
Visit(module.Globals);
Visit(module.Members);
}
void ExpandOnModuleNamespace(Module module, Action<Module> action)
{
EnterModuleNamespace(module);
try
{
action(module);
}
finally
{
LeaveNamespace();
}
}
private void EnterModuleNamespace(Module module)
{
EnterNamespace(InternalModule.ScopeFor(module));
}
public override bool EnterClassDefinition(ClassDefinition node)
{
if (WasVisited(node))
return false;
_visited.Add(node);
return true;
}
bool _referenced;
internal void EnsureCompilerAssemblyReference(CompilerContext context)
{
if (_referenced)
return;
if (null != context.References.Find("Boo.Lang.Compiler"))
{
_referenced = true;
return;
}
context.References.Add(typeof(CompilerContext).Assembly);
_referenced = true;
}
override public void OnMacroStatement(MacroStatement node)
{
EnsureCompilerAssemblyReference(Context);
var macroType = ResolveMacroName(node) as IType;
if (null != macroType)
{
ExpandKnownMacro(node, macroType);
return;
}
if (_ignoringUnknownMacros.Value)
Cancel();
ExpandUnknownMacro(node);
}
private bool IsTopLevelExpansion()
{
return _expansionDepth == 0;
}
private void BubbleUpPendingTypeMembers()
{
while (_pendingExpansions.Count > 0)
TypeMemberStatementBubbler.BubbleTypeMemberStatementsUp(_pendingExpansions.Dequeue());
}
private void ExpandKnownMacro(MacroStatement node, IType macroType)
{
ExpandChildrenOfMacroOnMacroNamespace(node, macroType);
ProcessMacro(macroType, node);
}
private void ExpandChildrenOfMacroOnMacroNamespace(MacroStatement node, IType macroType)
{
EnterMacroNamespace(macroType);
try
{
ExpandChildrenOf(node);
}
finally
{
LeaveNamespace();
}
}
private void EnterMacroNamespace(IType macroType)
{
EnsureNestedMacrosCanBeSeenAsMembers(macroType);
EnterNamespace(new NamespaceDelegator(CurrentNamespace, macroType));
}
private static void EnsureNestedMacrosCanBeSeenAsMembers(IType macroType)
{
var internalMacroType = macroType as InternalClass;
if (null != internalMacroType)
TypeMemberStatementBubbler.BubbleTypeMemberStatementsUp(internalMacroType.TypeDefinition);
}
private void ExpandUnknownMacro(MacroStatement node)
{
ExpandChildrenOf(node);
if (IsTypeMemberMacro(node))
UnknownTypeMemberMacro(node);
else
TreatMacroAsMethodInvocation(node);
}
private static bool IsTypeMemberMacro(MacroStatement node)
{
return node.ParentNode.NodeType == NodeType.StatementTypeMember;
}
private void UnknownTypeMemberMacro(MacroStatement node)
{
var error = LooksLikeOldStyleFieldDeclaration(node)
? CompilerErrorFactory.UnknownClassMacroWithFieldHint(node, node.Name)
: CompilerErrorFactory.UnknownMacro(node, node.Name);
ProcessingError(error);
}
private static bool LooksLikeOldStyleFieldDeclaration(MacroStatement node)
{
return node.Arguments.Count == 0 && node.Body.IsEmpty;
}
private void ExpandChildrenOf(MacroStatement node)
{
EnterExpansion();
try
{
Visit(node.Body);
Visit(node.Arguments);
}
finally
{
LeaveExpansion();
}
}
private void LeaveExpansion()
{
--_expansionDepth;
}
private void EnterExpansion()
{
++_expansionDepth;
}
private void ProcessMacro(IType macroType, MacroStatement node)
{
var externalType = macroType as ExternalType;
if (externalType == null)
{
InternalClass internalType = (InternalClass) macroType;
ProcessInternalMacro(internalType, node);
return;
}
ProcessMacro(externalType.ActualType, node);
}
private void ProcessInternalMacro(InternalClass klass, MacroStatement node)
{
TypeDefinition macroDefinition = klass.TypeDefinition;
if (MacroDefinitionContainsMacroApplication(macroDefinition, node))
{
ProcessingError(CompilerErrorFactory.InvalidMacro(node, klass));
return;
}
var macroCompiler = My<MacroCompiler>.Instance;
bool firstTry = !macroCompiler.AlreadyCompiled(macroDefinition);
Type macroType = macroCompiler.Compile(macroDefinition);
if (macroType == null)
{
if (firstTry)
ProcessingError(CompilerErrorFactory.AstMacroMustBeExternal(node, klass));
else
RemoveCurrentNode();
return;
}
ProcessMacro(macroType, node);
}
private static bool MacroDefinitionContainsMacroApplication(TypeDefinition definition, MacroStatement statement)
{
return statement.GetAncestors<TypeDefinition>().Any(ancestor => ancestor == definition);
}
private int _expansionDepth;
private bool WasVisited(TypeDefinition node)
{
return _visited.Contains(node);
}
private void ProcessingError(CompilerError error)
{
Errors.Add(error);
RemoveCurrentNode();
}
private void ProcessMacro(Type actualType, MacroStatement node)
{
if (!typeof(IAstMacro).IsAssignableFrom(actualType))
{
ProcessingError(CompilerErrorFactory.InvalidMacro(node, Map(actualType)));
return;
}
++_expanded;
try
{
var macroExpansion = ExpandMacro(actualType, node);
var completeExpansion = ExpandMacroExpansion(node, macroExpansion);
ReplaceCurrentNode(completeExpansion);
if (completeExpansion != null && IsTopLevelExpansion())
_pendingExpansions.Enqueue(completeExpansion);
}
catch (LongJumpException)
{
throw;
}
catch (Exception error)
{
ProcessingError(CompilerErrorFactory.MacroExpansionError(node, error));
}
}
private IType Map(Type actualType)
{
return TypeSystemServices.Map(actualType);
}
private Statement ExpandMacroExpansion(MacroStatement node, Statement expansion)
{
if (null == expansion)
return null;
Statement modifiedExpansion = ApplyMacroModifierToExpansion(node, expansion);
modifiedExpansion.InitializeParent(node.ParentNode);
return Visit(modifiedExpansion);
}
private static Statement ApplyMacroModifierToExpansion(MacroStatement node, Statement expansion)
{
if (node.Modifier == null)
return expansion;
return NormalizeStatementModifiers.CreateModifiedStatement(node.Modifier, expansion);
}
private void TreatMacroAsMethodInvocation(MacroStatement node)
{
var invocation = new MethodInvocationExpression(node.LexicalInfo, new ReferenceExpression(node.LexicalInfo, node.Name))
{ Arguments = node.Arguments };
if (node.ContainsAnnotation("compound") || !IsNullOrEmpty(node.Body))
invocation.Arguments.Add(new BlockExpression(node.Body));
ReplaceCurrentNode(new ExpressionStatement(node.LexicalInfo, invocation, node.Modifier));
}
private static bool IsNullOrEmpty(Block block)
{
return block == null || block.IsEmpty;
}
private Statement ExpandMacro(Type macroType, MacroStatement node)
{
var macro = (IAstMacro) Activator.CreateInstance(macroType);
macro.Initialize(Context);
//use new-style BOO-1077 generator macro interface if available
var gm = macro as IAstGeneratorMacro;
if (gm != null)
return ExpandGeneratorMacro(gm, node);
return macro.Expand(node);
}
private static Statement ExpandGeneratorMacro(IAstGeneratorMacro macroType, MacroStatement node)
{
IEnumerable<Node> generatedNodes = macroType.ExpandGenerator(node);
if (null == generatedNodes)
return null;
return new NodeGeneratorExpander(node).Expand(generatedNodes);
}
private IEntity ResolveMacroName(MacroStatement node)
{
var macroTypeName = BuildMacroTypeName(node.Name);
var entity = ResolvePreferringInternalMacros(macroTypeName)
?? ResolvePreferringInternalMacros(node.Name);
if (entity is IType)
return entity;
if (entity == null)
return null;
//we got something interesting, check if it is/has an extension method
//that resolves a nested macro extension
return ResolveMacroExtensionType(node, entity as IMethod)
?? ResolveMacroExtensionType(node, entity as Ambiguous)
?? entity; //return as-is
}
private IEntity ResolvePreferringInternalMacros(string macroTypeName)
{
IEntity resolved = NameResolutionService.ResolveQualifiedName(macroTypeName);
Ambiguous ambiguous = resolved as Ambiguous;
if (null != ambiguous && ambiguous.AllEntitiesAre(EntityType.Type))
return Entities.PreferInternalEntitiesOverExternalOnes(ambiguous);
return resolved;
}
IEntity ResolveMacroExtensionType(MacroStatement node, Ambiguous extensions)
{
if (null == extensions)
return null;
foreach (var entity in extensions.Entities)
{
var extensionType = ResolveMacroExtensionType(node, entity as IMethod);
if (null != extensionType)
return extensionType;
}
return null;
}
IEntity ResolveMacroExtensionType(MacroStatement node, IMethod extension)
{
if (null == extension)
return null;
IType extendedMacroType = GetExtendedMacroType(extension);
if (null == extendedMacroType)
return null;
//ok now check if extension is correctly nested under parent
foreach (MacroStatement parent in node.GetAncestors<MacroStatement>())
if (ResolveMacroName(parent) == extendedMacroType)
return GetExtensionMacroType(extension);
return null;
}
IType GetExtendedMacroType(IMethod method)
{
InternalMethod internalMethod = method as InternalMethod;
if (null != internalMethod)
{
Method extension = internalMethod.Method;
if (!extension.Attributes.Contains(Types.CompilerGeneratedAttribute.FullName))
return null;
SimpleTypeReference sref = extension.Parameters[0].Type as SimpleTypeReference;
if (null != sref && extension.Parameters.Count == 2)
{
IType type = NameResolutionService.ResolveQualifiedName(sref.Name) as IType;
if (type != null && type.Name.EndsWith("Macro")) //no entity yet
return type;
}
}
else if (method is ExternalMethod && method.IsExtension)
{
var parameters = method.GetParameters();
if (parameters.Length == 2 && TypeSystemServices.IsMacro(parameters[0].Type))
return parameters[0].Type;
}
return null;
}
IType GetExtensionMacroType(IMethod method)
{
InternalMethod internalMethod = method as InternalMethod;
if (null != internalMethod)
{
Method extension = internalMethod.Method;
SimpleTypeReference sref = extension.ReturnType as SimpleTypeReference;
if (null != sref)
{
IType type = NameResolutionService.ResolveQualifiedName(sref.Name) as IType;
if (type != null && type.Name.EndsWith("Macro"))//no entity yet
return type;
}
}
else if (method is ExternalMethod)
return method.ReturnType;
return null;
}
private StringBuilder _buffer = new StringBuilder();
private string BuildMacroTypeName(string name)
{
_buffer.Length = 0;
if (!char.IsUpper(name[0]))
{
_buffer.Append(char.ToUpper(name[0]));
_buffer.Append(name.Substring(1));
_buffer.Append("Macro");
}
else
{
_buffer.Append(name);
_buffer.Append("Macro");
}
return _buffer.ToString();
}
}
}
| |
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.ModelBinding;
using System.Web.Security;
using Microsoft.AspNet.Identity;
using umbraco.cms.businesslogic.packager;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Web.Models;
using Umbraco.Web.Security;
using IUser = Umbraco.Core.Models.Membership.IUser;
namespace Umbraco.Web.Editors
{
internal class PasswordChanger
{
private readonly ILogger _logger;
private readonly IUserService _userService;
private readonly HttpContextBase _httpContext;
public PasswordChanger(ILogger logger, IUserService userService, HttpContextBase httpContext)
{
_logger = logger;
_userService = userService;
_httpContext = httpContext;
}
/// <summary>
/// Changes the password for a user based on the many different rules and config options
/// </summary>
/// <param name="currentUser">The user performing the password save action</param>
/// <param name="savingUser">The user who's password is being changed</param>
/// <param name="passwordModel"></param>
/// <param name="userMgr"></param>
/// <returns></returns>
public async Task<Attempt<PasswordChangedModel>> ChangePasswordWithIdentityAsync(
IUser currentUser,
IUser savingUser,
ChangingPasswordModel passwordModel,
BackOfficeUserManager<BackOfficeIdentityUser> userMgr)
{
if (passwordModel == null) throw new ArgumentNullException("passwordModel");
if (userMgr == null) throw new ArgumentNullException("userMgr");
//check if this identity implementation is powered by an underlying membership provider (it will be in most cases)
var membershipPasswordHasher = userMgr.PasswordHasher as IMembershipProviderPasswordHasher;
//check if this identity implementation is powered by an IUserAwarePasswordHasher (it will be by default in 7.7+ but not for upgrades)
var userAwarePasswordHasher = userMgr.PasswordHasher as IUserAwarePasswordHasher<BackOfficeIdentityUser, int>;
if (membershipPasswordHasher != null && userAwarePasswordHasher == null)
{
//if this isn't using an IUserAwarePasswordHasher, then fallback to the old way
if (membershipPasswordHasher.MembershipProvider.RequiresQuestionAndAnswer)
throw new NotSupportedException("Currently the user editor does not support providers that have RequiresQuestionAndAnswer specified");
return ChangePasswordWithMembershipProvider(savingUser.Username, passwordModel, membershipPasswordHasher.MembershipProvider);
}
//if we are here, then a IUserAwarePasswordHasher is available, however we cannot proceed in that case if for some odd reason
//the user has configured the membership provider to not be hashed. This will actually never occur because the BackOfficeUserManager
//will throw if it's not hashed, but we should make sure to check anyways (i.e. in case we want to unit test!)
if (membershipPasswordHasher != null && membershipPasswordHasher.MembershipProvider.PasswordFormat != MembershipPasswordFormat.Hashed)
{
throw new InvalidOperationException("The membership provider cannot have a password format of " + membershipPasswordHasher.MembershipProvider.PasswordFormat + " and be configured with secured hashed passwords");
}
//Are we resetting the password?
//This flag indicates that either an admin user is changing another user's password without knowing the original password
// or that the password needs to be reset to an auto-generated one.
if (passwordModel.Reset.HasValue && passwordModel.Reset.Value)
{
//if it's the current user, the current user cannot reset their own password
if (currentUser.Username == savingUser.Username)
{
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset is not allowed", new[] { "resetPassword" }) });
}
//if the current user has access to reset/manually change the password
if (currentUser.HasSectionAccess(Umbraco.Core.Constants.Applications.Users) == false)
{
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("The current user is not authorized", new[] { "resetPassword" }) });
}
//ok, we should be able to reset it
var resetToken = await userMgr.GeneratePasswordResetTokenAsync(savingUser.Id);
var newPass = passwordModel.NewPassword.IsNullOrWhiteSpace()
? userMgr.GeneratePassword()
: passwordModel.NewPassword;
var resetResult = await userMgr.ChangePasswordWithResetAsync(savingUser.Id, resetToken, newPass);
if (resetResult.Succeeded == false)
{
var errors = string.Join(". ", resetResult.Errors);
_logger.Warn<PasswordChanger>(string.Format("Could not reset user password {0}", errors));
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult(errors, new[] { "resetPassword" }) });
}
return Attempt.Succeed(new PasswordChangedModel());
}
//we're not resetting it so we need to try to change it.
if (passwordModel.NewPassword.IsNullOrWhiteSpace())
{
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Cannot set an empty password", new[] { "value" }) });
}
//we cannot arbitrarily change the password without knowing the old one and no old password was supplied - need to return an error
if (passwordModel.OldPassword.IsNullOrWhiteSpace())
{
//if password retrieval is not enabled but there is no old password we cannot continue
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) });
}
//get the user
var backOfficeIdentityUser = await userMgr.FindByIdAsync(savingUser.Id);
if (backOfficeIdentityUser == null)
{
//this really shouldn't ever happen... but just in case
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password could not be verified", new[] { "oldPassword" }) });
}
//is the old password correct?
var validateResult = await userMgr.CheckPasswordAsync(backOfficeIdentityUser, passwordModel.OldPassword);
if(validateResult == false)
{
//no, fail with an error message for "oldPassword"
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Incorrect password", new[] { "oldPassword" }) });
}
//can we change to the new password?
var changeResult = await userMgr.ChangePasswordAsync(savingUser.Id, passwordModel.OldPassword, passwordModel.NewPassword);
if (changeResult.Succeeded == false)
{
//no, fail with error messages for "password"
var errors = string.Join(". ", changeResult.Errors);
_logger.Warn<PasswordChanger>(string.Format("Could not change user password {0}", errors));
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult(errors, new[] { "password" }) });
}
return Attempt.Succeed(new PasswordChangedModel());
}
/// <summary>
/// Changes password for a member/user given the membership provider and the password change model
/// </summary>
/// <param name="username">The username of the user having their password changed</param>
/// <param name="passwordModel"></param>
/// <param name="membershipProvider"></param>
/// <returns></returns>
public Attempt<PasswordChangedModel> ChangePasswordWithMembershipProvider(string username, ChangingPasswordModel passwordModel, MembershipProvider membershipProvider)
{
var umbracoBaseProvider = membershipProvider as MembershipProviderBase;
// YES! It is completely insane how many options you have to take into account based on the membership provider. yikes!
if (passwordModel == null) throw new ArgumentNullException("passwordModel");
if (membershipProvider == null) throw new ArgumentNullException("membershipProvider");
BackOfficeUserManager<BackOfficeIdentityUser> backofficeUserManager = null;
var userId = -1;
if (membershipProvider.IsUmbracoUsersProvider())
{
backofficeUserManager = _httpContext.GetOwinContext().GetBackOfficeUserManager();
if (backofficeUserManager != null)
{
var profile = _userService.GetProfileByUserName(username);
if (profile != null)
int.TryParse(profile.Id.ToString(), out userId);
}
}
//Are we resetting the password?
//This flag indicates that either an admin user is changing another user's password without knowing the original password
// or that the password needs to be reset to an auto-generated one.
if (passwordModel.Reset.HasValue && passwordModel.Reset.Value)
{
//if a new password is supplied then it's an admin user trying to change another user's password without knowing the original password
//this is only possible when using a membership provider if the membership provider supports AllowManuallyChangingPassword
if (passwordModel.NewPassword.IsNullOrWhiteSpace() == false)
{
if (umbracoBaseProvider !=null && umbracoBaseProvider.AllowManuallyChangingPassword)
{
//this provider allows manually changing the password without the old password, so we can just do it
try
{
var result = umbracoBaseProvider.ChangePassword(username, string.Empty, passwordModel.NewPassword);
if (result && backofficeUserManager != null && userId >= 0)
backofficeUserManager.RaisePasswordChangedEvent(userId);
return result == false
? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "value" }) })
: Attempt.Succeed(new PasswordChangedModel());
}
catch (Exception ex)
{
_logger.WarnWithException<PasswordChanger>("Could not change member password", ex);
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) });
}
}
else
{
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Provider does not support manually changing passwords", new[] { "value" }) });
}
}
//we've made it here which means we need to generate a new password
var canReset = membershipProvider.CanResetPassword(_userService);
if (canReset == false)
{
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset is not enabled", new[] { "resetPassword" }) });
}
if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace())
{
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset requires a password answer", new[] { "resetPassword" }) });
}
//ok, we should be able to reset it
try
{
var newPass = membershipProvider.ResetPassword(
username,
membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null);
if (membershipProvider.IsUmbracoUsersProvider() && backofficeUserManager != null && userId >= 0)
backofficeUserManager.RaisePasswordResetEvent(userId);
//return the generated pword
return Attempt.Succeed(new PasswordChangedModel { ResetPassword = newPass });
}
catch (Exception ex)
{
_logger.WarnWithException<PasswordChanger>("Could not reset member password", ex);
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not reset password, error: " + ex.Message + " (see log for full details)", new[] { "resetPassword" }) });
}
}
//we're not resetting it so we need to try to change it.
if (passwordModel.NewPassword.IsNullOrWhiteSpace())
{
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Cannot set an empty password", new[] { "value" }) });
}
//without being able to retrieve the original password,
//we cannot arbitrarily change the password without knowing the old one and no old password was supplied - need to return an error
if (passwordModel.OldPassword.IsNullOrWhiteSpace() && membershipProvider.EnablePasswordRetrieval == false)
{
//if password retrieval is not enabled but there is no old password we cannot continue
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) });
}
if (passwordModel.OldPassword.IsNullOrWhiteSpace() == false)
{
//if an old password is suplied try to change it
try
{
var result = membershipProvider.ChangePassword(username, passwordModel.OldPassword, passwordModel.NewPassword);
if (result && backofficeUserManager != null && userId >= 0)
backofficeUserManager.RaisePasswordChangedEvent(userId);
return result == false
? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "oldPassword" }) })
: Attempt.Succeed(new PasswordChangedModel());
}
catch (Exception ex)
{
_logger.WarnWithException<PasswordChanger>("Could not change member password", ex);
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) });
}
}
if (membershipProvider.EnablePasswordRetrieval == false)
{
//we cannot continue if we cannot get the current password
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) });
}
if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace())
{
//if the question answer is required but there isn't one, we cannot continue
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the password answer", new[] { "value" }) });
}
//lets try to get the old one so we can change it
try
{
var oldPassword = membershipProvider.GetPassword(
username,
membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null);
try
{
var result = membershipProvider.ChangePassword(username, oldPassword, passwordModel.NewPassword);
return result == false
? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password", new[] { "value" }) })
: Attempt.Succeed(new PasswordChangedModel());
}
catch (Exception ex1)
{
_logger.WarnWithException<PasswordChanger>("Could not change member password", ex1);
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex1.Message + " (see log for full details)", new[] { "value" }) });
}
}
catch (Exception ex2)
{
_logger.WarnWithException<PasswordChanger>("Could not retrieve member password", ex2);
return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex2.Message + " (see log for full details)", new[] { "value" }) });
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Reflection;
using DotSpatial.Controls;
using DotSpatial.Data;
using DotSpatial.Symbology;
using DotSpatial.Tests.Common;
using NUnit.Framework;
namespace DotSpatial.Serialization.Tests
{
public enum TestEnum
{
Default,
One,
Two
}
[TestFixture]
public class SerializationTests
{
private readonly List<string> _filesToRemove = new List<string>();
[TestFixtureTearDown]
public void Clear()
{
foreach (var tempFile in _filesToRemove)
{
try
{
File.Delete(tempFile);
}
catch (Exception)
{
// ignore exceptions
}
}
}
[Test]
public void TestSimpleGraph()
{
Node rootNode = new Node(1);
Node intNode = new Node(42);
rootNode.Nodes.Add(intNode);
intNode.Nodes.Add(rootNode);
Graph g = new Graph(rootNode);
XmlSerializer s = new XmlSerializer();
string result = s.Serialize(g);
XmlDeserializer d = new XmlDeserializer();
Graph newGraph = d.Deserialize<Graph>(result);
Assert.IsNotNull(newGraph);
Assert.AreEqual(g.Root.Data, newGraph.Root.Data);
Assert.AreEqual(g.Root.Nodes[0].Data, newGraph.Root.Nodes[0].Data);
Assert.AreEqual(g.Root.Nodes[0].Nodes[0].Data, newGraph.Root.Nodes[0].Nodes[0].Data);
Assert.AreSame(newGraph.Root, newGraph.Root.Nodes[0].Nodes[0]);
}
[Test]
public void TestGraphWithEnumNode()
{
Node rootNode = new Node(1);
Node intNode = new Node(42);
Node enumNode = new Node(TestEnum.Two);
rootNode.Nodes.Add(intNode);
rootNode.Nodes.Add(enumNode);
intNode.Nodes.Add(rootNode);
Graph g = new Graph(rootNode);
XmlSerializer s = new XmlSerializer();
string result = s.Serialize(g);
XmlDeserializer d = new XmlDeserializer();
Graph newGraph = d.Deserialize<Graph>(result);
Assert.IsNotNull(newGraph);
Assert.AreEqual(g.Root.Data, newGraph.Root.Data);
Assert.AreEqual(g.Root.Nodes[0].Data, newGraph.Root.Nodes[0].Data);
Assert.AreEqual(g.Root.Nodes[1].Data, newGraph.Root.Nodes[1].Data);
Assert.AreEqual(g.Root.Nodes[0].Nodes[0].Data, newGraph.Root.Nodes[0].Nodes[0].Data);
Assert.AreSame(newGraph.Root, newGraph.Root.Nodes[0].Nodes[0]);
}
[Test]
public void TestGraphWithStringNode()
{
Node rootNode = new Node(1);
Node intNode = new Node(42);
Node stringNode = new Node("test string with <invalid> characters!");
rootNode.Nodes.Add(intNode);
rootNode.Nodes.Add(stringNode);
intNode.Nodes.Add(rootNode);
Graph g = new Graph(rootNode);
XmlSerializer s = new XmlSerializer();
string result = s.Serialize(g);
XmlDeserializer d = new XmlDeserializer();
Graph newGraph = d.Deserialize<Graph>(result);
Assert.IsNotNull(newGraph);
Assert.AreEqual(g.Root.Data, newGraph.Root.Data);
Assert.AreEqual(g.Root.Nodes[0].Data, newGraph.Root.Nodes[0].Data);
Assert.AreEqual(g.Root.Nodes[1].Data, newGraph.Root.Nodes[1].Data);
Assert.AreEqual(g.Root.Nodes[0].Nodes[0].Data, newGraph.Root.Nodes[0].Nodes[0].Data);
Assert.AreSame(newGraph.Root, newGraph.Root.Nodes[0].Nodes[0]);
}
[Test]
public void TestDictionary()
{
Dictionary<int, object> dictionary = new Dictionary<int, object>();
dictionary.Add(1, new Node(42));
dictionary.Add(2, "Hello <insert name here>!");
XmlSerializer s = new XmlSerializer();
string result = s.Serialize(dictionary);
XmlDeserializer d = new XmlDeserializer();
Dictionary<int, object> newDictionary = d.Deserialize<Dictionary<int, object>>(result);
foreach (var key in dictionary.Keys)
{
Assert.AreEqual(dictionary[key], newDictionary[key]);
}
}
[Test]
public void TestMapPointLayer()
{
string filename = Path.Combine("Data", "test-RandomPts.shp");
IFeatureSet fs = FeatureSet.Open(filename);
MapPointLayer l = new MapPointLayer(fs);
XmlSerializer s = new XmlSerializer();
string result = s.Serialize(l);
XmlDeserializer d = new XmlDeserializer();
MapPointLayer newPointLayer = d.Deserialize<MapPointLayer>(result);
Assert.IsNotNull(newPointLayer);
Assert.True(filename.Contains(newPointLayer.DataSet.Filename));
}
/// <summary>
/// Test for DotSpatial Issue #254
/// </summary>
[Test]
public void TestMapFrameIsNotNull()
{
string filename = Path.Combine("Data", "test-RandomPts.shp");
string projectFileName = FileTools.GetTempFileName(".dspx");
_filesToRemove.Add(projectFileName);
AppManager manager = new AppManager();
Map map = new Map();
manager.Map = map;
IFeatureSet fs = FeatureSet.Open(filename);
MapPointLayer l = new MapPointLayer(fs);
map.Layers.Add(l);
Assert.Greater(map.Layers.Count, 0);
manager.SerializationManager.SaveProject(projectFileName);
Assert.True(File.Exists(projectFileName));
//reopen the project
map.Layers.Clear();
Assert.AreEqual(map.Layers.Count, 0);
manager.SerializationManager.OpenProject(projectFileName);
Assert.Greater(map.Layers.Count, 0);
Assert.IsNotNull(map.Layers[0].MapFrame);
}
/// <summary>
/// Test for DotSpatial Issue #254
/// </summary>
[Test]
public void TestMapFrameIsNotNull_Group()
{
string filename = Path.Combine("Data", "test-RandomPts.shp");
string projectFileName = FileTools.GetTempFileName(".dspx");
_filesToRemove.Add(projectFileName);
AppManager manager = new AppManager();
Map map = new Map();
manager.Map = map;
//new map group added to map
MapGroup grp = new MapGroup(map, "group1");
//new map layer added to group
IFeatureSet fs = FeatureSet.Open(filename);
MapPointLayer l = new MapPointLayer(fs);
//add layer to group
grp.Layers.Add(l);
Assert.Greater(map.Layers.Count, 0);
Assert.IsNotNull(l.MapFrame);
manager.SerializationManager.SaveProject(projectFileName);
Assert.True(File.Exists(projectFileName));
//reopen the project
map.Layers.Clear();
Assert.AreEqual(map.Layers.Count, 0);
manager.SerializationManager.OpenProject(projectFileName);
List<ILayer> layers = map.GetAllLayers();
Assert.IsNotNull(layers[0].MapFrame);
}
[Test]
public void TestFormatter()
{
ObjectWithIntMember obj = new ObjectWithIntMember(0xBEEF);
XmlSerializer s = new XmlSerializer();
string xml = s.Serialize(obj);
XmlDeserializer d = new XmlDeserializer();
ObjectWithIntMember result1 = d.Deserialize<ObjectWithIntMember>(xml);
Assert.IsNotNull(result1);
Assert.AreEqual(0xBEEF, result1.Number);
ObjectWithIntMember result2 = new ObjectWithIntMember(0);
d.Deserialize(result2, xml);
Assert.IsNotNull(result2);
Assert.AreEqual(0xBEEF, result2.Number);
}
[Test]
public void TestPointSerializationMap()
{
var pt = new Point(1, 2);
var s = new XmlSerializer();
var xml = s.Serialize(pt);
var d = new XmlDeserializer();
var result = d.Deserialize<Point>(xml);
Assert.AreEqual(pt, result);
}
[Test]
public void TestRectangleSerializationMap()
{
var rectangle = new Rectangle(1, 1, 2, 2);
XmlSerializer s = new XmlSerializer();
string xml = s.Serialize(rectangle);
XmlDeserializer d = new XmlDeserializer();
Rectangle result = d.Deserialize<Rectangle>(xml);
Assert.AreEqual(1, result.X);
Assert.AreEqual(1, result.Y);
Assert.AreEqual(2, result.Width);
Assert.AreEqual(2, result.Height);
}
}
#region SerializationMap classes
// ReSharper disable UnusedMember.Global
public class PointSerializationMap : SerializationMap
// ReSharper restore UnusedMember.Global
{
public PointSerializationMap()
:base(typeof(Point))
{
var t = typeof(Point);
var x = t.GetField("x", BindingFlags.Instance | BindingFlags.NonPublic);
var y = t.GetField("y", BindingFlags.Instance | BindingFlags.NonPublic);
Serialize(x, "X").AsConstructorArgument(0);
Serialize(y, "Y").AsConstructorArgument(1);
}
}
// ReSharper disable UnusedMember.Global
public class RectangleSerializationMap : SerializationMap
// ReSharper restore UnusedMember.Global
{
public RectangleSerializationMap()
: base(typeof(Rectangle))
{
Type t = typeof(Rectangle);
var x = t.GetField("x", BindingFlags.Instance | BindingFlags.NonPublic);
var y = t.GetField("y", BindingFlags.Instance | BindingFlags.NonPublic);
var width = t.GetField("width", BindingFlags.Instance | BindingFlags.NonPublic);
var height = t.GetField("height", BindingFlags.Instance | BindingFlags.NonPublic);
Serialize(x, "X").AsConstructorArgument(0);
Serialize(y, "Y").AsConstructorArgument(1);
Serialize(width, "Width").AsConstructorArgument(2);
Serialize(height, "Height").AsConstructorArgument(3);
}
}
#endregion
}
| |
using System;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityStandardAssets.CinematicEffects
{
[ExecuteInEditMode]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Cinematic Image Effects/Screen Space Reflections")]
public class ScreenSpaceReflection : MonoBehaviour
{
public enum SSRResolution
{
High = 0,
Low = 2
}
public enum SSRReflectionBlendType
{
PhysicallyBased,
Additive
}
[Serializable]
public struct SSRSettings
{
[AttributeUsage(AttributeTargets.Field)]
public class LayoutAttribute : PropertyAttribute
{
}
[Layout]
public ReflectionSettings reflectionSettings;
[Layout]
public IntensitySettings intensitySettings;
[Layout]
public ScreenEdgeMask screenEdgeMask;
private static readonly SSRSettings s_Default = new SSRSettings
{
reflectionSettings = new ReflectionSettings
{
blendType = SSRReflectionBlendType.PhysicallyBased,
reflectionQuality = SSRResolution.High,
maxDistance = 100.0f,
iterationCount = 256,
stepSize = 3,
widthModifier = 0.5f,
reflectionBlur = 1.0f,
reflectBackfaces = true
},
intensitySettings = new IntensitySettings
{
reflectionMultiplier = 1.0f,
fadeDistance = 100.0f,
fresnelFade = 1.0f,
fresnelFadePower = 1.0f,
},
screenEdgeMask = new ScreenEdgeMask
{
intensity = 0.03f
}
};
public static SSRSettings defaultSettings
{
get
{
return s_Default;
}
}
}
[Serializable]
public struct IntensitySettings
{
[Tooltip("Nonphysical multiplier for the SSR reflections. 1.0 is physically based.")]
[Range(0.0f, 2.0f)]
public float reflectionMultiplier;
[Tooltip("How far away from the maxDistance to begin fading SSR.")]
[Range(0.0f, 1000.0f)]
public float fadeDistance;
[Tooltip("Amplify Fresnel fade out. Increase if floor reflections look good close to the surface and bad farther 'under' the floor.")]
[Range(0.0f, 1.0f)]
public float fresnelFade;
[Tooltip("Higher values correspond to a faster Fresnel fade as the reflection changes from the grazing angle.")]
[Range(0.1f, 10.0f)]
public float fresnelFadePower;
}
[Serializable]
public struct ReflectionSettings
{
// When enabled, we just add our reflections on top of the existing ones. This is physically incorrect, but several
// popular demos and games have taken this approach, and it does hide some artifacts.
[Tooltip("How the reflections are blended into the render.")]
public SSRReflectionBlendType blendType;
[Tooltip("Half resolution SSRR is much faster, but less accurate.")]
public SSRResolution reflectionQuality;
[Tooltip("Maximum reflection distance in world units.")]
[Range(0.1f, 300.0f)]
public float maxDistance;
/// REFLECTIONS
[Tooltip("Max raytracing length.")]
[Range(16, 1024)]
public int iterationCount;
[Tooltip("Log base 2 of ray tracing coarse step size. Higher traces farther, lower gives better quality silhouettes.")]
[Range(1, 16)]
public int stepSize;
[Tooltip("Typical thickness of columns, walls, furniture, and other objects that reflection rays might pass behind.")]
[Range(0.01f, 10.0f)]
public float widthModifier;
[Tooltip("Blurriness of reflections.")]
[Range(0.1f, 8.0f)]
public float reflectionBlur;
[Tooltip("Enable for a performance gain in scenes where most glossy objects are horizontal, like floors, water, and tables. Leave on for scenes with glossy vertical objects.")]
public bool reflectBackfaces;
}
[Serializable]
public struct ScreenEdgeMask
{
[Tooltip("Higher = fade out SSRR near the edge of the screen so that reflections don't pop under camera motion.")]
[Range(0.0f, 1.0f)]
public float intensity;
}
[SerializeField]
public SSRSettings settings = SSRSettings.defaultSettings;
///////////// Unexposed Variables //////////////////
[Tooltip("Enable to limit the effect a few bright pixels can have on rougher surfaces")]
private bool highlightSuppression = false;
[Tooltip("Enable to allow rays to pass behind objects. This can lead to more screen-space reflections, but the reflections are more likely to be wrong.")]
private bool traceBehindObjects = true;
[Tooltip("Enable to force more surfaces to use reflection probes if you see streaks on the sides of objects or bad reflections of their backs.")]
private bool treatBackfaceHitAsMiss = false;
[Tooltip("Drastically improves reflection reconstruction quality at the expense of some performance.")]
private bool bilateralUpsample = true;
///////////// Unexposed Variables //////////////////
[SerializeField]
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/ScreenSpaceReflection");
return m_Shader;
}
}
private Material m_Material;
public Material material
{
get
{
if (m_Material == null)
m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
private Camera m_Camera;
public Camera camera_
{
get
{
if (m_Camera == null)
m_Camera = GetComponent<Camera>();
return m_Camera;
}
}
private CommandBuffer m_CommandBuffer;
private static int kNormalAndRoughnessTexture;
private static int kHitPointTexture;
private static int[] kReflectionTextures;
private static int kFilteredReflections;
private static int kBlurTexture;
private static int kFinalReflectionTexture;
private static int kTempTexture;
// Shader pass indices used by the effect
private enum PassIndex
{
RayTraceStep = 0,
CompositeFinal = 1,
Blur = 2,
CompositeSSR = 3,
MinMipGeneration = 4,
HitPointToReflections = 5,
BilateralKeyPack = 6,
BlitDepthAsCSZ = 7,
PoissonBlur = 8,
}
private void OnEnable()
{
if (!ImageEffectHelper.IsSupported(shader, false, true, this))
{
enabled = false;
return;
}
camera_.depthTextureMode |= DepthTextureMode.Depth;
kReflectionTextures = new int[5];
kNormalAndRoughnessTexture = Shader.PropertyToID("_NormalAndRoughnessTexture");
kHitPointTexture = Shader.PropertyToID("_HitPointTexture");
kReflectionTextures[0] = Shader.PropertyToID("_ReflectionTexture0");
kReflectionTextures[1] = Shader.PropertyToID("_ReflectionTexture1");
kReflectionTextures[2] = Shader.PropertyToID("_ReflectionTexture2");
kReflectionTextures[3] = Shader.PropertyToID("_ReflectionTexture3");
kReflectionTextures[4] = Shader.PropertyToID("_ReflectionTexture4");
kBlurTexture = Shader.PropertyToID("_BlurTexture");
kFilteredReflections = Shader.PropertyToID("_FilteredReflections");
kFinalReflectionTexture = Shader.PropertyToID("_FinalReflectionTexture");
kTempTexture = Shader.PropertyToID("_TempTexture");
}
void OnDisable()
{
if (m_Material)
DestroyImmediate(m_Material);
m_Material = null;
if (camera_ != null)
{
if (m_CommandBuffer != null)
{
camera_.RemoveCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
}
m_CommandBuffer = null;
}
}
#if UNITY_EDITOR
void OnValidate()
{
if (camera_ != null)
{
if (m_CommandBuffer != null)
{
camera_.RemoveCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
}
m_CommandBuffer = null;
}
}
#endif
// [ImageEffectOpaque]
public void OnPreRender()
{
if (material == null)
{
return;
}
else if (Camera.current.actualRenderingPath != RenderingPath.DeferredShading)
{
return;
}
int downsampleAmount = (settings.reflectionSettings.reflectionQuality == SSRResolution.High) ? 1 : 2;
var rtW = camera_.pixelWidth / downsampleAmount;
var rtH = camera_.pixelHeight / downsampleAmount;
float sWidth = camera_.pixelWidth;
float sHeight = camera_.pixelHeight;
float sx = sWidth / 2.0f;
float sy = sHeight / 2.0f;
const int maxMip = 5;
RenderTextureFormat intermediateFormat = camera_.hdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
material.SetInt("_RayStepSize", settings.reflectionSettings.stepSize);
material.SetInt("_AdditiveReflection", settings.reflectionSettings.blendType == SSRReflectionBlendType.Additive ? 1 : 0);
material.SetInt("_BilateralUpsampling", bilateralUpsample ? 1 : 0);
material.SetInt("_TreatBackfaceHitAsMiss", treatBackfaceHitAsMiss ? 1 : 0);
material.SetInt("_AllowBackwardsRays", settings.reflectionSettings.reflectBackfaces ? 1 : 0);
material.SetInt("_TraceBehindObjects", traceBehindObjects ? 1 : 0);
material.SetInt("_MaxSteps", settings.reflectionSettings.iterationCount);
material.SetInt("_FullResolutionFiltering", 0);
material.SetInt("_HalfResolution", (settings.reflectionSettings.reflectionQuality != SSRResolution.High) ? 1 : 0);
material.SetInt("_HighlightSuppression", highlightSuppression ? 1 : 0);
/** The height in pixels of a 1m object if viewed from 1m away. */
float pixelsPerMeterAtOneMeter = sWidth / (-2.0f * (float)(Math.Tan(camera_.fieldOfView / 180.0 * Math.PI * 0.5)));
material.SetFloat("_PixelsPerMeterAtOneMeter", pixelsPerMeterAtOneMeter);
material.SetFloat("_ScreenEdgeFading", settings.screenEdgeMask.intensity);
material.SetFloat("_ReflectionBlur", settings.reflectionSettings.reflectionBlur);
material.SetFloat("_MaxRayTraceDistance", settings.reflectionSettings.maxDistance);
material.SetFloat("_FadeDistance", settings.intensitySettings.fadeDistance);
material.SetFloat("_LayerThickness", settings.reflectionSettings.widthModifier);
material.SetFloat("_SSRMultiplier", settings.intensitySettings.reflectionMultiplier);
material.SetFloat("_FresnelFade", settings.intensitySettings.fresnelFade);
material.SetFloat("_FresnelFadePower", settings.intensitySettings.fresnelFadePower);
Matrix4x4 P = camera_.projectionMatrix;
Vector4 projInfo = new Vector4
((-2.0f / (sWidth * P[0])),
(-2.0f / (sHeight * P[5])),
((1.0f - P[2]) / P[0]),
((1.0f + P[6]) / P[5]));
Vector3 cameraClipInfo = (float.IsPositiveInfinity(camera_.farClipPlane)) ?
new Vector3(camera_.nearClipPlane, -1.0f, 1.0f) :
new Vector3(camera_.nearClipPlane * camera_.farClipPlane, camera_.nearClipPlane - camera_.farClipPlane, camera_.farClipPlane);
material.SetVector("_ReflectionBufferSize", new Vector2(rtW, rtH));
material.SetVector("_ScreenSize", new Vector2(sWidth, sHeight));
material.SetVector("_InvScreenSize", new Vector2((float)(1.0f / sWidth), (float)(1.0f / sHeight)));
material.SetVector("_ProjInfo", projInfo); // used for unprojection
material.SetVector("_CameraClipInfo", cameraClipInfo);
Matrix4x4 warpToScreenSpaceMatrix = new Matrix4x4();
warpToScreenSpaceMatrix.SetRow(0, new Vector4(sx, 0.0f, 0.0f, sx));
warpToScreenSpaceMatrix.SetRow(1, new Vector4(0.0f, sy, 0.0f, sy));
warpToScreenSpaceMatrix.SetRow(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));
warpToScreenSpaceMatrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
Matrix4x4 projectToPixelMatrix = warpToScreenSpaceMatrix * P;
material.SetMatrix("_ProjectToPixelMatrix", projectToPixelMatrix);
material.SetMatrix("_WorldToCameraMatrix", camera_.worldToCameraMatrix);
material.SetMatrix("_CameraToWorldMatrix", camera_.worldToCameraMatrix.inverse);
if (m_CommandBuffer == null)
{
m_CommandBuffer = new CommandBuffer();
m_CommandBuffer.name = "Screen Space Reflections";
// RGB: Normals, A: Roughness.
// Has the nice benefit of allowing us to control the filtering mode as well.
m_CommandBuffer.GetTemporaryRT(kNormalAndRoughnessTexture, -1, -1, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
m_CommandBuffer.GetTemporaryRT(kHitPointTexture, rtW, rtH, 0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
for (int i = 0; i < maxMip; ++i)
{
// We explicitly interpolate during bilateral upsampling.
m_CommandBuffer.GetTemporaryRT(kReflectionTextures[i], rtW >> i, rtH >> i, 0, FilterMode.Bilinear, intermediateFormat);
}
m_CommandBuffer.GetTemporaryRT(kFilteredReflections, rtW, rtH, 0, bilateralUpsample ? FilterMode.Point : FilterMode.Bilinear, intermediateFormat);
m_CommandBuffer.GetTemporaryRT(kFinalReflectionTexture, rtW, rtH, 0, FilterMode.Point, intermediateFormat);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kNormalAndRoughnessTexture, material, (int)PassIndex.BilateralKeyPack);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kHitPointTexture, material, (int)PassIndex.RayTraceStep);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kFilteredReflections, material, (int)PassIndex.HitPointToReflections);
m_CommandBuffer.Blit(kFilteredReflections, kReflectionTextures[0], material, (int)PassIndex.PoissonBlur);
for (int i = 1; i < maxMip; ++i)
{
int inputTex = kReflectionTextures[i - 1];
int lowMip = i;
m_CommandBuffer.GetTemporaryRT(kBlurTexture, rtW >> lowMip, rtH >> lowMip, 0, FilterMode.Bilinear, intermediateFormat);
m_CommandBuffer.SetGlobalVector("_Axis", new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
m_CommandBuffer.SetGlobalFloat("_CurrentMipLevel", i - 1.0f);
m_CommandBuffer.Blit(inputTex, kBlurTexture, material, (int)PassIndex.Blur);
m_CommandBuffer.SetGlobalVector("_Axis", new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
inputTex = kReflectionTextures[i];
m_CommandBuffer.Blit(kBlurTexture, inputTex, material, (int)PassIndex.Blur);
m_CommandBuffer.ReleaseTemporaryRT(kBlurTexture);
}
m_CommandBuffer.Blit(kReflectionTextures[0], kFinalReflectionTexture, material, (int)PassIndex.CompositeSSR);
m_CommandBuffer.GetTemporaryRT(kTempTexture, camera_.pixelWidth, camera_.pixelHeight, 0, FilterMode.Bilinear, intermediateFormat);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kTempTexture, material, (int)PassIndex.CompositeFinal);
m_CommandBuffer.Blit(kTempTexture, BuiltinRenderTextureType.CameraTarget);
m_CommandBuffer.ReleaseTemporaryRT(kTempTexture);
camera_.AddCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
extern alias pt;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Ast;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.TestAdapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
using PythonConstants = pt::Microsoft.PythonTools.PythonConstants;
namespace TestAdapterTests {
[TestClass]
public class TestDiscovererTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
private const string _runSettings = @"<?xml version=""1.0""?><RunSettings><DataCollectionRunSettings><DataCollectors /></DataCollectionRunSettings><RunConfiguration><ResultsDirectory>C:\Visual Studio 2015\Projects\PythonApplication107\TestResults</ResultsDirectory><TargetPlatform>X86</TargetPlatform><TargetFrameworkVersion>Framework45</TargetFrameworkVersion></RunConfiguration><Python><TestCases><Project path=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\PythonApplication107.pyproj"" home=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\"" nativeDebugging="""" djangoSettingsModule="""" workingDir=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\"" interpreter=""C:\Python35-32\python.exe"" pathEnv=""PYTHONPATH""><Environment /><SearchPaths><Search value=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\"" /></SearchPaths>
<Test className=""Test_test1"" file=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py"" line=""17"" column=""9"" method=""test_A"" />
<Test className=""Test_test1"" file=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py"" line=""21"" column=""9"" method=""test_B"" />
<Test className=""Test_test2"" file=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py"" line=""48"" column=""9"" method=""test_C"" /></Project></TestCases></Python></RunSettings>";
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void TestDiscover() {
var ctx = new MockDiscoveryContext(new MockRunSettings(_runSettings));
var sink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
const string projectPath = @"C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\PythonApplication107.pyproj";
const string testFilePath = @"C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py";
new TestDiscoverer().DiscoverTests(
new[] { testFilePath },
ctx,
logger,
sink
);
PrintTestCases(sink.Tests);
var expectedTests = new[] {
TestInfo.FromRelativePaths("Test_test1", "test_A", projectPath, testFilePath, 17, TestOutcome.Passed),
TestInfo.FromRelativePaths("Test_test1", "test_B", projectPath, testFilePath, 21, TestOutcome.Passed),
TestInfo.FromRelativePaths("Test_test2", "test_C", projectPath, testFilePath, 48, TestOutcome.Passed)
};
Assert.AreEqual(expectedTests.Length, sink.Tests.Count);
foreach (var expectedTest in expectedTests) {
var expectedFullyQualifiedName = TestReader.MakeFullyQualifiedTestName(expectedTest.RelativeClassFilePath, expectedTest.ClassName, expectedTest.MethodName);
var actualTestCase = sink.Tests.SingleOrDefault(tc => tc.FullyQualifiedName == expectedFullyQualifiedName);
Assert.IsNotNull(actualTestCase, expectedFullyQualifiedName);
Assert.AreEqual(expectedTest.MethodName, actualTestCase.DisplayName, expectedFullyQualifiedName);
Assert.AreEqual(new Uri(PythonConstants.TestExecutorUriString), actualTestCase.ExecutorUri);
Assert.AreEqual(expectedTest.SourceCodeLineNumber, actualTestCase.LineNumber, expectedFullyQualifiedName);
Assert.IsTrue(IsSameFile(expectedTest.SourceCodeFilePath, actualTestCase.CodeFilePath), expectedFullyQualifiedName);
sink.Tests.Remove(actualTestCase);
}
Debug.WriteLine("");
Debug.WriteLine("");
Debug.WriteLine("");
Debug.WriteLine("");
PrintTestCases(sink.Tests);
}
private static IEnumerable<TestCaseInfo> GetTestCasesFromAst(string code, PythonAnalyzer analyzer) {
var codeStream = new MemoryStream(Encoding.UTF8.GetBytes(code));
var m = AstPythonModule.FromStream(analyzer.Interpreter, codeStream, "<string>", analyzer.LanguageVersion);
return TestAnalyzer.GetTestCasesFromAst(m, null);
}
[TestMethod, Priority(1)]
public void DecoratedTests() {
using (var analyzer = MakeTestAnalyzer()) {
var code = @"import unittest
def decorator(fn):
def wrapped(*args, **kwargs):
return fn(*args, **kwargs)
return wrapped
class MyTest(unittest.TestCase):
@decorator
def testAbc(self):
pass
";
var entry = AddModule(analyzer, "Fob", code);
entry.Analyze(CancellationToken.None, true);
analyzer.AnalyzeQueuedEntries(CancellationToken.None);
var test = TestAnalyzer.GetTestCasesFromAnalysis(entry).Single();
Assert.AreEqual("testAbc", test.MethodName);
Assert.AreEqual(10, test.StartLine);
test = GetTestCasesFromAst(code, analyzer).Single();
Assert.AreEqual("testAbc", test.MethodName);
Assert.AreEqual(10, test.StartLine);
}
}
[TestMethod, Priority(1)]
public void TestCaseSubclasses() {
using (var analyzer = MakeTestAnalyzer()) {
var entry1 = AddModule(analyzer, "Pkg.SubPkg", @"import unittest
class TestBase(unittest.TestCase):
pass
");
var entry2 = AddModule(
analyzer,
"Pkg",
moduleFile: "Pkg\\__init__.py",
code: @"from .SubPkg import TestBase"
);
var code = @"from Pkg.SubPkg import TestBase as TB1
from Pkg import TestBase as TB2
from Pkg import *
class MyTest1(TB1):
def test1(self):
pass
class MyTest2(TB2):
def test2(self):
pass
class MyTest3(TestBase):
def test3(self):
pass
";
var entry3 = AddModule(analyzer, "__main__", code);
entry1.Analyze(CancellationToken.None, true);
entry2.Analyze(CancellationToken.None, true);
entry3.Analyze(CancellationToken.None, true);
analyzer.AnalyzeQueuedEntries(CancellationToken.None);
var test = TestAnalyzer.GetTestCasesFromAnalysis(entry3).ToList();
AssertUtil.ContainsExactly(test.Select(t => t.MethodName), "test1", "test2", "test3");
// Cannot discover tests from subclasses with just the AST
test = GetTestCasesFromAst(code, analyzer).ToList();
AssertUtil.ContainsExactly(test.Select(t => t.MethodName));
}
}
[TestMethod, Priority(1)]
public void TestCaseRunTests() {
using (var analyzer = MakeTestAnalyzer()) {
var code = @"import unittest
class TestBase(unittest.TestCase):
def runTests(self):
pass # should not discover this as it isn't runTest or test*
def runTest(self):
pass
";
var entry = AddModule(analyzer, "__main__", code);
entry.Analyze(CancellationToken.None, true);
analyzer.AnalyzeQueuedEntries(CancellationToken.None);
var test = TestAnalyzer.GetTestCasesFromAnalysis(entry).ToList();
AssertUtil.ContainsExactly(test.Select(t => t.ClassName), "TestBase");
test = GetTestCasesFromAst(code, analyzer).ToList();
AssertUtil.ContainsExactly(test.Select(t => t.ClassName), "TestBase");
}
}
/// <summary>
/// If we have test* and runTest we shouldn't discover runTest
/// </summary>
[TestMethod, Priority(1)]
public void TestCaseRunTestsWithTest() {
using (var analyzer = MakeTestAnalyzer()) {
var code = @"import unittest
class TestBase(unittest.TestCase):
def test_1(self):
pass
def runTest(self):
pass
";
var entry = AddModule(analyzer, "__main__", code);
entry.Analyze(CancellationToken.None, true);
analyzer.AnalyzeQueuedEntries(CancellationToken.None);
var test = TestAnalyzer.GetTestCasesFromAnalysis(entry).ToList();
AssertUtil.ContainsExactly(test.Select(t => t.MethodName), "test_1");
test = GetTestCasesFromAst(code, analyzer).ToList();
AssertUtil.ContainsExactly(test.Select(t => t.MethodName), "test_1");
}
}
private PythonAnalyzer MakeTestAnalyzer() {
return PythonAnalyzer.CreateAsync(InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7))).Result;
}
private IPythonProjectEntry AddModule(PythonAnalyzer analyzer, string moduleName, string code, string moduleFile = null) {
using (var source = new StringReader(code)) {
var entry = analyzer.AddModule(
moduleName,
TestData.GetPath("Fob\\" + (moduleFile ?? moduleName.Replace('.', '\\') + ".py"))
);
using (var parser = Parser.CreateParser(source, PythonLanguageVersion.V27, new ParserOptions() { BindReferences = true })) {
entry.UpdateTree(parser.ParseFile(), null);
}
return entry;
}
}
private static bool IsSameFile(string a, string b) {
return String.Compare(new FileInfo(a).FullName, new FileInfo(b).FullName, StringComparison.CurrentCultureIgnoreCase) == 0;
}
private static void PrintTestCases(IEnumerable<TestCase> testCases) {
foreach (var tst in testCases) {
Console.WriteLine("Test: " + tst.FullyQualifiedName);
Console.WriteLine("Source: " + tst.Source);
Console.WriteLine("Display: " + tst.DisplayName);
Console.WriteLine("Location: " + tst.CodeFilePath);
Console.WriteLine("Location: " + tst.LineNumber.ToString());
Console.WriteLine("");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
/// <summary>
/// SemaphoreSlim unit tests
/// </summary>
public class SemaphoreSlimTests
{
/// <summary>
/// SemaphoreSlim public methods and properties to be tested
/// </summary>
private enum SemaphoreSlimActions
{
Constructor,
Wait,
WaitAsync,
Release,
Dispose,
CurrentCount,
AvailableWaitHandle
}
[Fact]
public static void RunSemaphoreSlimTest0_Ctor()
{
RunSemaphoreSlimTest0_Ctor(0, 10, null);
RunSemaphoreSlimTest0_Ctor(5, 10, null);
RunSemaphoreSlimTest0_Ctor(10, 10, null);
}
[Fact]
public static void RunSemaphoreSlimTest0_Ctor_Negative()
{
RunSemaphoreSlimTest0_Ctor(10, 0, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest0_Ctor(10, -1, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest0_Ctor(-1, 10, typeof(ArgumentOutOfRangeException));
}
[Fact]
public static void RunSemaphoreSlimTest1_Wait()
{
// Infinite timeout
RunSemaphoreSlimTest1_Wait(10, 10, -1, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, -1, true, null);
// Zero timeout
RunSemaphoreSlimTest1_Wait(10, 10, 0, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, 0, true, null);
RunSemaphoreSlimTest1_Wait(0, 10, 0, false, null);
// Positive timeout
RunSemaphoreSlimTest1_Wait(10, 10, 10, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, 10, true, null);
RunSemaphoreSlimTest1_Wait(0, 10, 10, false, null);
}
[Fact]
public static void RunSemaphoreSlimTest1_Wait_NegativeCases()
{
// Invalid timeout
RunSemaphoreSlimTest1_Wait(10, 10, -10, true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_Wait
(10, 10, new TimeSpan(0, 0, Int32.MaxValue), true, typeof(ArgumentOutOfRangeException));
}
[Fact]
public static void RunSemaphoreSlimTest1_WaitAsync()
{
// Infinite timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, -1, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, -1, true, null);
// Zero timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, 0, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, 0, true, null);
RunSemaphoreSlimTest1_WaitAsync(0, 10, 0, false, null);
// Positive timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, 10, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, 10, true, null);
RunSemaphoreSlimTest1_WaitAsync(0, 10, 10, false, null);
}
[Fact]
public static void RunSemaphoreSlimTest1_WaitAsync_NegativeCases()
{
// Invalid timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, -10, true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_WaitAsync
(10, 10, new TimeSpan(0, 0, Int32.MaxValue), true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_WaitAsync2();
}
[Fact]
public static void RunSemaphoreSlimTest2_Release()
{
// Valid release count
RunSemaphoreSlimTest2_Release(5, 10, 1, null);
RunSemaphoreSlimTest2_Release(0, 10, 1, null);
RunSemaphoreSlimTest2_Release(5, 10, 5, null);
}
[Fact]
public static void RunSemaphoreSlimTest2_Release_NegativeCases()
{
// Invalid release count
RunSemaphoreSlimTest2_Release(5, 10, 0, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest2_Release(5, 10, -1, typeof(ArgumentOutOfRangeException));
// Semaphore Full
RunSemaphoreSlimTest2_Release(10, 10, 1, typeof(SemaphoreFullException));
RunSemaphoreSlimTest2_Release(5, 10, 6, typeof(SemaphoreFullException));
RunSemaphoreSlimTest2_Release(int.MaxValue - 1, int.MaxValue, 10, typeof(SemaphoreFullException));
}
[Fact]
public static void RunSemaphoreSlimTest4_Dispose()
{
RunSemaphoreSlimTest4_Dispose(5, 10, null, null);
RunSemaphoreSlimTest4_Dispose(5, 10, SemaphoreSlimActions.CurrentCount, null);
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.Wait, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.WaitAsync, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.Release, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.AvailableWaitHandle, typeof(ObjectDisposedException));
}
[Fact]
public static void RunSemaphoreSlimTest5_CurrentCount()
{
RunSemaphoreSlimTest5_CurrentCount(5, 10, null);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Wait);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.WaitAsync);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Release);
}
[Fact]
public static void RunSemaphoreSlimTest7_AvailableWaitHandle()
{
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, null, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, null, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.Wait, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.WaitAsync, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, SemaphoreSlimActions.Release, true);
}
[Fact]
[OuterLoop]
public static void RunSemaphoreSlimCurrentTests()
{
RunSemaphoreSlimTest8_ConcWaitAndRelease
(5, 1000, 50, 50, 50, 0, 5, 1000);
RunSemaphoreSlimTest8_ConcWaitAndRelease
(0, 1000, 50, 25, 25, 25, 0, 5000);
RunSemaphoreSlimTest8_ConcWaitAndRelease
(0, 1000, 50, 0, 0, 50, 0, 100);
RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease
(5, 1000, 50, 50, 50, 0, 5, 1000);
RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease
(0, 1000, 50, 25, 25, 25, 0, 5000);
RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease
(0, 1000, 50, 0, 0, 50, 0, 100);
TestConcurrentWaitAndWaitAsync(10, 10);
TestConcurrentWaitAndWaitAsync(1, 10);
TestConcurrentWaitAndWaitAsync(10, 1);
}
/// <summary>
/// Test SemaphoreSlim constructor
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest0_Ctor(int initial, int maximum, Type exceptionType)
{
string methodFailed = "RunSemaphoreSlimTest0_Ctor(" + initial + "," + maximum + "): FAILED. ";
Exception exception = null;
try
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Assert.Equal(initial, semaphore.CurrentCount);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
exception = ex;
}
}
/// <summary>
/// Test SemaphoreSlim Wait
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param>
/// <param name="returnValue">The expected wait return value</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest1_Wait
(int initial, int maximum, object timeout, bool returnValue, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
bool result = false;
if (timeout is TimeSpan)
{
result = semaphore.Wait((TimeSpan)timeout);
}
else
{
result = semaphore.Wait((int)timeout);
}
Assert.Equal(returnValue, result);
if (result)
{
Assert.Equal(initial - 1, semaphore.CurrentCount);
}
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim WaitAsync
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param>
/// <param name="returnValue">The expected wait return value</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest1_WaitAsync
(int initial, int maximum, object timeout, bool returnValue, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
bool result = false;
if (timeout is TimeSpan)
{
result = semaphore.WaitAsync((TimeSpan)timeout).Result;
}
else
{
result = semaphore.WaitAsync((int)timeout).Result;
}
Assert.Equal(returnValue, result);
if (result)
{
Assert.Equal(initial - 1, semaphore.CurrentCount);
}
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim WaitAsync
/// The test verifies that SemaphoreSlim.Release() does not execute any user code synchronously.
/// </summary>
private static void RunSemaphoreSlimTest1_WaitAsync2()
{
SemaphoreSlim semaphore = new SemaphoreSlim(1);
ThreadLocal<int> counter = new ThreadLocal<int>(() => 0);
bool nonZeroObserved = false;
const int asyncActions = 20;
int remAsyncActions = asyncActions;
ManualResetEvent mre = new ManualResetEvent(false);
Action<int> doWorkAsync = async delegate (int i)
{
await semaphore.WaitAsync();
if (counter.Value > 0)
{
nonZeroObserved = true;
}
counter.Value = counter.Value + 1;
semaphore.Release();
counter.Value = counter.Value - 1;
if (Interlocked.Decrement(ref remAsyncActions) == 0) mre.Set();
};
semaphore.Wait();
for (int i = 0; i < asyncActions; i++) doWorkAsync(i);
semaphore.Release();
mre.WaitOne();
Assert.False(nonZeroObserved, "RunSemaphoreSlimTest1_WaitAsync2: FAILED. SemaphoreSlim.Release() seems to have synchronously invoked a continuation.");
}
/// <summary>
/// Test SemaphoreSlim Release
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="releaseCount">The release count for the release method</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest2_Release
(int initial, int maximum, int releaseCount, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
int oldCount = semaphore.Release(releaseCount);
Assert.Equal(initial, oldCount);
Assert.Equal(initial + releaseCount, semaphore.CurrentCount);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Call specific SemaphoreSlim method or property
/// </summary>
/// <param name="semaphore">The SemaphoreSlim instance</param>
/// <param name="action">The action name</param>
/// <param name="param">The action parameter, null if it takes no parameters</param>
/// <returns>The action return value, null if the action returns void</returns>
private static object CallSemaphoreAction
(SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param)
{
if (action == SemaphoreSlimActions.Wait)
{
if (param is TimeSpan)
{
return semaphore.Wait((TimeSpan)param);
}
else if (param is int)
{
return semaphore.Wait((int)param);
}
semaphore.Wait();
return null;
}
else if (action == SemaphoreSlimActions.WaitAsync)
{
if (param is TimeSpan)
{
return semaphore.WaitAsync((TimeSpan)param).Result;
}
else if (param is int)
{
return semaphore.WaitAsync((int)param).Result;
}
semaphore.WaitAsync().Wait();
return null;
}
else if (action == SemaphoreSlimActions.Release)
{
if (param != null)
{
return semaphore.Release((int)param);
}
return semaphore.Release();
}
else if (action == SemaphoreSlimActions.Dispose)
{
semaphore.Dispose();
return null;
}
else if (action == SemaphoreSlimActions.CurrentCount)
{
return semaphore.CurrentCount;
}
else if (action == SemaphoreSlimActions.AvailableWaitHandle)
{
return semaphore.AvailableWaitHandle;
}
return null;
}
/// <summary>
/// Test SemaphoreSlim Dispose
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called after Dispose</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
semaphore.Dispose();
CallSemaphoreAction(semaphore, action, null);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim CurrentCount property
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called before CurentCount</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest5_CurrentCount(int initial, int maximum, SemaphoreSlimActions? action)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
CallSemaphoreAction(semaphore, action, null);
if (action == null)
{
Assert.Equal(initial, semaphore.CurrentCount);
}
else
{
Assert.Equal(initial + (action == SemaphoreSlimActions.Release ? 1 : -1), semaphore.CurrentCount);
}
}
/// <summary>
/// Test SemaphoreSlim AvailableWaitHandle property
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called before WaitHandle</param>
/// <param name="state">The expected wait handle state</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest7_AvailableWaitHandle(int initial, int maximum, SemaphoreSlimActions? action, bool state)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
CallSemaphoreAction(semaphore, action, null);
Assert.NotNull(semaphore.AvailableWaitHandle);
Assert.Equal(state, semaphore.AvailableWaitHandle.WaitOne(0));
}
/// <summary>
/// Test SemaphoreSlim Wait and Release methods concurrently
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="waitThreads">Number of the threads that call Wait method</param>
/// <param name="releaseThreads">Number of the threads that call Release method</param>
/// <param name="succeededWait">Number of succeeded wait threads</param>
/// <param name="failedWait">Number of failed wait threads</param>
/// <param name="finalCount">The final semaphore count</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest8_ConcWaitAndRelease(int initial, int maximum,
int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Task[] threads = new Task[waitThreads + releaseThreads];
int succeeded = 0;
int failed = 0;
ManualResetEvent mre = new ManualResetEvent(false);
// launch threads
for (int i = 0; i < threads.Length; i++)
{
if (i < waitThreads)
{
// We are creating the Task using TaskCreationOptions.LongRunning to
// force usage of another thread (which will be the case on the default scheduler
// with its current implementation). Without this, the release tasks will likely get
// queued behind the wait tasks in the pool, making it very likely that the wait tasks
// will starve the very tasks that when run would unblock them.
threads[i] = new Task(delegate ()
{
mre.WaitOne();
if (semaphore.Wait(timeout))
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failed);
}
}, TaskCreationOptions.LongRunning);
}
else
{
threads[i] = new Task(delegate ()
{
mre.WaitOne();
semaphore.Release();
});
}
threads[i].Start(TaskScheduler.Default);
}
mre.Set();
//wait work to be done;
Task.WaitAll(threads);
//check the number of succeeded and failed wait
Assert.Equal(succeededWait, succeeded);
Assert.Equal(failedWait, failed);
Assert.Equal(finalCount, semaphore.CurrentCount);
}
/// <summary>
/// Test SemaphoreSlim WaitAsync and Release methods concurrently
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="waitThreads">Number of the threads that call Wait method</param>
/// <param name="releaseThreads">Number of the threads that call Release method</param>
/// <param name="succeededWait">Number of succeeded wait threads</param>
/// <param name="failedWait">Number of failed wait threads</param>
/// <param name="finalCount">The final semaphore count</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease(int initial, int maximum,
int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Task[] tasks = new Task[waitThreads + releaseThreads];
int succeeded = 0;
int failed = 0;
ManualResetEvent mre = new ManualResetEvent(false);
// launch threads
for (int i = 0; i < tasks.Length; i++)
{
if (i < waitThreads)
{
tasks[i] = Task.Run(async delegate
{
mre.WaitOne();
if (await semaphore.WaitAsync(timeout))
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failed);
}
});
}
else
{
tasks[i] = Task.Run(delegate
{
mre.WaitOne();
semaphore.Release();
});
}
}
mre.Set();
//wait work to be done;
Task.WaitAll(tasks);
Assert.Equal(succeededWait, succeeded);
Assert.Equal(failedWait, failed);
Assert.Equal(finalCount, semaphore.CurrentCount);
}
private static void TestConcurrentWaitAndWaitAsync(int syncWaiters, int asyncWaiters)
{
int totalWaiters = syncWaiters + asyncWaiters;
var semaphore = new SemaphoreSlim(0);
Task[] tasks = new Task[totalWaiters];
const int ITERS = 10;
int randSeed = (int)DateTime.Now.Ticks;
for (int i = 0; i < syncWaiters; i++)
{
tasks[i] = Task.Run(delegate
{
//Random rand = new Random(Interlocked.Increment(ref randSeed));
for (int iter = 0; iter < ITERS; iter++)
{
semaphore.Wait();
semaphore.Release();
}
});
}
for (int i = syncWaiters; i < totalWaiters; i++)
{
tasks[i] = Task.Run(async delegate
{
//Random rand = new Random(Interlocked.Increment(ref randSeed));
for (int iter = 0; iter < ITERS; iter++)
{
await semaphore.WaitAsync();
semaphore.Release();
}
});
}
semaphore.Release(totalWaiters / 2);
Task.WaitAll(tasks);
}
}
}
| |
/*
* 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.Concurrent;
using System.Reflection;
using System.Threading;
using log4net;
using OpenSim.Framework;
namespace OpenSim.Framework.Monitoring
{
public class JobEngine
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public int LogLevel { get; set; }
public string Name { get; private set; }
public string LoggingName { get; private set; }
/// <summary>
/// Is this engine running?
/// </summary>
public bool IsRunning { get; private set; }
/// <summary>
/// The current job that the engine is running.
/// </summary>
/// <remarks>
/// Will be null if no job is currently running.
/// </remarks>
public Job CurrentJob { get; private set; }
/// <summary>
/// Number of jobs waiting to be processed.
/// </summary>
public int JobsWaiting { get { return m_jobQueue.Count; } }
/// <summary>
/// The timeout in milliseconds to wait for at least one event to be written when the recorder is stopping.
/// </summary>
public int RequestProcessTimeoutOnStop { get; set; }
/// <summary>
/// Controls whether we need to warn in the log about exceeding the max queue size.
/// </summary>
/// <remarks>
/// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
/// order to avoid spamming the log with lots of warnings.
/// </remarks>
private bool m_warnOverMaxQueue = true;
private BlockingCollection<Job> m_jobQueue;
private CancellationTokenSource m_cancelSource;
/// <summary>
/// Used to signal that we are ready to complete stop.
/// </summary>
private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
public JobEngine(string name, string loggingName)
{
Name = name;
LoggingName = loggingName;
RequestProcessTimeoutOnStop = 5000;
}
public void Start()
{
lock (this)
{
if (IsRunning)
return;
IsRunning = true;
m_finishedProcessingAfterStop.Reset();
m_jobQueue = new BlockingCollection<Job>(new ConcurrentQueue<Job>(), 5000);
m_cancelSource = new CancellationTokenSource();
WorkManager.StartThread(
ProcessRequests,
Name,
ThreadPriority.Normal,
false,
true,
null,
int.MaxValue);
}
}
public void Stop()
{
lock (this)
{
try
{
if (!IsRunning)
return;
IsRunning = false;
int requestsLeft = m_jobQueue.Count;
if (requestsLeft <= 0)
{
m_cancelSource.Cancel();
}
else
{
m_log.InfoFormat("[{0}]: Waiting to write {1} events after stop.", LoggingName, requestsLeft);
while (requestsLeft > 0)
{
if (!m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop))
{
// After timeout no events have been written
if (requestsLeft == m_jobQueue.Count)
{
m_log.WarnFormat(
"[{0}]: No requests processed after {1} ms wait. Discarding remaining {2} requests",
LoggingName, RequestProcessTimeoutOnStop, requestsLeft);
break;
}
}
requestsLeft = m_jobQueue.Count;
}
}
}
finally
{
m_cancelSource.Dispose();
}
}
}
/// <summary>
/// Make a job.
/// </summary>
/// <remarks>
/// We provide this method to replace the constructor so that we can later pool job objects if necessary to
/// reduce memory churn. Normally one would directly call QueueJob() with parameters anyway.
/// </remarks>
/// <returns></returns>
/// <param name="name">Name.</param>
/// <param name="action">Action.</param>
/// <param name="commonId">Common identifier.</param>
public static Job MakeJob(string name, Action action, string commonId = null)
{
return Job.MakeJob(name, action, commonId);
}
/// <summary>
/// Remove the next job queued for processing.
/// </summary>
/// <remarks>
/// Returns null if there is no next job.
/// Will not remove a job currently being performed.
/// </remarks>
public Job RemoveNextJob()
{
Job nextJob;
m_jobQueue.TryTake(out nextJob);
return nextJob;
}
/// <summary>
/// Queue the job for processing.
/// </summary>
/// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
/// <param name="name">Name of job. This appears on the console and in logging.</param>
/// <param name="action">Action to perform.</param>
/// <param name="commonId">
/// Common identifier for a set of jobs. This is allows a set of jobs to be removed
/// if required (e.g. all jobs for a given agent. Optional.
/// </param>
public bool QueueJob(string name, Action action, string commonId = null)
{
return QueueJob(MakeJob(name, action, commonId));
}
/// <summary>
/// Queue the job for processing.
/// </summary>
/// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
/// <param name="job">The job</param>
/// </param>
public bool QueueJob(Job job)
{
if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
{
m_jobQueue.Add(job);
if (!m_warnOverMaxQueue)
m_warnOverMaxQueue = true;
return true;
}
else
{
if (m_warnOverMaxQueue)
{
m_log.WarnFormat(
"[{0}]: Job queue at maximum capacity, not recording job from {1} in {2}",
LoggingName, job.Name, Name);
m_warnOverMaxQueue = false;
}
return false;
}
}
private void ProcessRequests()
{
try
{
while (IsRunning || m_jobQueue.Count > 0)
{
try
{
CurrentJob = m_jobQueue.Take(m_cancelSource.Token);
}
catch (ObjectDisposedException e)
{
// If we see this whilst not running then it may be due to a race where this thread checks
// IsRunning after the stopping thread sets it to false and disposes of the cancellation source.
if (IsRunning)
throw e;
else
break;
}
if (LogLevel >= 1)
m_log.DebugFormat("[{0}]: Processing job {1}", LoggingName, CurrentJob.Name);
try
{
CurrentJob.Action();
}
catch (Exception e)
{
m_log.Error(
string.Format(
"[{0}]: Job {1} failed, continuing. Exception ", LoggingName, CurrentJob.Name), e);
}
if (LogLevel >= 1)
m_log.DebugFormat("[{0}]: Processed job {1}", LoggingName, CurrentJob.Name);
CurrentJob = null;
}
}
catch (OperationCanceledException)
{
}
m_finishedProcessingAfterStop.Set();
}
public class Job
{
/// <summary>
/// Name of the job.
/// </summary>
/// <remarks>
/// This appears on console and debug output.
/// </remarks>
public string Name { get; private set; }
/// <summary>
/// Common ID for this job.
/// </summary>
/// <remarks>
/// This allows all jobs with a certain common ID (e.g. a client UUID) to be removed en-masse if required.
/// Can be null if this is not required.
/// </remarks>
public string CommonId { get; private set; }
/// <summary>
/// Action to perform when this job is processed.
/// </summary>
public Action Action { get; private set; }
private Job(string name, string commonId, Action action)
{
Name = name;
CommonId = commonId;
Action = action;
}
/// <summary>
/// Make a job. It needs to be separately queued.
/// </summary>
/// <remarks>
/// We provide this method to replace the constructor so that we can pool job objects if necessary to
/// to reduce memory churn. Normally one would directly call JobEngine.QueueJob() with parameters anyway.
/// </remarks>
/// <returns></returns>
/// <param name="name">Name.</param>
/// <param name="action">Action.</param>
/// <param name="commonId">Common identifier.</param>
public static Job MakeJob(string name, Action action, string commonId = null)
{
return new Job(name, commonId, action);
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type OnenoteSectionGroupsCollectionRequest.
/// </summary>
public partial class OnenoteSectionGroupsCollectionRequest : BaseRequest, IOnenoteSectionGroupsCollectionRequest
{
/// <summary>
/// Constructs a new OnenoteSectionGroupsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public OnenoteSectionGroupsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified SectionGroup to the collection via POST.
/// </summary>
/// <param name="sectionGroup">The SectionGroup to add.</param>
/// <returns>The created SectionGroup.</returns>
public System.Threading.Tasks.Task<SectionGroup> AddAsync(SectionGroup sectionGroup)
{
return this.AddAsync(sectionGroup, CancellationToken.None);
}
/// <summary>
/// Adds the specified SectionGroup to the collection via POST.
/// </summary>
/// <param name="sectionGroup">The SectionGroup to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created SectionGroup.</returns>
public System.Threading.Tasks.Task<SectionGroup> AddAsync(SectionGroup sectionGroup, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<SectionGroup>(sectionGroup, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IOnenoteSectionGroupsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IOnenoteSectionGroupsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<OnenoteSectionGroupsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest Expand(Expression<Func<SectionGroup, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest Select(Expression<Func<SectionGroup, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionGroupsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using SharpDX;
using SharpDX.Direct3D11;
using Format = SharpDX.DXGI.Format;
using System;
using System.IO;
using System.Runtime.InteropServices;
using SharpDX.Win32;
using System.Diagnostics;
using SharpDX.Direct3D;
static class DdsLoader {
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct DdsPixelFormat {
public static readonly int SIZE = Marshal.SizeOf<DdsPixelFormat>();
public uint size;
public uint flags;
public uint fourCC;
public uint RGBBitCount;
public uint RBitMask;
public uint GBitMask;
public uint BBitMask;
public uint ABitMask;
public bool IsBitMask(uint r, uint g, uint b, uint a) {
return (RBitMask == r && GBitMask == g && BBitMask == b && ABitMask == a);
}
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct DdsHeader {
public static readonly int SIZE = Marshal.SizeOf<DdsHeader>();
public uint size;
public uint flags;
public uint height;
public uint width;
public uint pitchOrLinearSize;
public uint depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
public uint mipMapCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)] uint[] reserved1;
public DdsPixelFormat ddspf;
public uint caps;
public uint caps2;
public uint caps3;
public uint caps4;
public uint reserved2;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct DdsHeaderDxt10 {
public static readonly int SIZE = Marshal.SizeOf<DdsHeaderDxt10>();
public Format dxgiFormat;
public ResourceDimension resourceDimension;
public ResourceOptionFlags miscFlag; // see D3D11_RESOURCE_MISC_FLAG
public uint arraySize;
public uint miscFlags2;
};
const uint DDS_MAGIC = 0x20534444; // "DDS "
const uint DDS_FOURCC = 0x00000004; // DDPF_FOURCC
const uint DDS_RGB = 0x00000040; // DDPF_RGB
const uint DDS_LUMINANCE = 0x00020000; // DDPF_LUMINANCE
const uint DDS_ALPHA = 0x00000002; // DDPF_ALPHA
const uint DDS_BUMPDUDV = 0x00080000; // DDPF_BUMPDUDV
const uint DDS_HEADER_FLAGS_VOLUME = 0x00800000; // DDSD_DEPTH
const uint DDS_HEIGHT = 0x00000002; // DDSD_HEIGHT
const uint DDS_WIDTH = 0x00000004; // DDSD_WIDTH
const uint DDS_CUBEMAP_POSITIVEX = 0x00000600; // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
const uint DDS_CUBEMAP_NEGATIVEX = 0x00000a00; // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
const uint DDS_CUBEMAP_POSITIVEY = 0x00001200; // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
const uint DDS_CUBEMAP_NEGATIVEY = 0x00002200; // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
const uint DDS_CUBEMAP_POSITIVEZ = 0x00004200; // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
const uint DDS_CUBEMAP_NEGATIVEZ = 0x00008200; // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
const uint DDS_CUBEMAP_ALLFACES = (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |
DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |
DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ);
const uint DDS_CUBEMAP = 0x00000200; // DDSCAPS2_CUBEMAP
private static int MakeFourCC(int ch0, int ch1, int ch2, int ch3) {
return ((int)(byte)(ch0) | ((int)(byte)(ch1) << 8) | ((int)(byte)(ch2) << 16) | ((int)(byte)(ch3) << 24));
}
private static int BitsPerPixel(Format fmt) {
switch (fmt) {
case Format.R32G32B32A32_Typeless:
case Format.R32G32B32A32_Float:
case Format.R32G32B32A32_UInt:
case Format.R32G32B32A32_SInt:
return 128;
case Format.R32G32B32_Typeless:
case Format.R32G32B32_Float:
case Format.R32G32B32_UInt:
case Format.R32G32B32_SInt:
return 96;
case Format.R16G16B16A16_Typeless:
case Format.R16G16B16A16_Float:
case Format.R16G16B16A16_UNorm:
case Format.R16G16B16A16_UInt:
case Format.R16G16B16A16_SNorm:
case Format.R16G16B16A16_SInt:
case Format.R32G32_Typeless:
case Format.R32G32_Float:
case Format.R32G32_UInt:
case Format.R32G32_SInt:
case Format.R32G8X24_Typeless:
case Format.D32_Float_S8X24_UInt:
case Format.R32_Float_X8X24_Typeless:
case Format.X32_Typeless_G8X24_UInt:
case Format.Y416:
case Format.Y210:
case Format.Y216:
return 64;
case Format.R10G10B10A2_Typeless:
case Format.R10G10B10A2_UNorm:
case Format.R10G10B10A2_UInt:
case Format.R11G11B10_Float:
case Format.R8G8B8A8_Typeless:
case Format.R8G8B8A8_UNorm:
case Format.R8G8B8A8_UNorm_SRgb:
case Format.R8G8B8A8_UInt:
case Format.R8G8B8A8_SNorm:
case Format.R8G8B8A8_SInt:
case Format.R16G16_Typeless:
case Format.R16G16_Float:
case Format.R16G16_UNorm:
case Format.R16G16_UInt:
case Format.R16G16_SNorm:
case Format.R16G16_SInt:
case Format.R32_Typeless:
case Format.D32_Float:
case Format.R32_Float:
case Format.R32_UInt:
case Format.R32_SInt:
case Format.R24G8_Typeless:
case Format.D24_UNorm_S8_UInt:
case Format.R24_UNorm_X8_Typeless:
case Format.X24_Typeless_G8_UInt:
case Format.R9G9B9E5_Sharedexp:
case Format.R8G8_B8G8_UNorm:
case Format.G8R8_G8B8_UNorm:
case Format.B8G8R8A8_UNorm:
case Format.B8G8R8X8_UNorm:
case Format.R10G10B10_Xr_Bias_A2_UNorm:
case Format.B8G8R8A8_Typeless:
case Format.B8G8R8A8_UNorm_SRgb:
case Format.B8G8R8X8_Typeless:
case Format.B8G8R8X8_UNorm_SRgb:
case Format.AYUV:
case Format.Y410:
case Format.YUY2:
return 32;
case Format.P010:
case Format.P016:
return 24;
case Format.R8G8_Typeless:
case Format.R8G8_UNorm:
case Format.R8G8_UInt:
case Format.R8G8_SNorm:
case Format.R8G8_SInt:
case Format.R16_Typeless:
case Format.R16_Float:
case Format.D16_UNorm:
case Format.R16_UNorm:
case Format.R16_UInt:
case Format.R16_SNorm:
case Format.R16_SInt:
case Format.B5G6R5_UNorm:
case Format.B5G5R5A1_UNorm:
case Format.A8P8:
case Format.B4G4R4A4_UNorm:
return 16;
case Format.NV12:
case Format.Opaque420:
case Format.NV11:
return 12;
case Format.R8_Typeless:
case Format.R8_UNorm:
case Format.R8_UInt:
case Format.R8_SNorm:
case Format.R8_SInt:
case Format.A8_UNorm:
case Format.AI44:
case Format.IA44:
case Format.P8:
return 8;
case Format.R1_UNorm:
return 1;
case Format.BC1_Typeless:
case Format.BC1_UNorm:
case Format.BC1_UNorm_SRgb:
case Format.BC4_Typeless:
case Format.BC4_UNorm:
case Format.BC4_SNorm:
return 4;
case Format.BC2_Typeless:
case Format.BC2_UNorm:
case Format.BC2_UNorm_SRgb:
case Format.BC3_Typeless:
case Format.BC3_UNorm:
case Format.BC3_UNorm_SRgb:
case Format.BC5_Typeless:
case Format.BC5_UNorm:
case Format.BC5_SNorm:
case Format.BC6H_Typeless:
case Format.BC6H_Uf16:
case Format.BC6H_Sf16:
case Format.BC7_Typeless:
case Format.BC7_UNorm:
case Format.BC7_UNorm_SRgb:
return 8;
default:
return 0;
}
}
private static Format GetDXGIFormat(DdsPixelFormat ddpf) {
if ((ddpf.flags & DDS_RGB) != 0) {
// Note that sRGB formats are written using the "DX10" extended header
switch (ddpf.RGBBitCount) {
case 32:
if (ddpf.IsBitMask(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) {
return Format.R8G8B8A8_UNorm;
}
if (ddpf.IsBitMask(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) {
return Format.B8G8R8A8_UNorm;
}
if (ddpf.IsBitMask(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000)) {
return Format.B8G8R8X8_UNorm;
}
// No DXGI format maps to ddpf.ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0x00000000) aka D3DFMT_X8B8G8R8
// Note that many common DDS reader/writers (including D3DX) swap the
// the RED/BLUE masks for 10:10:10:2 formats. We assume
// below that the 'backwards' header mask is being used since it is most
// likely written by D3DX. The more robust solution is to use the 'DX10'
// header extension and specify the Format.R10G10B10A2_UNorm format directly
// For 'correct' writers, this should be 0x000003ff,0x000ffc00,0x3ff00000 for RGB data
if (ddpf.IsBitMask(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000)) {
return Format.R10G10B10A2_UNorm;
}
// No DXGI format maps to ddpf.ISBITMASK(0x000003ff,0x000ffc00,0x3ff00000,0xc0000000) aka D3DFMT_A2R10G10B10
if (ddpf.IsBitMask(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) {
return Format.R16G16_UNorm;
}
if (ddpf.IsBitMask(0xffffffff, 0x00000000, 0x00000000, 0x00000000)) {
// Only 32-bit color channel format in D3D9 was R32F
return Format.R32_Float; // D3DX writes this out as a FourCC of 114
}
break;
case 24:
// No 24bpp DXGI formats aka D3DFMT_R8G8B8
break;
case 16:
if (ddpf.IsBitMask(0x7c00, 0x03e0, 0x001f, 0x8000)) {
return Format.B5G5R5A1_UNorm;
}
if (ddpf.IsBitMask(0xf800, 0x07e0, 0x001f, 0x0000)) {
return Format.B5G6R5_UNorm;
}
// No DXGI format maps to ddpf.ISBITMASK(0x7c00,0x03e0,0x001f,0x0000) aka D3DFMT_X1R5G5B5
if (ddpf.IsBitMask(0x0f00, 0x00f0, 0x000f, 0xf000)) {
return Format.B4G4R4A4_UNorm;
}
// No DXGI format maps to ddpf.ISBITMASK(0x0f00,0x00f0,0x000f,0x0000) aka D3DFMT_X4R4G4B4
// No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
break;
}
} else if ((ddpf.flags & DDS_LUMINANCE) != 0) {
if (8 == ddpf.RGBBitCount) {
if (ddpf.IsBitMask(0x000000ff, 0x00000000, 0x00000000, 0x00000000)) {
return Format.R8_UNorm; // D3DX10/11 writes this out as DX10 extension
}
// No DXGI format maps to ddpf.ISBITMASK(0x0f,0x00,0x00,0xf0) aka D3DFMT_A4L4
if (ddpf.IsBitMask(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) {
return Format.R8G8_UNorm; // Some DDS writers assume the bitcount should be 8 instead of 16
}
}
if (16 == ddpf.RGBBitCount) {
if (ddpf.IsBitMask(0x0000ffff, 0x00000000, 0x00000000, 0x00000000)) {
return Format.R16_UNorm; // D3DX10/11 writes this out as DX10 extension
}
if (ddpf.IsBitMask(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) {
return Format.R8G8_UNorm; // D3DX10/11 writes this out as DX10 extension
}
}
} else if ((ddpf.flags & DDS_ALPHA) != 0) {
if (8 == ddpf.RGBBitCount) {
return Format.A8_UNorm;
}
} else if ((ddpf.flags & DDS_BUMPDUDV) != 0) {
if (16 == ddpf.RGBBitCount) {
if (ddpf.IsBitMask(0x00ff, 0xff00, 0x0000, 0x0000)) {
return Format.R8G8_SNorm; // D3DX10/11 writes this out as DX10 extension
}
}
if (32 == ddpf.RGBBitCount) {
if (ddpf.IsBitMask(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) {
return Format.R8G8B8A8_SNorm; // D3DX10/11 writes this out as DX10 extension
}
if (ddpf.IsBitMask(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) {
return Format.R16G16_SNorm; // D3DX10/11 writes this out as DX10 extension
}
// No DXGI format maps to ddpf.ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000) aka D3DFMT_A2W10V10U10
}
} else if ((ddpf.flags & DDS_FOURCC) != 0) {
if (MakeFourCC('D', 'X', 'T', '1') == ddpf.fourCC) {
return Format.BC1_UNorm;
}
if (MakeFourCC('D', 'X', 'T', '3') == ddpf.fourCC) {
return Format.BC2_UNorm;
}
if (MakeFourCC('D', 'X', 'T', '5') == ddpf.fourCC) {
return Format.BC3_UNorm;
}
// While pre-multiplied alpha isn't directly supported by the DXGI formats,
// they are basically the same as these BC formats so they can be mapped
if (MakeFourCC('D', 'X', 'T', '2') == ddpf.fourCC) {
return Format.BC2_UNorm;
}
if (MakeFourCC('D', 'X', 'T', '4') == ddpf.fourCC) {
return Format.BC3_UNorm;
}
if (MakeFourCC('A', 'T', 'I', '1') == ddpf.fourCC) {
return Format.BC4_UNorm;
}
if (MakeFourCC('B', 'C', '4', 'U') == ddpf.fourCC) {
return Format.BC4_UNorm;
}
if (MakeFourCC('B', 'C', '4', 'S') == ddpf.fourCC) {
return Format.BC4_SNorm;
}
if (MakeFourCC('A', 'T', 'I', '2') == ddpf.fourCC) {
return Format.BC5_UNorm;
}
if (MakeFourCC('B', 'C', '5', 'U') == ddpf.fourCC) {
return Format.BC5_UNorm;
}
if (MakeFourCC('B', 'C', '5', 'S') == ddpf.fourCC) {
return Format.BC5_SNorm;
}
// BC6H and BC7 are written using the "DX10" extended header
if (MakeFourCC('R', 'G', 'B', 'G') == ddpf.fourCC) {
return Format.R8G8_B8G8_UNorm;
}
if (MakeFourCC('G', 'R', 'G', 'B') == ddpf.fourCC) {
return Format.G8R8_G8B8_UNorm;
}
if (MakeFourCC('Y', 'U', 'Y', '2') == ddpf.fourCC) {
return Format.YUY2;
}
// Check for D3DFORMAT enums being set here
switch (ddpf.fourCC) {
case 36: // D3DFMT_A16B16G16R16
return Format.R16G16B16A16_UNorm;
case 110: // D3DFMT_Q16W16V16U16
return Format.R16G16B16A16_SNorm;
case 111: // D3DFMT_R16F
return Format.R16_Float;
case 112: // D3DFMT_G16R16F
return Format.R16G16_Float;
case 113: // D3DFMT_A16B16G16R16F
return Format.R16G16B16A16_Float;
case 114: // D3DFMT_R32F
return Format.R32_Float;
case 115: // D3DFMT_G32R32F
return Format.R32G32_Float;
case 116: // D3DFMT_A32B32G32R32F
return Format.R32G32B32A32_Float;
}
}
return Format.Unknown;
}
private static void CreateTextureFromDDS(
Device d3dDevice,
DdsHeader header,
DdsHeaderDxt10? headerDxt10,
IntPtr bitData,
int bitSize,
int maxsize,
ResourceUsage usage,
BindFlags bindFlags,
CpuAccessFlags cpuAccessFlags,
ResourceOptionFlags miscFlags,
bool forceSRGB,
out Resource texture,
out ShaderResourceView textureView) {
Result hr = Result.Ok;
int width = (int)header.width;
int height = (int)header.height;
int depth = (int)header.depth;
ResourceDimension resDim = ResourceDimension.Unknown;
uint arraySize = 1;
SharpDX.DXGI.Format format = SharpDX.DXGI.Format.Unknown;
bool isCubeMap = false;
int mipCount = (int)header.mipMapCount;
if (0 == mipCount) {
mipCount = 1;
}
if (headerDxt10.HasValue) {
DdsHeaderDxt10 d3d10ext = headerDxt10.Value;
arraySize = d3d10ext.arraySize;
if (arraySize == 0) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.InvalidData));
}
switch (d3d10ext.dxgiFormat) {
case Format.AI44:
case Format.IA44:
case Format.P8:
case Format.A8P8:
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
default:
if (BitsPerPixel(d3d10ext.dxgiFormat) == 0) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
break;
}
format = d3d10ext.dxgiFormat;
switch (d3d10ext.resourceDimension) {
case ResourceDimension.Texture1D:
// D3DX writes 1D textures with a fixed Height of 1
if ((header.flags & DDS_HEIGHT) != 0 && height != 1) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.InvalidData));
}
height = depth = 1;
break;
case ResourceDimension.Texture2D:
if ((d3d10ext.miscFlag & ResourceOptionFlags.TextureCube) != 0) {
arraySize *= 6;
isCubeMap = true;
}
depth = 1;
break;
case ResourceDimension.Texture3D:
if ((header.flags & DDS_HEADER_FLAGS_VOLUME) == 0) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.InvalidData));
}
if (arraySize > 1) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.InvalidData));
}
break;
default:
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.InvalidData));
}
resDim = d3d10ext.resourceDimension;
} else {
format = GetDXGIFormat(header.ddspf);
if (format == Format.Unknown) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
if ((header.flags & DDS_HEADER_FLAGS_VOLUME) != 0) {
resDim = ResourceDimension.Texture3D;
} else {
if ((header.caps2 & DDS_CUBEMAP) != 0) {
// We require all six faces to be defined
if ((header.caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
arraySize = 6;
isCubeMap = true;
}
depth = 1;
resDim = ResourceDimension.Texture2D;
// Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
}
Debug.Assert(BitsPerPixel(format) != 0);
}
// Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
if (mipCount > Resource.MaximumMipLevels) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
switch (resDim) {
case ResourceDimension.Texture1D:
if ((arraySize > Resource.MaximumTexture1DArraySize) ||
(width > Resource.MaximumTexture1DSize)) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
break;
case ResourceDimension.Texture2D:
if (isCubeMap) {
// This is the right bound because we set arraySize to (NumCubes*6) above
if ((arraySize > Resource.MaximumTexture2DArraySize) ||
(width > Resource.MaximumTextureCubeSize) ||
(height > Resource.MaximumTextureCubeSize)) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
} else if ((arraySize > Resource.MaximumTexture2DArraySize) ||
(width > Resource.MaximumTexture2DSize) ||
(height > Resource.MaximumTexture2DSize)) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
break;
case ResourceDimension.Texture3D:
if ((arraySize > 1) ||
(width > Resource.MaximumTexture3DSize) ||
(height > Resource.MaximumTexture3DSize) ||
(depth > Resource.MaximumTexture3DSize)) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
break;
default:
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.NotSupported));
}
// Create the texture
DataBox[] initData = new DataBox[mipCount * arraySize];
FillInitData(width, height, depth, mipCount, (int)arraySize, format, maxsize, bitSize, bitData,
out int twidth, out int theight, out int tdepth, out int skipMip, initData);
CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, (int)arraySize,
format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
isCubeMap, initData, out texture, out textureView);
}
private static void GetSurfaceInfo(
int width,
int height,
Format fmt,
out int outNumBytes,
out int outRowBytes,
out int outNumRows) {
int numBytes = 0;
int rowBytes = 0;
int numRows = 0;
bool bc = false;
bool packed = false;
bool planar = false;
int bpe = 0;
switch (fmt) {
case Format.BC1_Typeless:
case Format.BC1_UNorm:
case Format.BC1_UNorm_SRgb:
case Format.BC4_Typeless:
case Format.BC4_UNorm:
case Format.BC4_SNorm:
bc = true;
bpe = 8;
break;
case Format.BC2_Typeless:
case Format.BC2_UNorm:
case Format.BC2_UNorm_SRgb:
case Format.BC3_Typeless:
case Format.BC3_UNorm:
case Format.BC3_UNorm_SRgb:
case Format.BC5_Typeless:
case Format.BC5_UNorm:
case Format.BC5_SNorm:
case Format.BC6H_Typeless:
case Format.BC6H_Uf16:
case Format.BC6H_Sf16:
case Format.BC7_Typeless:
case Format.BC7_UNorm:
case Format.BC7_UNorm_SRgb:
bc = true;
bpe = 16;
break;
case Format.R8G8_B8G8_UNorm:
case Format.G8R8_G8B8_UNorm:
case Format.YUY2:
packed = true;
bpe = 4;
break;
case Format.Y210:
case Format.Y216:
packed = true;
bpe = 8;
break;
case Format.NV12:
case Format.Opaque420:
planar = true;
bpe = 2;
break;
case Format.P010:
case Format.P016:
planar = true;
bpe = 4;
break;
}
if (bc) {
int numBlocksWide = 0;
if (width > 0) {
numBlocksWide = Math.Max(1, (width + 3) / 4);
}
int numBlocksHigh = 0;
if (height > 0) {
numBlocksHigh = Math.Max(1, (height + 3) / 4);
}
rowBytes = numBlocksWide * bpe;
numRows = numBlocksHigh;
numBytes = rowBytes * numBlocksHigh;
} else if (packed) {
rowBytes = ((width + 1) >> 1) * bpe;
numRows = height;
numBytes = rowBytes * height;
} else if (fmt == Format.NV11) {
rowBytes = ((width + 3) >> 2) * 4;
numRows = height * 2; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data
numBytes = rowBytes * numRows;
} else if (planar) {
rowBytes = ((width + 1) >> 1) * bpe;
numBytes = (rowBytes * height) + ((rowBytes * height + 1) >> 1);
numRows = height + ((height + 1) >> 1);
} else {
int bpp = BitsPerPixel(fmt);
rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
numRows = height;
numBytes = rowBytes * height;
}
outNumBytes = numBytes;
outRowBytes = rowBytes;
outNumRows = numRows;
}
private static void FillInitData(
int width,
int height,
int depth,
int mipCount,
int arraySize,
Format format,
int maxsize,
int bitSize,
IntPtr bitData,
out int twidth,
out int theight,
out int tdepth,
out int skipMip,
DataBox[] initData) {
if (bitData == IntPtr.Zero || initData == null) {
throw new SharpDXException(Result.InvalidPointer);
}
skipMip = 0;
twidth = 0;
theight = 0;
tdepth = 0;
IntPtr pSrcBits = bitData;
IntPtr pEndBits = bitData + bitSize;
int index = 0;
for (int j = 0; j < arraySize; j++) {
int w = width;
int h = height;
int d = depth;
for (int i = 0; i < mipCount; i++) {
GetSurfaceInfo(w,
h,
format,
out int NumBytes,
out int RowBytes,
out int NumRows
);
if ((mipCount <= 1) || (maxsize == 0) || (w <= maxsize && h <= maxsize && d <= maxsize)) {
if (twidth == 0) {
twidth = w;
theight = h;
tdepth = d;
}
Debug.Assert(index < mipCount * arraySize);
initData[index].DataPointer = pSrcBits;
initData[index].RowPitch = RowBytes;
initData[index].SlicePitch = NumBytes;
++index;
} else if (j == 0) {
// Count number of skipped mipmaps (first item only)
++skipMip;
}
if ((long)pSrcBits + (NumBytes * d) > (long)pEndBits) {
throw new SharpDXException(ErrorCodeHelper.ToResult(ErrorCode.HandleEof));
}
pSrcBits += NumBytes * d;
w = w >> 1;
h = h >> 1;
d = d >> 1;
if (w == 0) {
w = 1;
}
if (h == 0) {
h = 1;
}
if (d == 0) {
d = 1;
}
}
}
if (index > 0) {
return;
} else {
throw new SharpDXException(Result.Fail);
}
}
private static Format MakeSRGB(Format format) {
switch (format) {
case Format.R8G8B8A8_UNorm:
return Format.R8G8B8A8_UNorm_SRgb;
case Format.BC1_UNorm:
return Format.BC1_UNorm_SRgb;
case Format.BC2_UNorm:
return Format.BC2_UNorm_SRgb;
case Format.BC3_UNorm:
return Format.BC3_UNorm_SRgb;
case Format.B8G8R8A8_UNorm:
return Format.B8G8R8A8_UNorm_SRgb;
case Format.B8G8R8X8_UNorm:
return Format.B8G8R8X8_UNorm_SRgb;
case Format.BC7_UNorm:
return Format.BC7_UNorm_SRgb;
default:
return format;
}
}
private static void CreateD3DResources(
Device d3dDevice,
ResourceDimension resDim,
int width,
int height,
int depth,
int mipCount,
int arraySize,
Format format,
ResourceUsage usage,
BindFlags bindFlags,
CpuAccessFlags cpuAccessFlags,
ResourceOptionFlags miscFlags,
bool forceSRGB,
bool isCubeMap,
DataBox[] initData,
out Resource texture,
out ShaderResourceView textureView) {
if (d3dDevice == null)
throw new SharpDXException(Result.InvalidPointer);
if (forceSRGB) {
format = MakeSRGB(format);
}
switch (resDim) {
case ResourceDimension.Texture1D: {
Texture1DDescription desc;
desc.Width = width;
desc.MipLevels = mipCount;
desc.ArraySize = arraySize;
desc.Format = format;
desc.Usage = usage;
desc.BindFlags = bindFlags;
desc.CpuAccessFlags = cpuAccessFlags;
desc.OptionFlags = miscFlags & ~ResourceOptionFlags.TextureCube;
using (Texture1D tex = new Texture1D(d3dDevice, desc, initData)) {
ShaderResourceViewDescription SRVDesc = default(ShaderResourceViewDescription);
SRVDesc.Format = format;
if (arraySize > 1) {
SRVDesc.Dimension = ShaderResourceViewDimension.Texture1DArray;
SRVDesc.Texture1DArray.MipLevels = (mipCount == 0) ? -1 : desc.MipLevels;
SRVDesc.Texture1DArray.ArraySize = arraySize;
} else {
SRVDesc.Dimension = ShaderResourceViewDimension.Texture1D;
SRVDesc.Texture1D.MipLevels = (mipCount == 0) ? -1 : desc.MipLevels;
}
textureView = new ShaderResourceView(d3dDevice, tex, SRVDesc);
texture = tex.QueryInterface<Texture1D>();
}
}
break;
case ResourceDimension.Texture2D: {
Texture2DDescription desc;
desc.Width = width;
desc.Height = height;
desc.MipLevels = mipCount;
desc.ArraySize = arraySize;
desc.Format = format;
desc.SampleDescription.Count = 1;
desc.SampleDescription.Quality = 0;
desc.Usage = usage;
desc.BindFlags = bindFlags;
desc.CpuAccessFlags = cpuAccessFlags;
if (isCubeMap) {
desc.OptionFlags = miscFlags | ResourceOptionFlags.TextureCube;
} else {
desc.OptionFlags = miscFlags & ~ResourceOptionFlags.TextureCube;
}
using (Texture2D tex = new Texture2D(d3dDevice, desc, initData)) {
ShaderResourceViewDescription SRVDesc = default(ShaderResourceViewDescription);
SRVDesc.Format = format;
if (isCubeMap) {
if (arraySize > 6) {
SRVDesc.Dimension = ShaderResourceViewDimension.TextureCubeArray;
SRVDesc.TextureCubeArray.MipLevels = (mipCount == 0) ? -1 : desc.MipLevels;
// Earlier we set arraySize to (NumCubes * 6)
SRVDesc.TextureCubeArray.CubeCount = arraySize / 6;
} else {
SRVDesc.Dimension = ShaderResourceViewDimension.TextureCube;
SRVDesc.TextureCube.MipLevels = (mipCount == 0) ? -1 : desc.MipLevels;
}
} else if (arraySize > 1) {
SRVDesc.Dimension = ShaderResourceViewDimension.Texture2DArray;
SRVDesc.Texture2DArray.MipLevels = (mipCount == 0) ? -1 : desc.MipLevels;
SRVDesc.Texture2DArray.ArraySize = arraySize;
} else {
SRVDesc.Dimension = ShaderResourceViewDimension.Texture2D;
SRVDesc.Texture2D.MipLevels = (mipCount == 0) ? -1 : desc.MipLevels;
}
textureView = new ShaderResourceView(d3dDevice, tex, SRVDesc);
texture = tex.QueryInterface<Texture2D>();
}
}
break;
case ResourceDimension.Texture3D: {
Texture3DDescription desc;
desc.Width = width;
desc.Height = height;
desc.Depth = depth;
desc.MipLevels = mipCount;
desc.Format = format;
desc.Usage = usage;
desc.BindFlags = bindFlags;
desc.CpuAccessFlags = cpuAccessFlags;
desc.OptionFlags = miscFlags & ~ResourceOptionFlags.TextureCube;
using (Texture3D tex = new Texture3D(d3dDevice, desc, initData)) {
ShaderResourceViewDescription SRVDesc = default(ShaderResourceViewDescription);
SRVDesc.Format = format;
SRVDesc.Dimension = ShaderResourceViewDimension.Texture3D;
SRVDesc.Texture3D.MipLevels = (mipCount == 0) ? -1 : desc.MipLevels;
textureView = new ShaderResourceView(d3dDevice, tex, SRVDesc);
texture = tex.QueryInterface<Texture3D>();
}
}
break;
default:
throw new SharpDXException(Result.Fail);
}
}
public static void CreateDDSTextureFromMemory(Device d3dDevice,
DataPointer dataPointer,
out Resource texture,
out ShaderResourceView textureView,
int maxsize = 0,
ResourceUsage usage = ResourceUsage.Default,
BindFlags bindFlags = BindFlags.ShaderResource,
CpuAccessFlags cpuAccessFlags = CpuAccessFlags.None,
ResourceOptionFlags miscFlags = ResourceOptionFlags.None,
bool forceSRGB = false
) {
texture = null;
textureView = null;
if (d3dDevice == null) {
throw new SharpDXException(Result.InvalidArg);
}
// Validate DDS file in memory
if (dataPointer.Size < (sizeof(uint) + DdsHeader.SIZE)) {
throw new SharpDXException(Result.Fail);
}
uint magicNumber = Marshal.PtrToStructure<uint>(dataPointer.Pointer);
if (magicNumber != DDS_MAGIC) {
throw new SharpDXException(Result.Fail);
}
DdsHeader header = Marshal.PtrToStructure<DdsHeader>(dataPointer.Pointer + sizeof(uint));
// Verify header to validate DDS file
if (header.size != DdsHeader.SIZE ||
header.ddspf.size != DdsPixelFormat.SIZE) {
throw new SharpDXException(Result.Fail);
}
// Check for DX10 extension
DdsHeaderDxt10? headerDxt10;
bool bDXT10Header = false;
if ((header.ddspf.flags & DDS_FOURCC) != 0 &&
(MakeFourCC('D', 'X', '1', '0') == header.ddspf.fourCC)) {
// Must be long enough for both headers and magic value
if (dataPointer.Size < (DdsHeader.SIZE + sizeof(uint) + DdsHeaderDxt10.SIZE)) {
throw new SharpDXException(Result.Fail);
}
bDXT10Header = true;
headerDxt10 = Marshal.PtrToStructure<DdsHeaderDxt10>(dataPointer.Pointer + sizeof(uint) + DdsHeader.SIZE);
} else {
headerDxt10 = null;
}
int offset = sizeof(uint)
+ DdsHeader.SIZE
+ (bDXT10Header ? DdsHeaderDxt10.SIZE : 0);
CreateTextureFromDDS(d3dDevice, header, headerDxt10,
dataPointer.Pointer + offset, dataPointer.Size - offset, maxsize,
usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
out texture, out textureView);
}
public static void CreateDDSTextureFromMemory(Device d3dDevice,
byte[] ddsData,
out Resource texture,
out ShaderResourceView textureView,
int maxsize = 0,
ResourceUsage usage = ResourceUsage.Default,
BindFlags bindFlags = BindFlags.ShaderResource,
CpuAccessFlags cpuAccessFlags = CpuAccessFlags.None,
ResourceOptionFlags miscFlags = ResourceOptionFlags.None,
bool forceSRGB = false
) {
GCHandle ddsDataHandle = GCHandle.Alloc(ddsData, GCHandleType.Pinned);
try {
CreateDDSTextureFromMemory(
d3dDevice,
new DataPointer(ddsDataHandle.AddrOfPinnedObject(), ddsData.Length),
out texture,
out textureView,
maxsize,
usage,
bindFlags,
cpuAccessFlags,
miscFlags,
forceSRGB);
} finally {
ddsDataHandle.Free();
}
}
}
| |
using System;
using System.IO;
namespace ToolBelt
{
// TODO: Make these extension methods
public static class StreamUtility
{
const int DefaultBufferSize = 8 * 1024;
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadFully(Stream input)
{
return ReadFully(input, DefaultBufferSize);
}
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array, using the given buffer size.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="bufferSize">The size of buffer to use when reading</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">bufferSize is less than 1</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadFully(Stream input, int bufferSize)
{
if (bufferSize < 1)
{
throw new ArgumentOutOfRangeException("bufferSize");
}
return ReadFully(input, new byte[bufferSize]);
}
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array, using the given buffer for transferring data. Note that the
/// current contents of the buffer is ignored, so the buffer needn't
/// be cleared beforehand.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The buffer to use to transfer data</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentNullException">buffer is null</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadFully(Stream input, IBuffer buffer)
{
if (buffer==null)
{
throw new ArgumentNullException("buffer");
}
return ReadFully(input, buffer.Bytes);
}
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array, using the given buffer for transferring data. Note that the
/// current contents of the buffer is ignored, so the buffer needn't
/// be cleared beforehand.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The buffer to use to transfer data</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentNullException">buffer is null</exception>
/// <exception cref="ArgumentException">buffer is a zero-length array</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadFully(Stream input, byte[] buffer)
{
if (buffer==null)
{
throw new ArgumentNullException("buffer");
}
if (input==null)
{
throw new ArgumentNullException("input");
}
if (buffer.Length==0)
{
throw new ArgumentException("Buffer has length of 0");
}
// We could do all our own work here, but using MemoryStream is easier
// and likely to be just as efficient.
using (MemoryStream tempStream = new MemoryStream())
{
Copy(input, tempStream, buffer);
// No need to copy the buffer if it's the right size
if (tempStream.Length==tempStream.GetBuffer().Length)
{
return tempStream.GetBuffer();
}
// Okay, make a copy that's the right size
return tempStream.ToArray();
}
}
/// <summary>
/// Copies all the data from one stream into another.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="output">The stream to write to</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentNullException">output is null</exception>
/// <exception cref="IOException">An error occurs while reading or writing</exception>
public static void Copy(Stream input, Stream output)
{
Copy(input, output, DefaultBufferSize);
}
/// <summary>
/// Copies all the data from one stream into another, using a buffer
/// of the given size.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="output">The stream to write to</param>
/// <param name="bufferSize">The size of buffer to use when reading</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentNullException">output is null</exception>
/// <exception cref="ArgumentOutOfRangeException">bufferSize is less than 1</exception>
/// <exception cref="IOException">An error occurs while reading or writing</exception>
public static void Copy(Stream input, Stream output, int bufferSize)
{
if (bufferSize < 1)
{
throw new ArgumentOutOfRangeException("bufferSize");
}
Copy(input, output, new byte[bufferSize]);
}
/// <summary>
/// Copies all the data from one stream into another, using the given
/// buffer for transferring data. Note that the current contents of
/// the buffer is ignored, so the buffer needn't be cleared beforehand.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="output">The stream to write to</param>
/// <param name="buffer">The buffer to use to transfer data</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentNullException">output is null</exception>
/// <exception cref="ArgumentNullException">buffer is null</exception>
/// <exception cref="IOException">An error occurs while reading or writing</exception>
public static void Copy(Stream input, Stream output, IBuffer buffer)
{
if (buffer==null)
{
throw new ArgumentNullException("buffer");
}
Copy(input, output, buffer.Bytes);
}
/// <summary>
/// Copies all the data from one stream into another, using the given
/// buffer for transferring data. Note that the current contents of
/// the buffer is ignored, so the buffer needn't be cleared beforehand.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="output">The stream to write to</param>
/// <param name="buffer">The buffer to use to transfer data</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentNullException">output is null</exception>
/// <exception cref="ArgumentNullException">buffer is null</exception>
/// <exception cref="ArgumentException">buffer is a zero-length array</exception>
/// <exception cref="IOException">An error occurs while reading or writing</exception>
public static void Copy(Stream input, Stream output, byte[] buffer)
{
if (buffer==null)
{
throw new ArgumentNullException("buffer");
}
if (input==null)
{
throw new ArgumentNullException("input");
}
if (output==null)
{
throw new ArgumentNullException("output");
}
if (buffer.Length==0)
{
throw new ArgumentException("Buffer has length of 0");
}
int read;
while ( (read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
/// <summary>
/// Reads exactly the given number of bytes from the specified stream.
/// If the end of the stream is reached before the specified amount
/// of data is read, an exception is thrown.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="bytesToRead">The number of bytes to read</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">bytesToRead is less than 1</exception>
/// <exception cref="EndOfStreamException">The end of the stream is reached before
/// enough data has been read</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadExactly(Stream input, int bytesToRead)
{
return ReadExactly(input, new byte[bytesToRead]);
}
/// <summary>
/// Reads into a buffer, filling it completely.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The buffer to read into</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">The buffer is of zero length</exception>
/// <exception cref="EndOfStreamException">The end of the stream is reached before
/// enough data has been read</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadExactly(Stream input, IBuffer buffer)
{
return ReadExactly(input, buffer.Bytes);
}
/// <summary>
/// Reads into a buffer, filling it completely.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The buffer to read into</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">The buffer is of zero length</exception>
/// <exception cref="EndOfStreamException">The end of the stream is reached before
/// enough data has been read</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadExactly(Stream input, byte[] buffer)
{
return ReadExactly(input, buffer, buffer.Length);
}
/// <summary>
/// Reads into a buffer, for the given number of bytes.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The buffer to read into</param>
/// <param name="bytesToRead">The number of bytes to read</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">The buffer is of zero length, or bytesToRead
/// exceeds the buffer length</exception>
/// <exception cref="EndOfStreamException">The end of the stream is reached before
/// enough data has been read</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadExactly(Stream input, IBuffer buffer, int bytesToRead)
{
return ReadExactly(input, buffer.Bytes, bytesToRead);
}
/// <summary>
/// Reads exactly the given number of bytes from the specified stream,
/// into the given buffer, starting at position 0 of the array.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The byte array to read into</param>
/// <param name="bytesToRead">The number of bytes to read</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">bytesToRead is less than 1</exception>
/// <exception cref="EndOfStreamException">The end of the stream is reached before
/// enough data has been read</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
public static byte[] ReadExactly(Stream input, byte[] buffer, int bytesToRead)
{
return ReadExactly(input, buffer, 0, bytesToRead);
}
/// <summary>
/// Reads into a buffer, for the given number of bytes, from the specified location
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The buffer to read into</param>
/// <param name="startIndex">The index into the buffer at which to start writing</param>
/// <param name="bytesToRead">The number of bytes to read</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">The buffer is of zero length, or startIndex+bytesToRead
/// exceeds the buffer length</exception>
/// <exception cref="EndOfStreamException">The end of the stream is reached before
/// enough data has been read</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
/// <returns>The data read from the stream</returns>
public static byte[] ReadExactly(Stream input, IBuffer buffer, int startIndex, int bytesToRead)
{
return ReadExactly(input, buffer.Bytes, 0, bytesToRead);
}
/// <summary>
/// Reads exactly the given number of bytes from the specified stream,
/// into the given buffer, starting at position 0 of the array.
/// </summary>
/// <param name="input">The stream to read from</param>
/// <param name="buffer">The byte array to read into</param>
/// <param name="startIndex">The index into the buffer at which to start writing</param>
/// <param name="bytesToRead">The number of bytes to read</param>
/// <exception cref="ArgumentNullException">input is null</exception>
/// <exception cref="ArgumentOutOfRangeException">bytesToRead is less than 1, startIndex is less than 0,
/// or startIndex+bytesToRead is greater than the buffer length</exception>
/// <exception cref="EndOfStreamException">The end of the stream is reached before
/// enough data has been read</exception>
/// <exception cref="IOException">An error occurs while reading from the stream</exception>
public static byte[] ReadExactly(Stream input, byte[] buffer, int startIndex, int bytesToRead)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (startIndex < 0 || startIndex >= buffer.Length)
{
throw new ArgumentOutOfRangeException("startIndex");
}
if (bytesToRead < 1 || startIndex + bytesToRead > buffer.Length)
{
throw new ArgumentOutOfRangeException("bytesToRead");
}
int index = 0;
while (index < bytesToRead)
{
int read = input.Read(buffer, startIndex + index, bytesToRead - index);
if (read == 0)
{
throw new EndOfStreamException
(String.Format("End of stream reached with {0} byte{1} left to read.",
bytesToRead - index,
bytesToRead - index == 1 ? "s" : ""));
}
index += read;
}
return buffer;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kemel.Orm.Schema;
using Kemel.Orm.Entity;
using Kemel.Orm.Constants;
namespace Kemel.Orm.QueryDef
{
public class JoinConditionCollection : List<JoinCondition>
{
new public JoinCondition Add(JoinCondition item)
{
base.Add(item);
return item;
}
}
public class JoinCondition
{
#region Properties
public QueryJoin Parent { get; set; }
public ConstraintType ConstraintType { get; set; }
public ColumnQuery ColumnFrom { get; set; }
public ComparisonOperator Operator { get; set; }
public ColumnQuery ColumnTo { get; set; }
public object Value { get; set; }
private Query Query
{
get
{
return this.Parent.Parent;
}
}
#endregion
#region Constructor
private JoinCondition(QueryJoin parent, ConstraintType constraintType, ColumnQuery columnfrom)
{
this.Parent = parent;
this.ConstraintType = constraintType;
this.ColumnFrom = columnfrom;
}
#endregion
#region Static Methods
public static JoinCondition On(ColumnSchema columnFrom, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(columnFrom);
return new JoinCondition(parent, ConstraintType.Where, column);
}
public static JoinCondition And(ColumnSchema columnFrom, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(columnFrom);
return new JoinCondition(parent, ConstraintType.And, column);
}
public static JoinCondition Or(ColumnSchema columnFrom, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(columnFrom);
return new JoinCondition(parent, ConstraintType.Or, column);
}
public static JoinCondition On(string columnName, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(columnName);
if (column == null)
column = new ColumnQuery(columnName, parent);
return new JoinCondition(parent, ConstraintType.Where, column);
}
public static JoinCondition And(string columnName, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(columnName);
if (column == null)
column = new ColumnQuery(columnName, parent);
return new JoinCondition(parent, ConstraintType.And, column);
}
public static JoinCondition Or(string columnName, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(columnName);
if (column == null)
column = new ColumnQuery(columnName, parent);
return new JoinCondition(parent, ConstraintType.Or, column);
}
public static JoinCondition On(string tableName, ColumnSchema columnFrom, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(tableName, columnFrom);
return new JoinCondition(parent, ConstraintType.Where, column);
}
public static JoinCondition And(string tableName, ColumnSchema columnFrom, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(tableName, columnFrom);
return new JoinCondition(parent, ConstraintType.And, column);
}
public static JoinCondition Or(string tableName, ColumnSchema columnFrom, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(tableName, columnFrom);
return new JoinCondition(parent, ConstraintType.Or, column);
}
public static JoinCondition On(string tableName, string columnName, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(tableName, columnName);
if (column == null)
column = new ColumnQuery(columnName, parent);
return new JoinCondition(parent, ConstraintType.Where, column);
}
public static JoinCondition And(string tableName, string columnName, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(tableName, columnName);
if (column == null)
column = new ColumnQuery(columnName, parent);
return new JoinCondition(parent, ConstraintType.And, column);
}
public static JoinCondition Or(string tableName, string columnName, QueryJoin parent)
{
ColumnQuery column = parent.FindColumnQuery(tableName, columnName);
if (column == null)
column = new ColumnQuery(columnName, parent);
return new JoinCondition(parent, ConstraintType.Or, column);
}
#endregion
#region Operators
#region ColumnSchema
public QueryJoin Equal(ColumnSchema columnTo)
{
this.ColumnTo = this.Query.FindColumnQueryInTables(columnTo);
this.Operator = ComparisonOperator.Equal;
return this.Parent;
}
public QueryJoin Different(ColumnSchema columnTo)
{
this.ColumnTo = this.Query.FindColumnQueryInTables(columnTo);
this.Operator = ComparisonOperator.Different;
return this.Parent;
}
public QueryJoin GreaterThan(ColumnSchema columnTo)
{
this.ColumnTo = this.Query.FindColumnQueryInTables(columnTo);
this.Operator = ComparisonOperator.GreaterThan;
return this.Parent;
}
public QueryJoin LessThan(ColumnSchema columnTo)
{
this.ColumnTo = this.Query.FindColumnQueryInTables(columnTo);
this.Operator = ComparisonOperator.LessThan;
return this.Parent;
}
public QueryJoin GreaterThanOrEqual(ColumnSchema columnTo)
{
this.ColumnTo = this.Query.FindColumnQueryInTables(columnTo);
this.Operator = ComparisonOperator.GreaterThanOrEqual;
return this.Parent;
}
public QueryJoin LessOrEqualThan(ColumnSchema columnTo)
{
this.ColumnTo = this.Query.FindColumnQueryInTables(columnTo);
this.Operator = ComparisonOperator.LessThanOrEqual;
return this.Parent;
}
public QueryJoin IsNull()
{
this.ColumnTo = null;
this.Operator = ComparisonOperator.IsNull;
return this.Parent;
}
public QueryJoin IsNotNull()
{
this.ColumnTo = null;
this.Operator = ComparisonOperator.IsNotNull;
return this.Parent;
}
#endregion
#region columnName
public QueryJoin Equal(TableSchema table, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.Equal;
return this.Parent;
}
public QueryJoin Different(TableSchema table, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.Different;
return this.Parent;
}
public QueryJoin GreaterThan(TableSchema table, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.GreaterThan;
return this.Parent;
}
public QueryJoin LessThan(TableSchema table, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.LessThan;
return this.Parent;
}
public QueryJoin GreaterThanOrEqual(TableSchema table, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.GreaterThanOrEqual;
return this.Parent;
}
public QueryJoin LessOrEqualThan(TableSchema table, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.LessThanOrEqual;
return this.Parent;
}
#endregion
#region entity e columnName
public QueryJoin Equal<TEtt>(string columnName)
where TEtt : EntityBase
{
TableSchema table = SchemaContainer.GetSchema<TEtt>();
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.Equal;
return this.Parent;
}
public QueryJoin Different<TEtt>(string columnName)
where TEtt : EntityBase
{
TableSchema table = SchemaContainer.GetSchema<TEtt>();
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.Different;
return this.Parent;
}
public QueryJoin GreaterThan<TEtt>(string columnName)
where TEtt : EntityBase
{
TableSchema table = SchemaContainer.GetSchema<TEtt>();
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.GreaterThan;
return this.Parent;
}
public QueryJoin LessThan<TEtt>(string columnName)
where TEtt : EntityBase
{
TableSchema table = SchemaContainer.GetSchema<TEtt>();
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.LessThan;
return this.Parent;
}
public QueryJoin GreaterThanOrEqual<TEtt>(string columnName)
where TEtt : EntityBase
{
TableSchema table = SchemaContainer.GetSchema<TEtt>();
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.GreaterThanOrEqual;
return this.Parent;
}
public QueryJoin LessOrEqualThan<TEtt>(string columnName)
where TEtt : EntityBase
{
TableSchema table = SchemaContainer.GetSchema<TEtt>();
TableQuery tq = this.Query.FindTableQuery(table);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.LessThanOrEqual;
return this.Parent;
}
#endregion
#region tableName e columnName
public QueryJoin Equal(string tableName, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(tableName);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.Equal;
return this.Parent;
}
public QueryJoin Different(string tableName, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(tableName);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.Different;
return this.Parent;
}
public QueryJoin GreaterThan(string tableName, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(tableName);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.GreaterThan;
return this.Parent;
}
public QueryJoin LessThan(string tableName, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(tableName);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.LessThan;
return this.Parent;
}
public QueryJoin GreaterThanOrEqual(string tableName, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(tableName);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.GreaterThanOrEqual;
return this.Parent;
}
public QueryJoin LessOrEqualThan(string tableName, string columnName)
{
TableQuery tq = this.Query.FindTableQuery(tableName);
this.ColumnTo = new ColumnQuery(columnName, tq);
this.Operator = ComparisonOperator.LessThanOrEqual;
return this.Parent;
}
#endregion
#region Values
public QueryJoin Equal(object value)
{
this.Value = value;
this.Operator = ComparisonOperator.Equal;
return this.Parent;
}
public QueryJoin Different(object value)
{
this.Value = value;
this.Operator = ComparisonOperator.Different;
return this.Parent;
}
public QueryJoin GreaterThan(object value)
{
this.Value = value;
this.Operator = ComparisonOperator.GreaterThan;
return this.Parent;
}
public QueryJoin LessThan(object value)
{
this.Value = value;
this.Operator = ComparisonOperator.LessThan;
return this.Parent;
}
public QueryJoin GreaterThanOrEqual(object value)
{
this.Value = value;
this.Operator = ComparisonOperator.GreaterThanOrEqual;
return this.Parent;
}
public QueryJoin LessOrEqualThan(object value)
{
this.Value = value;
this.Operator = ComparisonOperator.LessThanOrEqual;
return this.Parent;
}
#endregion
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.RestApi.Swagger.Internals
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Exceptions;
using Microsoft.DocAsCode.Plugins;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
internal class SwaggerJsonBuilder
{
private readonly IDictionary<JsonLocationInfo, SwaggerObjectBase> _documentObjectCache;
private const string DefinitionsKey = "definitions";
private const string ReferenceKey = "$ref";
private const string ParametersKey = "parameters";
private const string InternalRefNameKey = "x-internal-ref-name";
private const string InternalLoopRefNameKey = "x-internal-loop-ref-name";
public SwaggerJsonBuilder()
{
_documentObjectCache = new Dictionary<JsonLocationInfo, SwaggerObjectBase>();
}
public SwaggerObjectBase Read(string swaggerPath)
{
var swagger = Load(swaggerPath);
RemoveReferenceDefinitions((SwaggerObject) swagger);
return ResolveReferences(swagger, swaggerPath, new Stack<JsonLocationInfo>());
}
private SwaggerObjectBase Load(string swaggerPath)
{
using (JsonReader reader = new JsonTextReader(EnvironmentContext.FileAbstractLayer.OpenReadText(swaggerPath)))
{
var token = JToken.ReadFrom(reader);
return LoadCore(token, swaggerPath);
}
}
private SwaggerObjectBase LoadCore(JToken token, string swaggerPath)
{
// Fetch from cache first
var location = JsonLocationHelper.GetLocation(token);
var jsonLocationInfo = new JsonLocationInfo(swaggerPath, location);
if (_documentObjectCache.TryGetValue(jsonLocationInfo, out SwaggerObjectBase existingObject))
{
return existingObject;
}
if (token is JObject jObject)
{
// Only one $ref is allowed inside a swagger JObject
if (jObject.TryGetValue(ReferenceKey, out JToken referenceToken))
{
if (referenceToken.Type != JTokenType.String && referenceToken.Type != JTokenType.Null)
{
throw new JsonException($"JSON reference $ref property must have a string or null value, instead of {referenceToken.Type}, location: {referenceToken.Path}.");
}
var swaggerReference = RestApiHelper.FormatReferenceFullPath((string)referenceToken);
switch (swaggerReference.Type)
{
case SwaggerFormattedReferenceType.InternalReference:
var deferredObject = new SwaggerReferenceObject
{
DeferredReference = swaggerReference.Path,
ReferenceName = swaggerReference.Name,
Location = location
};
// For swagger, other properties are still allowed besides $ref, e.g.
// "schema": {
// "$ref": "#/definitions/foo"
// "example": { }
// }
// Use Token property to keep other properties
// These properties cannot be referenced
jObject.Remove("$ref");
deferredObject.Token = jObject;
_documentObjectCache.Add(jsonLocationInfo, deferredObject);
return deferredObject;
case SwaggerFormattedReferenceType.ExternalReference:
jObject.Remove("$ref");
var externalJObject = LoadExternalReference(Path.Combine(Path.GetDirectoryName(swaggerPath), swaggerReference.ExternalFilePath));
RestApiHelper.CheckSpecificKey(externalJObject, ReferenceKey, () =>
{
throw new DocfxException($"{ReferenceKey} in {swaggerReference.ExternalFilePath} is not supported in external reference currently.");
});
foreach (var item in externalJObject)
{
if (jObject.TryGetValue(item.Key, out JToken value))
{
Logger.LogWarning($"{item.Key} inside {jObject.Path} would be overwritten by the value of same key inside {swaggerReference.ExternalFilePath} with path {externalJObject.Path}.");
}
jObject[item.Key] = item.Value;
}
var resolved = new SwaggerValue
{
Location = location,
Token = jObject
};
_documentObjectCache.Add(jsonLocationInfo, resolved);
return resolved;
case SwaggerFormattedReferenceType.ExternalEmbeddedReference:
// Defer resolving external reference to resolve step, to prevent loop reference.
var externalDeferredObject = new SwaggerReferenceObject
{
ExternalFilePath = Path.Combine(Path.GetDirectoryName(swaggerPath), swaggerReference.ExternalFilePath),
DeferredReference = swaggerReference.Path,
ReferenceName = swaggerReference.Name,
Location = location
};
jObject.Remove("$ref");
externalDeferredObject.Token = jObject;
_documentObjectCache.Add(jsonLocationInfo, externalDeferredObject);
return externalDeferredObject;
default:
throw new DocfxException($"{referenceToken} does not support type {swaggerReference.Type}.");
}
}
var swaggerObject = new SwaggerObject { Location = location };
foreach (KeyValuePair<string, JToken> property in jObject)
{
swaggerObject.Dictionary.Add(property.Key, LoadCore(property.Value, swaggerPath));
}
_documentObjectCache.Add(jsonLocationInfo, swaggerObject);
return swaggerObject;
}
if (token is JArray jArray)
{
var swaggerArray = new SwaggerArray { Location = location };
foreach (var property in jArray)
{
swaggerArray.Array.Add(LoadCore(property, swaggerPath));
}
return swaggerArray;
}
return new SwaggerValue
{
Location = location,
Token = token
};
}
private static JObject LoadExternalReference(string externalSwaggerPath)
{
if (!EnvironmentContext.FileAbstractLayer.Exists(externalSwaggerPath))
{
throw new DocfxException($"External swagger path not exist: {externalSwaggerPath}.");
}
using (JsonReader reader = new JsonTextReader(EnvironmentContext.FileAbstractLayer.OpenReadText(externalSwaggerPath)))
{
return JObject.Load(reader);
}
}
private static void RemoveReferenceDefinitions(SwaggerObject root)
{
// Remove definitions and parameters which has been added into _documentObjectCache
if (root.Dictionary.ContainsKey(DefinitionsKey))
{
root.Dictionary.Remove(DefinitionsKey);
}
if (root.Dictionary.ContainsKey(ParametersKey))
{
root.Dictionary.Remove(ParametersKey);
}
}
private SwaggerObjectBase ResolveReferences(SwaggerObjectBase swaggerBase, string swaggerPath, Stack<JsonLocationInfo> refStack)
{
if (swaggerBase.ReferencesResolved)
{
return swaggerBase;
}
swaggerBase.ReferencesResolved = true;
switch (swaggerBase.ObjectType)
{
case SwaggerObjectType.ReferenceObject:
{
var swagger = (SwaggerReferenceObject)swaggerBase;
if (!string.IsNullOrEmpty(swagger.DeferredReference))
{
if (swagger.DeferredReference[0] != '/')
{
throw new JsonException($"reference \"{swagger.DeferredReference}\" is not supported. Reference must be inside current schema document starting with /");
}
var jsonLocationInfo = new JsonLocationInfo(swagger.ExternalFilePath ?? swaggerPath, swagger.DeferredReference);
if (!_documentObjectCache.TryGetValue(jsonLocationInfo, out SwaggerObjectBase referencedObjectBase))
{
if (swagger.ExternalFilePath == null)
{
throw new JsonException($"Could not resolve reference '{swagger.DeferredReference}' in the document.");
}
// Load external swagger, to fill in the document cache.
Load(swagger.ExternalFilePath);
if (!_documentObjectCache.TryGetValue(jsonLocationInfo, out referencedObjectBase))
{
throw new JsonException($"Could not resolve reference '{swagger.DeferredReference}' in the document.");
}
}
if (refStack.Contains(jsonLocationInfo))
{
var loopRef = new SwaggerLoopReferenceObject();
loopRef.Dictionary.Add(InternalLoopRefNameKey, new SwaggerValue { Token = swagger.ReferenceName });
return loopRef;
}
// Clone to avoid change the reference object in _documentObjectCache
refStack.Push(jsonLocationInfo);
var resolved = ResolveReferences(referencedObjectBase.Clone(), jsonLocationInfo.FilePath, refStack);
var swaggerObject = ResolveSwaggerObject(resolved);
if (!swaggerObject.Dictionary.ContainsKey(InternalRefNameKey))
{
swaggerObject.Dictionary.Add(InternalRefNameKey, new SwaggerValue { Token = swagger.ReferenceName });
}
swagger.Reference = swaggerObject;
refStack.Pop();
}
return swagger;
}
case SwaggerObjectType.Object:
{
var swagger = (SwaggerObject)swaggerBase;
foreach (var key in swagger.Dictionary.Keys.ToList())
{
swagger.Dictionary[key] = ResolveReferences(swagger.Dictionary[key], swaggerPath, refStack);
}
return swagger;
}
case SwaggerObjectType.Array:
{
var swagger = (SwaggerArray)swaggerBase;
for (int i = 0; i < swagger.Array.Count; i++)
{
swagger.Array[i] = ResolveReferences(swagger.Array[i], swaggerPath, refStack);
}
return swagger;
}
case SwaggerObjectType.ValueType:
return swaggerBase;
default:
throw new NotSupportedException(swaggerBase.ObjectType.ToString());
}
}
private static SwaggerObject ResolveSwaggerObject(SwaggerObjectBase swaggerObjectBase)
{
if (swaggerObjectBase is SwaggerObject swaggerObject)
{
return swaggerObject;
}
if (swaggerObjectBase is SwaggerReferenceObject swaggerReferenceObject)
{
return swaggerReferenceObject.Reference;
}
throw new ArgumentException($"When resolving reference for {nameof(SwaggerReferenceObject)}, only support {nameof(SwaggerObject)} and {nameof(SwaggerReferenceObject)} as parameter.");
}
}
}
| |
/*++
Copyright (c) 2003 Microsoft Corporation
Module Name:
NegotiateStream.cs
Abstract:
A public implementation an authenticated stream based on NEGO SSP
The class that can be used by client and server side applications
- to transfer Identities across the stream
- to ecnrypt data based on NEGO SSP package
In most cases the innerStream will be of type NetworkStream.
On Win9x data encryption is not available and both sides have
to explicitly drop SecurityLevel and MuatualAuth requirements.
This is a simple wrapper class.
All real work is done by internal NegoState class and partial implementaion in _NegoStream.cs
Author:
Alexei Vopilov Sept 28-2003
Revision History:
--*/
namespace System.Net.Security {
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.Security.Principal;
//
// Negotiate
//
public partial class NegotiateStream: AuthenticatedStream
{
private NegoState _NegoState;
private string _Package;
private IIdentity _RemoteIdentity;
public NegotiateStream(Stream innerStream): this(innerStream, false)
{
}
public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen): base(innerStream, leaveInnerStreamOpen)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
_NegoState = new NegoState(innerStream, leaveInnerStreamOpen);
_Package = NegoState.DefaultPackage;
InitializeStreamPart();
#if DEBUG
}
#endif
}
//
// Client side auth
//
public virtual void AuthenticateAsClient()
{
AuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public virtual void AuthenticateAsClient(NetworkCredential credential, string targetName)
{
AuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName)
{
AuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
//
public virtual void AuthenticateAsClient( NetworkCredential credential,
string targetName,
ProtectionLevel requiredProtectionLevel, //this will be the ultimate result or exception
TokenImpersonationLevel allowedImpersonationLevel) //this OR LOWER will be ultimate result in auth context
{
AuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
}
//
public virtual void AuthenticateAsClient(NetworkCredential credential,
ChannelBinding binding,
string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.[....])) {
#endif
_NegoState.ValidateCreateContext(_Package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
_NegoState.ProcessAuthentication(null);
#if DEBUG
}
#endif
}
//
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
//
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(credential, null, targetName,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
//
[HostProtection(ExternalThreading = true)]
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(credential, binding, targetName,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
//
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential,
string targetName,
ProtectionLevel requiredProtectionLevel, //this will be ultimatelly the result or exception
TokenImpersonationLevel allowedImpersonationLevel, //this OR LOWER will be ultimate result in auth context
AsyncCallback asyncCallback,
object asyncState)
{
return BeginAuthenticateAsClient(credential, null, targetName,
requiredProtectionLevel, allowedImpersonationLevel,
asyncCallback, asyncState);
}
//
[HostProtection(ExternalThreading = true)]
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential,
ChannelBinding binding,
string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
_NegoState.ValidateCreateContext(_Package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
LazyAsyncResult result = new LazyAsyncResult(_NegoState, asyncState, asyncCallback);
_NegoState.ProcessAuthentication(result);
return result;
#if DEBUG
}
#endif
}
//
public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
_NegoState.EndProcessAuthentication(asyncResult);
#if DEBUG
}
#endif
}
//
//
//Server side Authenticate
//
public virtual void AuthenticateAsServer()
{
AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
//
public virtual void AuthenticateAsServer(ExtendedProtectionPolicy policy)
{
AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
//
public virtual void AuthenticateAsServer( NetworkCredential credential,
ProtectionLevel requiredProtectionLevel, //throw if the result is below than this
TokenImpersonationLevel requiredImpersonationLevel) //throw if the result is below than this
{
AuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel);
}
//
public virtual void AuthenticateAsServer(NetworkCredential credential,
ExtendedProtectionPolicy policy,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.[....])) {
#endif
_NegoState.ValidateCreateContext(_Package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
_NegoState.ProcessAuthentication(null);
#if DEBUG
}
#endif
}
//
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
}
//
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
}
//
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginAuthenticateAsServer(NetworkCredential credential,
ProtectionLevel requiredProtectionLevel, //throw if the result is below than this
TokenImpersonationLevel requiredImpersonationLevel, //throw if the result is below than this
AsyncCallback asyncCallback,
object asyncState)
{
return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState);
}
//
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginAuthenticateAsServer(NetworkCredential credential,
ExtendedProtectionPolicy policy,
ProtectionLevel requiredProtectionLevel, //throw if the result is below than this
TokenImpersonationLevel requiredImpersonationLevel, //throw if the result is below than this
AsyncCallback asyncCallback,
object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
_NegoState.ValidateCreateContext(_Package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
LazyAsyncResult result = new LazyAsyncResult(_NegoState, asyncState, asyncCallback);
_NegoState.ProcessAuthentication(result);
return result;
#if DEBUG
}
#endif
}
//
public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
_NegoState.EndProcessAuthentication(asyncResult);
#if DEBUG
}
#endif
}
//************* Task-based async public methods *************************
[HostProtection(ExternalThreading = true)]
public virtual Task AuthenticateAsClientAsync()
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, null);
}
[HostProtection(ExternalThreading=true)]
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName)
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, targetName, null);
}
[HostProtection(ExternalThreading=true)]
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
[HostProtection(ExternalThreading = true)]
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding binding, string targetName)
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, binding, targetName, null);
}
[HostProtection(ExternalThreading=true)]
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, ChannelBinding binding,
string targetName, ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
[HostProtection(ExternalThreading = true)]
public virtual Task AuthenticateAsServerAsync()
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, null);
}
[HostProtection(ExternalThreading = true)]
public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy)
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, policy, null);
}
[HostProtection(ExternalThreading = true)]
public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, credential, requiredProtectionLevel, requiredImpersonationLevel, null);
}
[HostProtection(ExternalThreading = true)]
public virtual Task AuthenticateAsServerAsync(
NetworkCredential credential, ExtendedProtectionPolicy policy,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(credential, policy, requiredProtectionLevel, requiredImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
//
// Base class properties
//
public override bool IsAuthenticated {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
return _NegoState.IsAuthenticated;
#if DEBUG
}
#endif
}
}
//
public override bool IsMutuallyAuthenticated {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
return _NegoState.IsMutuallyAuthenticated;
#if DEBUG
}
#endif
}
}
//
public override bool IsEncrypted {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
return _NegoState.IsEncrypted;
#if DEBUG
}
#endif
}
}
//
public override bool IsSigned {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
return _NegoState.IsSigned;
#if DEBUG
}
#endif
}
}
//
public override bool IsServer {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
return _NegoState.IsServer;
#if DEBUG
}
#endif
}
}
//
// Informational NEGO properties
//
public virtual TokenImpersonationLevel ImpersonationLevel
{
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
return _NegoState.AllowedImpersonation;
#if DEBUG
}
#endif
}
}
//
public virtual IIdentity RemoteIdentity
{
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
if (_RemoteIdentity == null)
{
_RemoteIdentity = _NegoState.GetIdentity();
}
return _RemoteIdentity;
#if DEBUG
}
#endif
}
}
//
//
// Stream contract implementation
//
//
//
public override bool CanSeek {
get {
return false;
}
}
//
public override bool CanRead {
get {
return IsAuthenticated && InnerStream.CanRead;
}
}
//
public override bool CanTimeout {
get {
return InnerStream.CanTimeout;
}
}
//
public override bool CanWrite {
get {
return IsAuthenticated && InnerStream.CanWrite;
}
}
//
//
public override int ReadTimeout {
get {
return InnerStream.ReadTimeout;
}
set {
InnerStream.ReadTimeout = value;
}
}
//
//
public override int WriteTimeout {
get {
return InnerStream.WriteTimeout;
}
set {
InnerStream.WriteTimeout = value;
}
}
//
public override long Length {
get {
return InnerStream.Length;
}
}
//
public override long Position {
get {
return InnerStream.Position;
}
set {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
//
public override void SetLength(long value) {
InnerStream.SetLength(value);
}
//
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
// Should this not block?
public override void Flush() {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.[....])) {
#endif
InnerStream.Flush();
#if DEBUG
}
#endif
}
//
//
protected override void Dispose(bool disposing) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
try {
_NegoState.Close();
}
finally {
base.Dispose(disposing);
}
#if DEBUG
}
#endif
}
//
//
public override int Read(byte[] buffer, int offset, int count)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.[....])) {
#endif
_NegoState.CheckThrow(true);
if (!_NegoState.CanGetSecureStream)
return InnerStream.Read(buffer, offset, count);
return ProcessRead(buffer, offset, count, null);
#if DEBUG
}
#endif
}
//
//
public override void Write(byte[] buffer, int offset, int count)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.[....])) {
#endif
_NegoState.CheckThrow(true);
if (!_NegoState.CanGetSecureStream)
{
InnerStream.Write(buffer, offset, count);
return;
}
ProcessWrite(buffer, offset, count, null);
#if DEBUG
}
#endif
}
//
//
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
_NegoState.CheckThrow(true);
if (!_NegoState.CanGetSecureStream)
return InnerStream.BeginRead(buffer, offset, count, asyncCallback, asyncState);
BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback);
AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult);
ProcessRead(buffer, offset, count, asyncRequest );
return bufferResult;
#if DEBUG
}
#endif
}
//
//
public override int EndRead(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
_NegoState.CheckThrow(true);
if (!_NegoState.CanGetSecureStream)
return InnerStream.EndRead(asyncResult);
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
if (bufferResult == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
}
if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
{
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
bufferResult.InternalWaitForCompletion();
if (bufferResult.Result is Exception)
{
if (bufferResult.Result is IOException)
{
throw (Exception)bufferResult.Result;
}
throw new IOException(SR.GetString(SR.net_io_read), (Exception)bufferResult.Result);
}
return (int) bufferResult.Result;
#if DEBUG
}
#endif
}
//
//
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
_NegoState.CheckThrow(true);
if (!_NegoState.CanGetSecureStream)
return InnerStream.BeginWrite(buffer, offset, count, asyncCallback, asyncState);
BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, true, asyncState, asyncCallback);
AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult);
ProcessWrite(buffer, offset, count, asyncRequest);
return bufferResult;
#if DEBUG
}
#endif
}
//
//
public override void EndWrite(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
_NegoState.CheckThrow(true);
if (!_NegoState.CanGetSecureStream)
{
InnerStream.EndWrite(asyncResult);
return;
}
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
if (bufferResult == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
}
if (Interlocked.Exchange(ref _NestedWrite, 0) == 0)
{
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndWrite"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
bufferResult.InternalWaitForCompletion();
if (bufferResult.Result is Exception)
{
if (bufferResult.Result is IOException)
{
throw (Exception)bufferResult.Result;
}
throw new IOException(SR.GetString(SR.net_io_write), (Exception)bufferResult.Result);
}
#if DEBUG
}
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class HttpResponseStreamTests : IDisposable
{
private HttpListenerFactory _factory;
private HttpListener _listener;
private GetContextHelper _helper;
public HttpResponseStreamTests()
{
_factory = new HttpListenerFactory();
_listener = _factory.GetListener();
_helper = new GetContextHelper(_listener, _factory.ListeningUrl);
}
public void Dispose()
{
_factory.Dispose();
_helper.Dispose();
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task SimpleRequest_WriteAsynchronously_Succeeds(bool sendChunked)
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
response.SendChunked = sendChunked;
Stream outputStream = response.OutputStream;
try
{
await outputStream.WriteAsync(responseBuffer, 0, responseBuffer.Length);
}
finally
{
outputStream.Close();
}
byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent.");
await outputStream.WriteAsync(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length);
}
string clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task SimpleRequest_WriteSynchronouslyNonEmpty_Succeeds(bool sendChunked)
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
response.SendChunked = sendChunked;
Stream outputStream = response.OutputStream;
try
{
outputStream.Write(responseBuffer, 0, responseBuffer.Length);
}
finally
{
outputStream.Close();
}
byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent.");
outputStream.Write(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length);
}
string clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteAsynchronouslyInParts_Succeeds()
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
using (Stream outputStream = response.OutputStream)
{
await outputStream.WriteAsync(responseBuffer, 0, 5);
await outputStream.WriteAsync(responseBuffer, 5, responseBuffer.Length - 5);
}
}
var clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteSynchronouslyInParts_Succeeds()
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
using (Stream outputStream = response.OutputStream)
{
outputStream.Write(responseBuffer, 0, 5);
outputStream.Write(responseBuffer, 5, responseBuffer.Length - 5);
}
}
var clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteAynchronouslyEmpty_Succeeds()
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
response.ContentLength64 = 0;
using (Stream outputStream = response.OutputStream)
{
await outputStream.WriteAsync(new byte[0], 0, 0);
}
}
Assert.Empty(await clientTask);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteSynchronouslyEmpty_Succeeds()
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
response.ContentLength64 = 0;
using (Stream outputStream = response.OutputStream)
{
outputStream.Write(new byte[0], 0, 0);
}
}
Assert.Empty(await clientTask);
}
}
[Fact]
public async Task CanSeek_Get_ReturnsFalse()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
Assert.False(outputStream.CanSeek);
Assert.Throws<NotSupportedException>(() => outputStream.Length);
Assert.Throws<NotSupportedException>(() => outputStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => outputStream.Position);
Assert.Throws<NotSupportedException>(() => outputStream.Position = 1);
Assert.Throws<NotSupportedException>(() => outputStream.Seek(0, SeekOrigin.Begin));
}
}
[Fact]
public async Task CanRead_Get_ReturnsFalse()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
Assert.False(outputStream.CanRead);
Assert.Throws<InvalidOperationException>(() => outputStream.Read(new byte[0], 0, 0));
await Assert.ThrowsAsync<InvalidOperationException>(() => outputStream.ReadAsync(new byte[0], 0, 0));
Assert.Throws<InvalidOperationException>(() => outputStream.EndRead(null));
}
}
[Fact]
public async Task CanWrite_Get_ReturnsTrue()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
Assert.True(outputStream.CanWrite);
// Flushing the output stream is a no-op.
outputStream.Flush();
Assert.Equal(Task.CompletedTask, outputStream.FlushAsync(CancellationToken.None));
}
}
[Fact]
public async Task Write_NullBuffer_ThrowsArgumentNullException()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => outputStream.Write(null, 0, 0));
await Assert.ThrowsAsync<ArgumentNullException>("buffer", () => outputStream.WriteAsync(null, 0, 0));
}
}
[Theory]
[InlineData(-1)]
[InlineData(3)]
public async Task Write_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset)
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => outputStream.Write(new byte[2], offset, 0));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => outputStream.WriteAsync(new byte[2], offset, 0));
}
}
[Theory]
[InlineData(0, 3)]
[InlineData(1, 2)]
[InlineData(2, 1)]
public async Task Write_InvalidOffsetSize_ThrowsArgumentOutOfRangeException(int offset, int size)
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => outputStream.Write(new byte[2], offset, size));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("size", () => outputStream.WriteAsync(new byte[2], offset, size));
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_TooMuch_ThrowsProtocolViolationException()
{
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await _listener.GetContextAsync();
using (HttpListenerResponse response = serverContext.Response)
{
Stream output = response.OutputStream;
byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
response.ContentLength64 = responseBuffer.Length - 1;
try
{
Assert.Throws<ProtocolViolationException>(() => output.Write(responseBuffer, 0, responseBuffer.Length));
await Assert.ThrowsAsync<ProtocolViolationException>(() => output.WriteAsync(responseBuffer, 0, responseBuffer.Length));
}
finally
{
// Write the remaining bytes to guarantee a successful shutdown.
output.Write(responseBuffer, 0, (int)response.ContentLength64);
output.Close();
}
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_TooLittleAsynchronouslyAndClose_ThrowsInvalidOperationException()
{
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await _listener.GetContextAsync();
using (HttpListenerResponse response = serverContext.Response)
{
Stream output = response.OutputStream;
byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
response.ContentLength64 = responseBuffer.Length + 1;
// Throws when there are bytes left to write
await output.WriteAsync(responseBuffer, 0, responseBuffer.Length);
Assert.Throws<InvalidOperationException>(() => output.Close());
// Write the final byte and make sure we can close.
await output.WriteAsync(new byte[1], 0, 1);
output.Close();
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_TooLittleSynchronouslyAndClose_ThrowsInvalidOperationException()
{
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await _listener.GetContextAsync();
using (HttpListenerResponse response = serverContext.Response)
{
Stream output = response.OutputStream;
byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
response.ContentLength64 = responseBuffer.Length + 1;
// Throws when there are bytes left to write
output.Write(responseBuffer, 0, responseBuffer.Length);
Assert.Throws<InvalidOperationException>(() => output.Close());
// Write the final byte and make sure we can close.
output.Write(new byte[1], 0, 1);
output.Close();
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_HeadersToClosedConnectionAsynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
client.Shutdown(SocketShutdown.Both);
Helpers.WaitForSocketShutdown(client);
// Writing to a disconnected client should fail.
await Assert.ThrowsAsync<HttpListenerException>(() => context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length));
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_HeadersToClosedConnectionSynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
client.Shutdown(SocketShutdown.Both);
Helpers.WaitForSocketShutdown(client);
// Writing to, a closed connection should fail.
Assert.Throws<HttpListenerException>(() => context.Response.OutputStream.Write(buffer, 0, buffer.Length));
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
[ActiveIssue(18188, platforms: TestPlatforms.Windows)] // Indeterminate failure - socket not always fully disconnected.
public async Task Write_ContentToClosedConnectionAsynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Write the headers to the Socket.
await context.Response.OutputStream.WriteAsync(buffer, 0, 1);
// Disconnect the Socket from the HttpListener.
client.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
// Writing non-header content to a disconnected client should fail, only if IgnoreWriteExceptions is false.
if (ignoreWriteExceptions)
{
await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
}
else
{
await Assert.ThrowsAsync<HttpListenerException>(() => context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length));
}
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
[ActiveIssue(18188, platforms: TestPlatforms.Windows)] // Indeterminate failure - socket not always fully disconnected.
public async Task Write_ContentToClosedConnectionSynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Write the headers to the Socket.
context.Response.OutputStream.Write(buffer, 0, 1);
// Disconnect the Socket from the HttpListener.
client.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
// Writing non-header content to a disconnected client should fail, only if IgnoreWriteExceptions is false.
if (ignoreWriteExceptions)
{
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
else
{
Assert.Throws<HttpListenerException>(() => context.Response.OutputStream.Write(buffer, 0, buffer.Length));
}
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EndWrite_NullAsyncResult_ThrowsArgumentNullException(bool ignoreWriteExceptions)
{
_listener.IgnoreWriteExceptions = ignoreWriteExceptions;
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentNullException>("asyncResult", () => outputStream.EndWrite(null));
}
}
[Fact]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)]
public async Task EndWrite_InvalidAsyncResult_ThrowsArgumentException()
{
using (HttpListenerResponse response1 = await _helper.GetResponse())
using (Stream outputStream1 = response1.OutputStream)
using (HttpListenerResponse response2 = await _helper.GetResponse())
using (Stream outputStream2 = response2.OutputStream)
{
IAsyncResult beginWriteResult = outputStream1.BeginWrite(new byte[0], 0, 0, null, null);
AssertExtensions.Throws<ArgumentException>("asyncResult", () => outputStream2.EndWrite(new CustomAsyncResult()));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => outputStream2.EndWrite(beginWriteResult));
}
}
[Fact]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)]
public async Task EndWrite_CalledTwice_ThrowsInvalidOperationException()
{
using (HttpListenerResponse response1 = await _helper.GetResponse())
using (Stream outputStream = response1.OutputStream)
{
IAsyncResult beginWriteResult = outputStream.BeginWrite(new byte[0], 0, 0, null, null);
outputStream.EndWrite(beginWriteResult);
Assert.Throws<InvalidOperationException>(() => outputStream.EndWrite(beginWriteResult));
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
// ReSharper disable UnusedMember.Global
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
namespace System.Management.Automation
{
internal static class ArrayOps
{
internal static object[] SlicingIndex(object target, object[] indexes, Func<object, object, object> indexer)
{
var result = new object[indexes.Length];
int j = 0;
foreach (object t in indexes)
{
var value = indexer(target, t);
if (value != AutomationNull.Value)
{
result[j++] = value;
}
}
if (j != indexes.Length)
{
var shortResult = new object[j];
Array.Copy(result, shortResult, j);
return shortResult;
}
return result;
}
/// <summary>
/// Efficiently multiplies collection by integer
/// </summary>
/// <param name="array">collection to multiply</param>
/// <param name="times">number of times the collection is to be multiplied/copied</param>
/// <returns>collection multiplied by integer</returns>
internal static T[] Multiply<T>(T[] array, uint times)
{
Diagnostics.Assert(array != null, "Caller should verify the arguments for array multiplication");
if (times == 1)
{
return array;
}
if (times == 0 || array.Length == 0)
{
return new T[0]; // don't use Utils.EmptyArray, always return a new array
}
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context != null &&
context.LanguageMode == PSLanguageMode.RestrictedLanguage && (array.Length * times) > 1024)
{
throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException),
null, "ArrayMultiplyToolongInDataSection", ParserStrings.ArrayMultiplyToolongInDataSection, 1024);
}
var uncheckedLength = array.Length * times;
int elements = -1;
try
{
elements = checked((int)uncheckedLength);
}
catch (OverflowException)
{
LanguagePrimitives.ThrowInvalidCastException(uncheckedLength, typeof(int));
}
// Make the minimum number of calls to Array.Copy by doubling the array up to
// the most significant bit in times, then do one final Array.Copy to get the
// remaining copies.
T[] result = new T[elements];
int resultLength = array.Length;
Array.Copy(array, 0, result, 0, resultLength);
times >>= 1;
while (times != 0)
{
Array.Copy(result, 0, result, resultLength, resultLength);
resultLength *= 2;
times >>= 1;
}
if (result.Length != resultLength)
{
Array.Copy(result, 0, result, resultLength, (result.Length - resultLength));
}
return result;
}
internal static object GetMDArrayValue(Array array, int[] indexes, bool slicing)
{
if (array.Rank != indexes.Length)
{
ReportIndexingError(array, indexes, null);
}
for (int i = 0; i < indexes.Length; ++i)
{
int ub = array.GetUpperBound(i);
int lb = array.GetLowerBound(i);
if (indexes[i] < lb)
{
indexes[i] = indexes[i] + ub + 1;
}
if (indexes[i] < lb || indexes[i] > ub)
{
// In strict mode, don't return, fall through and let Array.GetValue raise an exception.
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context != null && !context.IsStrictVersion(3))
{
// If we're slicing, return AutomationNull.Value to signal no result)
return slicing ? AutomationNull.Value : null;
}
}
}
// All indexes have been validated, so this won't raise an exception.
return array.GetValue(indexes);
}
internal static object GetMDArrayValueOrSlice(Array array, object indexes)
{
Exception whyFailed = null;
int[] indexArray = null;
try
{
indexArray = (int[])LanguagePrimitives.ConvertTo(indexes, typeof(int[]), NumberFormatInfo.InvariantInfo);
}
catch (InvalidCastException ice)
{
// Ignore an exception here as we may actually be looking at an array of arrays
// which could still be ok. Save the exception as we may use it later...
whyFailed = ice;
}
if (indexArray != null)
{
if (indexArray.Length != array.Rank)
{
// rank failed to match so error...
ReportIndexingError(array, indexes, null);
}
return GetMDArrayValue(array, indexArray, false);
}
var indexList = new List<int[]>();
var ie = LanguagePrimitives.GetEnumerator(indexes);
while (EnumerableOps.MoveNext(null, ie))
{
var currentIndex = EnumerableOps.Current(ie);
try
{
indexArray = LanguagePrimitives.ConvertTo<int[]>(currentIndex);
}
catch (InvalidCastException)
{
indexArray = null;
}
if (indexArray == null || indexArray.Length != array.Rank)
{
if (whyFailed != null)
{
// If the first fails, report the original exception and all indices
ReportIndexingError(array, indexes, whyFailed);
Diagnostics.Assert(false, "ReportIndexingError must throw");
}
// If the second or subsequent index fails, report the failure for just that index
ReportIndexingError(array, currentIndex, null);
Diagnostics.Assert(false, "ReportIndexingError must throw");
}
// Only use whyFailed the first time through, otherwise
whyFailed = null;
indexList.Add(indexArray);
}
// Optimistically assume all indices are valid so the result array is the same size.
// If that turns out to be wrong, we'll just copy the elements produced.
var result = new object[indexList.Count];
int j = 0;
foreach (var i in indexList)
{
var value = GetMDArrayValue(array, i, true);
if (value != AutomationNull.Value)
{
result[j++] = value;
}
}
if (j != indexList.Count)
{
var shortResult = new object[j];
Array.Copy(result, shortResult, j);
return shortResult;
}
return result;
}
private static void ReportIndexingError(Array array, object index, Exception reason)
{
// Convert this index into something printable (we hope)...
string msgString = IndexStringMessage(index);
if (reason == null)
{
throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), null,
"NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, array.Rank, msgString);
}
throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), null,
"NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, reason, array.Rank, msgString);
}
internal static string IndexStringMessage(object index)
{
// Convert this index into something printable (we hope)...
string msgString = PSObject.ToString(null, index, ",", null, null, true, true);
if (msgString.Length > 20)
msgString = msgString.Substring(0, 20) + " ...";
return msgString;
}
internal static object SetMDArrayValue(Array array, int[] indexes, object value)
{
if (array.Rank != indexes.Length)
{
ReportIndexingError(array, indexes, null);
}
for (int i = 0; i < indexes.Length; ++i)
{
int ub = array.GetUpperBound(i);
int lb = array.GetLowerBound(i);
if (indexes[i] < lb)
{
indexes[i] = indexes[i] + ub + 1;
}
}
array.SetValue(value, indexes);
return value;
}
internal static object GetNonIndexable(object target, object[] indices)
{
// We want to allow:
// $x[0]
// and
// $x[-1]
// to be the same as
// $x
// But disallow anything else:
// if in the strict mode, throw exception
// otherwise, return AutomationNull.Value to signal no result
if (indices.Length == 1)
{
var index = indices[0];
if (index != null && (LanguagePrimitives.Equals(0, index) || LanguagePrimitives.Equals(-1, index)))
{
return target;
}
}
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context == null || !context.IsStrictVersion(2))
{
return AutomationNull.Value;
}
throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), null, "CannotIndex",
ParserStrings.CannotIndex, target.GetType());
}
}
}
| |
#region License
/*
* Copyright 2009- Marko Lahma
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.Text;
using Quartz.Util;
namespace Quartz.Impl.AdoJobStore.Common
{
/// <summary>
/// Concrete implementation of <see cref="IDbProvider" />.
/// </summary>
/// <author>Marko Lahma</author>
public class DbProvider : IDbProvider
{
protected const string PropertyDbProvider = "quartz.dbprovider";
protected const string DbProviderResourceName = "Quartz.Impl.AdoJobStore.Common.dbproviders.properties";
private string connectionString;
private readonly DbMetadata dbMetadata;
private static readonly Dictionary<string, DbMetadata> dbMetadataLookup = new Dictionary<string, DbMetadata>();
private static readonly DbMetadata notInitializedMetadata = new DbMetadata();
/// <summary>
/// Parse metadata once in static constructor.
/// </summary>
static DbProvider()
{
// parse metadata
PropertiesParser pp = PropertiesParser.ReadFromEmbeddedAssemblyResource(DbProviderResourceName);
IList<string> providers = pp.GetPropertyGroups(PropertyDbProvider);
foreach (string providerName in providers)
{
dbMetadataLookup[providerName] = notInitializedMetadata;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DbProvider"/> class.
/// </summary>
/// <param name="dbProviderName">Name of the db provider.</param>
/// <param name="connectionString">The connection string.</param>
public DbProvider(string dbProviderName, string connectionString)
{
List<string> deprecatedProviders = new List<string> { "Npgsql-10", "SqlServer-11" };
if (deprecatedProviders.Contains(dbProviderName))
{
throw new InvalidConfigurationException(dbProviderName + " provider is no longer supported.");
}
this.connectionString = connectionString;
dbMetadata = GetDbMetadata(dbProviderName);
if (dbMetadata == null)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid DB provider name: {0}{1}{2}", dbProviderName, Environment.NewLine, GenerateValidProviderNamesInfo()));
}
}
public void Initialize()
{
// do nothing, initialized in static constructor
}
///<summary>
/// Registers DB metadata information for given provider name.
///</summary>
///<param name="dbProviderName"></param>
///<param name="metadata"></param>
public static void RegisterDbMetadata(string dbProviderName, DbMetadata metadata)
{
dbMetadataLookup[dbProviderName] = metadata;
}
protected virtual DbMetadata GetDbMetadata(string providerName)
{
DbMetadata data;
dbMetadataLookup.TryGetValue(providerName, out data);
if (data == notInitializedMetadata)
{
try
{
PropertiesParser pp =
PropertiesParser.ReadFromEmbeddedAssemblyResource(DbProviderResourceName);
DbMetadata metadata = new DbMetadata();
NameValueCollection props =
pp.GetPropertyGroup(PropertyDbProvider + "." + providerName, true);
ObjectUtils.SetObjectProperties(metadata, props);
metadata.Init();
RegisterDbMetadata(providerName, metadata);
return metadata;
}
catch (Exception ex)
{
throw new Exception("Error while reading metadata information for provider '" + providerName + "'",
ex);
}
}
return data;
}
protected static string GenerateValidProviderNamesInfo()
{
StringBuilder sb = new StringBuilder("Valid DB Provider names are:").Append(Environment.NewLine);
foreach (string providerName in dbMetadataLookup.Keys)
{
sb.Append("\t").Append(providerName).Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Returns a new command object for executing SQL statments/Stored Procedures
/// against the database.
/// </summary>
/// <returns>An new <see cref="IDbCommand"/></returns>
public virtual IDbCommand CreateCommand()
{
return ObjectUtils.InstantiateType<IDbCommand>(dbMetadata.CommandType);
}
/// <summary>
/// Returns a new instance of the providers CommandBuilder class.
/// </summary>
/// <returns>A new Command Builder</returns>
/// <remarks>In .NET 1.1 there was no common base class or interface
/// for command builders, hence the return signature is object to
/// be portable (but more loosely typed) across .NET 1.1/2.0</remarks>
public virtual object CreateCommandBuilder()
{
return ObjectUtils.InstantiateType<object>(dbMetadata.CommandBuilderType);
}
/// <summary>
/// Returns a new connection object to communicate with the database.
/// </summary>
/// <returns>A new <see cref="IDbConnection"/></returns>
public virtual IDbConnection CreateConnection()
{
IDbConnection conn = ObjectUtils.InstantiateType<IDbConnection>(dbMetadata.ConnectionType);
conn.ConnectionString = ConnectionString;
return conn;
}
/// <summary>
/// Returns a new parameter object for binding values to parameter
/// placeholders in SQL statements or Stored Procedure variables.
/// </summary>
/// <returns>A new <see cref="IDbDataParameter"/></returns>
public virtual IDbDataParameter CreateParameter()
{
return ObjectUtils.InstantiateType<IDbDataParameter>(dbMetadata.ParameterType);
}
/// <summary>
/// Connection string used to create connections.
/// </summary>
/// <value></value>
public virtual string ConnectionString
{
get { return connectionString; }
set { connectionString = value; }
}
/// <summary>
/// Gets the metadata.
/// </summary>
/// <value>The metadata.</value>
public virtual DbMetadata Metadata
{
get { return dbMetadata; }
}
/// <summary>
/// Shutdowns this instance.
/// </summary>
public virtual void Shutdown()
{
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
[SecuritySafeCritical]
public struct TestStruct
{
public int TestInt;
}
[SecuritySafeCritical]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TestUnicodeStringStruct
{
public string TestString;
}
[SecuritySafeCritical]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TestAnsiStringStruct
{
public string TestString;
}
[SecuritySafeCritical]
public struct TestMultiMemberStruct1
{
public double TestDouble;
public int TestInt;
}
[SecuritySafeCritical]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TestMultiMemberStruct2
{
public int TestInt;
public string TestString;
}
[SecuritySafeCritical]
public struct TestMultiStructs1
{
public float TestFloat;
public TestUnicodeStringStruct TestUnicodeStringStruct;
}
[SecuritySafeCritical]
public struct TestMultiStructs2
{
public float TestFloat;
public TestMultiMemberStruct2 TestMultiMemberStruct2;
}
[SecuritySafeCritical]
public enum TestEnum
{
ENUM_VALUE1,
ENUM_VALUE2
}
[SecuritySafeCritical]
public struct TestGenericStruct<T>
{
public T TestVal;
}
/// <summary>
/// SizeOf(System.Object)
/// </summary>
[SecuritySafeCritical]
public class MarshalSizeOf1
{
#region Private Fields
private const int c_STRING_MIN_LENGTH = 1;
private const int c_STRING_MAX_LENGTH = 1024;
#endregion
private int NextHighestMultipleOf(int n, int k)
{
return k * ((int)Math.Ceiling( ((double)n) / ((double)k)));
}
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Get size of an instance of struct contains one field");
try
{
TestStruct obj = new TestStruct();
obj.TestInt = TestLibrary.Generator.GetInt32(-55);
int expectedSize = 4;
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("001.1", "Get size of an instance of struct contains one field returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestInt = " + obj.TestInt);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Get size of an instance of struct contains unicode string field");
try
{
TestUnicodeStringStruct obj = new TestUnicodeStringStruct();
string randValue = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH);
obj.TestString = randValue;
int expectedSize = IntPtr.Size;
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("002.1", "Get size of an instance of struct contains unicode string field returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", randValue = " + randValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Get size of an instance of struct contains ansi string field");
try
{
TestAnsiStringStruct obj = new TestAnsiStringStruct();
string randValue = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH);
obj.TestString = randValue;
int expectedSize = IntPtr.Size;
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("003.1", "Get size of an instance of struct contains ansi string field returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", randValue = " + randValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Get size of an instance of struct contains multiple fields");
try
{
TestMultiMemberStruct1 obj = new TestMultiMemberStruct1();
obj.TestInt = TestLibrary.Generator.GetInt32(-55);
obj.TestDouble = TestLibrary.Generator.GetDouble(-55);
int expectedSize = 16; // sizeof(double) + sizeof(int) + padding
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("004.1", "Get size of an instance of struct contains multiple fields returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestInt = " + obj.TestInt + ", obj.TestDouble = " + obj.TestDouble);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Get size of an instance of struct contains value type and reference type fields");
try
{
TestMultiMemberStruct2 obj = new TestMultiMemberStruct2();
obj.TestInt = TestLibrary.Generator.GetInt32(-55);
obj.TestString = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH);
int expectedSize = NextHighestMultipleOf(Marshal.SizeOf(typeof(int)) + IntPtr.Size , TestLibrary.Utilities.Is64 ? 8 : 4); // sizeof(object) + sizeof(int)
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("005.1", "Get size of an instance of struct contains value type and reference type fields returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestInt = " + obj.TestInt + ", obj.TestString = " + obj.TestString);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Get size of an instance of struct contains nested one field struct");
try
{
TestMultiStructs1 obj = new TestMultiStructs1();
obj.TestFloat = TestLibrary.Generator.GetSingle(-55);
obj.TestUnicodeStringStruct.TestString = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH);
int expectedSize = NextHighestMultipleOf(IntPtr.Size + Marshal.SizeOf(typeof(int)), TestLibrary.Utilities.Is64 ? 8 : 4); // sizeof(string) + sizeof(int)
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("006.1", "Get size of an instance of struct contains nested one field struct returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestFloat = " + obj.TestFloat + ", obj.TestUnicodeStringStruct.TestString = " + obj.TestUnicodeStringStruct.TestString);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Get size of an instance of struct contains nested multiple fields struct");
try
{
TestMultiStructs2 obj = new TestMultiStructs2();
obj.TestFloat = TestLibrary.Generator.GetSingle(-55);
obj.TestMultiMemberStruct2.TestInt = TestLibrary.Generator.GetInt32(-55);
obj.TestMultiMemberStruct2.TestString = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH);
int expectedSize = NextHighestMultipleOf(Marshal.SizeOf(typeof(TestMultiMemberStruct2)) + Marshal.SizeOf(typeof(float)),
TestLibrary.Utilities.Is64 ? 8 : 4); // sizeof(int) + sizeof(float) + sizeof(string)
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("007.1", "Get size of an instance of struct contains nested multiple fields struct returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestFloat = " + obj.TestFloat + ", obj.TestMultiMemberStruct2.TestInt = " + obj.TestMultiMemberStruct2.TestInt + ", obj.TestMultiMemberStruct2.TestString = " + obj.TestMultiMemberStruct2.TestString);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8: Get size of an instance of value type");
try
{
int obj = TestLibrary.Generator.GetInt32(-55);
int expectedSize = 4;
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("008.1", "Get size of an instance of value type returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj = " + obj);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest9: Get size of an instance of generic struct type");
try
{
TestGenericStruct<int> obj = new TestGenericStruct<int>();
obj.TestVal = TestLibrary.Generator.GetInt32(-55);
int expectedSize = 4;
int actualSize = Marshal.SizeOf(obj);
if (expectedSize != actualSize)
{
TestLibrary.TestFramework.LogError("009.1", "Get size of an instance of generic struct type returns wrong size");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestVal = " + obj.TestVal);
retVal = false;
}
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException should be thrown when The structure parameter is a null reference.");
try
{
int size = Marshal.SizeOf(null);
TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when The structure parameter is a null reference.");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentException should be thrown when the value is a enum type");
try
{
TestEnum obj = TestEnum.ENUM_VALUE1;
int size = Marshal.SizeOf(obj);
TestLibrary.TestFramework.LogError("102.1", "ArgumentException is not thrown when the value is a enum type");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException should be thrown when the value is a reference type");
try
{
Object obj = new Object();
int size = Marshal.SizeOf(obj);
TestLibrary.TestFramework.LogError("103.1", "ArgumentException is not thrown when the value is a reference type");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
MarshalSizeOf1 test = new MarshalSizeOf1();
TestLibrary.TestFramework.BeginTestCase("MarshalSizeOf1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Owin;
namespace Gate.Middleware
{
internal static partial class ShowExceptions
{
static void ErrorPage(IDictionary<string, object> env, Exception ex, Action<string> write)
{
// XXX test this more thoroughly on mono, it shouldn't throw NullRef,
// but rather, branch gracefully if something comes up null
try
{
var request = new Request(env);
var path = request.PathBase + request.Path;
var frames = StackFrames(ex);
var first = frames.FirstOrDefault();
var location = "";
if (ex.TargetSite != null && ex.TargetSite.DeclaringType != null)
{
location = ex.TargetSite.DeclaringType.FullName + "." + ex.TargetSite.Name;
}
else if (first != null)
{
location = first.Function;
}
// adapted from Django <djangoproject.com>
// Copyright (c) 2005, the Lawrence Journal-World
// Used under the modified BSD license:
// http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5
write(@"
<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd"">
<html lang=""en"">
<head>
<meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" />
<meta name=""robots"" content=""NONE,NOARCHIVE"" />
<title>");
write(h(ex.GetType().Name));
write(@" at ");
write(h(path));
write(@"</title>
<style type=""text/css"">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; }
h2 { margin-bottom:.8em; }
h2 span { font-size:80%; color:#666; font-weight:normal; }
h3 { margin:1em 0 .5em 0; }
h4 { margin:0 0 .5em 0; font-weight: normal; }
table {
border:1px solid #ccc; border-collapse: collapse; background:white; }
tbody td, tbody th { vertical-align:top; padding:2px 3px; }
thead th {
padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
font-weight:normal; font-size:11px; border:1px solid #ddd; }
tbody th { text-align:right; color:#666; padding-right:.5em; }
table.vars { margin:5px 0 2px 40px; }
table.vars td, table.req td { font-family:monospace; }
table td.code { width:100%;}
table td.code div { overflow:hidden; }
table.source th { color:#666; }
table.source td {
font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
ul.traceback { list-style-type:none; }
ul.traceback li.frame { margin-bottom:1em; }
div.context { margin: 10px 0; }
div.context ol {
padding-left:30px; margin:0 10px; list-style-position: inside; }
div.context ol li {
font-family:monospace; white-space:pre; color:#666; cursor:pointer; }
div.context ol.context-line li { color:black; background-color:#ccc; }
div.context ol.context-line li span { float: right; }
div.commands { margin-left: 40px; }
div.commands a { color:black; text-decoration:none; }
#summary { background: #ffc; }
#summary h2 { font-weight: normal; color: #666; }
#summary ul#quicklinks { list-style-type: none; margin-bottom: 2em; }
#summary ul#quicklinks li { float: left; padding: 0 1em; }
#summary ul#quicklinks>li+li { border-left: 1px #666 solid; }
#explanation { background:#eee; }
#template, #template-not-exist { background:#f6f6f6; }
#template-not-exist ul { margin: 0 0 0 20px; }
#traceback { background:#eee; }
#requestinfo { background:#f6f6f6; padding-left:120px; }
#summary table { border:none; background:transparent; }
#requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
#requestinfo h3 { margin-bottom:-1em; }
.error { background: #ffc; }
.specific { color:#cc3300; font-weight:bold; }
</style>
<script type=""text/javascript"">
//<!--
function getElementsByClassName(oElm, strTagName, strClassName){
// Written by Jonathan Snook, http://www.snook.ca/jon;
// Add-ons by Robert Nyman, http://www.robertnyman.com
var arrElements = (strTagName == ""*"" && document.all)? document.all :
oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, ""\\-"");
var oRegExp = new RegExp(""(^|\\s)"" + strClassName + ""(\\s|$$)"");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}
function hideAll(elems) {
for (var e = 0; e < elems.length; e++) {
elems[e].style.display = 'none';
}
}
window.onload = function() {
hideAll(getElementsByClassName(document, 'table', 'vars'));
hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
hideAll(getElementsByClassName(document, 'ol', 'post-context'));
}
function toggle() {
for (var i = 0; i < arguments.length; i++) {
var e = document.getElementById(arguments[i]);
if (e) {
e.style.display = e.style.display == 'none' ? 'block' : 'none';
}
}
return false;
}
function varToggle(link, id) {
toggle('v' + id);
var s = link.getElementsByTagName('span')[0];
var uarr = String.fromCharCode(0x25b6);
var darr = String.fromCharCode(0x25bc);
s.innerHTML = s.innerHTML == uarr ? darr : uarr;
return false;
}
//-->
</script>
</head>
<body>
<div id=""summary"">
<h1>");
write(h(ex.GetType().Name));
write(@" at ");
write(h(path));
write(@"</h1>
<h2>");
write(h(ex.Message));
write(@"</h2>
<table><tr>
<th>.NET</th>
<td>
");
if (!string.IsNullOrEmpty(location) && !string.IsNullOrEmpty(first.File))
{
write(@"
<code>");
write(h(location));
write(@"</code>: in <code>");
write(h(first.File));
write(@"</code>, line ");
write(h(first.Line));
write(@"
");
}
else if (!string.IsNullOrEmpty(location))
{
write(@"
<code>");
write(h(location));
write(@"</code>
");
}
else
{
write(@"
unknown location
");
}
write(@"
</td>
</tr><tr>
<th>Web</th>
<td><code>");
write(h(request.Method));
write(@" ");
write(h(request.Host + path));
write(@" </code></td>
</tr></table>
<h3>Jump to:</h3>
<ul id=""quicklinks"">
<li><a href=""#get-info"">GET</a></li>
<li><a href=""#post-info"">POST</a></li>
<li><a href=""#cookie-info"">Cookies</a></li>
<li><a href=""#header-info"">Headers</a></li>
<li><a href=""#env-info"">ENV</a></li>
</ul>
</div>
<div id=""traceback"">
<h2>Traceback <span>(innermost first)</span></h2>
<ul class=""traceback"">
");
foreach (var frameIndex in frames.Select((frame, index) => Tuple.Create(frame, index)))
{
var frame = frameIndex.Item1;
var index = frameIndex.Item2;
write(@"
<li class=""frame"">
<code>");
write(h(frame.File));
write(@"</code>: in <code>");
write(h(frame.Function));
write(@"</code>
");
if (frame.ContextCode != null)
{
write(@"
<div class=""context"" id=""c{%=h frame.object_id %}"">
");
if (frame.PreContextCode != null)
{
write(@"
<ol start=""");
write(h(frame.PreContextLine + 1));
write(@""" class=""pre-context"" id=""pre");
write(h(index));
write(@""">
");
foreach (var line in frame.PreContextCode)
{
write(@"
<li onclick=""toggle('pre");
write(h(index));
write(@"', 'post");
write(h(index));
write(@"')"">");
write(h(line));
write(@"</li>
");
}
write(@"
</ol>
");
}
write(@"
<ol start=""");
write(h(frame.Line));
write(@""" class=""context-line"">
<li onclick=""toggle('pre");
write(h(index));
write(@"', 'post");
write(h(index));
write(@"')"">");
write(h(frame.ContextCode));
write(@"<span>...</span></li></ol>
");
if (frame.PostContextCode != null)
{
write(@"
<ol start='");
write(h(frame.Line + 1));
write(@"' class=""post-context"" id=""post");
write(h(index));
write(@""">
");
foreach (var line in frame.PostContextCode)
{
write(@"
<li onclick=""toggle('pre");
write(h(index));
write(@"', 'post");
write(h(index));
write(@"')"">");
write(h(line));
write(@"</li>
");
}
write(@"
</ol>
");
}
write(@"
</div>
");
}
write(@"
</li>
");
}
write(@"
</ul>
</div>
<div id=""requestinfo"">
<h2>Request information</h2>
<h3 id=""get-info"">GET</h3>
");
if (request.Query.Any())
{
write(@"
<table class=""req"">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
");
foreach (var kv in request.Query.OrderBy(kv => kv.Key))
{
write(@"
<tr>
<td>");
write(h(kv.Key));
write(@"</td>
<td class=""code""><div>");
write(h(kv.Value));
write(@"</div></td>
</tr>
");
}
write(@"
</tbody>
</table>
");
}
else
{
write(@"
<p>No GET data.</p>
");
}
write(@"
<h3 id=""post-info"">POST</h3>
");
var form = request.ReadForm();
if (form.Any())
{
write(@"
<table class=""req"">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
");
foreach (var kv in form.OrderBy(kv => kv.Key))
{
write(@"
<tr>
<td>");
write(h(kv.Key));
write(@"</td>
<td class=""code""><div>");
write(h(kv.Value));
write(@"</div></td>
</tr>
");
}
write(@"
</tbody>
</table>
");
}
else
{
write(@"
<p>No POST data.</p>
");
}
write(@"
<h3 id=""cookie-info"">COOKIES</h3>
");
if (request.Cookies.Any())
{
write(@"
<table class=""req"">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
");
foreach (var kv in request.Cookies.OrderBy(kv => kv.Key))
{
write(@"
<tr>
<td>");
write(h(kv.Key));
write(@"</td>
<td class=""code""><div>");
write(h(kv.Value));
write(@"</div></td>
</tr>
");
}
write(@"
</tbody>
</table>
");
}
else
{
write(@"
<p>No cookie data.</p>
");
}
write(@"
<h3 id=""cookie-info"">HEADERS</h3>
");
if (request.Headers.Any())
{
write(@"
<table class=""req"">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
");
foreach (var kv in request.Headers.OrderBy(kv => kv.Key))
{
write(@"
<tr>
<td nowrap=""nowrap"">");
write(h(kv.Key));
write(@"</td>
<td class=""code""><div>");
foreach (var v in kv.Value)
{
write(h(v));
write(@"<br/>");
}
write(@"</div></td>
</tr>
");
}
write(@"
</tbody>
</table>
");
}
else
{
write(@"
<p>No header data.</p>
");
}
write(@"
<h3 id=""env-info"">OWIN ENV</h3>
<table class=""req"">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
");
foreach (var kv in env.OrderBy(kv => kv.Key))
{
write(@"
<tr>
<td>");
write(h(kv.Key));
write(@"</td>
<td class=""code""><div>");
write(h(kv.Value));
write(@"</div></td>
</tr>
");
}
write(@"
</tbody>
</table>
</div>
<div id=""explanation"">
<p>
You're seeing this error because you use <code>Gate.Helpers.ShowExceptions</code>.
</p>
</div>
</body>
</html>
");
}
catch
{
return;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using uSignalR.Http;
using uSignalR.Hubs;
using uSignalR.Infrastructure;
using uSignalR.Transports;
using uTasks;
using UnityEngine;
namespace uSignalR
{
public class Connection : IConnection
{
internal static readonly TimeSpan DefaultAbortTimeout = TimeSpan.FromSeconds(30);
private static Version _assemblyVersion;
/// <summary>
/// Used to synchronize state changes
/// </summary>
private readonly object _stateLock = new object();
private IClientTransport _transport;
/// <summary>
/// Used to synchronize starting and stopping specifically
/// </summary>
private readonly object _startLock = new object();
/// <summary>
/// Used to ensure we don't write to the Trace TextWriter from multiple threads simultaneously
/// </summary>
private readonly object _traceLock = new object();
private TextWriter _traceWriter;
private Task _connectTask;
/// <summary>
/// The default connection state is disconnected
/// </summary>
private ConnectionState _state;
/// <summary>
/// Initializes a new instance of the <see cref="Connection" /> class.
/// </summary>
/// <param name="url">The url to connect to.</param>
public Connection(string url)
: this(url, (string) null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Connection" /> class.
/// </summary>
/// <param name="url">The url to connect to.</param>
/// <param name="queryString">The query string data to pass to the server.</param>
public Connection(string url, IDictionary<string, string> queryString)
: this(url, CreateQueryString(queryString))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Connection" /> class.
/// </summary>
/// <param name="url">The url to connect to.</param>
/// <param name="queryString">The query string data to pass to the server.</param>
public Connection(string url, string queryString)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
if (url.Contains("?"))
{
throw new ArgumentException(
"Url cannot contain QueryString directly. Pass QueryString values in using available overload.",
"url");
}
if (!url.EndsWith("/", StringComparison.Ordinal))
{
url += "/";
}
Url = url;
QueryString = queryString;
Groups = new List<string>();
Items = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
State = ConnectionState.Disconnected;
TraceWriter = new DebugTextWriter();
Headers = new HeaderDictionary(this);
}
/// <summary>
/// Occurs when the <see cref="Connection"/> is stopped.
/// </summary>
public event Action Closed;
public event Action<string> Received;
public event Action<Exception> Error;
public CookieContainer CookieContainer { get; set; }
/// <summary>
/// Gets the current <see cref="ConnectionState" /> of the connection.
/// </summary>
public ConnectionState State
{
get { return _state; }
private set
{
lock (_stateLock)
{
if (_state == value)
return;
var stateChange = new StateChange(_state, value);
_state = value;
if (StateChanged != null)
{
StateChanged(stateChange);
}
}
}
}
public IDictionary<string, string> Headers { get; private set; }
public ICredentials Credentials { get; set; }
public IEnumerable<string> Groups { get; set; }
public string Url { get; private set; }
public bool IsActive { get; private set; }
public string MessageId { get; set; }
public string ConnectionId { get; set; }
public IDictionary<string, object> Items { get; private set; }
public string QueryString { get; private set; }
public IClientTransport Transport
{
get
{
return _transport;
}
}
public string ConnectionToken { get; set; }
public string GroupsToken { get; set; }
/// <summary>
/// Stops the <see cref="Connection"/> and sends an abort message to the server.
/// </summary>
public void Stop()
{
Stop(DefaultAbortTimeout);
}
/// <summary>
/// Stops the <see cref="Connection"/> and sends an abort message to the server.
/// <param name="timeout">The timeout</param>
/// </summary>
public void Stop(TimeSpan timeout)
{
lock (_startLock)
{
// todo: connect task
// todo: receive queue
lock (_stateLock)
{
// Do nothing if the connection is offline
if (State != ConnectionState.Disconnected)
{
Trace(TraceLevels.Events, "Stop");
Transport.Stop(this);
Disconnect();
}
}
}
}
/// <summary>
/// Stops the <see cref="Connection"/> without sending an abort message to the server.
/// This function is called after we receive a disconnect message from the server.
/// </summary>
void IConnection.Disconnect()
{
Disconnect();
}
private void Disconnect()
{
lock (_stateLock)
{
// Do nothing if the connection is offline
if (State != ConnectionState.Disconnected)
{
// Change state before doing anything else in case something later in the method throws
State = ConnectionState.Disconnected;
Trace(TraceLevels.StateChanges, "Disconnect");
// todo: cancellation token source
Trace(TraceLevels.Events, "Closed");
// Clear the state for this connection
ConnectionId = null;
ConnectionToken = null;
GroupsToken = null;
MessageId = null;
// TODO: Do we want to trigger Closed if we are connecting?
OnClosed();
}
}
}
protected virtual void OnClosed()
{
if (Closed != null)
{
Closed();
}
}
/// <summary>
/// Sends data asynchronously over the connection.
/// </summary>
/// <param name="data">The data to send.</param>
/// <returns>A task that represents when the data has been sent.</returns>
public virtual Task<HubResult> Send(string data)
{
if (State == ConnectionState.Disconnected)
{
throw new InvalidOperationException("The Start method must be called before data can be sent.");
}
if (State == ConnectionState.Connecting)
{
throw new InvalidOperationException("The connection has not been established.");
}
return Transport.Send(this, data);
}
/// <summary>
/// Sends an object that will be JSON serialized asynchronously over the connection.
/// </summary>
/// <param name="value">The value to serialize.</param>
/// <returns>A task that represents when the data has been sent.</returns>
public Task Send(object value)
{
return Send(JsonConvert.SerializeObject(value));
}
void IConnection.OnReceived(JToken message)
{
OnReceived(message);
}
void IConnection.OnError(Exception error)
{
if (Error != null)
Error(error);
}
void IConnection.OnReconnected()
{
if (Reconnected != null)
Reconnected();
}
void IConnection.PrepareRequest(IRequest request)
{
request.UserAgent = CreateUserAgentString("SignalR.Client");
if (Credentials != null)
request.Credentials = Credentials;
if (CookieContainer != null)
request.CookieContainer = CookieContainer;
if (Headers.Count > 0)
{
request.SetRequestHeaders(Headers);
}
}
/// <summary>
/// Occurs when the <see cref="Connection" /> state changes.
/// </summary>
public event Action<StateChange> StateChanged;
public event Action Reconnected;
/// <summary>
/// Starts the <see cref="Connection" />.
/// </summary>
/// <returns>A task that represents when the connection has started.</returns>
public Task Start()
{
return Start(new DefaultHttpClient());
}
/// <summary>
/// Starts the <see cref="Connection" />.
/// </summary>
/// <param name="httpClient">The http client</param>
/// <returns>A task that represents when the connection has started.</returns>
public Task Start(IHttpClient httpClient)
{
return Start(new AutoTransport(httpClient));
}
/// <summary>
/// Starts the <see cref="Connection" />.
/// </summary>
/// <param name="transport">The transport to use.</param>
/// <returns>A task that represents when the connection has started.</returns>
public Task Start(IClientTransport transport)
{
lock (_startLock)
{
if (!ChangeState(ConnectionState.Disconnected, ConnectionState.Connecting))
{
return _connectTask ?? TaskAsyncHelper.Empty;
}
IsActive = true;
_transport = transport;
_connectTask = Negotiate(transport);
}
return _connectTask;
}
protected virtual string OnSending()
{
return null;
}
private Task Negotiate(IClientTransport transport)
{
return transport.Negotiate(this)
.ContinueWithNewResult(task =>
{
var response = task.Result;
VerifyProtocolVersion(response.ProtocolVersion);
ConnectionId = response.ConnectionId;
ConnectionToken = response.ConnectionToken;
var data = OnSending();
StartTransport(data);
return response;
});
}
private void StartTransport(string data)
{
// todo: implement with task
_transport.Start(this, data);
ChangeState(ConnectionState.Connecting, ConnectionState.Connected);
}
private bool ChangeState(ConnectionState oldState, ConnectionState newState)
{
return ((IConnection)this).ChangeState(oldState, newState);
}
bool IConnection.ChangeState(ConnectionState oldState, ConnectionState newState)
{
lock (_stateLock)
{
// If we're in the expected old state then change state and return true
if (_state == oldState)
{
Trace(TraceLevels.StateChanges, "ChangeState({0}, {1})", oldState, newState);
State = newState;
return true;
}
}
// Invalid transition
return false;
}
private void VerifyProtocolVersion(string versionString)
{
Version version;
if (String.IsNullOrEmpty(versionString) ||
!TryParseVersion(versionString, out version) ||
!(version.Major == 1 && version.Minor == 2))
{
throw new InvalidOperationException("Incompatible protocol version.");
}
}
public TraceLevels TraceLevel { get; set; }
public TextWriter TraceWriter
{
get
{
return _traceWriter;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_traceWriter = value;
}
}
public void Trace(TraceLevels level, string format, params object[] args)
{
lock (_traceLock)
{
if ((TraceLevel & level) == level)
{
_traceWriter.WriteLine(
DateTime.UtcNow.ToString("HH:mm:ss.fffffff", CultureInfo.InvariantCulture) + " - " +
(ConnectionId ?? "null") + " - " +
format,
args);
}
}
}
protected virtual void OnReceived(JToken message)
{
if (Received != null)
Received(message.ToString());
}
private static string CreateUserAgentString(string client)
{
if (_assemblyVersion == null)
_assemblyVersion = new AssemblyName(typeof (Connection).Assembly.FullName).Version;
return String.Format(
CultureInfo.InvariantCulture,
"{0}/{1} ({2})",
client,
_assemblyVersion,
Environment.OSVersion);
}
private static bool TryParseVersion(string versionString, out Version version)
{
try
{
version = new Version(versionString);
return true;
}
catch (ArgumentException)
{
version = new Version();
return false;
}
}
private static string CreateQueryString(IDictionary<string, string> queryString)
{
return String.Join("&", queryString.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray());
}
/// <summary>
/// Default text writer
/// </summary>
private class DebugTextWriter : TextWriter
{
public DebugTextWriter()
: base(CultureInfo.InvariantCulture)
{
}
public override void WriteLine(string value)
{
Debug.LogError(value);
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace HWD.DetailsControls
{
public class Services : System.Windows.Forms.UserControl
{
private Crownwood.DotNetMagic.Controls.ButtonWithStyle button7;
private System.Windows.Forms.ListView listViewServiceslistView1;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private string ServiceName;
private string ServiceAction;
private ListViewItem ServiceItem;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.ImageList imageList1;
public delegate void Status(string e);
public event Status ChangeStatus;
private System.Resources.ResourceManager m_ResourceManager;
public System.Resources.ResourceManager rsxmgr
{
set
{
this.m_ResourceManager = value;
}
}
public Services()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Services));
this.button7 = new Crownwood.DotNetMagic.Controls.ButtonWithStyle();
this.listViewServiceslistView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// button7
//
this.button7.Location = new System.Drawing.Point(512, 4);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(96, 32);
this.button7.TabIndex = 29;
this.button7.Text = "Get Services";
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// listViewServiceslistView1
//
this.listViewServiceslistView1.BackColor = System.Drawing.Color.White;
this.listViewServiceslistView1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.listViewServiceslistView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3,
this.columnHeader4});
this.listViewServiceslistView1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.listViewServiceslistView1.FullRowSelect = true;
this.listViewServiceslistView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listViewServiceslistView1.Location = new System.Drawing.Point(0, 49);
this.listViewServiceslistView1.Name = "listViewServiceslistView1";
this.listViewServiceslistView1.Size = new System.Drawing.Size(614, 240);
this.listViewServiceslistView1.SmallImageList = this.imageList1;
this.listViewServiceslistView1.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.listViewServiceslistView1.TabIndex = 28;
this.listViewServiceslistView1.View = System.Windows.Forms.View.Details;
this.listViewServiceslistView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.listViewServiceslistView1_MouseDown);
//
// columnHeader1
//
this.columnHeader1.Text = "Service";
this.columnHeader1.Width = 220;
//
// columnHeader2
//
this.columnHeader2.Text = "Start Mode";
this.columnHeader2.Width = 90;
//
// columnHeader3
//
this.columnHeader3.Text = "Status";
this.columnHeader3.Width = 90;
//
// columnHeader4
//
this.columnHeader4.Text = "Account";
this.columnHeader4.Width = 100;
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// Services
//
this.Controls.Add(this.button7);
this.Controls.Add(this.listViewServiceslistView1);
this.Name = "Services";
this.Size = new System.Drawing.Size(614, 289);
this.Load += new System.EventHandler(this.Services_Load);
this.ResumeLayout(false);
}
#endregion
private void changeStatus(string stringStatus)
{
if (ChangeStatus != null)
ChangeStatus(stringStatus);
}
private void button7_Click(object sender, System.EventArgs e)
{
this.changeStatus("Getting Services...");
this.Cursor = Cursors.WaitCursor;
string[] lvData = new string[4];
try
{
foreach (System.Management.ManagementObject mo in HWD.Details.Consulta("SELECT * FROM Win32_Service"))
{
int icon = 1;
lvData[0] = mo["Name"].ToString();
lvData[1] = mo["StartMode"].ToString();
if (mo["Started"].Equals(true))
{
lvData[2] = "Started";
}
else
{
lvData[2] = "Stop";
icon = 0;
}
lvData[3] = mo["StartName"].ToString();
ListViewItem lvItem = new ListViewItem(lvData,icon);
this.listViewServiceslistView1.Items.Add(lvItem);
}
}
catch
{
MessageBox.Show(this, "Error getting services.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
this.button7.Enabled = false;
this.changeStatus("Online");
this.Cursor = Cursors.Default;
}
private void listViewServiceslistView1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
System.Windows.Forms.ListView listViewObject = (System.Windows.Forms.ListView) sender;
ContextMenu mnuContextMenu = new ContextMenu();
MenuItem menuItem = new MenuItem();
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
ServiceName = listViewObject.GetItemAt(e.X, e.Y).Text;
ServiceItem = listViewObject.GetItemAt(e.X,e.Y);
listViewObject.ContextMenu = mnuContextMenu;
try
{
foreach (System.Management.ManagementObject mo in HWD.Details.Consulta("SELECT * FROM Win32_Service Where Name = '" + ServiceName + "'"))
{
if (mo["Started"].Equals(true))
{
menuItem.Text = "Stop";
ServiceAction = "StopService";
}
else
{
menuItem.Text = "Start";
ServiceAction = "StartService";
}
mnuContextMenu.MenuItems.Add(menuItem);
menuItem.Click += new System.EventHandler(this.menuItem3_Click);
}
}
catch
{
MessageBox.Show("Can't get service status");
}
}
}
private void menuItem3_Click(object sender, System.EventArgs e)
{
ListViewItem lvItem;
System.Management.ManagementOperationObserver observer = new System.Management.ManagementOperationObserver();
Handler completionHandlerObj = new Handler();
observer.ObjectReady += new System.Management.ObjectReadyEventHandler(completionHandlerObj.Done);
foreach (System.Management.ManagementObject mo in HWD.Details.Consulta("Select * from Win32_Service Where Name = '" + ServiceName + "'"))
{
mo.InvokeMethod(observer, ServiceAction, null);
}
int intCount = 0;
while (!completionHandlerObj.IsComplete)
{
if (intCount > 10)
{
MessageBox.Show("Terminate process timed out.", "Terminate Process Status");
break;
}
System.Threading.Thread.Sleep(500);
intCount++;
}
if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
{
lvItem = ServiceItem;
if (ServiceAction == "StartService")
{
lvItem.SubItems[2].Text = "Started";
lvItem.ImageIndex = 1;
}
else
{
lvItem.SubItems[2].Text = "Stop";
lvItem.ImageIndex = 0;
}
}
else
{
MessageBox.Show("Failed to change state of service " + ServiceName + ".", "Start/Stop Service Failure");
}
ServiceName = "";
ServiceAction = "";
ServiceItem = null;
}
private void Services_Load(object sender, System.EventArgs e)
{
//this.button7.Text = m_ResourceManager.GetString("dbutton7");
//this.columnHeader1.Text = m_ResourceManager.GetString("dcolumnHeader1");
//this.columnHeader2.Text = m_ResourceManager.GetString("dcolumnHeader2");
//this.columnHeader4.Text = m_ResourceManager.GetString("dcolumnHeader4");
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System.ComponentModel;
using Microsoft.MultiverseInterfaceStudio.FrameXml.Controls;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Drawing.Design;
namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization
{
/// Generated from Ui.xsd into two pieces and merged here.
/// Manually modified later - DO NOT REGENERATE
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "3.5.20706.1")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.multiverse.net/ui")]
[System.Xml.Serialization.XmlRootAttribute("FontString", Namespace = "http://www.multiverse.net/ui", IsNullable = false)]
public partial class FontStringType : LayoutFrameType
{
public FontStringType()
{
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[TypeConverter(typeof(FontTypeConverter))]
[Category("Appearance")]
public string font
{
get
{
return this.Properties.GetValue<string>("font");
}
set
{
this.Properties["font"] = value;
}
}
/// <remarks/>
//[System.Xml.Serialization.XmlAttributeAttribute()]
//[System.ComponentModel.DefaultValueAttribute(255)]
//[Category("Appearance")]
//public int bytes
//{
// get
// {
// return this.Properties.GetValue<int>("bytes");
// }
// set
// {
// this.Properties["bytes"] = value;
// }
//}
/// <remarks/>
[XmlAttribute]
[Browsable(false)]
public string text
{
get
{
return this.Properties.GetValue<string>("text");
}
set
{
this.Properties["text"] = value;
}
}
/// <remarks/>
//[System.Xml.Serialization.XmlAttributeAttribute()]
//[System.ComponentModel.DefaultValueAttribute(0f)]
//[Category("Appearance")]
//public float spacing
//{
// get
// {
// return this.Properties.GetValue<float>("spacing");
// }
// set
// {
// this.Properties["spacing"] = value;
// }
//}
/// <remarks/>
//[System.Xml.Serialization.XmlAttributeAttribute()]
//[System.ComponentModel.DefaultValueAttribute(OUTLINETYPE.NONE)]
//[Category("Appearance")]
//public OUTLINETYPE outline
//{
// get
// {
// return this.Properties.GetValue<OUTLINETYPE>("outline");
// }
// set
// {
// this.Properties["outline"] = value;
// }
//}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(false)]
[Category("Appearance")]
public bool monochrome
{
get
{
return this.Properties.GetValue<bool>("monochrome");
}
set
{
this.Properties["monochrome"] = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(false)]
[Category("Behavior")]
public bool nonspacewrap
{
get
{
return this.Properties.GetValue<bool>("nonspacewrap");
}
set
{
this.Properties["nonspacewrap"] = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(JUSTIFYVTYPE.MIDDLE)]
[Category("Appearance")]
public JUSTIFYVTYPE justifyV
{
get
{
return this.Properties.GetValue<JUSTIFYVTYPE>("justifyV");
}
set
{
this.Properties["justifyV"] = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(JUSTIFYHTYPE.CENTER)]
[Category("Appearance")]
public JUSTIFYHTYPE justifyH
{
get
{
return this.Properties.GetValue<JUSTIFYHTYPE>("justifyH");
}
set
{
this.Properties["justifyH"] = value;
}
}
/// <remarks/>
//[System.Xml.Serialization.XmlAttributeAttribute()]
//[System.ComponentModel.DefaultValueAttribute(typeof(uint), "0")]
//[Category("Appearance")]
//public uint maxLines
//{
// get
// {
// return this.Properties.GetValue<uint>("maxLines");
// }
// set
// {
// this.Properties["maxLines"] = value;
// }
//}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmTopSelect : System.Windows.Forms.Form
{
List<RadioButton> optType = new List<RadioButton>();
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2149;
//Product Performance|Checked
if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1172;
//Report Options|Checked
if (modRecordSet.rsLang.RecordCount){_Frame1_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Frame1_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2152;
//Normal Item Listing|Checked
if (modRecordSet.rsLang.RecordCount){_optType_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2153;
//Items per Group|Checked
if (modRecordSet.rsLang.RecordCount){_optType_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2154;
//Group Totals|Checked
if (modRecordSet.rsLang.RecordCount){_optType_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1173;
//Group On|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1174;
//Page break after each group|Checked
if (modRecordSet.rsLang.RecordCount){chkPageBreak.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkPageBreak.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1175;
//Report Sort Order|Checked
if (modRecordSet.rsLang.RecordCount){_Frame1_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Frame1_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2158;
//Sort Field|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2159;
//Sort Order|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1178;
//Report Filter|Checked
if (modRecordSet.rsLang.RecordCount){_Frame1_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Frame1_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1006;
//Filter|Checked
if (modRecordSet.rsLang.RecordCount){cmdGroup.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdGroup.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1181;
//Show/Print Report|Checked
if (modRecordSet.rsLang.RecordCount){cmdLoad.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdLoad.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmTopSelect.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdGroup_Click(System.Object eventSender, System.EventArgs eventArgs)
{
ADODB.Recordset rs = default(ADODB.Recordset);
int lID = 0;
modReport.cnnDBreport.Execute("DELETE aftDataItem.* From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE aftData.* From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO aftData ( ftData_PersonID, ftData_FieldName, ftData_SQL, ftData_Heading ) SELECT LinkData.LinkData_PersonID, LinkData.LinkData_FieldName, LinkData.LinkData_SQL, LinkData.LinkData_Heading From LinkData WHERE (((LinkData.LinkData_LinkID)=2) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO aftDataItem ( ftDataItem_PersonID, ftDataItem_FieldName, ftDataItem_ID ) SELECT LinkDataItem.LinkDataItem_PersonID, LinkDataItem.LinkDataItem_FieldName, LinkDataItem.LinkDataItem_ID From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=2) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
My.MyProject.Forms.frmFilter.Close();
My.MyProject.Forms.frmFilter.buildCriteria(ref "Sale");
My.MyProject.Forms.frmFilter.loadFilter(ref "Sale");
My.MyProject.Forms.frmFilter.buildCriteria(ref "Sale");
modReport.cnnDBreport.Execute("UPDATE Link SET Link.Link_Name = '" + Strings.Replace(My.MyProject.Forms.frmFilter.gHeading, "'", "''") + "', Link.Link_SQL = '" + Strings.Replace(My.MyProject.Forms.frmFilter.gCriteria, "'", "''") + "' WHERE (((Link.LinkID)=2) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE LinkDataItem.* From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=2) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE LinkData.* From LinkData WHERE (((LinkData.LinkData_LinkID)=2) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO LinkData ( LinkData_LinkID, LinkData_SectionID, LinkData_PersonID, LinkData_FieldName, LinkData_SQL, LinkData_Heading ) SELECT 2, 1, aftData.ftData_PersonID, aftData.ftData_FieldName, aftData.ftData_SQL, aftData.ftData_Heading From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO LinkDataItem ( LinkDataItem_LinkID, LinkDataItem_SectionID, LinkDataItem_PersonID, LinkDataItem_FieldName, LinkDataItem_ID ) SELECT 2, 1, aftDataItem.ftDataItem_PersonID, aftDataItem.ftDataItem_FieldName, aftDataItem.ftDataItem_ID From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
lblGroup.Text = My.MyProject.Forms.frmFilter.gHeading;
}
private void setup()
{
ADODB.Recordset rs = default(ADODB.Recordset);
rs = modReport.getRSreport(ref "SELECT Link.Link_PersonID From Link WHERE (((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));");
if (rs.BOF | rs.EOF) {
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 1, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 1, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 2, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 2, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 3, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 4, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 5, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 6, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 7, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 8, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 9, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 10, 3, " + modRecordSet.gPersonID + ", '', '';");
}
rs = modReport.getRSreport(ref "SELECT Link.Link_Name From Link WHERE (((Link.LinkID)=2) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));");
lblGroup.Text = rs.Fields("Link_Name").Value;
}
private void cmdLoad_Click(System.Object eventSender, System.EventArgs eventArgs)
{
ADODB.Recordset rs = default(ADODB.Recordset);
string sql = null;
ADODB.Recordset rsData = default(ADODB.Recordset);
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ReportNone.Load("cryNoRecords.rpt");
string lOrder = null;
CrystalDecisions.CrystalReports.Engine.DatabaseFieldDefinition CRXDatabaseField = default(CrystalDecisions.CrystalReports.Engine.DatabaseFieldDefinition);
switch (this.cmbSortField.SelectedIndex) {
case 0:
lOrder = "StockItem_Name";
break;
case 1:
lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]";
break;
case 2:
lOrder = "[exclusiveSum]-[depositSum]";
break;
case 3:
lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]";
break;
case 4:
lOrder = "IIf([exclusiveSum]=0,0,([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum])";
break;
case 5:
lOrder = "StockList.quantitySum";
break;
}
if (this.cmbSort.SelectedIndex)
lOrder = lOrder + " DESC";
lOrder = " ORDER BY " + lOrder;
//UPGRADE_NOTE: Object Report may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
Report = null;
if (_optType_0.Checked) {
Report.Load("cryStockitemTop1.rpt");
} else if (_optType_1.Checked) {
Report.Load("cryStockitemTopByGroup.rpt");
} else {
Report.Load("cryStockitemTopGroup.rpt");
}
while (Report.DataDefinition.SortFields.Count) {
//'Report.RecordSortFields.delete(1)
}
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modReport.getRSreport(ref "SELECT Report.Report_Heading, aCompany.Company_Name FROM aCompany, Report;");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtDayend", rs.Fields("Report_Heading"));
rs.Close();
rs = modReport.getRSreport(ref "SELECT * FROM Link Where LinkID=2 AND Link_SectionID=1");
Report.SetParameterValue("txtFilter", Strings.Replace(rs.Fields("Link_Name").Value, "''", "'"));
if (_optType_0.Checked) {
if (!string.IsNullOrEmpty(rs.Fields("Link_SQL").Value)) {
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aStockGroup.StockGroup_Name AS department FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID ";
} else {
switch (this.cmbSortField.SelectedIndex) {
case 0:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name ";
break;
case 1:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, ([exclusiveSum]-[depositSum]-[listCostSum]) ";
break;
//lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]"
case 2:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, ([exclusiveSum]-[depositSum]) ";
break;
//lOrder = "[exclusiveSum]-[depositSum]"
case 3:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, ([exclusiveSum]-[depositSum]-[listCostSum]) ";
break;
//lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]"
case 4:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, IIf([exclusiveSum]=0,0,([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]) ";
break;
//lOrder = "IIf([exclusiveSum]=0,0,([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum])"
case 5:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, StockList.quantitySum ";
break;
//lOrder = "StockList.quantitySum"
}
}
} else if (_optType_1.Checked) {
if (!string.IsNullOrEmpty(rs.Fields("Link_SQL").Value)) {
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aStockGroup.StockGroup_Name AS department FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID ";
} else {
switch (this.cmbSortField.SelectedIndex) {
case 0:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name ";
break;
case 1:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, ([exclusiveSum]-[depositSum]-[listCostSum]) ";
break;
//lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]"
case 2:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, ([exclusiveSum]-[depositSum]) ";
break;
//lOrder = "[exclusiveSum]-[depositSum]"
case 3:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, ([exclusiveSum]-[depositSum]-[listCostSum]) ";
break;
//lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]"
case 4:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, IIf([exclusiveSum]=0,0,([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]) ";
break;
//lOrder = "IIf([exclusiveSum]=0,0,([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum])"
case 5:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department ";
sql = sql + "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name, StockList.quantitySum ";
break;
//lOrder = "StockList.quantitySum"
}
//sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department "
//sql = sql & "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name "
}
switch (this.cmbGroup.SelectedIndex) {
case 0:
sql = Strings.Replace(sql, "StockGroup", "PricingGroup");
Report.SetParameterValue("txtTitle", "Product Performance - by Pricing Group");
break;
case 1:
Report.SetParameterValue("txtTitle", "Product Performance - by Stock Group");
break;
case 2:
sql = Strings.Replace(sql, "StockGroup", "Supplier");
sql = Strings.Replace(sql, "aSupplier", "Supplier");
Report.SetParameterValue("txtTitle", "Product Performance - by Supplier");
break;
case 3:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aReportGroup1.ReportGroup_Name AS department FROM StockList INNER JOIN (aStockItem1 INNER JOIN aReportGroup1 ON aStockItem1.StockItem_ReportID = aReportGroup1.ReportID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID ";
Report.SetParameterValue("txtTitle", "Product Performance - by Report Group");
break;
}
if (this.chkPageBreak.CheckState) {
Report.ReportDefinition.Sections(5).SectionFormat.EnableNewPageAfter = true;
} else {
Report.ReportDefinition.Sections(5).SectionFormat.EnableNewPageAfter = false;
}
} else {
//If rs("Link_SQL") <> "" Then
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aStockGroup.StockGroup_Name AS department FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID ";
//Else
// sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, Sum(StockList.inclusiveSum) AS inclusive, Sum(StockList.exclusiveSum) AS exclusive, Sum([exclusiveSum]-[depositSum]) AS price, Sum([exclusiveSum]-[depositSum]) AS content, Sum([exclusiveSum]-[depositSum]-[listCostSum]) AS listProfit, Sum([exclusiveSum]-[depositSum]-[actualCostSum]) AS actualProfit, Sum(StockList.quantitySum) AS quantity, Sum(StockList.listCostSum) AS listCost, Sum(StockList.actualCostSum) AS actualCost, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0)) AS gpActual, Sum(IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0)) AS gpList, aStockGroup.StockGroup_Name AS department "
// sql = sql & "FROM StockList INNER JOIN (aStockItem1 INNER JOIN aStockGroup ON aStockItem1.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID GROUP BY aStockItem1.StockItemID, aStockItem1.StockItem_Name, aStockGroup.StockGroup_Name "
//End If
switch (this.cmbGroup.SelectedIndex) {
case 0:
sql = Strings.Replace(sql, "StockGroup", "PricingGroup");
Report.SetParameterValue("txtTitle", "Product Performance - by Pricing Group");
break;
case 1:
Report.SetParameterValue("txtTitle", "Product Performance - by Stock Group");
break;
case 2:
sql = Strings.Replace(sql, "StockGroup", "Supplier");
sql = Strings.Replace(sql, "aSupplier", "Supplier");
Report.SetParameterValue("txtTitle", "Product Performance - by Supplier");
break;
case 3:
sql = "SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aReportGroup1.ReportGroup_Name AS department FROM StockList INNER JOIN (aStockItem1 INNER JOIN aReportGroup1 ON aStockItem1.StockItem_ReportID = aReportGroup1.ReportID) ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID ";
Report.SetParameterValue("txtTitle", "Product Performance - by Report Group");
break;
}
if (this.chkPageBreak.CheckState) {
Report.ReportDefinition.Sections(5).SectionFormat.EnableNewPageAfter = true;
} else {
Report.ReportDefinition.Sections(5).SectionFormat.EnableNewPageAfter = false;
}
}
//for customer
//SELECT aStockItem1.StockItemID, aStockItem1.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aCustomer.Customer_InvoiceName AS department
//FROM aCustomer INNER JOIN (CustomerTransaction INNER JOIN (Sale INNER JOIN (SaleItem INNER JOIN (StockList INNER JOIN aStockItem1 ON StockList.SaleItem_StockItemID = aStockItem1.StockItemID) ON SaleItem.SaleItem_StockItemID = StockList.SaleItem_StockItemID) ON Sale.SaleID = SaleItem.SaleItem_SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID
//WHERE (((aCustomer.CustomerID)=2) AND ((CustomerTransaction.CustomerTransaction_TransactionTypeID)=2)) OR (((CustomerTransaction.CustomerTransaction_TransactionTypeID)=3));
if (string.IsNullOrEmpty(rs.Fields("Link_SQL").Value)) {
} else {
sql = sql + rs.Fields("Link_SQL").Value;
}
sql = sql + lOrder;
Debug.Print(sql);
rs = modReport.getRSreport(ref sql);
if (rs.BOF | rs.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
// Report.ExportOptions.DiskFileName = "C:\4POSServer\PerfumeGarden\test.html"
// Report.ExportOptions.HTMLFileName = "C:\4POSServer\PerfumeGarden\test.html"
// Report.ExportOptions.DestinationType = crEDTDiskFile
// Report.ExportOptions.FormatType = crEFTExplorer32Extend
// Report.Export False
// Screen.MousePointer = vbDefault
//Report.VerifyOnEveryPrint = True
Report.Database.Tables(1).SetDataSource(rs);
//Report.Database.SetDataSource(rs, 3)
//Report.VerifyOnEveryPrint = True
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void cmdLoad_Click__OLD()
{
ADODB.Recordset rs = default(ADODB.Recordset);
string sql = null;
ADODB.Recordset rsData = default(ADODB.Recordset);
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ReportNone.Load("cryNoRecords.rpt");
string lOrder = null;
CrystalDecisions.CrystalReports.Engine.DatabaseFieldDefinition CRXDatabaseField = default(CrystalDecisions.CrystalReports.Engine.DatabaseFieldDefinition);
switch (this.cmbSortField.SelectedIndex) {
case 0:
lOrder = "StockItem_Name";
break;
case 1:
lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]";
break;
case 2:
lOrder = "[exclusiveSum]-[depositSum]";
break;
case 3:
lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]";
break;
case 4:
lOrder = "IIf([exclusiveSum]=0,0,([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum])";
break;
case 5:
lOrder = "StockList.quantitySum";
break;
}
if (this.cmbSort.SelectedIndex)
lOrder = lOrder + " DESC";
lOrder = " ORDER BY " + lOrder;
//UPGRADE_NOTE: Object Report may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
Report = null;
if (_optType_0.Checked) {
Report.Load("cryStockitemTop1.rpt");
} else if (_optType_1.Checked) {
Report.Load("cryStockitemTopByGroup.rpt");
} else {
Report.Load("cryStockitemTopGroup.rpt");
}
while (Report.DataDefinition.SortFields.Count) {
//Report.RecordSortFields.delete(1)
}
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modReport.getRSreport(ref "SELECT Report.Report_Heading, aCompany.Company_Name FROM aCompany, Report;");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtDayend", rs.Fields("Report_Heading"));
rs.Close();
rs = modReport.getRSreport(ref "SELECT * FROM Link Where LinkID=2 AND Link_SectionID=1");
Report.SetParameterValue("txtFilter", Strings.Replace(rs.Fields("Link_Name").Value, "''", "'"));
if (_optType_0.Checked) {
sql = "SELECT aStockItem.StockItemID, aStockItem.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aStockGroup.StockGroup_Name AS department FROM StockList INNER JOIN (aStockItem INNER JOIN aStockGroup ON aStockItem.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem.StockItemID ";
} else {
sql = "SELECT aStockItem.StockItemID, aStockItem.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aStockGroup.StockGroup_Name AS department FROM StockList INNER JOIN (aStockItem INNER JOIN aStockGroup ON aStockItem.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem.StockItemID ";
switch (this.cmbGroup.SelectedIndex) {
case 0:
sql = Strings.Replace(sql, "StockGroup", "PricingGroup");
Report.SetParameterValue("txtTitle", "Product Performance - by Pricing Group");
break;
case 1:
Report.SetParameterValue("txtTitle", "Product Performance - by Stock Group");
break;
case 2:
sql = Strings.Replace(sql, "StockGroup", "Supplier");
sql = Strings.Replace(sql, "aSupplier", "Supplier");
Report.SetParameterValue("txtTitle", "Product Performance - by Supplier");
break;
}
if (this.chkPageBreak.CheckState) {
Report.ReportDefinition.Sections(5).SectionFormat.EnableNewPageAfter = true;
} else {
Report.ReportDefinition.Sections(5).SectionFormat.EnableNewPageAfter = false;
}
}
if (string.IsNullOrEmpty(rs.Fields("Link_SQL").Value)) {
} else {
sql = sql + rs.Fields("Link_SQL").Value;
}
sql = sql + lOrder;
//Debug.Print sql
rs = modReport.getRSreport(ref sql);
if (rs.BOF | rs.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
//Report.VerifyOnEveryPrint = True
Report.Database.Tables(1).SetDataSource(rs);
//Report.Database.SetDataSource(rs, 3)
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void frmTopSelect_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
this.Close();
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmTopSelect_Load(System.Object eventSender, System.EventArgs eventArgs)
{
optType.AddRange(new RadioButton[] {
_optType_0,
_optType_1,
_optType_2
});
RadioButton rb = new RadioButton();
foreach (RadioButton rb_loopVariable in optType) {
rb = rb_loopVariable;
rb.CheckedChanged += optType_CheckedChanged;
}
setup();
loadLanguage();
this.cmbGroup.SelectedIndex = 0;
this.cmbSort.SelectedIndex = 0;
this.cmbSortField.SelectedIndex = 0;
}
private void optType_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (eventSender.Checked) {
int Index = 0;
RadioButton rb = new RadioButton();
rb = (RadioButton)eventSender;
Index = GetIndex.GetIndexer(ref rb, ref optType);
if (Index) {
cmbGroup.Enabled = true;
} else {
cmbGroup.Enabled = false;
}
this.chkPageBreak.Enabled = (Index == 1);
}
}
}
}
| |
// **********************************************************************************
// The MIT License (MIT)
//
// Copyright (c) 2014 Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// **********************************************************************************
#region Using Directives
using System;
using System.Windows.Media;
#endregion
namespace Alteridem.GitHub.Converters
{
// An HSB color
public struct HsbColor
{
public double A;
public double H;
public double S;
public double B;
}
public static class ColorExtensions
{
/// <summary>
/// Converts an RGB color to an HSB color.
/// </summary>
/// <param name="rgbColor">The RGB color to convert.</param>
/// <returns>The HSB color equivalent of the RGBA color passed in.</returns>
/// <remarks>Source: http://msdn.microsoft.com/en-us/library/ms771620.aspx</remarks>
public static HsbColor ToHsb(this Color rgbColor)
{
/* Hue values range between 0 and 360. All
* other values range between 0 and 1. */
// Create HSB color object
var hsbColor = new HsbColor();
// Get RGB color component values
var r = (int)rgbColor.R;
var g = (int)rgbColor.G;
var b = (int)rgbColor.B;
var a = (int)rgbColor.A;
// Get min, max, and delta values
double min = Math.Min(Math.Min(r, g), b);
double max = Math.Max(Math.Max(r, g), b);
double delta = max - min;
/* Black (max = 0) is a special case. We
* simply set HSB values to zero and exit. */
// Black: Set HSB and return
if (max == 0.0)
{
hsbColor.H = 0.0;
hsbColor.S = 0.0;
hsbColor.B = 0.0;
hsbColor.A = a;
return hsbColor;
}
/* Now we process the normal case. */
// Set HSB Alpha value
var alpha = (double)a;
hsbColor.A = alpha / 255;
// Set HSB Hue value
if (r == max) hsbColor.H = (g - b) / delta;
else if (g == max) hsbColor.H = 2 + (b - r) / delta;
else if (b == max) hsbColor.H = 4 + (r - g) / delta;
hsbColor.H *= 60;
if (hsbColor.H < 0.0) hsbColor.H += 360;
// Set other HSB values
hsbColor.S = delta / max;
hsbColor.B = max / 255;
// Set return value
return hsbColor;
}
/// <summary>
/// Converts an HSB color to an RGB color.
/// </summary>
/// <param name="hsbColor">The HSB color to convert.</param>
/// <returns>The RGB color equivalent of the HSB color passed in.</returns>
/// Source: http://msdn.microsoft.com/en-us/library/ms771620.aspx
public static Color ToRgb(this HsbColor hsbColor)
{
// Initialize
var rgbColor = new Color();
/* Gray (zero saturation) is a special case.We simply
* set RGB values to HSB Brightness value and exit. */
// Gray: Set RGB and return
if (hsbColor.S == 0.0)
{
rgbColor.A = (byte)(hsbColor.A * 255);
rgbColor.R = (byte)(hsbColor.B * 255);
rgbColor.G = (byte)(hsbColor.B * 255);
rgbColor.B = (byte)(hsbColor.B * 255);
return rgbColor;
}
/* Now we process the normal case. */
var h = (hsbColor.H == 360) ? 0 : hsbColor.H / 60;
var i = (int)(Math.Truncate(h));
var f = h - i;
var p = hsbColor.B * (1.0 - hsbColor.S);
var q = hsbColor.B * (1.0 - (hsbColor.S * f));
var t = hsbColor.B * (1.0 - (hsbColor.S * (1.0 - f)));
double r, g, b;
switch (i)
{
case 0:
r = hsbColor.B;
g = t;
b = p;
break;
case 1:
r = q;
g = hsbColor.B;
b = p;
break;
case 2:
r = p;
g = hsbColor.B;
b = t;
break;
case 3:
r = p;
g = q;
b = hsbColor.B;
break;
case 4:
r = t;
g = p;
b = hsbColor.B;
break;
default:
r = hsbColor.B;
g = p;
b = q;
break;
}
// Set WPF Color object
rgbColor.A = (byte)(hsbColor.A * 255);
rgbColor.R = (byte)(r * 255);
rgbColor.G = (byte)(g * 255);
rgbColor.B = (byte)(b * 255);
// Set return value
return rgbColor;
}
public static Color ParseColor(this string colorString)
{
try
{
if (!string.IsNullOrWhiteSpace(colorString))
{
object color = ColorConverter.ConvertFromString("#" + colorString);
if (color != null)
return (Color)color;
}
}
catch (FormatException)
{
}
return Color.FromArgb(0, 0, 0, 0);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CustomDomainsOperations operations.
/// </summary>
public partial interface ICustomDomainsOperations
{
/// <summary>
/// Lists all of the existing custom domains within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CustomDomain>>> ListByEndpointWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets an exisitng custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> GetWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> CreateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an existing custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> DeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disable https delivery of the custom domain.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> DisableCustomHttpsWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enable https delivery of the custom domain.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> EnableCustomHttpsWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an existing custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the existing custom domains within an endpoint.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CustomDomain>>> ListByEndpointNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* SerialPort.cs - Implementation of the "System.IO.Ports.SerialPort" class.
*
* Copyright (C) 2003-2004 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.IO.Ports
{
#if CONFIG_SERIAL_PORTS
using System.ComponentModel;
using System.Security;
using System.Text;
using Platform;
public class SerialPort
#if CONFIG_COMPONENT_MODEL
: Component
#endif
{
// Internal state.
private String resource;
private int portType;
private int portNumber;
private Encoding encoding;
private IntPtr handle;
private PortMethods.Parameters parameters;
private Stream baseStream;
private String newLine;
private byte[] newLineBuffer;
private SerialPinChangedEventHandler pinChanged;
private SerialReceivedEventHandler received;
private static readonly int[] validBaudRates =
{50, 75, 110, 134, 150, 200, 300, 600, 1200,
1800, 2400, 4800, 9600, 19200, 38400, 57600,
115200, 230400, 460800, 500000, 576000, 921600,
1000000, 1152000, 1500000, 2000000, 2500000,
3000000, 3500000, 4000000};
// Timeout value that indicates an infinite timeout.
public static readonly int InfiniteTimeout = 0;
// Constructors.
public SerialPort()
{
resource = null;
portType = PortMethods.SERIAL_REGULAR;
portNumber = 0;
encoding = new UTF8Encoding();
handle = IntPtr.Zero;
parameters = new PortMethods.Parameters();
parameters.baudRate = 9600;
parameters.parity = (int)(Parity.None);
parameters.dataBits = 8;
parameters.stopBits = (int)(StopBits.One);
parameters.handshake = (int)(Handshake.None);
parameters.parityReplace = (byte)0;
parameters.discardNull = false;
PortMethods.GetRecommendedBufferSizes
(out parameters.readBufferSize,
out parameters.writeBufferSize,
out parameters.receivedBytesThreshold);
parameters.readTimeout = InfiniteTimeout;
parameters.writeTimeout = InfiniteTimeout;
baseStream = null;
newLine = "\n"; // MS defaults to \n
newLineBuffer = null;
}
[TODO]
public SerialPort(IContainer container) : this()
{
// TODO
}
public SerialPort(String resource) : this()
{
PortName = resource;
}
public SerialPort(String resource, int baudRate)
: this(resource, baudRate, Parity.None, 8, StopBits.One) {}
public SerialPort(String resource, int baudRate, Parity parity)
: this(resource, baudRate, parity, 8, StopBits.One) {}
public SerialPort(String resource, int baudRate,
Parity parity, int dataBits)
: this(resource, baudRate, parity, dataBits, StopBits.One) {}
public SerialPort(String resource, int baudRate,
Parity parity, int dataBits, StopBits stopBits)
: this()
{
PortName = resource;
BaudRate = baudRate;
Parity = parity;
DataBits = dataBits;
StopBits = stopBits;
}
#if !CONFIG_COMPONENT_MODEL
// Destructor.
~SerialPort()
{
Dispose(false);
}
#endif
// Get the base stream that wraps the serial port.
public Stream BaseStream
{
get
{
return baseStream;
}
}
// Get or set the serial port's properties.
public int BaudRate
{
get
{
return parameters.baudRate;
}
set
{
if(Array.IndexOf(validBaudRates, value) == -1)
{
throw new ArgumentException
(S._("Arg_PortBaudRate"), "value");
}
lock(this)
{
if(parameters.baudRate != value)
{
parameters.baudRate = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
public int DataBits
{
get
{
return parameters.dataBits;
}
set
{
if(value != 7 && value != 8)
{
throw new ArgumentException
(S._("Arg_PortDataBits"), "value");
}
lock(this)
{
if(parameters.dataBits != value)
{
parameters.dataBits = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
public Parity Parity
{
get
{
return (Parity)(parameters.parity);
}
set
{
if(((int)value) < ((int)(Parity.None)) ||
((int)value) > ((int)(Parity.Space)))
{
throw new ArgumentException
(S._("Arg_PortParity"), "value");
}
lock(this)
{
if(parameters.parity != (int)value)
{
parameters.parity = (int)value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
public StopBits StopBits
{
get
{
return (StopBits)(parameters.stopBits);
}
set
{
if(((int)value) < ((int)(StopBits.One)) ||
((int)value) > ((int)(StopBits.OnePointFive)))
{
throw new ArgumentException
(S._("Arg_PortStopBits"), "value");
}
lock(this)
{
if(parameters.stopBits != (int)value)
{
parameters.stopBits = (int)value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
// Get the number of bytes that can be read or written.
public int BytesToRead
{
get
{
lock(this)
{
if(handle != IntPtr.Zero)
{
return PortMethods.GetBytesToRead(handle);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
}
public int BytesToWrite
{
get
{
lock(this)
{
if(handle != IntPtr.Zero)
{
return PortMethods.GetBytesToWrite(handle);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
}
// Read a serial port pin.
private bool ReadPin(int pin)
{
lock(this)
{
if(handle != IntPtr.Zero)
{
return ((PortMethods.ReadPins(handle) & pin) != 0);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Write a serial port pin.
private void WritePin(int pin, bool value)
{
lock(this)
{
if(handle != IntPtr.Zero)
{
if(value)
{
PortMethods.WritePins(handle, pin, pin);
}
else
{
PortMethods.WritePins(handle, pin, 0);
}
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Check or set the state of various pins.
public bool BreakState
{
get
{
return ReadPin(PortMethods.PIN_BREAK);
}
set
{
WritePin(PortMethods.PIN_BREAK, value);
}
}
public bool CDHolding
{
get
{
return ReadPin(PortMethods.PIN_CD);
}
}
public bool CtsHolding
{
get
{
return ReadPin(PortMethods.PIN_CTS);
}
}
public bool DsrHolding
{
get
{
return ReadPin(PortMethods.PIN_DSR);
}
}
public bool DtrEnable
{
get
{
return ReadPin(PortMethods.PIN_DTR);
}
set
{
WritePin(PortMethods.PIN_DTR, value);
}
}
public bool RtsEnable
{
get
{
return ReadPin(PortMethods.PIN_RTS);
}
set
{
WritePin(PortMethods.PIN_RTS, value);
}
}
// Get or set the "discard NUL" flag.
public bool DiscardNull
{
get
{
return parameters.discardNull;
}
set
{
lock(this)
{
if(parameters.discardNull != value)
{
parameters.discardNull = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
// Get or set the encoding used for text conversion.
public Encoding Encoding
{
get
{
return encoding;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
encoding = value;
newLineBuffer = null;
}
}
// Get or set the handshaking mode.
public Handshake Handshake
{
get
{
return (Handshake)(parameters.handshake);
}
set
{
if(((int)value) < ((int)(Handshake.None)) ||
((int)value) > ((int)(Handshake.RequestToSendXOnXOff)))
{
throw new ArgumentException
(S._("Arg_PortHandshake"), "value");
}
lock(this)
{
if(parameters.handshake != (int)value)
{
parameters.handshake = (int)value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
// Determine if the serial port is currently open.
public bool IsOpen
{
get
{
lock(this)
{
return (handle != IntPtr.Zero);
}
}
}
// Get or set the newline sequence to use for text writes.
public String NewLine
{
get
{
return newLine;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
newLine = value;
newLineBuffer = null;
}
}
// Get or set the byte value to use to replace parity errors.
public byte ParityReplace
{
get
{
return parameters.parityReplace;
}
set
{
lock(this)
{
if(parameters.parityReplace != value)
{
parameters.parityReplace = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
// Get or set the name of the port. We only allow port names
// of the form "COMn", "COMn:", "IRCOMMn", "IRCOMMn:", "USBn",
// and "USBn:" in this implementation. "COM" ports are regular
// serial ports, "IRCOMM" ports are infrared ports, and "USB"
// are ports on the USB bus. The numbers are 1-based.
public String PortName
{
get
{
return resource;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
int posn;
int type;
if(value.Length > 3 &&
(value[0] == 'c' || value[0] == 'C') &&
(value[1] == 'o' || value[1] == 'O') &&
(value[2] == 'm' || value[2] == 'M'))
{
posn = 3;
type = PortMethods.SERIAL_REGULAR;
}
else if(value.Length > 6 &&
(value[0] == 'i' || value[0] == 'I') &&
(value[1] == 'r' || value[1] == 'R') &&
(value[2] == 'c' || value[2] == 'C') &&
(value[3] == 'o' || value[3] == 'O') &&
(value[4] == 'm' || value[4] == 'M') &&
(value[5] == 'm' || value[5] == 'M'))
{
posn = 6;
type = PortMethods.SERIAL_INFRARED;
}
else if(value.Length > 6 &&
(value[0] == 'r' || value[0] == 'R') &&
(value[1] == 'f' || value[1] == 'F') &&
(value[2] == 'c' || value[2] == 'C') &&
(value[3] == 'o' || value[3] == 'O') &&
(value[4] == 'm' || value[4] == 'M') &&
(value[5] == 'm' || value[5] == 'M'))
{
posn = 6;
type = PortMethods.SERIAL_RFCOMM;
}
else if(value.Length > 3 &&
(value[0] == 'u' || value[0] == 'U') &&
(value[1] == 's' || value[1] == 'S') &&
(value[2] == 'b' || value[2] == 'B'))
{
posn = 3;
type = PortMethods.SERIAL_USB;
}
else
{
throw new ArgumentException
(S._("Arg_PortName"), "value");
}
if(value[posn] < '0' || value[posn] > '9')
{
throw new ArgumentException
(S._("Arg_PortName"), "value");
}
int number = (int)(value[posn] - '0');
++posn;
while(posn < value.Length &&
value[posn] >= '0' && value[posn] <= '9')
{
number = number * 10 + (int)(value[posn] - '0');
++posn;
}
if(posn == value.Length ||
((posn + 1) == value.Length && value[posn] == ':'))
{
if(!PortMethods.IsValid(type, number))
{
throw new ArgumentException
(S._("Arg_PortName"), "value");
}
lock(this)
{
if(handle != IntPtr.Zero)
{
throw new InvalidOperationException
(S._("Invalid_PortOpen"));
}
portType = type;
portNumber = number;
resource = value;
}
}
else
{
throw new ArgumentException
(S._("Arg_PortName"), "value");
}
}
}
// Get or set the buffer sizes.
public int ReadBufferSize
{
get
{
return parameters.readBufferSize;
}
set
{
if(value < 0)
{
throw new ArgumentOutOfRangeException
("value", S._("ArgRange_NonNegative"));
}
lock(this)
{
if(parameters.readBufferSize != value)
{
parameters.readBufferSize = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
public int WriteBufferSize
{
get
{
return parameters.writeBufferSize;
}
set
{
if(value < 0)
{
throw new ArgumentOutOfRangeException
("value", S._("ArgRange_NonNegative"));
}
lock(this)
{
if(parameters.writeBufferSize != value)
{
parameters.writeBufferSize = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
public int ReceivedBytesThreshold
{
get
{
return parameters.receivedBytesThreshold;
}
set
{
if(value < 0)
{
throw new ArgumentOutOfRangeException
("value", S._("ArgRange_NonNegative"));
}
lock(this)
{
if(parameters.receivedBytesThreshold != value)
{
parameters.receivedBytesThreshold = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
// Get or set the timeout values.
public int ReadTimeout
{
get
{
return parameters.readTimeout;
}
set
{
if(value < -1)
{
throw new ArgumentOutOfRangeException
("value", S._("ArgRange_NonNegOrNegOne"));
}
lock(this)
{
if(parameters.readTimeout != value)
{
parameters.readTimeout = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
public int WriteTimeout
{
get
{
return parameters.writeTimeout;
}
set
{
if(value < -1)
{
throw new ArgumentOutOfRangeException
("value", S._("ArgRange_NonNegOrNegOne"));
}
lock(this)
{
if(parameters.writeTimeout != value)
{
parameters.writeTimeout = value;
if(handle != IntPtr.Zero)
{
PortMethods.Modify(handle, parameters);
}
}
}
}
}
// Close this serial port.
public void Close()
{
lock(this)
{
if(handle != IntPtr.Zero)
{
PortMethods.Close(handle);
handle = IntPtr.Zero;
}
baseStream = null;
}
}
// Discard the contents of the input buffer.
public void DiscardInBuffer()
{
lock(this)
{
if(handle != IntPtr.Zero)
{
PortMethods.DiscardInBuffer(handle);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Discard the contents of the output buffer.
public void DiscardOutBuffer()
{
lock(this)
{
if(handle != IntPtr.Zero)
{
PortMethods.DiscardOutBuffer(handle);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Dispose of this serial port.
#if !CONFIG_COMPONENT_MODEL
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endif
protected override void Dispose(bool disposing)
{
Close();
}
// Open the serial port with the current parameters.
public void Open()
{
lock(this)
{
if(handle != IntPtr.Zero)
{
throw new InvalidOperationException
(S._("Invalid_PortOpen"));
}
if(resource == null)
{
throw new ArgumentException
(S._("Arg_PortNameNotSet"), "PortName");
}
if(!PortMethods.IsAccessible(portType, portNumber))
{
throw new SecurityException
(S._("Arg_CannotAccessPort"));
}
handle = PortMethods.Open(portType, portNumber, parameters);
if(handle == IntPtr.Zero)
{
throw new InvalidOperationException
(S._("Invalid_CannotOpenPort"));
}
baseStream = new PortStream(this);
}
}
// Read data from the serial port.
public int Read(byte[] buffer, int offset, int count)
{
lock(this)
{
if(baseStream != null)
{
return baseStream.Read(buffer, offset, count);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
[TODO]
public int Read(char[] buffer, int offset, int count)
{
// TODO
return 0;
}
// Read a single byte from the serial port.
public int ReadByte()
{
lock(this)
{
if(baseStream != null)
{
return baseStream.ReadByte();
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Read a single character from the serial port.
[TODO]
public int ReadChar()
{
// TODO
return -1;
}
// ???
[TODO]
public String ReadExisting()
{
// TODO
int toRead = BytesToRead;
if(toRead > 0)
{
byte[] buffer = new byte[toRead];
if(Read(buffer, 0, toRead) > 0)
{
return encoding.GetString(buffer);
}
}
return null;
}
// Read a single line from the serial port.
[TODO]
public String ReadLine()
{
lock(this)
{
if(baseStream != null)
{
int[] backbuffer = new int[this.newLine.Length];
int bytesinbuffer = 0;
int outbufferpos = 0;
bool pendingeol = false;
bool eolfailed = false;
StringBuilder inLine = new StringBuilder();
while(true)
{
int retByte;
// read the next byte
if(bytesinbuffer > 0 && eolfailed == true)
{
retByte = backbuffer[outbufferpos++];
if(--bytesinbuffer == 0)
{
// backbuffer is flushed. reset for next multibyte eol search
eolfailed = false;
outbufferpos = 0;
}
}
else
{
retByte = baseStream.ReadByte();
}
// is this an eol byte?
if(retByte == this.newLine[bytesinbuffer])
{
backbuffer[bytesinbuffer++] = retByte;
if(this.newLine.Length == bytesinbuffer)
{
bytesinbuffer = 0;
return(inLine.ToString());
}
else
{
pendingeol = true;
}
}
else
{
if(bytesinbuffer > 0)
{
// eol search failed after finding at least one of a multi
// byte eol marker. set eolfailed so that we flush the bytes
// that we stored during failed multi byte eol match
eolfailed = true;
}
if(retByte == -1)
{
// FIXME need to store the inLine data so that we do not lose it
// if another ReadLine is issued after this timeout
return null;
}
inLine.Append((char) retByte);
}
}
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
// TODO
return null;
}
// Read until we encounter a specific value.
[TODO]
public String ReadTo(String value)
{
// TODO
return null;
}
// Write a string to the serial port.
public void Write(String str)
{
if(str != null)
{
byte[] bytes = encoding.GetBytes(str);
Write(bytes, 0, bytes.Length);
}
}
// Write a buffer to the serial port.
public void Write(byte[] buffer, int offset, int count)
{
lock(this)
{
if(baseStream != null)
{
baseStream.Write(buffer, offset, count);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
public void Write(char[] buffer, int offset, int count)
{
byte[] bytes = encoding.GetBytes(buffer, offset, count);
Write(bytes, 0, bytes.Length);
}
// Write a string followed by a newline to the serial port.
public void WriteLine(String str)
{
Write(str);
lock(this)
{
if(newLineBuffer == null)
{
newLineBuffer = encoding.GetBytes(newLine);
}
Write(newLineBuffer, 0, newLineBuffer.Length);
}
}
// Event that is emitted when an error occurs (ignored in this version).
public event SerialErrorEventHandler ErrorEvent;
// Event that is emitted when incoming serial pins change state.
[TODO]
public event SerialPinChangedEventHandler PinChangedEvent
{
add
{
lock(this)
{
bool empty = (pinChanged == null);
pinChanged = pinChanged + value;
if(empty && pinChanged != null)
{
// TODO: launch the pin notification thread.
}
}
}
remove
{
lock(this)
{
pinChanged = pinChanged - value;
if(pinChanged == null)
{
// TODO: shut down the pin notification thread.
}
}
}
}
// Event that is emitted when data is received.
[TODO]
public event SerialReceivedEventHandler ReceivedEvent
{
add
{
lock(this)
{
bool empty = (received == null);
received = received + value;
if(empty && received != null)
{
// TODO: launch the data received thread.
}
}
}
remove
{
lock(this)
{
received = received - value;
if(received == null)
{
// TODO: shut down the data received thread.
}
}
}
}
// Stream class that wraps up a serial port.
private sealed class PortStream : Stream
{
// Internal state.
private SerialPort port;
private byte[] byteBuffer;
// Constructor.
public PortStream(SerialPort port)
{
this.port = port;
this.byteBuffer = new byte [1];
}
// Close the stream.
public override void Close()
{
port.Close();
}
// Flush the pending contents in this stream.
public override void Flush()
{
lock(port)
{
if(port.handle != IntPtr.Zero)
{
PortMethods.DrainOutBuffer(port.handle);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Read data from this stream.
public override int Read(byte[] buffer, int offset, int count)
{
ValidateBuffer(buffer, offset, count);
lock(port)
{
if(port.handle != IntPtr.Zero)
{
return PortMethods.Read
(port.handle, buffer, offset, count);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Read a single byte from this stream.
public override int ReadByte()
{
lock(port)
{
if(port.handle != IntPtr.Zero)
{
int count = PortMethods.Read
(port.handle, byteBuffer, 0, 1);
if(count > 0)
{
return (int)(byteBuffer[0]);
}
else
{
// Timeout probably.
return -1;
}
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Seek to a new position within this stream.
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
// Set the length of this stream.
public override void SetLength(long value)
{
throw new NotSupportedException
(S._("IO_NotSupp_SetLength"));
}
// Write a buffer of bytes to this stream.
public override void Write(byte[] buffer, int offset, int count)
{
ValidateBuffer(buffer, offset, count);
lock(port)
{
if(port.handle != IntPtr.Zero)
{
PortMethods.Write
(port.handle, buffer, offset, count);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Write a single byte to this stream.
public override void WriteByte(byte value)
{
lock(port)
{
if(port.handle != IntPtr.Zero)
{
byteBuffer[0] = value;
PortMethods.Write
(port.handle, byteBuffer, 0, 1);
}
else
{
throw new InvalidOperationException
(S._("Invalid_PortNotOpen"));
}
}
}
// Determine if it is possible to read from this stream.
public override bool CanRead
{
get
{
return true;
}
}
// Determine if it is possible to seek within this stream.
public override bool CanSeek
{
get
{
return false;
}
}
// Determine if it is possible to write to this stream.
public override bool CanWrite
{
get
{
return true;
}
}
// Get the length of this stream.
public override long Length
{
get
{
throw new NotSupportedException
(S._("IO_NotSupp_Seek"));
}
}
// Get the current position within the stream.
public override long Position
{
get
{
throw new NotSupportedException
(S._("IO_NotSupp_Seek"));
}
set
{
throw new NotSupportedException
(S._("IO_NotSupp_Seek"));
}
}
}; // class PortStream
// Helper methods for validating buffer arguments.
internal static void ValidateBuffer(byte[] buffer, int offset, int count)
{
if(buffer == null)
{
throw new ArgumentNullException("buffer");
}
else if(offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException
("offset", S._("ArgRange_Array"));
}
else if(count < 0)
{
throw new ArgumentOutOfRangeException
("count", S._("ArgRange_Array"));
}
else if((buffer.Length - offset) < count)
{
throw new ArgumentException(S._("Arg_InvalidArrayRange"));
}
}
internal static void ValidateBuffer(char[] buffer, int offset, int count)
{
if(buffer == null)
{
throw new ArgumentNullException("buffer");
}
else if(offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException
("offset", S._("ArgRange_Array"));
}
else if(count < 0)
{
throw new ArgumentOutOfRangeException
("count", S._("ArgRange_Array"));
}
else if((buffer.Length - offset) < count)
{
throw new ArgumentException(S._("Arg_InvalidArrayRange"));
}
}
}; // class SerialPort
#endif // CONFIG_SERIAL_PORTS
}; // namespace System.IO.Ports
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using NLog;
using NLog.Targets;
using NLog.Config;
namespace NLog.UnitTests.Targets
{
public class MemoryTargetTests : NLogTestBase
{
[Fact]
public void MemoryTarget_LogLevelTest()
{
ILogger logger = LogManager.GetCurrentClassLogger();
var memoryTarget = new MemoryTarget
{
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);
Assert.True(memoryTarget.Logs.Count() == 0);
logger.Trace("TTT");
logger.Debug("DDD");
logger.Info("III");
logger.Warn("WWW");
logger.Error("EEE");
logger.Fatal("FFF");
LogManager.Configuration = null;
Assert.True(memoryTarget.Logs.Count() == 6);
Assert.True(memoryTarget.Logs[0] == "Trace TTT");
Assert.True(memoryTarget.Logs[1] == "Debug DDD");
Assert.True(memoryTarget.Logs[2] == "Info III");
Assert.True(memoryTarget.Logs[3] == "Warn WWW");
Assert.True(memoryTarget.Logs[4] == "Error EEE");
Assert.True(memoryTarget.Logs[5] == "Fatal FFF");
}
[Fact]
public void MemoryTarget_ReconfigureTest_SameTarget_ExpectLogsEmptied()
{
ILogger logger = LogManager.GetCurrentClassLogger();
var memoryTarget = new MemoryTarget
{
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);
logger.Debug("DDD");
logger.Info("III");
logger.Warn("WWW");
Assert.True(memoryTarget.Logs.Count() == 3);
Assert.True(memoryTarget.Logs[0] == "Debug DDD");
Assert.True(memoryTarget.Logs[1] == "Info III");
Assert.True(memoryTarget.Logs[2] == "Warn WWW");
LogManager.Configuration = null;
//
// Reconfigure the logger using the same MemoryTarget.
memoryTarget = new MemoryTarget
{
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);
logger.Trace("TTT");
logger.Error("EEE");
logger.Fatal("FFF");
Assert.True(memoryTarget.Logs.Count() == 3);
Assert.True(memoryTarget.Logs[0] == "Trace TTT");
Assert.True(memoryTarget.Logs[1] == "Error EEE");
Assert.True(memoryTarget.Logs[2] == "Fatal FFF");
}
[Fact]
public void MemoryTarget_ClearLogsTest()
{
ILogger logger = LogManager.GetCurrentClassLogger();
var memoryTarget = new MemoryTarget
{
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);
logger.Warn("WWW");
logger.Error("EEE");
logger.Fatal("FFF");
memoryTarget.Logs.Clear();
logger.Trace("TTT");
logger.Debug("DDD");
logger.Info("III");
LogManager.Configuration = null;
Assert.True(memoryTarget.Logs.Count() == 3);
Assert.True(memoryTarget.Logs[0] == "Trace TTT");
Assert.True(memoryTarget.Logs[1] == "Debug DDD");
Assert.True(memoryTarget.Logs[2] == "Info III");
}
[Fact]
public void MemoryTarget_NullMessageTest()
{
ILogger logger = LogManager.GetCurrentClassLogger();
var memoryTarget = new MemoryTarget
{
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);
string nullMessage = null;
logger.Trace("TTT");
logger.Debug((String)null);
logger.Info("III");
logger.Warn(nullMessage);
logger.Error("EEE");
LogManager.Configuration = null;
Assert.True(memoryTarget.Logs.Count() == 5);
Assert.True(memoryTarget.Logs[0] == "Trace TTT");
Assert.True(memoryTarget.Logs[1] == "Debug ");
Assert.True(memoryTarget.Logs[2] == "Info III");
Assert.True(memoryTarget.Logs[3] == "Warn ");
Assert.True(memoryTarget.Logs[4] == "Error EEE");
}
[Fact]
public void MemoryTarget_EmptyMessageTest()
{
ILogger logger = LogManager.GetCurrentClassLogger();
var memoryTarget = new MemoryTarget
{
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);
logger.Trace("TTT");
logger.Debug(String.Empty);
logger.Info("III");
logger.Warn("");
logger.Error("EEE");
LogManager.Configuration = null;
Assert.True(memoryTarget.Logs.Count() == 5);
Assert.True(memoryTarget.Logs[0] == "Trace TTT");
Assert.True(memoryTarget.Logs[1] == "Debug ");
Assert.True(memoryTarget.Logs[2] == "Info III");
Assert.True(memoryTarget.Logs[3] == "Warn ");
Assert.True(memoryTarget.Logs[4] == "Error EEE");
}
}
}
| |
using System;
using Cocos2D;
using Microsoft.Xna.Framework;
namespace tests
{
public class ParallaxDemo : CCLayer
{
protected CCTextureAtlas m_atlas;
public const int kTagTileMap = 1;
private const string s_pPathB1 = "Images/b1";
private const string s_pPathB2 = "Images/b2";
private const string s_pPathF1 = "Images/f1";
private const string s_pPathF2 = "Images/f2";
private const string s_pPathR1 = "Images/r1";
private const string s_pPathR2 = "Images/r2";
private CCGamePadButtonDelegate _GamePadButtonDelegate;
private CCGamePadDPadDelegate _GamePadDPadDelegate;
private CCGamePadStickUpdateDelegate _GamePadStickDelegate;
private CCGamePadTriggerDelegate _GamePadTriggerDelegate;
public ParallaxDemo()
{
_GamePadDPadDelegate = new CCGamePadDPadDelegate(MyOnGamePadDPadUpdate);
_GamePadButtonDelegate = new CCGamePadButtonDelegate(MyOnGamePadButtonUpdate);
_GamePadStickDelegate = new CCGamePadStickUpdateDelegate(MyOnGameStickUpdate);
_GamePadTriggerDelegate = new CCGamePadTriggerDelegate(MyGamePadTriggerUpdate);
}
#region GamePad Support
private bool _aButtonWasPressed = false;
private bool _yButtonWasPressed = false;
private bool _xButtonWasPressed = false;
private void MyOnGamePadButtonUpdate(CCGamePadButtonStatus backButton, CCGamePadButtonStatus startButton, CCGamePadButtonStatus systemButton, CCGamePadButtonStatus aButton, CCGamePadButtonStatus bButton, CCGamePadButtonStatus xButton, CCGamePadButtonStatus yButton, CCGamePadButtonStatus leftShoulder, CCGamePadButtonStatus rightShoulder, Microsoft.Xna.Framework.PlayerIndex player)
{
if (aButton == CCGamePadButtonStatus.Pressed)
{
_aButtonWasPressed = true;
}
else if (aButton == CCGamePadButtonStatus.Released && _aButtonWasPressed)
{
// Select the menu
restartCallback(null);
}
if (yButton == CCGamePadButtonStatus.Pressed)
{
_yButtonWasPressed = true;
}
else if (yButton == CCGamePadButtonStatus.Released && _yButtonWasPressed)
{
CCNode node = GetChildByTag(kTagTileMap);
node.RunAction(new CCRotateBy (1f, 15f));
}
if (xButton == CCGamePadButtonStatus.Pressed)
{
_xButtonWasPressed = true;
}
else if (xButton == CCGamePadButtonStatus.Released && _xButtonWasPressed)
{
CCNode node = GetChildByTag(kTagTileMap);
if (node != null)
{
node.RunAction(new CCRotateBy (1f, -15f));
}
}
}
private long _FirstTicks;
private bool _bDownPress = false;
private bool _bUpPress = false;
private void MyOnGamePadDPadUpdate(CCGamePadButtonStatus leftButton, CCGamePadButtonStatus upButton, CCGamePadButtonStatus rightButton, CCGamePadButtonStatus downButton, Microsoft.Xna.Framework.PlayerIndex player)
{
// Down and Up only
if (rightButton == CCGamePadButtonStatus.Pressed)
{
if (_FirstTicks == 0L)
{
_FirstTicks = DateTime.Now.Ticks;
_bDownPress = true;
}
}
else if (rightButton == CCGamePadButtonStatus.Released && _FirstTicks > 0L && _bDownPress)
{
_FirstTicks = 0L;
nextCallback(null);
_bDownPress = false;
}
if (leftButton == CCGamePadButtonStatus.Pressed)
{
if (_FirstTicks == 0L)
{
_FirstTicks = DateTime.Now.Ticks;
_bUpPress = true;
}
}
else if (leftButton == CCGamePadButtonStatus.Released && _FirstTicks > 0L && _bUpPress)
{
_FirstTicks = 0L;
backCallback(null);
_bUpPress = false;
}
}
private void MyGamePadTriggerUpdate(float leftTriggerStrength, float rightTriggerStrength, PlayerIndex player)
{
CCNode node = GetChildByTag(kTagTileMap);
if (node != null)
{
node.Rotation += rightTriggerStrength * CCMacros.CCDegreesToRadians(15f) - leftTriggerStrength * CCMacros.CCDegreesToRadians(15f);
}
}
private void MyOnGameStickUpdate(CCGameStickStatus left, CCGameStickStatus right, PlayerIndex player)
{
CCNode node = GetChildByTag(kTagTileMap);
if (node != null)
{
CCParallaxNode map = (CCParallaxNode)node;
if (left.Magnitude > 0f)
{
// use the left stick to move the map
CCPoint diff = left.Direction.InvertY * left.Magnitude * 10f;
CCPoint currentPos = node.Position;
node.Position = currentPos + diff;
}
if (right.Magnitude > 0f)
{
float scale = (1f - right.Direction.Y * right.Magnitude);
node.Scale += scale;
if (node.Scale < 1f)
{
node.Scale = 1f;
}
}
}
}
#endregion
public virtual string title()
{
return "No title";
}
public override void OnEnter()
{
base.OnEnter();
CCApplication.SharedApplication.GamePadButtonUpdate += _GamePadButtonDelegate;
CCApplication.SharedApplication.GamePadDPadUpdate += _GamePadDPadDelegate;
CCApplication.SharedApplication.GamePadStickUpdate += _GamePadStickDelegate;
CCApplication.SharedApplication.GamePadTriggerUpdate += _GamePadTriggerDelegate;
CCSize s = CCDirector.SharedDirector.WinSize;
CCLabelTTF label = new CCLabelTTF(title(), "arial", 28);
AddChild(label, 1);
label.Position = new CCPoint(s.Width / 2, s.Height - 50);
CCMenuItemImage item1 = new CCMenuItemImage(s_pPathB1, s_pPathB2, backCallback);
CCMenuItemImage item2 = new CCMenuItemImage(s_pPathR1, s_pPathR2, restartCallback);
CCMenuItemImage item3 = new CCMenuItemImage(s_pPathF1, s_pPathF2, nextCallback);
CCMenu menu = new CCMenu(item1, item2, item3);
menu.Position = new CCPoint(0, 0);
item1.Position = new CCPoint(s.Width / 2 - 100, 30);
item2.Position = new CCPoint(s.Width / 2, 30);
item3.Position = new CCPoint(s.Width / 2 + 100, 30);
AddChild(menu, 1);
}
public override void OnExit()
{
base.OnExit();
CCApplication.SharedApplication.GamePadButtonUpdate -= _GamePadButtonDelegate;
CCApplication.SharedApplication.GamePadDPadUpdate -= _GamePadDPadDelegate;
CCApplication.SharedApplication.GamePadStickUpdate -= _GamePadStickDelegate;
CCApplication.SharedApplication.GamePadTriggerUpdate -= _GamePadTriggerDelegate;
}
public void restartCallback(object pSender)
{
CCScene s = new ParallaxTestScene();
s.AddChild(ParallaxTestScene.restartParallaxAction());
CCDirector.SharedDirector.ReplaceScene(s);
}
public void nextCallback(object pSender)
{
CCScene s = new ParallaxTestScene();
s.AddChild(ParallaxTestScene.nextParallaxAction());
CCDirector.SharedDirector.ReplaceScene(s);
}
public void backCallback(object pSender)
{
CCScene s = new ParallaxTestScene();
s.AddChild(ParallaxTestScene.backParallaxAction());
CCDirector.SharedDirector.ReplaceScene(s);
}
}
}
| |
using System;
namespace Raksha.Asn1.X509
{
/**
* The Holder object.
* <p>
* For an v2 attribute certificate this is:
*
* <pre>
* Holder ::= SEQUENCE {
* baseCertificateID [0] IssuerSerial OPTIONAL,
* -- the issuer and serial number of
* -- the holder's Public Key Certificate
* entityName [1] GeneralNames OPTIONAL,
* -- the name of the claimant or role
* objectDigestInfo [2] ObjectDigestInfo OPTIONAL
* -- used to directly authenticate the holder,
* -- for example, an executable
* }
* </pre>
* </p>
* <p>
* For an v1 attribute certificate this is:
*
* <pre>
* subject CHOICE {
* baseCertificateID [0] IssuerSerial,
* -- associated with a Public Key Certificate
* subjectName [1] GeneralNames },
* -- associated with a name
* </pre>
* </p>
*/
public class Holder
: Asn1Encodable
{
internal readonly IssuerSerial baseCertificateID;
internal readonly GeneralNames entityName;
internal readonly ObjectDigestInfo objectDigestInfo;
private readonly int version;
public static Holder GetInstance(
object obj)
{
if (obj is Holder)
{
return (Holder) obj;
}
if (obj is Asn1Sequence)
{
return new Holder((Asn1Sequence) obj);
}
if (obj is Asn1TaggedObject)
{
return new Holder((Asn1TaggedObject) obj);
}
throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
}
/**
* Constructor for a holder for an v1 attribute certificate.
*
* @param tagObj The ASN.1 tagged holder object.
*/
public Holder(
Asn1TaggedObject tagObj)
{
switch (tagObj.TagNo)
{
case 0:
baseCertificateID = IssuerSerial.GetInstance(tagObj, false);
break;
case 1:
entityName = GeneralNames.GetInstance(tagObj, false);
break;
default:
throw new ArgumentException("unknown tag in Holder");
}
this.version = 0;
}
/**
* Constructor for a holder for an v2 attribute certificate. *
*
* @param seq The ASN.1 sequence.
*/
private Holder(
Asn1Sequence seq)
{
if (seq.Count > 3)
throw new ArgumentException("Bad sequence size: " + seq.Count);
for (int i = 0; i != seq.Count; i++)
{
Asn1TaggedObject tObj = Asn1TaggedObject.GetInstance(seq[i]);
switch (tObj.TagNo)
{
case 0:
baseCertificateID = IssuerSerial.GetInstance(tObj, false);
break;
case 1:
entityName = GeneralNames.GetInstance(tObj, false);
break;
case 2:
objectDigestInfo = ObjectDigestInfo.GetInstance(tObj, false);
break;
default:
throw new ArgumentException("unknown tag in Holder");
}
}
this.version = 1;
}
public Holder(
IssuerSerial baseCertificateID)
: this(baseCertificateID, 1)
{
}
/**
* Constructs a holder from a IssuerSerial.
* @param baseCertificateID The IssuerSerial.
* @param version The version of the attribute certificate.
*/
public Holder(
IssuerSerial baseCertificateID,
int version)
{
this.baseCertificateID = baseCertificateID;
this.version = version;
}
/**
* Returns 1 for v2 attribute certificates or 0 for v1 attribute
* certificates.
* @return The version of the attribute certificate.
*/
public int Version
{
get { return version; }
}
/**
* Constructs a holder with an entityName for v2 attribute certificates or
* with a subjectName for v1 attribute certificates.
*
* @param entityName The entity or subject name.
*/
public Holder(
GeneralNames entityName)
: this(entityName, 1)
{
}
/**
* Constructs a holder with an entityName for v2 attribute certificates or
* with a subjectName for v1 attribute certificates.
*
* @param entityName The entity or subject name.
* @param version The version of the attribute certificate.
*/
public Holder(
GeneralNames entityName,
int version)
{
this.entityName = entityName;
this.version = version;
}
/**
* Constructs a holder from an object digest info.
*
* @param objectDigestInfo The object digest info object.
*/
public Holder(
ObjectDigestInfo objectDigestInfo)
{
this.objectDigestInfo = objectDigestInfo;
this.version = 1;
}
public IssuerSerial BaseCertificateID
{
get { return baseCertificateID; }
}
/**
* Returns the entityName for an v2 attribute certificate or the subjectName
* for an v1 attribute certificate.
*
* @return The entityname or subjectname.
*/
public GeneralNames EntityName
{
get { return entityName; }
}
public ObjectDigestInfo ObjectDigestInfo
{
get { return objectDigestInfo; }
}
/**
* The Holder object.
* <pre>
* Holder ::= Sequence {
* baseCertificateID [0] IssuerSerial OPTIONAL,
* -- the issuer and serial number of
* -- the holder's Public Key Certificate
* entityName [1] GeneralNames OPTIONAL,
* -- the name of the claimant or role
* objectDigestInfo [2] ObjectDigestInfo OPTIONAL
* -- used to directly authenticate the holder,
* -- for example, an executable
* }
* </pre>
*/
public override Asn1Object ToAsn1Object()
{
if (version == 1)
{
Asn1EncodableVector v = new Asn1EncodableVector();
if (baseCertificateID != null)
{
v.Add(new DerTaggedObject(false, 0, baseCertificateID));
}
if (entityName != null)
{
v.Add(new DerTaggedObject(false, 1, entityName));
}
if (objectDigestInfo != null)
{
v.Add(new DerTaggedObject(false, 2, objectDigestInfo));
}
return new DerSequence(v);
}
if (entityName != null)
{
return new DerTaggedObject(false, 1, entityName);
}
return new DerTaggedObject(false, 0, baseCertificateID);
}
}
}
| |
/*
* 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.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.UserProfilesService;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using Microsoft.CSharp;
namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")]
public class UserProfileModule : IProfileModule, INonSharedRegionModule
{
/// <summary>
/// Logging
/// </summary>
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// The pair of Dictionaries are used to handle the switching of classified ads
// by maintaining a cache of classified id to creator id mappings and an interest
// count. The entries are removed when the interest count reaches 0.
Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>();
Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>();
private JsonRpcRequestManager rpc = new JsonRpcRequestManager();
public Scene Scene
{
get; private set;
}
/// <summary>
/// Gets or sets the ConfigSource.
/// </summary>
/// <value>
/// The configuration
/// </value>
public IConfigSource Config
{
get;
set;
}
/// <summary>
/// Gets or sets the URI to the profile server.
/// </summary>
/// <value>
/// The profile server URI.
/// </value>
public string ProfileServerUri
{
get;
set;
}
IProfileModule ProfileModule
{
get; set;
}
IUserManagement UserManagementModule
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether this
/// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled.
/// </summary>
/// <value>
/// <c>true</c> if enabled; otherwise, <c>false</c>.
/// </value>
public bool Enabled
{
get;
set;
}
public string MyGatekeeper
{
get; private set;
}
#region IRegionModuleBase implementation
/// <summary>
/// This is called to initialize the region module. For shared modules, this is called exactly once, after
/// creating the single (shared) instance. For non-shared modules, this is called once on each instance, after
/// the instace for the region has been created.
/// </summary>
/// <param name='source'>
/// Source.
/// </param>
public void Initialise(IConfigSource source)
{
Config = source;
ReplaceableInterface = typeof(IProfileModule);
IConfig profileConfig = Config.Configs["UserProfiles"];
if (profileConfig == null)
{
m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
Enabled = false;
return;
}
// If we find ProfileURL then we configure for FULL support
// else we setup for BASIC support
ProfileServerUri = profileConfig.GetString("ProfileServiceURL", "");
if (ProfileServerUri == "")
{
Enabled = false;
return;
}
m_log.Debug("[PROFILES]: Full Profiles Enabled");
ReplaceableInterface = null;
Enabled = true;
MyGatekeeper = Util.GetConfigVarFromSections<string>(source, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "UserProfiles" }, String.Empty);
}
/// <summary>
/// Adds the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void AddRegion(Scene scene)
{
if(!Enabled)
return;
Scene = scene;
Scene.RegisterModuleInterface<IProfileModule>(this);
Scene.EventManager.OnNewClient += OnNewClient;
Scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent;
UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
}
void HandleOnMakeRootAgent (ScenePresence obj)
{
if(obj.PresenceType == PresenceType.Npc)
return;
Util.FireAndForget(delegate
{
GetImageAssets(((IScenePresence)obj).UUID);
}, null, "UserProfileModule.GetImageAssets");
}
/// <summary>
/// Removes the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RemoveRegion(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// This will be called once for every scene loaded. In a shared module this will be multiple times in one
/// instance, while a nonshared module instance will only be called once. This method is called after AddRegion
/// has been called in all modules for that scene, providing an opportunity to request another module's
/// interface, or hook an event from another module.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RegionLoaded(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// If this returns non-null, it is the type of an interface that this module intends to register. This will
/// cause the loader to defer loading of this module until all other modules have been loaded. If no other
/// module has registered the interface by then, this module will be activated, else it will remain inactive,
/// letting the other module take over. This should return non-null ONLY in modules that are intended to be
/// easily replaceable, e.g. stub implementations that the developer expects to be replaced by third party
/// provided modules.
/// </summary>
/// <value>
/// The replaceable interface.
/// </value>
public Type ReplaceableInterface
{
get; private set;
}
/// <summary>
/// Called as the instance is closed.
/// </summary>
public void Close()
{
}
/// <value>
/// The name of the module
/// </value>
/// <summary>
/// Gets the module name.
/// </summary>
public string Name
{
get { return "UserProfileModule"; }
}
#endregion IRegionModuleBase implementation
#region Region Event Handlers
/// <summary>
/// Raises the new client event.
/// </summary>
/// <param name='client'>
/// Client.
/// </param>
void OnNewClient(IClientAPI client)
{
//Profile
client.OnRequestAvatarProperties += RequestAvatarProperties;
client.OnUpdateAvatarProperties += AvatarPropertiesUpdate;
client.OnAvatarInterestUpdate += AvatarInterestsUpdate;
// Classifieds
client.AddGenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest);
client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
client.OnClassifiedInfoRequest += ClassifiedInfoRequest;
client.OnClassifiedDelete += ClassifiedDelete;
// Picks
client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest);
client.AddGenericPacketHandler("pickinforequest", PickInfoRequest);
client.OnPickInfoUpdate += PickInfoUpdate;
client.OnPickDelete += PickDelete;
// Notes
client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest);
client.OnAvatarNotesUpdate += NotesUpdate;
// Preferences
client.OnUserInfoRequest += UserPreferencesRequest;
client.OnUpdateUserInfo += UpdateUserPreferences;
}
#endregion Region Event Handlers
#region Classified
///
/// <summary>
/// Handles the avatar classifieds request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void ClassifiedsRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetID;
UUID.TryParse(args[0], out targetID);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
UUID creatorId = UUID.Zero;
Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
UUID.TryParse(args[0], out creatorId);
parameters.Add("creatorId", OSD.FromUUID(creatorId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["classifieduuid"].AsUUID();
string name = m["name"].AsString();
classifieds[cid] = name;
lock (m_classifiedCache)
{
if (!m_classifiedCache.ContainsKey(cid))
{
m_classifiedCache.Add(cid,creatorId);
m_classifiedInterest.Add(cid, 0);
}
m_classifiedInterest[cid]++;
}
}
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
}
public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient)
{
UUID target = remoteClient.AgentId;
UserClassifiedAdd ad = new UserClassifiedAdd();
ad.ClassifiedId = queryClassifiedID;
lock (m_classifiedCache)
{
if (m_classifiedCache.ContainsKey(queryClassifiedID))
{
target = m_classifiedCache[queryClassifiedID];
m_classifiedInterest[queryClassifiedID] --;
if (m_classifiedInterest[queryClassifiedID] == 0)
{
m_classifiedInterest.Remove(queryClassifiedID);
m_classifiedCache.Remove(queryClassifiedID);
}
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(target, out serverURI);
object Ad = (object)ad;
if(!rpc.JsonRpcRequest(ref Ad, "classifieds_info_query", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error getting classified info", false);
return;
}
ad = (UserClassifiedAdd) Ad;
if(ad.CreatorId == UUID.Zero)
return;
Vector3 globalPos = new Vector3();
Vector3.TryParse(ad.GlobalPos, out globalPos);
remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate, (uint)ad.ExpirationDate,
(uint)ad.Category, ad.Name, ad.Description, ad.ParcelId, (uint)ad.ParentEstate,
ad.SnapshotId, ad.SimName, globalPos, ad.ParcelName, ad.Flags, ad.Price);
}
/// <summary>
/// Classifieds info update.
/// </summary>
/// <param name='queryclassifiedID'>
/// Queryclassified I.
/// </param>
/// <param name='queryCategory'>
/// Query category.
/// </param>
/// <param name='queryName'>
/// Query name.
/// </param>
/// <param name='queryDescription'>
/// Query description.
/// </param>
/// <param name='queryParcelID'>
/// Query parcel I.
/// </param>
/// <param name='queryParentEstate'>
/// Query parent estate.
/// </param>
/// <param name='querySnapshotID'>
/// Query snapshot I.
/// </param>
/// <param name='queryGlobalPos'>
/// Query global position.
/// </param>
/// <param name='queryclassifiedFlags'>
/// Queryclassified flags.
/// </param>
/// <param name='queryclassifiedPrice'>
/// Queryclassified price.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
int queryclassifiedPrice, IClientAPI remoteClient)
{
UserClassifiedAdd ad = new UserClassifiedAdd();
Scene s = (Scene) remoteClient.Scene;
Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
ScenePresence p = FindPresence(remoteClient.AgentId);
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
if (land == null)
{
ad.ParcelName = string.Empty;
}
else
{
ad.ParcelName = land.LandData.Name;
}
ad.CreatorId = remoteClient.AgentId;
ad.ClassifiedId = queryclassifiedID;
ad.Category = Convert.ToInt32(queryCategory);
ad.Name = queryName;
ad.Description = queryDescription;
ad.ParentEstate = Convert.ToInt32(queryParentEstate);
ad.SnapshotId = querySnapshotID;
ad.SimName = remoteClient.Scene.RegionInfo.RegionName;
ad.GlobalPos = queryGlobalPos.ToString ();
ad.Flags = queryclassifiedFlags;
ad.Price = queryclassifiedPrice;
ad.ParcelId = p.currentParcelUUID;
object Ad = ad;
OSD.SerializeMembers(Ad);
if(!rpc.JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating classified", false);
return;
}
}
/// <summary>
/// Classifieds delete.
/// </summary>
/// <param name='queryClassifiedID'>
/// Query classified I.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
UUID classifiedId;
OSDMap parameters= new OSDMap();
UUID.TryParse(queryClassifiedID.ToString(), out classifiedId);
parameters.Add("classifiedId", OSD.FromUUID(classifiedId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error classified delete", false);
return;
}
parameters = (OSDMap)Params;
}
#endregion Classified
#region Picks
/// <summary>
/// Handles the avatar picks request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PicksRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetId;
UUID.TryParse(args[0], out targetId);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetId, out serverURI);
Dictionary<UUID, string> picks = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
parameters.Add("creatorId", OSD.FromUUID(targetId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarpicksrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["pickuuid"].AsUUID();
string name = m["name"].AsString();
m_log.DebugFormat("[PROFILES]: PicksRequest {0}", name);
picks[cid] = name;
}
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
}
/// <summary>
/// Handles the pick info request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PickInfoRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
UUID targetID;
UUID.TryParse (args [0], out targetID);
string serverURI = string.Empty;
GetUserProfileServerURI (targetID, out serverURI);
string theirGatekeeperURI;
GetUserGatekeeperURI (targetID, out theirGatekeeperURI);
IClientAPI remoteClient = (IClientAPI)sender;
UserProfilePick pick = new UserProfilePick ();
UUID.TryParse (args [0], out pick.CreatorId);
UUID.TryParse (args [1], out pick.PickId);
object Pick = (object)pick;
if (!rpc.JsonRpcRequest (ref Pick, "pickinforequest", serverURI, UUID.Random ().ToString ())) {
remoteClient.SendAgentAlertMessage (
"Error selecting pick", false);
return;
}
pick = (UserProfilePick)Pick;
Vector3 globalPos = new Vector3(Vector3.Zero);
// Smoke and mirrors
if (pick.Gatekeeper == MyGatekeeper)
{
Vector3.TryParse(pick.GlobalPos,out globalPos);
}
else
{
// Setup the illusion
string region = string.Format("{0} {1}",pick.Gatekeeper,pick.SimName);
GridRegion target = Scene.GridService.GetRegionByName(Scene.RegionInfo.ScopeID, region);
if(target == null)
{
// This is a dead or unreachable region
}
else
{
// Work our slight of hand
int x = target.RegionLocX;
int y = target.RegionLocY;
dynamic synthX = globalPos.X - (globalPos.X/Constants.RegionSize) * Constants.RegionSize;
synthX += x;
globalPos.X = synthX;
dynamic synthY = globalPos.Y - (globalPos.Y/Constants.RegionSize) * Constants.RegionSize;
synthY += y;
globalPos.Y = synthY;
}
}
m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString());
// Pull the rabbit out of the hat
remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
pick.Desc,pick.SnapshotId,pick.User,pick.OriginalName,pick.SimName,
globalPos,pick.SortOrder,pick.Enabled);
}
/// <summary>
/// Updates the userpicks
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='pickID'>
/// Pick I.
/// </param>
/// <param name='creatorID'>
/// the creator of the pick
/// </param>
/// <param name='topPick'>
/// Top pick.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
/// <param name='desc'>
/// Desc.
/// </param>
/// <param name='snapshotID'>
/// Snapshot I.
/// </param>
/// <param name='sortOrder'>
/// Sort order.
/// </param>
/// <param name='enabled'>
/// Enabled.
/// </param>
public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
{
//TODO: See how this works with NPC, May need to test
m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString());
UserProfilePick pick = new UserProfilePick();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
ScenePresence p = FindPresence(remoteClient.AgentId);
Vector3 avaPos = p.AbsolutePosition;
// Getting the global position for the Avatar
Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.WorldLocX + avaPos.X,
remoteClient.Scene.RegionInfo.WorldLocY + avaPos.Y,
avaPos.Z);
string landOwnerName = string.Empty;
ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);
if (land != null)
{
if (land.LandData.IsGroupOwned)
{
IGroupsModule groupMod = p.Scene.RequestModuleInterface<IGroupsModule>();
UUID groupId = land.LandData.GroupID;
GroupRecord groupRecord = groupMod.GetGroupRecord(groupId);
landOwnerName = groupRecord.GroupName;
}
else
{
IUserAccountService accounts = p.Scene.RequestModuleInterface<IUserAccountService>();
UserAccount user = accounts.GetUserAccount(p.Scene.RegionInfo.ScopeID, land.LandData.OwnerID);
landOwnerName = user.Name;
}
}
else
{
m_log.WarnFormat(
"[PROFILES]: PickInfoUpdate found no parcel info at {0},{1} in {2}",
avaPos.X, avaPos.Y, p.Scene.Name);
}
pick.PickId = pickID;
pick.CreatorId = creatorID;
pick.TopPick = topPick;
pick.Name = name;
pick.Desc = desc;
pick.ParcelId = p.currentParcelUUID;
pick.SnapshotId = snapshotID;
pick.User = landOwnerName;
pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
pick.Gatekeeper = MyGatekeeper;
pick.GlobalPos = posGlobal.ToString();
pick.SortOrder = sortOrder;
pick.Enabled = enabled;
object Pick = (object)pick;
if(!rpc.JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating pick", false);
return;
}
m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString());
}
/// <summary>
/// Delete a Pick
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryPickID'>
/// Query pick I.
/// </param>
public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
OSDMap parameters= new OSDMap();
parameters.Add("pickId", OSD.FromUUID(queryPickID));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "picks_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error picks delete", false);
return;
}
}
#endregion Picks
#region Notes
/// <summary>
/// Handles the avatar notes request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void NotesRequest(Object sender, string method, List<String> args)
{
UserProfileNotes note = new UserProfileNotes();
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
note.UserId = remoteClient.AgentId;
UUID.TryParse(args[0], out note.TargetId);
object Note = (object)note;
if(!rpc.JsonRpcRequest(ref Note, "avatarnotesrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
return;
}
note = (UserProfileNotes) Note;
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
}
/// <summary>
/// Avatars the notes update.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryTargetID'>
/// Query target I.
/// </param>
/// <param name='queryNotes'>
/// Query notes.
/// </param>
public void NotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
{
UserProfileNotes note = new UserProfileNotes();
note.UserId = remoteClient.AgentId;
note.TargetId = queryTargetID;
note.Notes = queryNotes;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Note = note;
if(!rpc.JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating note", false);
return;
}
}
#endregion Notes
#region User Preferences
/// <summary>
/// Updates the user preferences.
/// </summary>
/// <param name='imViaEmail'>
/// Im via email.
/// </param>
/// <param name='visible'>
/// Visible.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UpdateUserPreferences(bool imViaEmail, bool visible, IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
pref.IMViaEmail = imViaEmail;
pref.Visible = visible;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_update", serverURI, UUID.Random().ToString()))
{
m_log.InfoFormat("[PROFILES]: UserPreferences update error");
remoteClient.SendAgentAlertMessage("Error updating preferences", false);
return;
}
}
/// <summary>
/// Users the preferences request.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UserPreferencesRequest(IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = (object)pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_request", serverURI, UUID.Random().ToString()))
{
// m_log.InfoFormat("[PROFILES]: UserPreferences request error");
// remoteClient.SendAgentAlertMessage("Error requesting preferences", false);
return;
}
pref = (UserPreferences) Pref;
remoteClient.SendUserInfoReply(pref.IMViaEmail, pref.Visible, pref.EMail);
}
#endregion User Preferences
#region Avatar Properties
/// <summary>
/// Update the avatars interests .
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='wantmask'>
/// Wantmask.
/// </param>
/// <param name='wanttext'>
/// Wanttext.
/// </param>
/// <param name='skillsmask'>
/// Skillsmask.
/// </param>
/// <param name='skillstext'>
/// Skillstext.
/// </param>
/// <param name='languages'>
/// Languages.
/// </param>
public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WantToMask = (int)wantmask;
prop.WantToText = wanttext;
prop.SkillsMask = (int)skillsmask;
prop.SkillsText = skillstext;
prop.Language = languages;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Param = prop;
if(!rpc.JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating interests", false);
return;
}
}
public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if (String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString()))
{
// Looking for a reason that some viewers are sending null Id's
m_log.DebugFormat("[PROFILES]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID);
return;
}
// Can't handle NPC yet...
ScenePresence p = FindPresence(avatarID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
UserAccount account = null;
Dictionary<string,object> userInfo;
if (!foreign)
{
account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID);
}
else
{
userInfo = new Dictionary<string, object>();
}
Byte[] charterMember = new Byte[1];
string born = String.Empty;
uint flags = 0x00;
if (null != account)
{
if (account.UserTitle == "")
{
charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes(account.UserTitle);
}
born = Util.ToDateTime(account.Created).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
flags = (uint)(account.UserFlags & 0xff);
}
else
{
if (GetUserAccountData(avatarID, out userInfo) == true)
{
if ((string)userInfo["user_title"] == "")
{
charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes((string)userInfo["user_title"]);
}
int val_born = (int)userInfo["user_created"];
born = Util.ToDateTime(val_born).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
// picky, picky
int val_flags = (int)userInfo["user_flags"];
flags = (uint)(val_flags & 0xff);
}
}
UserProfileProperties props = new UserProfileProperties();
string result = string.Empty;
props.UserId = avatarID;
if (!GetProfileData(ref props, foreign, out result))
{
// m_log.DebugFormat("Error getting profile for {0}: {1}", avatarID, result);
return;
}
remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, charterMember , props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText, (uint)props.SkillsMask,
props.SkillsText, props.Language);
}
/// <summary>
/// Updates the avatar properties.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='newProfile'>
/// New profile.
/// </param>
public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileData newProfile)
{
if (remoteClient.AgentId == newProfile.ID)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WebUrl = newProfile.ProfileUrl;
prop.ImageId = newProfile.Image;
prop.AboutText = newProfile.AboutText;
prop.FirstLifeImageId = newProfile.FirstLifeImage;
prop.FirstLifeText = newProfile.FirstLifeAboutText;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Prop = prop;
if(!rpc.JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating properties", false);
return;
}
RequestAvatarProperties(remoteClient, newProfile.ID);
}
}
/// <summary>
/// Gets the profile data.
/// </summary>
/// <returns>
/// The profile data.
/// </returns>
bool GetProfileData(ref UserProfileProperties properties, bool foreign, out string message)
{
// Can't handle NPC yet...
ScenePresence p = FindPresence(properties.UserId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
{
message = "Id points to NPC";
return false;
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(properties.UserId, out serverURI);
// This is checking a friend on the home grid
// Not HG friend
if (String.IsNullOrEmpty(serverURI))
{
message = "No Presence - foreign friend";
return false;
}
object Prop = (object)properties;
if (!rpc.JsonRpcRequest(ref Prop, "avatar_properties_request", serverURI, UUID.Random().ToString()))
{
// If it's a foreign user then try again using OpenProfile, in case that's what the grid is using
bool secondChanceSuccess = false;
if (foreign)
{
try
{
OpenProfileClient client = new OpenProfileClient(serverURI);
if (client.RequestAvatarPropertiesUsingOpenProfile(ref properties))
secondChanceSuccess = true;
}
catch (Exception e)
{
m_log.Debug(
string.Format(
"[PROFILES]: Request using the OpenProfile API for user {0} to {1} failed",
properties.UserId, serverURI),
e);
// Allow the return 'message' to say "JsonRpcRequest" and not "OpenProfile", because
// the most likely reason that OpenProfile failed is that the remote server
// doesn't support OpenProfile, and that's not very interesting.
}
}
if (!secondChanceSuccess)
{
message = string.Format("JsonRpcRequest for user {0} to {1} failed", properties.UserId, serverURI);
m_log.DebugFormat("[PROFILES]: {0}", message);
return false;
}
// else, continue below
}
properties = (UserProfileProperties)Prop;
message = "Success";
return true;
}
#endregion Avatar Properties
#region Utils
bool GetImageAssets(UUID avatarId)
{
string profileServerURI = string.Empty;
string assetServerURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarId, out profileServerURI);
if(!foreign)
return true;
assetServerURI = UserManagementModule.GetUserServerURL(avatarId, "AssetServerURI");
if(string.IsNullOrEmpty(profileServerURI) || string.IsNullOrEmpty(assetServerURI))
return false;
OSDMap parameters= new OSDMap();
parameters.Add("avatarId", OSD.FromUUID(avatarId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "image_assets_request", profileServerURI, UUID.Random().ToString()))
{
return false;
}
parameters = (OSDMap)Params;
if (parameters.ContainsKey("result"))
{
OSDArray list = (OSDArray)parameters["result"];
foreach (OSD asset in list)
{
OSDString assetId = (OSDString)asset;
Scene.AssetService.Get(string.Format("{0}/{1}", assetServerURI, assetId.AsString()));
}
return true;
}
else
{
m_log.ErrorFormat("[PROFILES]: Problematic response for image_assets_request from {0}", profileServerURI);
return false;
}
}
/// <summary>
/// Gets the user account data.
/// </summary>
/// <returns>
/// The user profile data.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='userInfo'>
/// If set to <c>true</c> user info.
/// </param>
bool GetUserAccountData(UUID userID, out Dictionary<string, object> userInfo)
{
Dictionary<string,object> info = new Dictionary<string, object>();
if (UserManagementModule.IsLocalGridUser(userID))
{
// Is local
IUserAccountService uas = Scene.UserAccountService;
UserAccount account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID);
info["user_flags"] = account.UserFlags;
info["user_created"] = account.Created;
if (!String.IsNullOrEmpty(account.UserTitle))
info["user_title"] = account.UserTitle;
else
info["user_title"] = "";
userInfo = info;
return false;
}
else
{
// Is Foreign
string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI");
if (String.IsNullOrEmpty(home_url))
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "Unavailable";
userInfo = info;
return true;
}
UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);
Dictionary<string, object> account;
try
{
account = uConn.GetUserInfo(userID);
}
catch (Exception e)
{
m_log.Debug("[PROFILES]: GetUserInfo call failed ", e);
account = new Dictionary<string, object>();
}
if (account.Count > 0)
{
if (account.ContainsKey("user_flags"))
info["user_flags"] = account["user_flags"];
else
info["user_flags"] = "";
if (account.ContainsKey("user_created"))
info["user_created"] = account["user_created"];
else
info["user_created"] = "";
info["user_title"] = "HG Visitor";
}
else
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "HG Visitor";
}
userInfo = info;
return true;
}
}
/// <summary>
/// Gets the user gatekeeper server URI.
/// </summary>
/// <returns>
/// The user gatekeeper server URI.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user URI.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server URI.
/// </param>
bool GetUserGatekeeperURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "GatekeeperURI");
// Is Foreign
return true;
}
else
{
serverURI = MyGatekeeper;
// Is local
return false;
}
}
/// <summary>
/// Gets the user profile server UR.
/// </summary>
/// <returns>
/// The user profile server UR.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server UR.
/// </param>
bool GetUserProfileServerURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI");
// Is Foreign
return true;
}
else
{
serverURI = ProfileServerUri;
// Is local
return false;
}
}
/// <summary>
/// Finds the presence.
/// </summary>
/// <returns>
/// The presence.
/// </returns>
/// <param name='clientID'>
/// Client I.
/// </param>
ScenePresence FindPresence(UUID clientID)
{
ScenePresence p;
p = Scene.GetScenePresence(clientID);
if (p != null && !p.IsChildAgent)
return p;
return null;
}
#endregion Util
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using DotVVM.Framework.Compilation;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Controls.Infrastructure;
using DotVVM.Framework.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using DotVVM.Framework.Utils;
using System.Text;
using System.Linq;
using AngleSharp.Html.Parser;
using AngleSharp.Html.Dom;
using AngleSharp.Html;
using System.Globalization;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Binding.Properties;
using DotVVM.Framework.Compilation.ViewCompiler;
using Newtonsoft.Json;
using DotVVM.Framework.ResourceManagement;
namespace DotVVM.Framework.Testing
{
public class ControlTestHelper
{
public readonly DotvvmConfiguration Configuration;
private readonly FakeMarkupFileLoader fileLoader;
private readonly DotvvmPresenter presenter;
IControlBuilderFactory controlBuilderFactory => Configuration.ServiceProvider.GetRequiredService<IControlBuilderFactory>();
public ControlTestHelper(bool debug = true, Action<DotvvmConfiguration>? config = null, Action<IServiceCollection>? services = null)
{
fileLoader = new FakeMarkupFileLoader(null);
this.Configuration = DotvvmTestHelper.CreateConfiguration(s => {
s.AddSingleton<IMarkupFileLoader>(fileLoader);
services?.Invoke(s);
});
this.Configuration.Markup.AddCodeControls("tc", exampleControl: typeof(FakeHeadResourceLink));
this.Configuration.ApplicationPhysicalPath = Path.GetTempPath();
this.Configuration.Debug = debug;
config?.Invoke(this.Configuration);
presenter = (DotvvmPresenter)this.Configuration.ServiceProvider.GetRequiredService<IDotvvmPresenter>();
}
public (ControlBuilderDescriptor descriptor, Lazy<IControlBuilder> builder) CompilePage(
string markup,
string fileName,
Dictionary<string, string>? markupFiles = null)
{
if (!fileLoader.MarkupFiles.TryAdd(fileName, markup))
throw new Exception($"File {fileName} already exists");
if (markupFiles is object) foreach (var markupFile in markupFiles)
{
if (!fileLoader.MarkupFiles.TryAdd(markupFile.Key, markupFile.Value))
throw new Exception($"File {markupFile.Value} already exists");
}
return controlBuilderFactory.GetControlBuilder(fileName);
}
private TestDotvvmRequestContext PrepareRequest(
string fileName,
PostbackRequestModel? postback = null
)
{
var context = DotvvmTestHelper.CreateContext(
Configuration,
route: new Framework.Routing.DotvvmRoute("testpage", fileName, null, _ => throw new Exception(), Configuration));
context.CsrfToken = null;
var httpContext = (TestHttpContext)context.HttpContext;
if (postback is object)
{
httpContext.Request.Method = "POST";
httpContext.Request.Headers["X-DotVVM-PostBack"] = new[] { "true" };
httpContext.Request.Body = new MemoryStream(
new UTF8Encoding(false).GetBytes(
JsonConvert.SerializeObject(postback)
)
);
}
return context;
}
private TestDotvvmRequestContext PreparePage(
string markup,
Dictionary<string, string>? markupFiles,
string? fileName
)
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
CultureInfo.CurrentUICulture = new CultureInfo("en-US");
Configuration.Freeze();
fileName = (fileName ?? "testpage") + ".dothtml";
var (_, controlBuilder) = CompilePage(markup, fileName, markupFiles);
return PrepareRequest(fileName);
}
public async Task<PageRunResult> RunPage(
Type viewModel,
string markup,
Dictionary<string, string>? markupFiles = null,
string directives = "",
bool renderResources = false,
[CallerMemberName] string? fileName = null)
{
if (!markup.Contains("<body"))
{
markup = $"<body Validation.Enabled=false >\n{markup}\n{(renderResources ? "" : "<tc:FakeBodyResourceLink />")}\n</body>";
}
else if (!renderResources)
{
markup = "<tc:FakeBodyResourceLink />" + markup;
}
if (!markup.Contains("<head"))
{
markup = $"<head></head>\n{markup}";
}
if (!renderResources)
{
markup = "<tc:FakeHeadResourceLink />" + markup;
}
markup = $"@viewModel {viewModel.ToString().Replace("+", ".")}\n{directives}\n\n{markup}";
var request = PreparePage(markup, markupFiles, fileName);
await presenter.ProcessRequest(request);
return CreatePageResult(request);
}
public async Task<CommandRunResult> RunCommand(
string filePath,
PostbackRequestModel model)
{
var request = PrepareRequest(filePath, model);
await presenter.ProcessRequest(request);
return CreateCommandResult(request);
}
private CommandRunResult CreateCommandResult(TestDotvvmRequestContext request)
{
return new CommandRunResult(
request.ViewModelJson
);
}
private IEnumerable<(DotvvmControl, DotvvmProperty, ICommandBinding)> FindCommands(DotvvmControl view) =>
from control in view.GetThisAndAllDescendants()
from property in control.Properties
let binding = property.Value as ICommandBinding
where binding != null
select (control, property.Key, binding);
private PageRunResult CreatePageResult(TestDotvvmRequestContext context)
{
var htmlOutput = System.Text.Encoding.UTF8.GetString(context.HttpContext.CastTo<TestHttpContext>().Response.Body.ToArray());
var commands = FindCommands(context.View).ToArray();
var headResources = context.View.GetAllDescendants().OfType<FakeHeadResourceLink>().FirstOrDefault()?.CapturedHtml;
var bodyResources = context.View.GetAllDescendants().OfType<FakeBodyResourceLink>().FirstOrDefault()?.CapturedHtml;
var p = new HtmlParser();
var htmlDocument = p.ParseDocument(htmlOutput);
foreach (var el in htmlDocument.All)
{
// order attributes by name
var attrs = el.Attributes.OrderBy(a => a.Name).ToArray();
foreach (var attr in attrs) el.RemoveAttribute(attr.NamespaceUri!, attr.LocalName);
foreach (var attr in attrs) el.SetAttribute(attr.NamespaceUri!, attr.LocalName, attr.Value);
}
return new PageRunResult(
this,
context.Route.VirtualPath,
context.ViewModelJson,
htmlOutput,
headResources,
bodyResources,
htmlDocument,
commands
);
}
}
public class CommandRunResult
{
public CommandRunResult(JObject resultJson)
{
this.ResultJson = resultJson;
}
public JObject ResultJson { get; }
public JObject? ViewModelJson => ResultJson["viewModel"] as JObject ?? ResultJson["viewModelDiff"] as JObject;
}
public class PostbackRequestModel
{
public PostbackRequestModel(
JObject viewModel,
string[] currentPath,
string command,
string? controlUniqueId,
object[] commandArgs,
string? validationTargetPath
)
{
ViewModel = viewModel;
CurrentPath = currentPath;
Command = command;
ControlUniqueId = controlUniqueId;
CommandArgs = commandArgs;
ValidationTargetPath = validationTargetPath;
}
[JsonProperty("viewModel")]
public JObject ViewModel { get; }
[JsonProperty("currentPath")]
public string[] CurrentPath { get; }
[JsonProperty("command")]
public string Command { get; }
[JsonProperty("controlUniqueId")]
public string? ControlUniqueId { get; }
[JsonProperty("commandArgs")]
public object[] CommandArgs { get; }
[JsonProperty("validationTargetPath")]
public string? ValidationTargetPath { get; }
}
public class PageRunResult
{
public PageRunResult(
ControlTestHelper testHelper,
string filePath,
JObject resultJson,
string outputString,
string? headResources,
string? bodyResources,
IHtmlDocument html,
(DotvvmControl, DotvvmProperty, ICommandBinding)[] commands
)
{
TestHelper = testHelper;
FilePath = filePath;
this.ResultJson = resultJson;
this.OutputString = outputString;
this.HeadResources = headResources;
this.BodyResources = bodyResources;
this.Html = html;
this.Commands = commands;
}
public ControlTestHelper TestHelper { get; }
public string FilePath { get; }
public JObject ResultJson { get; }
public JObject ViewModelJson => (JObject)ResultJson["viewModel"];
public dynamic ViewModel => ViewModelJson;
public string OutputString { get; }
public string? HeadResources { get; }
public string? BodyResources { get; }
public IHtmlDocument Html { get; }
public (DotvvmControl control, DotvvmProperty property, ICommandBinding command)[] Commands { get; }
public string FormattedHtml
{
get
{
var str = new StringWriter();
Html.ToHtml(str, new PrettyMarkupFormatter() { Indentation = "\t", NewLine = "\n" });
return str.ToString();
}
}
public (DotvvmControl, DotvvmProperty, ICommandBinding) FindCommand(string text, Func<object?, bool>? viewModel = null)
{
viewModel ??= _ => true;
var filtered =
this.Commands
.Where(c => c.command.GetProperty<OriginalStringBindingProperty>(ErrorHandlingMode.ReturnNull)?.Code?.Trim() == text.Trim()
&& (viewModel(c.control.DataContext)))
.ToArray();
if (filtered.Length == 0)
throw new Exception($"Command '{text}' was not found" + (viewModel is null ? "" : $" on viewModel={viewModel}"));
if (filtered.Length > 1)
throw new Exception($"Multiple commands '{text}' were found: " + string.Join(", ", filtered.Select(c => c.command)));
return filtered.Single();
}
public async Task<CommandRunResult> RunCommand(string text, Func<object?, bool>? viewModel = null, bool applyChanges = true, object[]? args = null)
{
var (control, property, binding) = FindCommand(text, viewModel);
if (binding is CommandBindingExpression command)
{
var path = control
.GetAllAncestors(true)
.Select(a => a.GetDataContextPathFragment())
.Where(x => x != null)
.Reverse()
.ToArray();
var viewModelJson = this.ViewModelJson; // TODO: process as on client-side
var r = await this.TestHelper.RunCommand(this.FilePath, new PostbackRequestModel(
viewModelJson,
path!,
command.BindingId,
null,
args ?? new object[0],
KnockoutHelper.GetValidationTargetExpression(control)
));
if (applyChanges)
{
JsonUtils.Patch(
(JObject)this.ResultJson["viewModel"],
r.ViewModelJson!
);
}
return r;
}
else
{
throw new NotSupportedException($"{binding} is not supported.");
}
}
}
public class FakeBodyResourceLink : BodyResourceLinks
{
public string? CapturedHtml { get; private set; }
protected override void RenderControl(IHtmlWriter writer, IDotvvmRequestContext context)
{
var str = new StringWriter();
var fakeWriter = new HtmlWriter(str, context);
base.RenderControl(fakeWriter, context);
this.CapturedHtml = str.ToString();
ResourcesRenderer.RenderResources(context.ResourceManager,
context.ResourceManager.GetNamedResourcesInOrder().Where(r => r.Resource is TemplateResource),
writer, context, ResourceRenderPosition.Body);
}
}
public class FakeHeadResourceLink : HeadResourceLinks
{
public string? CapturedHtml { get; private set; }
protected override void RenderControl(IHtmlWriter writer, IDotvvmRequestContext context)
{
var str = new StringWriter();
var fakeWriter = new HtmlWriter(str, context);
base.RenderControl(fakeWriter, context);
this.CapturedHtml = str.ToString();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis.Values {
internal class ClassInfo : AnalysisValue, IReferenceableContainer, IHasRichDescription {
private AnalysisUnit _analysisUnit;
private readonly List<IAnalysisSet> _bases;
internal Mro _mro;
private readonly InstanceInfo _instanceInfo;
private ClassScope _scope;
private readonly int _declVersion;
private VariableDef _metaclass;
private ReferenceDict _references;
private VariableDef _subclasses;
private IAnalysisSet _baseSpecialization;
private readonly PythonAnalyzer _projectState;
internal ClassInfo(ClassDefinition klass, AnalysisUnit outerUnit) {
_instanceInfo = new InstanceInfo(this);
_bases = new List<IAnalysisSet>();
_declVersion = outerUnit.ProjectEntry.AnalysisVersion;
_projectState = outerUnit.ProjectState;
_mro = new Mro(this);
}
public override AnalysisUnit AnalysisUnit {
get {
return _analysisUnit;
}
}
internal void SetAnalysisUnit(AnalysisUnit unit) {
Debug.Assert(_analysisUnit == null);
_analysisUnit = unit;
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
if (unit != null) {
return AddCall(node, keywordArgNames, unit, args);
}
return _instanceInfo.SelfSet;
}
private IAnalysisSet AddCall(Node node, NameExpression[] keywordArgNames, AnalysisUnit unit, IAnalysisSet[] args) {
var init = GetMemberNoReferences(node, unit, "__init__", false);
var initArgs = Utils.Concat(_instanceInfo.SelfSet, args);
foreach (var initFunc in init) {
initFunc.Call(node, unit, initArgs, keywordArgNames);
}
// TODO: If we checked for metaclass, we could pass it in as the cls arg here
var n = GetMemberNoReferences(node, unit, "__new__", false);
var newArgs = Utils.Concat(SelfSet, args);
var newResult = AnalysisSet.Empty;
bool anyCustom = false;
foreach (var newFunc in n) {
if (!(newFunc is BuiltinFunctionInfo)) {
anyCustom = true;
}
newResult = newResult.Union(newFunc.Call(node, unit, newArgs, keywordArgNames));
}
if (anyCustom) {
return newResult;
}
if (newResult.Count == 0 || newResult.All(ns => ns.IsOfType(unit.ProjectState.ClassInfos[BuiltinTypeId.Object]))) {
if (_baseSpecialization != null && _baseSpecialization.Count != 0) {
var specializedInstances = _baseSpecialization.Call(
node, unit, args, keywordArgNames
);
var res = (SpecializedInstanceInfo)unit.Scope.GetOrMakeNodeValue(
node,
NodeValueKind.SpecializedInstance,
(node_) => new SpecializedInstanceInfo(this, specializedInstances)
);
res._instances = specializedInstances;
return res;
}
return _instanceInfo.SelfSet;
}
return newResult;
}
public ClassDefinition ClassDefinition {
get { return _analysisUnit.Ast as ClassDefinition; }
}
private static string FormatExpression(Expression baseClass) {
NameExpression ne = baseClass as NameExpression;
if (ne != null) {
return ne.Name;
}
MemberExpression me = baseClass as MemberExpression;
if (me != null) {
string expr = FormatExpression(me.Target);
if (expr != null) {
return expr + "." + me.Name ?? string.Empty;
}
}
return null;
}
public IEnumerable<KeyValuePair<string, string>> GetRichDescription() {
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "class ");
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Name, FullName);
if (ClassDefinition.Bases.Count > 0) {
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "(");
bool comma = false;
foreach (var baseClass in ClassDefinition.Bases) {
if (comma) {
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Comma, ", ");
}
string baseStr = FormatExpression(baseClass.Expression);
if (baseStr != null) {
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Type, baseStr);
}
comma = true;
}
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, ")");
}
var doc = Documentation;
if (!string.IsNullOrWhiteSpace(doc)) {
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.EndOfDeclaration, "\r\n");
yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, doc);
}
}
private string FullName {
get {
var name = ClassDefinition.Name;
for (var stmt = ClassDefinition.Parent; stmt != null; stmt = stmt.Parent) {
if (stmt.IsGlobal) {
name = DeclaringModule.ModuleName + "." + name;
break;
} else if (!string.IsNullOrEmpty(stmt.Name)) {
name = stmt.Name + "." + name;
}
}
return name;
}
}
public override string ShortDescription {
get {
return ClassDefinition.Name;
}
}
public override string Name {
get {
return ClassDefinition.Name;
}
}
public VariableDef SubClasses {
get {
if (_subclasses == null) {
_subclasses = new VariableDef();
}
return _subclasses;
}
}
public VariableDef MetaclassVariable {
get {
return _metaclass;
}
}
public VariableDef GetOrCreateMetaclassVariable() {
if (_metaclass == null) {
_metaclass = new VariableDef();
}
return _metaclass;
}
public override string Documentation {
get {
if (ClassDefinition.Body != null) {
return ClassDefinition.Body.Documentation.TrimDocumentation();
}
return "";
}
}
public override IEnumerable<LocationInfo> Locations {
get {
if (_declVersion == DeclaringModule.AnalysisVersion) {
var start = ClassDefinition.NameExpression.GetStart(ClassDefinition.GlobalParent);
var end = ClassDefinition.GetEnd(ClassDefinition.GlobalParent);
return new[] { new LocationInfo(DeclaringModule.FilePath, start.Line, start.Column, end.Line, end.Column) };
}
return LocationInfo.Empty;
}
}
internal override BuiltinTypeId TypeId {
get {
return BuiltinTypeId.Type;
}
}
public override IPythonType PythonType {
get {
return _projectState.Types[BuiltinTypeId.Type];
}
}
internal override bool IsOfType(IAnalysisSet klass) {
return klass.Contains(_projectState.ClassInfos[BuiltinTypeId.Type]);
}
public override IPythonProjectEntry DeclaringModule {
get {
return _analysisUnit.ProjectEntry;
}
}
public override int DeclaringVersion {
get {
return _declVersion;
}
}
public override IEnumerable<OverloadResult> Overloads {
get {
var result = new List<OverloadResult>();
VariableDef init;
if (Scope.TryGetVariable("__init__", out init)) {
// this type overrides __init__, display that for it's help
foreach (var initFunc in init.TypesNoCopy) {
foreach (var overload in initFunc.Overloads) {
result.Add(GetInitOverloadResult(overload));
}
}
}
VariableDef @new;
if (Scope.TryGetVariable("__new__", out @new)) {
foreach (var newFunc in @new.TypesNoCopy) {
foreach (var overload in newFunc.Overloads) {
result.Add(GetNewOverloadResult(overload));
}
}
}
if (result.Count == 0) {
foreach (var baseClass in _bases) {
foreach (var ns in baseClass) {
if (ns.TypeId == BuiltinTypeId.Object) {
continue;
}
if (ns.Push()) {
try {
foreach (var overload in ns.Overloads) {
result.Add(
new SimpleOverloadResult(
overload.Parameters,
ClassDefinition.Name,
overload.Documentation
)
);
}
} finally {
ns.Pop();
}
}
}
}
}
if (result.Count == 0) {
// Old style class?
result.Add(new SimpleOverloadResult(new ParameterResult[0], ClassDefinition.Name, ClassDefinition.Body.Documentation.TrimDocumentation()));
}
// TODO: Filter out duplicates?
return result;
}
}
private SimpleOverloadResult GetNewOverloadResult(OverloadResult overload) {
var doc = overload.Documentation;
return new SimpleOverloadResult(
overload.Parameters.RemoveFirst(),
ClassDefinition.Name,
String.IsNullOrEmpty(doc) ? Documentation : doc
);
}
private SimpleOverloadResult GetInitOverloadResult(OverloadResult overload) {
var doc = overload.Documentation;
return new SimpleOverloadResult(
overload.Parameters.RemoveFirst(),
ClassDefinition.Name,
String.IsNullOrEmpty(doc) ? Documentation : doc
);
}
public IEnumerable<IAnalysisSet> Bases {
get {
return _bases;
}
}
public override IEnumerable<IAnalysisSet> Mro {
get {
return _mro;
}
}
public void SetBases(IEnumerable<IAnalysisSet> bases) {
_bases.Clear();
_bases.AddRange(bases);
_mro.Recompute();
RecomputeBaseSpecialization();
}
private void RecomputeBaseSpecialization() {
IAnalysisSet builtinClassSet = AnalysisSet.Empty;
foreach (var classInfo in _mro) {
BuiltinClassInfo builtin = classInfo as BuiltinClassInfo;
if (builtin != null && builtin.TypeId != BuiltinTypeId.Object) {
var builtinType = _projectState.GetBuiltinType(builtin.PythonType);
if (builtinType.GetType() != typeof(BuiltinClassInfo)) {
// we have a specialized built-in class, we want its behavior too...
builtinClassSet = builtinClassSet.Union(builtinType.SelfSet, true);
}
}
}
_baseSpecialization = builtinClassSet;
}
public void SetBase(int index, IAnalysisSet baseSet) {
while (index >= _bases.Count) {
_bases.Add(AnalysisSet.Empty);
}
_bases[index] = baseSet;
_mro.Recompute();
RecomputeBaseSpecialization();
}
public InstanceInfo Instance {
get {
return _instanceInfo;
}
}
public override IAnalysisSet GetInstanceType() {
return Instance;
}
/// <summary>
/// Gets all members of this class that are not inherited from its base classes.
/// </summary>
public IDictionary<string, IAnalysisSet> GetAllImmediateMembers(IModuleContext moduleContext, GetMemberOptions options) {
var result = new Dictionary<string, IAnalysisSet>(Scope.VariableCount);
foreach (var v in Scope.AllVariables) {
v.Value.ClearOldValues();
if (v.Value.VariableStillExists) {
result[v.Key] = v.Value.Types;
}
}
if (!options.HasFlag(GetMemberOptions.DeclaredOnly)) {
if (!result.ContainsKey("__doc__")) {
result["__doc__"] = GetObjectMember(moduleContext, "__doc__");
}
if (!result.ContainsKey("__class__")) {
result["__class__"] = GetObjectMember(moduleContext, "__class__");
}
}
return result;
}
public override IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext, GetMemberOptions options = GetMemberOptions.None) {
IDictionary<string, IAnalysisSet> result;
if (options.HasFlag(GetMemberOptions.DeclaredOnly)) {
result = GetAllImmediateMembers(moduleContext, options);
} else {
result = _mro.GetAllMembers(moduleContext, options);
}
if (_metaclass != null) {
foreach (var type in _metaclass.Types) {
if (type.Push()) {
try {
foreach (var nameValue in type.GetAllMembers(moduleContext)) {
result[nameValue.Key] = nameValue.Value.GetDescriptor(null, this, type, Instance.ProjectState._evalUnit);
}
} finally {
type.Pop();
}
}
}
}
return result;
}
private AnalysisValue GetObjectMember(IModuleContext moduleContext, string name) {
return _analysisUnit.ProjectState.GetAnalysisValueFromObjects(_analysisUnit.ProjectState.Types[BuiltinTypeId.Object].GetMember(moduleContext, name));
}
internal override void AddReference(Node node, AnalysisUnit unit) {
if (!unit.ForEval) {
if (_references == null) {
_references = new ReferenceDict();
}
_references.GetReferences(unit.DeclaringModule.ProjectEntry).AddReference(new EncodedLocation(unit, node));
}
}
public override IAnalysisSet GetTypeMember(Node node, AnalysisUnit unit, string name) {
return GetMemberNoReferences(node, unit, name).GetDescriptor(node, unit.ProjectState._noneInst, this, unit);
}
/// <summary>
/// Get the member of this class by name that is not inherited from one of its base classes.
/// </summary>
public IAnalysisSet GetImmediateMemberNoReferences(Node node, AnalysisUnit unit, string name, bool addRef = true) {
var result = AnalysisSet.Empty;
var v = Scope.GetVariable(node, unit, name, addRef);
if (v != null) {
result = v.Types;
}
return result;
}
public IAnalysisSet GetMemberNoReferences(Node node, AnalysisUnit unit, string name, bool addRef = true) {
var result = _mro.GetMemberNoReferences(node, unit, name, addRef);
if (result != null && result.Count > 0) {
return result;
}
if (_metaclass != null) {
foreach (var type in _metaclass.Types) {
if (type.Push()) {
try {
foreach (var metaValue in type.GetMember(node, unit, name)) {
foreach (var boundValue in metaValue.GetDescriptor(node, this, type, unit)) {
result = result.Union(boundValue);
}
}
} finally {
type.Pop();
}
}
}
if (result != null && result.Count > 0) {
return result;
}
}
return GetOldStyleMember(name, unit.DeclaringModule.InterpreterContext);
}
private IAnalysisSet GetOldStyleMember(string name, IModuleContext context) {
switch (name) {
case "__doc__":
case "__class__":
return GetObjectMember(context, name).SelfSet;
}
return AnalysisSet.Empty;
}
public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) {
var variable = Scope.CreateVariable(node, unit, name, false);
variable.AddAssignment(node, unit);
variable.AddTypes(unit, value);
}
public override void DeleteMember(Node node, AnalysisUnit unit, string name) {
var v = Scope.GetVariable(node, unit, name);
if (v != null) {
v.AddReference(node, unit);
}
}
public override PythonMemberType MemberType {
get {
return PythonMemberType.Class;
}
}
public override string ToString() {
return "user class " + _analysisUnit.FullName + " (" + _declVersion + ")";
}
public ClassScope Scope {
get { return _scope; }
set {
// Scope should only be set once
Debug.Assert(_scope == null);
_scope = value;
}
}
/// <summary>
/// Provides a stable ordering of class definitions that is used solely
/// to ensure that unioning two classes is symmetrical.
///
/// Otherwise, classes C and D would be merged asymmetrically:
///
/// class A: pass
/// class B: pass
/// class C(A, B): pass
/// class D(B, A): pass
/// </summary>
/// <remarks>
/// This does not have to be 100% reliable in order to avoid breaking
/// the analysis (except when FULL_VALIDATION is active). It is also
/// called very often, so there is more to be lost by making it robust
/// and slow.
///
/// The current implementation will break only when two classes are
/// defined with the same name at the same character index in two
/// different files and with problematic MROs.
/// </remarks>
private static bool IsFirstForMroUnion(ClassDefinition cd1, ClassDefinition cd2) {
if (cd1.StartIndex != cd2.StartIndex) {
return cd1.StartIndex > cd2.StartIndex;
}
return cd1.NameExpression.Name.CompareTo(cd2.NameExpression.Name) > 0;
}
internal override AnalysisValue UnionMergeTypes(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
return _projectState.ClassInfos[BuiltinTypeId.Type];
} else if (strength >= MergeStrength.ToBaseClass) {
var ci = ns as ClassInfo;
if (ci != null) {
IEnumerable<AnalysisValue> mro1;
AnalysisValue[] mro2;
if (IsFirstForMroUnion(ClassDefinition, ci.ClassDefinition)) {
mro1 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
} else {
mro1 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
}
return mro1.FirstOrDefault(cls => mro2.Contains(cls)) ?? _projectState.ClassInfos[BuiltinTypeId.Object];
}
var bci = ns as BuiltinClassInfo;
if (bci != null) {
return bci;
}
}
return base.UnionMergeTypes(ns, strength);
}
internal override bool UnionEquals(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
var type = _projectState.ClassInfos[BuiltinTypeId.Type];
return ns is ClassInfo || ns is BuiltinClassInfo || ns == type || ns == type.Instance;
} else if (strength >= MergeStrength.ToBaseClass) {
var ci = ns as ClassInfo;
if (ci != null) {
IEnumerable<AnalysisValue> mro1;
AnalysisValue[] mro2;
if (IsFirstForMroUnion(ClassDefinition, ci.ClassDefinition)) {
mro1 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
} else {
mro1 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
}
return mro1.Any(cls => mro2.Contains(cls));
}
var bci = ns as BuiltinClassInfo;
if (bci != null &&
!_projectState.DoNotUnionInMro.Contains(this) &&
!_projectState.DoNotUnionInMro.Contains(bci)) {
return Mro.Any(m => m.Contains(bci));
}
}
return base.UnionEquals(ns, strength);
}
internal override int UnionHashCode(int strength) {
if (strength >= MergeStrength.ToBaseClass) {
return _projectState.ClassInfos[BuiltinTypeId.Type].GetHashCode();
}
return base.UnionHashCode(strength);
}
#region IVariableDefContainer Members
public IEnumerable<IReferenceable> GetDefinitions(string name) {
var result = new List<IReferenceable>();
VariableDef def;
if (_scope.TryGetVariable(name, out def)) {
result.Add(def);
}
if (Push()) {
try {
result.AddRange(Bases.SelectMany(b => GetDefinitions(name, b)));
result.AddRange(GetDefinitions(name, SubClasses.TypesNoCopy));
} finally {
Pop();
}
}
return result;
}
private IEnumerable<IReferenceable> GetDefinitions(string name, IEnumerable<AnalysisValue> nses) {
var result = new List<IReferenceable>();
foreach (var subType in nses) {
if (subType.Push()) {
IReferenceableContainer container = subType as IReferenceableContainer;
if (container != null) {
result.AddRange(container.GetDefinitions(name));
}
subType.Pop();
}
}
return result;
}
#endregion
#region IReferenceable Members
internal override IEnumerable<LocationInfo> References {
get {
if (_references != null) {
return _references.AllReferences;
}
return new LocationInfo[0];
}
}
#endregion
}
/// <summary>
/// Represents the method resolution order of a Python class according to C3 rules.
/// </summary>
/// <remarks>
/// The rules are described in detail at http://www.python.org/download/releases/2.3/mro/
/// </remarks>
internal class Mro : DependentData, IEnumerable<IAnalysisSet> {
private readonly ClassInfo _classInfo;
private List<AnalysisValue> _mroList;
private bool _isValid = true;
public Mro(ClassInfo classInfo) {
_classInfo = classInfo;
_mroList = new List<AnalysisValue> { classInfo };
}
public bool IsValid {
get { return _isValid; }
}
public IEnumerator<IAnalysisSet> GetEnumerator() {
return _mroList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void Recompute() {
var mroList = new List<AnalysisValue> { _classInfo };
var isValid = true;
var bases = _classInfo.Bases;
if (bases.Any()) {
var mergeList = new List<List<AnalysisValue>>();
var finalMro = new List<AnalysisValue>();
foreach (var baseClass in bases.SelectMany()) {
var klass = baseClass as ClassInfo;
var builtInClass = baseClass as BuiltinClassInfo;
if (klass != null && klass.Push()) {
try {
if (!klass._mro.IsValid) {
isValid = false;
break;
}
finalMro.Add(klass);
mergeList.Add(klass.Mro.SelectMany().ToList());
} finally {
klass.Pop();
}
} else if (builtInClass != null && builtInClass.Push()) {
try {
finalMro.Add(builtInClass);
mergeList.Add(builtInClass.Mro.SelectMany().ToList());
} finally {
builtInClass.Pop();
}
}
}
if (isValid) {
mergeList.Add(finalMro);
mergeList.RemoveAll(mro => mro.Count == 0);
while (mergeList.Count > 0) {
AnalysisValue nextInMro = null;
for (int i = 0; i < mergeList.Count; ++i) {
// Select candidate head
var candidate = mergeList[i][0];
// Look for the candidate in the tails of every other MRO
if (!mergeList.Any(baseMro => baseMro.Skip(1).Contains(candidate))) {
// Candidate is good, so stop searching.
nextInMro = candidate;
break;
}
}
// No valid MRO for this class
if (nextInMro == null) {
isValid = false;
break;
}
mroList.Add(nextInMro);
// Remove all instances of that class from potentially being returned again
foreach (var mro in mergeList) {
mro.RemoveAll(ns => ns == nextInMro);
}
// Remove all lists that are now empty.
mergeList.RemoveAll(mro => mro.Count == 0);
}
}
}
// If the MRO is invalid, we only want the class itself to be there so that we
// will show all members defined in it, but nothing else.
if (!isValid) {
mroList.Clear();
mroList.Add(_classInfo);
}
if (_isValid != isValid || !_mroList.SequenceEqual(mroList)) {
_isValid = isValid;
_mroList = mroList;
EnqueueDependents();
}
}
public IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext, GetMemberOptions options) {
return GetAllMembersOfMro(this, moduleContext, options);
}
/// <summary>
/// Compute a list of all members, given the MRO list of types, and taking override rules into account.
/// </summary>
public static IDictionary<string, IAnalysisSet> GetAllMembersOfMro(IEnumerable<IAnalysisSet> mro, IModuleContext moduleContext, GetMemberOptions options) {
var result = new Dictionary<string, IAnalysisSet>();
// MRO is a list of namespaces corresponding to classes, but each entry can be a union of several different classes.
// Therefore, within a single entry, we want to make a union of members from each; but between entries, we
// want the first entry in MRO to suppress any members with the same names from the following entries.
foreach (var entry in mro) {
var entryMembers = new Dictionary<string, IAnalysisSet>();
foreach (var ns in entry) {
// If it's another non-builtin class, we don't want its inherited members, since we'll account
// for them while processing our own MRO - we only want its immediate members.
var classInfo = ns as ClassInfo;
var classMembers = classInfo != null ? classInfo.GetAllImmediateMembers(moduleContext, options) : ns.GetAllMembers(moduleContext);
foreach (var kvp in classMembers) {
IAnalysisSet existing;
if (!entryMembers.TryGetValue(kvp.Key, out existing)) {
entryMembers[kvp.Key] = kvp.Value;
} else {
entryMembers[kvp.Key] = existing.Union(kvp.Value);
}
}
}
foreach (var member in entryMembers) {
if (!result.ContainsKey(member.Key)) {
result.Add(member.Key, member.Value);
}
}
}
return result;
}
public IAnalysisSet GetMemberNoReferences(Node node, AnalysisUnit unit, string name, bool addRef = true) {
return GetMemberFromMroNoReferences(this, node, unit, name, addRef);
}
/// <summary>
/// Get the member by name, given the MRO list, and taking override rules into account.
/// </summary>
public static IAnalysisSet GetMemberFromMroNoReferences(IEnumerable<IAnalysisSet> mro, Node node, AnalysisUnit unit, string name, bool addRef = true) {
if (mro == null) {
return AnalysisSet.Empty;
}
// Union all members within a single MRO entry, but stop at the first entry that yields a non-empty set since it overrides any that follow.
var result = AnalysisSet.Empty;
foreach (var mroEntry in mro) {
foreach (var ns in mroEntry) {
var classInfo = ns as ClassInfo;
if (classInfo != null) {
var v = classInfo.Scope.GetVariable(node, unit, name, addRef);
if (v != null) {
result = result.Union(v.Types);
}
} else {
result = result.Union(ns.GetMember(node, unit, name));
}
}
if (result != null && result.Count > 0) {
break;
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using Cosmos.Common;
using Cosmos.Core;
using Cosmos.Core.IOGroup.Network;
using Cosmos.HAL.Network;
using IL2CPU.API.Attribs;
namespace Cosmos.HAL.Drivers.PCI.Network
{
public class AMDPCNetII : NetworkDevice
{
protected PCIDeviceNormal pciCard;
protected AMDPCNetIIIOGroup io;
protected MACAddress mac;
protected bool mInitDone;
protected ManagedMemoryBlock mInitBlock;
protected ManagedMemoryBlock mRxDescriptor;
protected ManagedMemoryBlock mTxDescriptor;
protected List<ManagedMemoryBlock> mRxBuffers;
protected List<ManagedMemoryBlock> mTxBuffers;
protected Queue<byte[]> mRecvBuffer;
protected Queue<byte[]> mTransmitBuffer;
private int mNextTXDesc;
public AMDPCNetII(PCIDeviceNormal device)
: base()
{
if (device == null)
{
throw new ArgumentException("PCI Device is null. Unable to get AMD PCNet card");
}
this.pciCard = device;
// this.pciCard.Claimed = true;
//this.pciCard.EnableDevice();
//this.io = new AMDPCNetIIIOGroup((ushort) this.pciCard.BaseAddresses[0].BaseAddress());
this.io.RegisterData.DWord = 0;
// Get the EEPROM MAC Address and set it as the devices MAC
byte[] eeprom_mac = new byte[6];
UInt32 result = io.MAC1.DWord;
eeprom_mac[0] = BinaryHelper.GetByteFrom32bit(result, 0);
eeprom_mac[1] = BinaryHelper.GetByteFrom32bit(result, 8);
eeprom_mac[2] = BinaryHelper.GetByteFrom32bit(result, 16);
eeprom_mac[3] = BinaryHelper.GetByteFrom32bit(result, 24);
result = io.MAC2.DWord;
eeprom_mac[4] = BinaryHelper.GetByteFrom32bit(result, 0);
eeprom_mac[5] = BinaryHelper.GetByteFrom32bit(result, 8);
mac = new MACAddress(eeprom_mac);
mInitBlock = new ManagedMemoryBlock(28, 4);
mRxDescriptor = new ManagedMemoryBlock(256, 16);
mTxDescriptor = new ManagedMemoryBlock(256, 16);
mInitBlock.Write32(0x00, (0x4 << 28) | (0x4 << 20));
mInitBlock.Write32(0x04,
(UInt32) (eeprom_mac[0] | (eeprom_mac[1] << 8) | (eeprom_mac[2] << 16) | (eeprom_mac[3] << 24)));
mInitBlock.Write32(0x08, (UInt32) (eeprom_mac[4] | (eeprom_mac[5] << 8)));
mInitBlock.Write32(0x0C, 0x0);
mInitBlock.Write32(0x10, 0x0);
mInitBlock.Write32(0x14, mRxDescriptor.Offset);
mInitBlock.Write32(0x18, mTxDescriptor.Offset);
InitializationBlockAddress = mInitBlock.Offset;
SoftwareStyleRegister = 0x03;
mRxBuffers = new List<ManagedMemoryBlock>();
mTxBuffers = new List<ManagedMemoryBlock>();
for (uint rxd = 0; rxd < 16; rxd++)
{
uint xOffset = rxd * 16;
ManagedMemoryBlock buffer = new ManagedMemoryBlock(2048);
mRxDescriptor.Write32(xOffset + 8, buffer.Offset);
UInt16 buffer_len = (UInt16) (~buffer.Size);
buffer_len++;
UInt32 flags = (UInt32) (buffer_len & 0x0FFF) | 0xF000 | 0x80000000;
mRxDescriptor.Write32(xOffset + 4, flags);
mRxBuffers.Add(buffer);
}
for (uint txd = 0; txd < 16; txd++)
{
uint xOffset = txd * 16;
ManagedMemoryBlock buffer = new ManagedMemoryBlock(2048);
mTxDescriptor.Write32(xOffset + 8, buffer.Offset);
mTxBuffers.Add(buffer);
}
mNextTXDesc = 0;
// Setup our Receive and Transmit Queues
mTransmitBuffer = new Queue<byte[]>();
mRecvBuffer = new Queue<byte[]>();
//INTs.SetIrqHandler(device.InterruptLine, HandleNetworkInterrupt);
}
protected void HandleNetworkInterrupt(ref INTs.IRQContext aContext)
{
UInt32 cur_status = StatusRegister;
//Console.WriteLine("AMD PCNet IRQ raised!");
if ((cur_status & 0x100) != 0)
{
mInitDone = true;
}
if ((cur_status & 0x200) != 0)
{
if (mTransmitBuffer.Count > 0)
{
byte[] data = mTransmitBuffer.Peek();
if (SendBytes(ref data) == true)
{
mTransmitBuffer.Dequeue();
}
}
}
if ((cur_status & 0x400) != 0)
{
ReadRawData();
}
StatusRegister = cur_status;
Cosmos.Core.Global.PIC.EoiSlave();
}
/// <summary>
/// Retrieve all AMD PCNetII network cards found on computer.
/// </summary>
public static void FindAll()
{
Console.WriteLine("Scanning for AMD PCNetII cards...");
// PCIDevice device = Cosmos.HAL.PCI.GetDevice(VendorID.AMD, DeviceID.PCNETII);
// if (device != null)
// {
// AMDPCNetII nic = new AMDPCNetII((PCIDeviceNormal) device);
//
// Console.WriteLine("Found AMD PCNetII NIC on PCI " + device.bus + ":" + device.slot + ":" +
// device.function);
// Console.WriteLine("NIC IRQ: " + device.InterruptLine);
// Console.WriteLine("NIC MAC Address: " + nic.MACAddress.ToString());
// }
}
#region Register Access Properties
protected UInt32 StatusRegister
{
get
{
io.RegisterAddress.DWord = 0x00;
return io.RegisterData.DWord;
}
set
{
io.RegisterAddress.DWord = 0x00;
io.RegisterData.DWord = value;
}
}
protected UInt32 InitializationBlockAddress
{
get
{
UInt32 result;
io.RegisterAddress.DWord = 0x01;
result = io.RegisterData.DWord;
io.RegisterAddress.DWord = 0x02;
result |= (io.RegisterData.DWord << 16);
return result;
}
set
{
io.RegisterAddress.DWord = 0x01;
io.RegisterData.DWord = (value & 0xFFFF);
io.RegisterAddress.DWord = 0x02;
io.RegisterData.DWord = (value >> 16);
}
}
protected UInt32 SoftwareStyleRegister
{
get
{
io.RegisterAddress.DWord = 0x14;
return io.BusData.DWord;
}
set
{
io.RegisterAddress.DWord = 0x14;
io.BusData.DWord = value;
}
}
#endregion
#region Network Device Implementation
public override MACAddress MACAddress
{
get { return mac; }
}
public override bool Ready
{
get { return mInitDone; }
}
public override bool Enable()
{
StatusRegister = 0x43;
return true;
}
[DebugStub(Off = true)]
public override bool QueueBytes(byte[] buffer, int offset, int length)
{
byte[] data = new byte[length];
for (int b = 0; b < length; b++)
{
data[b] = buffer[b + offset];
}
if (SendBytes(ref data) == false)
{
mTransmitBuffer.Enqueue(data);
}
return true;
}
public override bool ReceiveBytes(byte[] buffer, int offset, int max)
{
throw new NotImplementedException();
}
public override byte[] ReceivePacket()
{
if (mRecvBuffer.Count < 1)
{
return null;
}
byte[] data = mRecvBuffer.Dequeue();
return data;
}
public override int BytesAvailable()
{
if (mRecvBuffer.Count < 1)
{
return 0;
}
return mRecvBuffer.Peek().Length;
}
public override bool IsSendBufferFull()
{
return false;
}
public override bool IsReceiveBufferFull()
{
return false;
}
#endregion
#region Helper Functions
[DebugStub(Off = true)]
protected bool SendBytes(ref byte[] aData)
{
int txd = mNextTXDesc++;
if (mNextTXDesc >= 16)
{
mNextTXDesc = 0;
}
uint xOffset = (uint) (txd * 16);
UInt32 status = mTxDescriptor.Read32(xOffset + 4);
if ((status & 0x80000000) == 0)
{
for (uint b = 0; b < aData.Length; b++)
{
mTxBuffers[txd][b] = aData[b];
}
//UInt16 buffer_len = (UInt16)(aData.Length < 64 ? 64 : aData.Length);
UInt16 buffer_len = (UInt16) aData.Length;
buffer_len = (UInt16) (~buffer_len);
buffer_len++;
UInt32 flags = (UInt32) ((buffer_len) & 0x0FFF) | 0x0300F000 | 0x80000000;
mTxDescriptor.Write32(xOffset + 4, flags);
return true;
}
return false;
}
[DebugStub(Off = true)]
private void ReadRawData()
{
uint status;
UInt16 recv_size;
byte[] recv_data;
for (int rxd = 0; rxd < 16; rxd++)
{
uint xOffset = (uint) (rxd * 16);
status = mRxDescriptor.Read32(xOffset + 4);
if ((status & 0x80000000) == 0)
{
recv_size = (UInt16) (mRxDescriptor[xOffset + 0] & 0xFFF);
recv_data = new byte[recv_size];
for (uint b = 0; b < recv_size; b++)
{
recv_data[b] = mRxBuffers[rxd][b];
}
if (DataReceived != null)
{
DataReceived(recv_data);
}
else
{
mRecvBuffer.Enqueue(recv_data);
}
mRxDescriptor.Write32(xOffset + 4, status | 0x80000000);
}
}
}
#endregion
}
}
| |
// Copyright (C) 2009-2017 Luca Piccioni
//
// 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.
// ReSharper disable InconsistentNaming
using System;
namespace OpenGL
{
/// <summary>
/// Quaternion.
/// </summary>
/// <remarks>
/// <para>
/// Quaternion are used to represents a rotation in a three-dimensional space.
/// </para>
/// <para>
/// Theory links:
/// - http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
/// - http://en.wikipedia.org/wiki/Rotation_representation
/// </para>
/// </remarks>
public struct Quaternion
{
#region Constructors
/// <summary>
/// Construct a Quaternion from quaternion components.
/// </summary>
/// <param name="q1">
/// A <see cref="double"/> that specify the quaternion component <i>q1</i>.
/// </param>
/// <param name="q2">
/// A <see cref="double"/> that specify the quaternion component <i>q2</i>.
/// </param>
/// <param name="q3">
/// A <see cref="double"/> that specify the quaternion component <i>q3</i>.
/// </param>
/// <param name="q4">
/// A <see cref="double"/> that specify the quaternion component <i>q4</i> (scalar component).
/// </param>
public Quaternion(double q1, double q2, double q3, double q4)
{
// Set the default rotation axis
_DefaultVector = Vertex3d.UnitY;
// Setup quaternion components
_Vector.x = q1;
_Vector.y = q2;
_Vector.z = q3;
_CosAngle = q4;
// Derive default rotation vector (due quaternion definition)
_DefaultVector = RotationVector;
}
/// <summary>
/// Quaternion constructor from euler rotation axis and rotation angle.
/// </summary>
/// <param name="rVector">
/// A <see cref="Vertex3d"/> representing the rotation axis.
/// </param>
/// <param name="rAngle">
/// A <see cref="float"/> representing the rotation angle (in degrees).
/// </param>
/// <remarks>
/// This constructor is the base implementation for each other constructor.
/// </remarks>
public Quaternion(Vertex3f rVector, float rAngle)
{
// Set the default rotation axis
_DefaultVector = rVector;
// Make compiler happy
_Vector = new Vertex3d();
_CosAngle = 0.0f;
// Set quaternion
SetEuler(rVector, rAngle);
}
/// <summary>
/// Quaternion constructor from euler rotation axis and rotation angle.
/// </summary>
/// <param name="other">
/// A <see cref="Quaternion"/> representing the rotation axis.
/// </param>
public Quaternion(Quaternion other)
{
// Set the default rotation axis
_DefaultVector = other._DefaultVector;
// Copy quaternion fields
_Vector = other._Vector;
_CosAngle = other._CosAngle;
}
#endregion
#region Structure
/// <summary>
/// The default rotation axis used by this quaternion when it is an identity.
/// </summary>
private Vertex3d _DefaultVector;
/// <summary>
/// Quaternion vector values.
/// </summary>
/// <remarks>
/// If the quaternion is defined as a vector {q1, q2, q3, q4}, this field corresponds to the
/// vector component {q1, q2, q3}. This is not actually a vector!
/// </remarks>
private Vertex3d _Vector;
/// <summary>
/// Quaternion "scalar" component.
/// </summary>
/// <remarks>
/// If the quaternion is defined as a vector {q1, q2, q3, q4}, this field corresponds to the
/// scalar component q4. This is not actually an angle!
/// </remarks>
private double _CosAngle;
#endregion
#region Euler Definitions
/// <summary>
/// Get or set the quaternion rotation unit vector.
/// </summary>
public Vertex3f RotationVector
{
get
{
if (_Vector.ModuleSquared() >= float.Epsilon)
_DefaultVector = _Vector.Normalized;
return (Vertex3f)_DefaultVector;
}
set { SetEuler(value, RotationAngle); }
}
/// <summary>
/// Get or set the quaternion rotation angle (in degrees).
/// </summary>
public float RotationAngle
{
get { return (float)Angle.ToDegrees(2.0 * Math.Acos(_CosAngle)); }
set { SetEuler(RotationVector, value); }
}
/// <summary>
/// Set quaternion using rotation axis and rotation angle.
/// </summary>
/// <param name="rVector">
/// A <see cref="Vertex3d"/> representing the rotation axis. It will be normalized.
/// </param>
/// <param name="rAngle">
/// A <see cref="float"/> representing the rotation angle (in degrees).
/// </param>
/// <remarks>
/// This quaternion will result normalized.
/// </remarks>
public void SetEuler(Vertex3f rVector, float rAngle)
{
double qAngle = Angle.ToRadians(rAngle / 2.0f);
double qAngleSin = Math.Sin(qAngle);
_Vector.x = qAngleSin * rVector.x;
_Vector.y = qAngleSin * rVector.y;
_Vector.z = qAngleSin * rVector.z;
_CosAngle = Math.Cos(qAngle);
// Ensure normalized quaternion
Normalize();
}
#endregion
#region Quaternion Properties
/// <summary>
/// Quaternion <i>q1</i> component.
/// </summary>
public float X { get { return (float)_Vector.x; } set { _Vector.x = value; } }
/// <summary>
/// Quaternion <i>q2</i> component.
/// </summary>
public float Y { get { return (float)_Vector.y; } set { _Vector.y = value; } }
/// <summary>
/// Quaternion <i>q3</i> component.
/// </summary>
public float Z { get { return (float)_Vector.z; } set { _Vector.z = value; } }
/// <summary>
/// Quaternion <i>q4</i> component.
/// </summary>
public float W { get { return (float)_CosAngle; } set { _CosAngle = value; } }
/// <summary>
/// Compute this Quaternion magnitude.
/// </summary>
public double Magnitude
{
get {
double x2 = _Vector.x * _Vector.x;
double y2 = _Vector.y * _Vector.y;
double z2 = _Vector.z * _Vector.z;
double w2 = _CosAngle * _CosAngle;
return Math.Sqrt(x2 + y2 + z2 + w2);
}
}
/// <summary>
/// Determine whether this quaternion is identity (no rotation).
/// </summary>
public bool IsIdentity
{
get
{
if (Math.Abs(_Vector.Module()) >= float.Epsilon)
return false;
if (Math.Abs(_CosAngle - 1.0f) >= float.Epsilon)
return false;
return true;
}
}
/// <summary>
/// Determine whether this quaternion is normalized.
/// </summary>
public bool IsNormalized
{
get { return Math.Abs(Magnitude - 1.0) < float.Epsilon; }
}
#endregion
#region Quaternion Operations
/// <summary>
/// Normalize this Quaternion.
/// </summary>
public void Normalize()
{
double magnitude = Magnitude;
if (magnitude >= float.Epsilon) {
double scale = 1.0 / magnitude;
_Vector *= scale;
_CosAngle *= scale;
} else
throw new InvalidOperationException("zero magnitude quaternion");
}
/// <summary>
/// Conjugate this Quaternion.
/// </summary>
public void Conjugate()
{
_Vector = -_Vector;
}
/// <summary>
/// Get the conjugate of this Quaternion.
/// </summary>
public Quaternion Conjugated
{
get
{
Quaternion conjugate = new Quaternion(this);
conjugate._Vector = -conjugate._Vector;
return conjugate;
}
}
#endregion
#region Arithmetich Operators
/// <summary>
/// Quaternion multiplication (concatenate rotations).
/// </summary>
/// <param name="q1">
/// A <see cref="Quaternion"/> representing the left multiplication operand. This rotation is the "starting" state.
/// </param>
/// <param name="q2">
/// A <see cref="Quaternion"/> representing the right multiplication operand. This rotation is applied to <paramref name="q1"/>.
/// </param>
/// <returns>
/// It returns the multiplication between two quaternions.
/// </returns>
public static Quaternion operator *(Quaternion q1, Quaternion q2)
{
// double x1 = q1.mVector.x, y1 = q1.mVector.y, z1 = q1.mVector.z, w1 = q1.mCosAngle;
// double x2 = q2.mVector.x, y2 = q2.mVector.y, z2 = q2.mVector.z, w2 = q2.mCosAngle;
//
// double _q1 = w2 * x1 + x2 * w1 - y2 * z1 + z2 * y1;
// double _q2 = w2 * y1 + x2 * z1 + y2 * w1 - z2 * x1;
// double _q3 = w2 * z1 - x2 * y1 + y2 * x1 + z2 * w1;
// double _q4 = w2 * w1 - x2 * x1 - y2 * y1 - z2 * z1;
//
// return (new Quaternion(_q1, _q2, _q3, _q4));
double x1 = q1._Vector.x, y1 = q1._Vector.y, z1 = q1._Vector.z, w1 = q1._CosAngle;
double x2 = q2._Vector.x, y2 = q2._Vector.y, z2 = q2._Vector.z, w2 = q2._CosAngle;
double _q1 = w1*x2 + x1*w2 + y1*z2 - z1*y2;
double _q2 = w1*y2 + y1*w2 + x1*z2 - z1*x2;
double _q3 = w1*z2 + z1*w2 + x1*y2 - y1*x2;
double _q4 = w1*w2 - x1*x2 - y1*y2 - z1*z2;
return new Quaternion(_q1, _q2, _q3, _q4);
}
/// <summary>
/// Rotates a vector.
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> representing the rotation.
/// </param>
/// <param name="v">
/// A <see cref="Vertex3f"/> rotating on <paramref name="q"/>.
/// </param>
/// <returns>
/// The rotated <see cref="Vertex3f"/>.
/// </returns>
public static Vertex3f operator *(Quaternion q, Vertex3f v)
{
return (Matrix3x3f)q * v;
}
/// <summary>
/// Rotates a vector.
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> representing the rotation.
/// </param>
/// <param name="v">
/// A <see cref="Vertex3d"/> rotating on <paramref name="q"/>.
/// </param>
/// <returns>
/// The rotated <see cref="Vertex3d"/>.
/// </returns>
public static Vertex3d operator *(Quaternion q, Vertex3d v)
{
return (Matrix3x3d)q * v;
}
/// <summary>
/// Rotates a vector.
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> representing the rotation.
/// </param>
/// <param name="v">
/// A <see cref="Vertex4f"/> rotating on <paramref name="q"/>.
/// </param>
/// <returns>
/// The rotated <see cref="Vertex3f"/>.
/// </returns>
public static Vertex4f operator *(Quaternion q, Vertex4f v)
{
return (Matrix4x4f)q * v;
}
/// <summary>
/// Rotates a vector.
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> representing the rotation.
/// </param>
/// <param name="v">
/// A <see cref="Vertex4d"/> rotating on <paramref name="q"/>.
/// </param>
/// <returns>
/// The rotated <see cref="Vertex4d"/>.
/// </returns>
public static Vertex4d operator *(Quaternion q, Vertex4d v)
{
return (Matrix4x4d)q * v;
}
#endregion
#region Cast Operators
/// <summary>
///
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> to be casted to <see cref="Matrix3x3f"/>.
/// </param>
/// <returns>
/// It returns <see cref="Matrix3x3f"/> representing the equivalent rotation matrix.
/// </returns>
public static explicit operator Matrix3x3f(Quaternion q)
{
Matrix3x3f dcm = new Matrix3x3f(); // Direction cosine matrix
double q1 = q._Vector.x, q2 = q._Vector.y, q3 = q._Vector.z, q4 = q._CosAngle;
double q1__2 = q1*q1, q2__2 = q2*q2, q3__2 = q3*q3;
dcm[0,0] = (float)(1.0f - 2.0f * (q2__2 + q3__2));
dcm[1,0] = (float)( 2.0f * (q1*q2 - q3*q4));
dcm[2,0] = (float)( 2.0f * (q1*q3 + q2*q4));
dcm[0,1] = (float)( 2.0f * (q1*q2 + q3*q4));
dcm[1,1] = (float)(1.0f - 2.0f * (q1__2 + q3__2));
dcm[2,1] = (float)( 2.0f * (q2*q3 - q1*q4));
dcm[0,2] = (float)( 2.0f * (q1*q3 - q2*q4));
dcm[1,2] = (float)( 2.0f * (q1*q4 + q2*q3));
dcm[2,2] = (float)( 1.0f - 2.0f * (q1__2 + q2__2));
return dcm;
}
/// <summary>
///
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> to be casted to <see cref="Matrix3x3d"/>.
/// </param>
/// <returns>
/// It returns <see cref="Matrix3x3d"/> representing the equivalent rotation matrix.
/// </returns>
public static explicit operator Matrix3x3d(Quaternion q)
{
Matrix3x3d dcm = new Matrix3x3d(); // Direction cosine matrix
double q1 = q._Vector.x, q2 = q._Vector.y, q3 = q._Vector.z, q4 = q._CosAngle;
double q1__2 = q1 * q1, q2__2 = q2 * q2, q3__2 = q3 * q3;
dcm[0, 0] = 1.0 - 2.0 * (q2__2 + q3__2);
dcm[1, 0] = 2.0 * (q1 * q2 - q3 * q4);
dcm[2, 0] = 2.0 * (q1 * q3 + q2 * q4);
dcm[0, 1] = 2.0 * (q1 * q2 + q3 * q4);
dcm[1, 1] = 1.0 - 2.0f * (q1__2 + q3__2);
dcm[2, 1] = 2.0 * (q2 * q3 - q1 * q4);
dcm[0, 2] = 2.0 * (q1 * q3 - q2 * q4);
dcm[1, 2] = 2.0 * (q1 * q4 + q2 * q3);
dcm[2, 2] = 1.0 - 2.0f * (q1__2 + q2__2);
return dcm;
}
/// <summary>
///
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> to be casted to <see cref="Matrix4x4f"/>.
/// </param>
/// <returns>
/// It returns <see cref="Matrix4x4f"/> representing the equivalent rotation matrix.
/// </returns>
public static explicit operator Matrix4x4f(Quaternion q)
{
Matrix4x4f dcm = new Matrix4x4f(); // Direction cosine matrix
double q1 = q._Vector.x, q2 = q._Vector.y, q3 = q._Vector.z, q4 = q._CosAngle;
double q1__2 = q1*q1, q2__2 = q2*q2, q3__2 = q3*q3;
dcm[0,0] = (float)(1.0f - 2.0f * (q2__2 + q3__2));
dcm[1,0] = (float)( 2.0f * (q1*q2 - q3*q4));
dcm[2,0] = (float)( 2.0f * (q1*q3 + q2*q4));
dcm[3,0] = 0.0f;
dcm[0,1] = (float)( 2.0f * (q1*q2 + q3*q4));
dcm[1,1] = (float)(1.0f - 2.0f * (q1__2 + q3__2));
dcm[2,1] = (float)( 2.0f * (q2*q3 - q1*q4));
dcm[3,1] = 0.0f;
dcm[0,2] = (float)( 2.0f * (q1*q3 - q2*q4));
dcm[1,2] = (float)( 2.0f * (q1*q4 + q2*q3));
dcm[2,2] = (float)( 1.0f - 2.0f * (q1__2 + q2__2));
dcm[3,2] = 0.0f;
dcm[0,3] = 0.0f;
dcm[1,3] = 0.0f;
dcm[2,3] = 0.0f;
dcm[3,3] = 1.0f;
return dcm;
}
/// <summary>
///
/// </summary>
/// <param name="q">
/// A <see cref="Quaternion"/> to be casted to <see cref="Matrix4x4d"/>.
/// </param>
/// <returns>
/// It returns <see cref="Matrix4x4d"/> representing the equivalent rotation matrix.
/// </returns>
public static explicit operator Matrix4x4d(Quaternion q)
{
Matrix4x4d dcm = new Matrix4x4d(); // Direction cosine matrix
double q1 = q._Vector.x, q2 = q._Vector.y, q3 = q._Vector.z, q4 = q._CosAngle;
double q1__2 = q1 * q1, q2__2 = q2 * q2, q3__2 = q3 * q3;
dcm[0, 0] = 1.0 - 2.0 * (q2__2 + q3__2);
dcm[1, 0] = 2.0 * (q1 * q2 - q3 * q4);
dcm[2, 0] = 2.0 * (q1 * q3 + q2 * q4);
dcm[3, 0] = 0.0;
dcm[0, 1] = 2.0 * (q1 * q2 + q3 * q4);
dcm[1, 1] = 1.0 - 2.0f * (q1__2 + q3__2);
dcm[2, 1] = 2.0 * (q2 * q3 - q1 * q4);
dcm[3, 1] = 0.0;
dcm[0, 2] = 2.0 * (q1 * q3 - q2 * q4);
dcm[1, 2] = 2.0 * (q1 * q4 + q2 * q3);
dcm[2, 2] = 1.0 - 2.0f * (q1__2 + q2__2);
dcm[3, 2] = 0.0;
dcm[0, 3] = 0.0;
dcm[1, 3] = 0.0;
dcm[2, 3] = 0.0;
dcm[3, 3] = 1.0;
return dcm;
}
#endregion
#region Notable Quaternions
/// <summary>
/// Identity quaternion (no rotation).
/// </summary>
public static readonly Quaternion Identity = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
#endregion
#region Object Overrides
/// <summary>
/// Stringify this Quaternion.
/// </summary>
/// <returns>
/// Returns a <see cref="string"/> that represents this Quaternion.
/// </returns>
public override string ToString()
{
return $"Axis: {RotationVector} Angle: {RotationAngle}";
}
#endregion
}
}
| |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using Microsoft.VisualStudio.ProjectSystem;
using Microsoft.VisualStudio.ProjectSystem.Build;
using Microsoft.VisualStudio.Shell;
using nanoFramework.Tools.Debugger;
using nanoFramework.Tools.Debugger.Extensions;
using nanoFramework.Tools.VisualStudio.Extension.Resources;
using System.Reflection;
using nanoFramework.Tools.VisualStudio.Extension.ToolWindow.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using Task = System.Threading.Tasks.Task;
namespace nanoFramework.Tools.VisualStudio.Extension
{
[Export(typeof(IDeployProvider))]
[AppliesTo(NanoCSharpProjectUnconfigured.UniqueCapability)]
internal class DeployProvider : IDeployProvider
{
// number of retries when performing a deploy operation
private const int _numberOfRetries = 5;
// timeout when performing a deploy operation
private const int _timeoutMiliseconds = 1000;
private static ViewModelLocator _viewModelLocator;
private static Package _package;
private static AssemblyInformationalVersionAttribute _informationalVersionAttribute;
/// <summary>
/// Gets the service provider from the owner package.
/// </summary>
private IServiceProvider ServiceProvider { get { return _package; } }
INanoDeviceCommService NanoDeviceCommService { get { return ServiceProvider.GetService(typeof(NanoDeviceCommService)) as INanoDeviceCommService; } }
/// <summary>
/// Provides access to the project's properties.
/// </summary>
[Import]
private ProjectProperties Properties { get; set; }
[Import]
IProjectService ProjectService { get; set; }
[Import]
UnconfiguredProject UnconfiguredProject { get; set; }
[Import]
ConfiguredProject ConfiguredProject { get; set; }
public static void Initialize(AsyncPackage package, ViewModelLocator vmLocator)
{
_package = package;
_viewModelLocator = vmLocator;
// get details about assembly
_informationalVersionAttribute = Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyInformationalVersionAttribute))
as AssemblyInformationalVersionAttribute;
}
public async Task DeployAsync(CancellationToken cancellationToken, TextWriter outputPaneWriter)
{
List<byte[]> assemblies = new List<byte[]>();
string targetFlashDumpFileName = "";
int retryCount = 0;
await Task.Yield();
// output information about assembly running this to help debugging
MessageCentre.InternalErrorWriteLine($"Starting deployment transaction from v{_informationalVersionAttribute.InformationalVersion}");
//... we need to access the project name using reflection (step by step)
// get type for ConfiguredProject
var projSystemType = ConfiguredProject.GetType();
// get private property MSBuildProject
var buildProject = projSystemType.GetTypeInfo().GetDeclaredProperty("MSBuildProject");
// get value of MSBuildProject property from ConfiguredProject object
// this result is of type Microsoft.Build.Evaluation.Project
var projectResult = await ((System.Threading.Tasks.Task<Microsoft.Build.Evaluation.Project>)buildProject.GetValue(Properties.ConfiguredProject));
if (!string.Equals(projectResult.Properties.First(p => p.Name == "OutputType").EvaluatedValue, "Exe", StringComparison.InvariantCultureIgnoreCase))
{
// This is not an executable project, it must be a referenced assembly
MessageCentre.InternalErrorWriteLine($"Skipping deploy for project '{projectResult.FullPath}' because it is not an executable project.");
return;
}
// just in case....
if (_viewModelLocator?.DeviceExplorer.SelectedDevice == null)
{
// can't debug
// throw exception to signal deployment failure
#pragma warning disable S112 // OK to use Exception here
throw new Exception("There is no device selected. Please select a device in Device Explorer tool window.");
#pragma warning restore S112 // General exceptions should never be thrown
}
// get the device here so we are not always carrying the full path to the device
NanoDeviceBase device = NanoDeviceCommService.Device;
// user feedback
await outputPaneWriter.WriteLineAsync($"Getting things ready to deploy assemblies to nanoFramework device: {device.Description}.");
bool needsToCloseMessageOutput = false;
// device needs to be in 'initialized state' for a successful and correct deployment
// meaning that is not running nor stopped
bool deviceIsInInitializeState = false;
try
{
MessageCentre.InternalErrorWriteLine("Starting debug engine on nanoDevice");
// check if debugger engine exists
if (NanoDeviceCommService.Device.DebugEngine == null)
{
NanoDeviceCommService.Device.CreateDebugEngine();
}
await Task.Yield();
var logProgressIndicator = new Progress<string>(MessageCentre.InternalErrorWriteLine);
var progressIndicator = new Progress<MessageWithProgress>((m) => MessageCentre.StartMessageWithProgress(m));
MessageCentre.InternalErrorWrite("Connecting to debug engine...");
needsToCloseMessageOutput = true;
// connect to the device
if (device.DebugEngine.Connect(false, true))
{
needsToCloseMessageOutput = false;
MessageCentre.InternalErrorWriteAndCloseMessage("OK");
// do we have to generate a deployment image?
if (NanoFrameworkPackage.SettingGenerateDeploymentImage)
{
await Task.Run(async delegate
{
targetFlashDumpFileName = await DeploymentImageGenerator.RunPreparationStepsToGenerateDeploymentImageAsync(device, Properties.ConfiguredProject, outputPaneWriter);
});
}
//////////////////////////////////////////////////////////
// sanity check for devices without native assemblies ?!?!
if (device.DeviceInfo.NativeAssemblies.Count == 0)
{
MessageCentre.InternalErrorWriteLine("*** ERROR: device reporting no assemblies loaded. This can not happen. Sanity check failed ***");
// there are no assemblies deployed?!
throw new DeploymentException($"Couldn't find any native assemblies deployed in {_viewModelLocator.DeviceExplorer.SelectedDevice.Description}! If the situation persists reboot the device.");
}
// For a known project output assembly path, this shall contain the corresponding
// ConfiguredProject:
Dictionary<string, ConfiguredProject> configuredProjectsByOutputAssemblyPath =
new Dictionary<string, ConfiguredProject>();
// For a known ConfiguredProject, this shall contain the corresponding project output assembly
// path:
Dictionary<ConfiguredProject, string> outputAssemblyPathsByConfiguredProject =
new Dictionary<ConfiguredProject, string>();
// Fill these two dictionaries for all projects contained in the solution
// (whether they belong to the deployment or not):
await ReferenceCrawler.CollectProjectsAndOutputAssemblyPathsAsync(
ProjectService,
configuredProjectsByOutputAssemblyPath,
outputAssemblyPathsByConfiguredProject);
// This HashSet shall contain a list of full paths to all assemblies to be deployed, including
// the compiled output assemblies of our solution's project and also all assemblies such as
// NuGet packages referenced by those projects.
// The HashSet will take care of only containing any string once even if added multiple times.
// However, this is dependent on getting all paths always in the same casing.
// Be aware that on file systems which ignore casing, we would end up having assemblies added
// more than once here if the GetFullPathAsync() methods used below should not always reliably
// return the path to the same assembly in the same casing.
HashSet<string> assemblyPathsToDeploy = new HashSet<string>();
// Starting with the StartUp project, collect all assemblies to be deployed.
// This will only add assemblies of projects which are actually referenced directly or
// indirectly by the StartUp project. Any project in the solution which is not referenced
// directly or indirectly by the StartUp project will not be included in the list of assemblies
// to be deployed.
await ReferenceCrawler.CollectAssembliesToDeployAsync(
configuredProjectsByOutputAssemblyPath,
outputAssemblyPathsByConfiguredProject,
assemblyPathsToDeploy,
Properties.ConfiguredProject);
// build a list with the full path for each DLL, referenced DLL and EXE
List<DeploymentAssembly> assemblyList = new List<DeploymentAssembly>();
// set decompiler options
// - don't load assembly in memory (causes issues with next solution rebuild)
// - don't throw resolution errors as we are not interested on this, just the assembly metadata
var decompilerSettings = new DecompilerSettings
{
LoadInMemory = false,
ThrowOnAssemblyResolveErrors = false
};
foreach (string assemblyPath in assemblyPathsToDeploy)
{
// load assembly in order to get the versions
var decompiler = new CSharpDecompiler(assemblyPath, decompilerSettings);
var assemblyProperties = decompiler.DecompileModuleAndAssemblyAttributesToString();
// read attributes using a Regex
// AssemblyVersion
string pattern = @"(?<=AssemblyVersion\("")(.*)(?=\""\)])";
var match = Regex.Matches(assemblyProperties, pattern, RegexOptions.IgnoreCase);
string assemblyVersion = match[0].Value;
// AssemblyNativeVersion
pattern = @"(?<=AssemblyNativeVersion\("")(.*)(?=\""\)])";
match = Regex.Matches(assemblyProperties, pattern, RegexOptions.IgnoreCase);
// only class libs have this attribute, therefore sanity check is required
string nativeVersion = "";
if (match.Count == 1)
{
nativeVersion = match[0].Value;
}
assemblyList.Add(new DeploymentAssembly(assemblyPath, assemblyVersion, nativeVersion));
}
// if there are referenced project, the assembly list contains repeated assemblies so need to use Linq Distinct()
// an IEqualityComparer is required implementing the proper comparison
List<DeploymentAssembly> distinctAssemblyList = assemblyList.Distinct(new DeploymentAssemblyDistinctEquality()).ToList();
// build a list with the PE files corresponding to each DLL and EXE
List<DeploymentAssembly> peCollection = distinctAssemblyList.Select(a => new DeploymentAssembly(a.Path.Replace(".dll", ".pe").Replace(".exe", ".pe"), a.Version, a.NativeVersion)).ToList();
// build a list with the PE files corresponding to a DLL for native support checking
// only need to check libraries because EXEs don't have native counterpart
List<DeploymentAssembly> peCollectionToCheck = distinctAssemblyList.Where(i => i.Path.EndsWith(".dll")).Select(a => new DeploymentAssembly(a.Path.Replace(".dll", ".pe"), a.Version, a.NativeVersion)).ToList();
await Task.Yield();
var checkAssembliesResult = await CheckNativeAssembliesAvailabilityAsync(device.DeviceInfo.NativeAssemblies, peCollectionToCheck);
if (checkAssembliesResult != "")
{
// can't deploy
throw new DeploymentException(checkAssembliesResult);
}
await Task.Yield();
// Keep track of total assembly size
long totalSizeOfAssemblies = 0;
MessageCentre.InternalErrorWriteLine($"Assemblies to deploy:");
// now we will re-deploy all system assemblies
foreach (DeploymentAssembly peItem in peCollection)
{
// append to the deploy blob the assembly
using (FileStream fs = File.Open(peItem.Path, FileMode.Open, FileAccess.Read))
{
long length = (fs.Length + 3) / 4 * 4;
await outputPaneWriter.WriteLineAsync($"Adding {Path.GetFileNameWithoutExtension(peItem.Path)} v{peItem.Version} ({length} bytes) to deployment bundle");
MessageCentre.InternalErrorWriteLine($"Assembly: {Path.GetFileNameWithoutExtension(peItem.Path)} v{peItem.Version} ({length} bytes)");
byte[] buffer = new byte[length];
await Task.Yield();
await fs.ReadAsync(buffer, 0, (int)fs.Length);
assemblies.Add(buffer);
// Increment totalizer
totalSizeOfAssemblies += length;
}
}
await outputPaneWriter.WriteLineAsync($"Deploying {peCollection.Count:N0} assemblies to device... Total size in bytes is {totalSizeOfAssemblies}.");
MessageCentre.InternalErrorWriteLine($"Deploying {peCollection.Count:N0} assemblies to device");
// need to keep a copy of the deployment blob for the second attempt (if needed)
var assemblyCopy = new List<byte[]>(assemblies);
await Task.Yield();
await Task.Run(async delegate
{
// no need to reboot device
if (!device.DebugEngine.DeploymentExecute(
assemblyCopy,
false,
false,
progressIndicator,
logProgressIndicator))
{
// if the first attempt fails, give it another try
// wait before next pass
await Task.Delay(TimeSpan.FromSeconds(1));
await Task.Yield();
MessageCentre.InternalErrorWriteLine("Trying again to deploying assemblies");
// !! need to use the deployment blob copy
assemblyCopy = new List<byte[]>(assemblies);
// can't skip erase as we just did that
// no need to reboot device
if (!device.DebugEngine.DeploymentExecute(
assemblyCopy,
false,
false,
progressIndicator,
logProgressIndicator))
{
MessageCentre.InternalErrorWriteLine("*** ERROR: deployment failed ***");
// throw exception to signal deployment failure
throw new DeploymentException("Deploy failed.");
}
}
});
await Task.Yield();
// do we have to generate a deployment image?
if (NanoFrameworkPackage.SettingGenerateDeploymentImage)
{
await Task.Run(async delegate
{
await DeploymentImageGenerator.GenerateDeploymentImageAsync(device, targetFlashDumpFileName, assemblies, Properties.ConfiguredProject, outputPaneWriter);
});
}
// deployment successful
await outputPaneWriter.WriteLineAsync("Deployment successful.");
// reset the hash for the connected device so the deployment information can be refreshed
_viewModelLocator.DeviceExplorer.LastDeviceConnectedHash = 0;
}
else
{
MessageCentre.InternalErrorWriteAndCloseMessage("");
MessageCentre.InternalErrorWriteLine("*** ERROR: failing to connect to device ***");
// throw exception to signal deployment failure
throw new DeploymentException($"{_viewModelLocator.DeviceExplorer.SelectedDevice.Description} is not responding. Please retry the deployment. If the situation persists reboot the device.");
}
}
catch (DeploymentException)
{
// this exception is used to flag a failed deployment to VS, no need to show anything about the exception here
throw;
}
catch (Exception ex)
{
if (needsToCloseMessageOutput)
{
MessageCentre.InternalErrorWriteAndCloseMessage("");
}
MessageCentre.InternalErrorWriteLine($"Unhandled exception with deployment provider:" +
$"{Environment.NewLine} {ex.Message} " +
$"{Environment.NewLine} {ex.InnerException} " +
$"{Environment.NewLine} {ex.StackTrace}");
#pragma warning disable S112 // OK to throw exception here to properly report back to the UI
throw new Exception("Unexpected error. Please retry the deployment. If the situation persists reboot the device.");
#pragma warning restore S112 // General exceptions should never be thrown
}
finally
{
MessageCentre.StopProgressMessage();
}
}
private async System.Threading.Tasks.Task<string> CheckNativeAssembliesAvailabilityAsync(List<CLRCapabilities.NativeAssemblyProperties> nativeAssemblies, List<DeploymentAssembly> peCollection)
{
string errorMessage = string.Empty;
string wrongAssemblies = string.Empty;
string missingAssemblies = string.Empty;
// loop through each PE to deploy...
foreach (var peItem in peCollection)
{
// open the PE file and load content
using (FileStream fs = File.Open(peItem.Path, FileMode.Open, FileAccess.Read))
{
CLRCapabilities.NativeAssemblyProperties nativeAssembly;
// read the PE checksum from the byte array at position 0x14
byte[] buffer = new byte[4];
fs.Position = 0x14;
await fs.ReadAsync(buffer, 0, 4);
var nativeMethodsChecksum = BitConverter.ToUInt32(buffer, 0);
if (nativeMethodsChecksum == 0)
{
// PEs with native methods checksum equal to 0 DO NOT require native support
// OK to move to the next one
continue;
}
// try to find a native assembly matching the checksum for this PE
if (nativeAssemblies.Exists(a => a.Checksum == nativeMethodsChecksum))
{
nativeAssembly = nativeAssemblies.Find(a => a.Checksum == nativeMethodsChecksum);
// now check the native version against the requested version on the PE
if (nativeAssembly.Version.ToString(4) == peItem.NativeVersion)
{
// we are good with this one
continue;
}
// no suitable native assembly found build a (hopefully) helpful message to the developer
wrongAssemblies += $"Couldn't find a valid native assembly required by {Path.GetFileNameWithoutExtension(peItem.Path)} v{peItem.Version}, checksum 0x{nativeMethodsChecksum:X8}." + Environment.NewLine +
$"This project is referencing {Path.GetFileNameWithoutExtension(peItem.Path)} NuGet package requiring native v{peItem.NativeVersion}." + Environment.NewLine +
$"The connected target has v{nativeAssembly.Version.ToString(4)}." + Environment.NewLine;
MessageCentre.InternalErrorWriteLine($"Couldn't find a valid native assembly required by {Path.GetFileNameWithoutExtension(peItem.Path)} v{peItem.Version}, checksum 0x{nativeMethodsChecksum:X8}");
MessageCentre.InternalErrorWriteLine($"The connected target has v{nativeAssembly.Version.ToString(4)}");
}
else
{
// no suitable native assembly found build a (hopefully) helpful message to the developer
missingAssemblies += $"Couldn't find a valid native assembly required by {Path.GetFileNameWithoutExtension(peItem.Path)} v{peItem.Version}, checksum 0x{nativeMethodsChecksum.ToString("X8")}." + Environment.NewLine +
$"This project is referencing {Path.GetFileNameWithoutExtension(peItem.Path)} NuGet package requiring native v{peItem.NativeVersion}." + Environment.NewLine +
$"The connected target does not have support for {Path.GetFileNameWithoutExtension(peItem.Path)}." + Environment.NewLine;
MessageCentre.InternalErrorWriteLine($"Couldn't find a valid native assembly required by {Path.GetFileNameWithoutExtension(peItem.Path)} v{peItem.Version}, checksum 0x{nativeMethodsChecksum:X8}");
MessageCentre.InternalErrorWriteLine($"The connected target does not have support for {Path.GetFileNameWithoutExtension(peItem.Path)}.");
}
}
}
if (!string.IsNullOrEmpty(wrongAssemblies) ||
!string.IsNullOrEmpty(missingAssemblies))
{
// init error message
errorMessage = "Deploy failed." + Environment.NewLine +
"***************************************" + Environment.NewLine;
}
if (!string.IsNullOrEmpty(wrongAssemblies))
{
errorMessage += wrongAssemblies;
errorMessage += $"Please check: " + Environment.NewLine +
$" 1) if the target is running the most updated image." + Environment.NewLine +
$" 2) if the project is referring the appropriate version of the NuGet package." + Environment.NewLine;
}
if (!string.IsNullOrEmpty(missingAssemblies))
{
errorMessage += missingAssemblies;
errorMessage += "Please check: " + Environment.NewLine +
" 1) if the target is running the most updated image." + Environment.NewLine +
" 2) if the target image was built to include support for all referenced assemblies." + Environment.NewLine;
}
// close error message, if needed
if (!string.IsNullOrEmpty(errorMessage))
{
errorMessage += "" + Environment.NewLine;
errorMessage += "If the target is running a PREVIEW version the projects have to reference PREVIEW NuGet packages." + Environment.NewLine;
errorMessage += "Check the Visual Studio FAQ here: https://docs.nanoframework.net/content/faq/working-with-vs-extension.html" + Environment.NewLine;
errorMessage += "" + Environment.NewLine;
errorMessage += "***************************************";
}
return errorMessage;
}
public bool IsDeploySupported
{
get
{
return true;
}
}
public void Commit()
{
// required by the SDK
}
public void Rollback()
{
// required by the SDK
}
}
}
| |
///////////////////////////////////////////////////////////////
// BrowseMonkey - An offline filesystem browser //
// Shukri Adams (shukri.adams@gmail.com) //
// https://github.com/shukriadams/browsemonkey //
// MIT License (MIT) Copyright (c) 2014 Shukri Adams //
///////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Windows.Forms;
namespace BrowseMonkey
{
/// <summary>
/// Form used to select path from which volume will be created
/// </summary>
public class VolumePathSelectDialog : Form
{
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtPath = new System.Windows.Forms.TextBox();
this.lblStepOne = new System.Windows.Forms.Label();
this.btnAbortVolumeCreation = new Button();
this.btnGetPath = new System.Windows.Forms.Button();
this.btnListIt = new System.Windows.Forms.Button();
this.btnBuildVolumeXml = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.gbVolume = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.btnQuit = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.gbVolume.SuspendLayout();
this.SuspendLayout();
//
// txtPath
//
this.txtPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtPath.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtPath.ForeColor = System.Drawing.SystemColors.ControlText;
this.txtPath.Location = new System.Drawing.Point(8, 24);
this.txtPath.Name = "txtPath";
this.txtPath.ReadOnly = true;
this.txtPath.Size = new System.Drawing.Size(326, 20);
this.txtPath.TabIndex = 0;
this.txtPath.TabStop = false;
this.txtPath.Text = "";
this.txtPath.TextChanged += new System.EventHandler(this.txtPath_TextChanged);
//
// lblStepOne
//
this.lblStepOne.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblStepOne.Location = new System.Drawing.Point(8, 8);
this.lblStepOne.Name = "lblStepOne";
this.lblStepOne.Size = new System.Drawing.Size(152, 16);
this.lblStepOne.TabIndex = 49;
this.lblStepOne.Text = "Select the path to read from :";
//
// btnAbortVolumeCreation
//
this.btnAbortVolumeCreation.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAbortVolumeCreation.Image = null;
this.btnAbortVolumeCreation.Location = new System.Drawing.Point(0, 0);
this.btnAbortVolumeCreation.Name = "btnAbortVolumeCreation";
this.btnAbortVolumeCreation.Size = new System.Drawing.Size(75, 23);
this.btnAbortVolumeCreation.TabIndex = 0;
this.btnAbortVolumeCreation.Text = "ButtonXP102";
this.btnAbortVolumeCreation.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// btnGetPath
//
this.btnGetPath.Location = new System.Drawing.Point(336, 24);
this.btnGetPath.Name = "btnGetPath";
this.btnGetPath.Size = new System.Drawing.Size(20, 20);
this.btnGetPath.TabIndex = 0;
this.btnGetPath.Text = "...";
this.btnGetPath.Click += new System.EventHandler(this.btnGetPath_Click);
//
// btnListIt
//
this.btnListIt.Location = new System.Drawing.Point(8, 16);
this.btnListIt.Name = "btnListIt";
this.btnListIt.Size = new System.Drawing.Size(56, 23);
this.btnListIt.TabIndex = 1;
this.btnListIt.Text = "&Text";
this.btnListIt.Click += new System.EventHandler(this.btnListIt_Click);
//
// btnBuildVolumeXml
//
this.btnBuildVolumeXml.Location = new System.Drawing.Point(8, 16);
this.btnBuildVolumeXml.Name = "btnBuildVolumeXml";
this.btnBuildVolumeXml.Size = new System.Drawing.Size(56, 23);
this.btnBuildVolumeXml.TabIndex = 2;
this.btnBuildVolumeXml.Text = "&Volume";
this.btnBuildVolumeXml.Click += new System.EventHandler(this.btnBuildVolumeXml_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 48);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(64, 16);
this.label1.TabIndex = 55;
this.label1.Text = "Generate :";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.btnListIt);
this.groupBox1.Location = new System.Drawing.Point(8, 64);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(344, 48);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
//
// label2
//
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label2.Location = new System.Drawing.Point(72, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(200, 16);
this.label2.TabIndex = 54;
this.label2.Text = "Text list of folder and all nested items.";
//
// gbVolume
//
this.gbVolume.Controls.Add(this.label3);
this.gbVolume.Controls.Add(this.btnBuildVolumeXml);
this.gbVolume.Location = new System.Drawing.Point(8, 112);
this.gbVolume.Name = "gbVolume";
this.gbVolume.Size = new System.Drawing.Size(344, 48);
this.gbVolume.TabIndex = 2;
this.gbVolume.TabStop = false;
//
// label3
//
this.label3.Location = new System.Drawing.Point(72, 24);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(264, 16);
this.label3.TabIndex = 55;
this.label3.Text = "Fully browseable \"image\" of directory and contents.";
//
// btnQuit
//
this.btnQuit.Location = new System.Drawing.Point(280, 164);
this.btnQuit.Name = "btnQuit";
this.btnQuit.Size = new System.Drawing.Size(72, 23);
this.btnQuit.TabIndex = 3;
this.btnQuit.Text = "&Cancel";
this.btnQuit.Click += new System.EventHandler(this.btnQuit_Click);
//
// VolumePathSelectDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(362, 192);
this.Controls.Add(this.btnQuit);
this.Controls.Add(this.gbVolume);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnGetPath);
this.Controls.Add(this.lblStepOne);
this.Controls.Add(this.txtPath);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximumSize = new System.Drawing.Size(368, 216);
this.MinimumSize = new System.Drawing.Size(368, 216);
this.Name = "VolumePathSelectDialog";
this.Text = "Volume Creator";
this.Load += new System.EventHandler(this.VolumeCreator_Load);
this.groupBox1.ResumeLayout(false);
this.gbVolume.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region FIELDS
private System.Windows.Forms.TextBox txtPath;
private Label lblStepOne;
private System.ComponentModel.Container components = null;
private Button btnAbortVolumeCreation;
private System.Windows.Forms.Button btnGetPath;
private System.Windows.Forms.Button btnListIt;
private System.Windows.Forms.Button btnBuildVolumeXml;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button btnQuit;
private System.Windows.Forms.GroupBox gbVolume;
/// <summary>
///
/// </summary>
private string _forcePath;
#endregion
#region PROPERTIES
/// <summary>
/// Gets or sets the path to be read as volume
/// </summary>
public string Path
{
get
{
return txtPath.Text;
}
set
{
if (Directory.Exists(value))
txtPath.Text = value;
}
}
#endregion
#region CONSTRUCTORS
/// <summary>
///
/// </summary>
public VolumePathSelectDialog(
string forcePath
)
{
InitializeComponent();
_forcePath = forcePath;
this.ShowInTaskbar = false;
}
#endregion
#region DESTRUCTORS
/// <summary> </summary>
/// <param name="disposing"></param>
protected override void Dispose(
bool disposing
)
{
try
{
if(disposing)
{
if(components != null)
components.Dispose();
}
base.Dispose(disposing);
}
catch(Exception ex)
{
MainForm.ConsoleAdd(ex);
}
}
#endregion
#region METHODS
/// <summary>
/// Generates a folderbrowser dialog and inserts selected folder path into path text field
/// </summary>
private void GetTargetPath(
)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
// try to get last volume capture path from state holder
if (MainForm.StateBag.Contains("VolumePathSelector.LastVolumePath"))
dialog.SelectedPath = Convert.ToString(
MainForm.StateBag.Retrieve("VolumePathSelector.LastVolumePath"));
dialog.ShowDialog();
txtPath.Text = dialog.SelectedPath;
txtPath.SelectedText = "";
//gbVolume.Select();
btnBuildVolumeXml.Select();
// cleans up filedialogue
dialog.Dispose();
// dump currently selected volume path into statebag
MainForm.StateBag.Add(
"VolumePathSelector.LastVolumePath",
dialog.SelectedPath);
}
/// <summary>
///
/// </summary>
private void CreateVolume(
)
{
if (txtPath.Text.Length == 0)
{
MainForm.ConsoleAdd("Please specify a path to archive");
return;
}
else if (!Directory.Exists(txtPath.Text))
{
MainForm.ConsoleAdd("'" + txtPath.Text + "' is not a valid directory path");
return;
}
// hide the "path select" dialog, as we dont want to have two dialogs shown
// at the same time
this.Visible = false;
FormFactory.SpawnVolumeCreator(
txtPath.Text);
this.Close();
}
/// <summary>
///
/// </summary>
private void CreateList(
)
{
if (txtPath.Text.Length == 0)
{
MainForm.ConsoleAdd("Please specify a path to archive");
return;
}
else if (!Directory.Exists(txtPath.Text))
{
MainForm.ConsoleAdd("'" + txtPath.Text + "' is not a valid directory path");
return;
}
FormFactory.SpawnPathList(
txtPath.Text);
this.Close();
}
#endregion
#region EVENTS
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void VolumeCreator_Load(
object sender,
EventArgs e
)
{
try
{
// ###############################################
// sets path or restores it from state holder
// -----------------------------------------------
if (_forcePath != String.Empty && Directory.Exists(_forcePath))
txtPath.Text = _forcePath;
else if (MainForm.StateBag.Contains("VolumePathSelector.LastVolumePath"))
{
string path = MainForm.StateBag.Retrieve("VolumePathSelector.LastVolumePath").ToString();
if (Directory.Exists(path))
{
txtPath.Text = path;
btnBuildVolumeXml.Select();
}
}
// force a text changed event to ensure that
// txtPath-dependant properties are set
txtPath_TextChanged(null,null);
}
catch(Exception ex)
{
MainForm.ConsoleAdd(ex);
}
}
/// <summary>
/// Invokes process which gathers data from "new volume" form, so a new volume can be produced.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnBuildVolumeXml_Click(
object sender,
EventArgs e
)
{
try
{
CreateVolume();
}
catch(Exception ex)
{
MainForm.ConsoleAdd(ex);
}
}
/// <summary>
/// Invokes process which throws up a folder path dialogue - this will be used to produce a new volume
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetPath_Click(
object sender,
EventArgs e
)
{
try
{
GetTargetPath();
}
catch(Exception ex)
{
MainForm.ConsoleAdd(ex);
}
}
/// <summary>
/// Invoked by "cancel" button - abandons current work and closes this form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAnyClose_Click(
object sender,
EventArgs e
)
{
this.Dispose();
}
/// <summary>
/// Invoked when txtPath value changes. Disables the "create" button if no path is selected
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtPath_TextChanged(
object sender,
System.EventArgs e
)
{
btnBuildVolumeXml.Enabled = false;
btnListIt.Enabled = false;
if (txtPath.Text.Length > 0 && Directory.Exists(txtPath.Text))
{
btnListIt.Enabled = true;
btnBuildVolumeXml.Enabled = true;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnListIt_Click(
object sender,
System.EventArgs e)
{
CreateList();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnQuit_Click(
object sender,
System.EventArgs e)
{
this.Dispose();
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
/// Returns true if the current quality settings equal
/// this graphics quality level.
// boolean flag for vehicle control remappings
$vehicleMapped = false;
function GraphicsQualityLevel::isCurrent( %this )
{
// Test each pref to see if the current value
// equals our stored value.
for ( %i=0; %i < %this.count(); %i++ )
{
%pref = %this.getKey( %i );
%value = %this.getValue( %i );
if ( getVariable( %pref ) !$= %value )
return false;
}
return true;
}
/// Applies the graphics quality settings and calls
/// 'onApply' on itself or its parent group if its
/// been overloaded.
function GraphicsQualityLevel::apply( %this )
{
for ( %i=0; %i < %this.count(); %i++ )
{
%pref = %this.getKey( %i );
%value = %this.getValue( %i );
setVariable( %pref, %value );
}
// If we have an overloaded onApply method then
// call it now to finalize the changes.
if ( %this.isMethod( "onApply" ) )
%this.onApply();
else
{
%group = %this.getGroup();
if ( isObject( %group ) && %group.isMethod( "onApply" ) )
%group.onApply( %this );
}
}
function GraphicsQualityPopup::init( %this, %qualityGroup )
{
assert( isObject( %this ) );
assert( isObject( %qualityGroup ) );
// Clear the existing content first.
%this.clear();
// Fill it.
%select = -1;
for ( %i=0; %i < %qualityGroup.getCount(); %i++ )
{
%level = %qualityGroup.getObject( %i );
if ( %level.isCurrent() )
%select = %i;
%this.add( %level.getInternalName(), %i );
}
// Setup a default selection.
if ( %select == -1 )
%this.setText( "Custom" );
else
%this.setSelected( %select );
}
function GraphicsQualityPopup::apply( %this, %qualityGroup, %testNeedApply )
{
assert( isObject( %this ) );
assert( isObject( %qualityGroup ) );
%quality = %this.getText();
%index = %this.findText( %quality );
if ( %index == -1 )
return false;
%level = %qualityGroup.getObject( %index );
if ( isObject( %level ) && !%level.isCurrent() )
{
if ( %testNeedApply )
return true;
%level.apply();
}
return false;
}
function OptionsDlg::setPane(%this, %pane)
{
%this-->OptAudioPane.setVisible(false);
%this-->OptGraphicsPane.setVisible(false);
%this-->OptNetworkPane.setVisible(false);
%this-->OptControlsPane.setVisible(false);
%this.findObjectByInternalName( "Opt" @ %pane @ "Pane", true ).setVisible(true);
%this.fillRemapList();
// Update the state of the apply button.
%this._updateApplyState();
}
function OptionsDlg::onWake(%this)
{
if ( isFunction("getWebDeployment") && getWebDeployment() )
{
// Cannot enable full screen under web deployment
%this-->OptGraphicsFullscreenToggle.setStateOn( false );
%this-->OptGraphicsFullscreenToggle.setVisible( false );
}
else
{
%this-->OptGraphicsFullscreenToggle.setStateOn( Canvas.isFullScreen() );
}
%this-->OptGraphicsVSyncToggle.setStateOn( !$pref::Video::disableVerticalSync );
OptionsDlg.initResMenu();
%resSelId = OptionsDlg-->OptGraphicsResolutionMenu.findText( _makePrettyResString( $pref::Video::mode ) );
if( %resSelId != -1 )
OptionsDlg-->OptGraphicsResolutionMenu.setSelected( %resSelId );
OptGraphicsDriverMenu.clear();
%buffer = getDisplayDeviceList();
%count = getFieldCount( %buffer );
for(%i = 0; %i < %count; %i++)
OptGraphicsDriverMenu.add(getField(%buffer, %i), %i);
%selId = OptGraphicsDriverMenu.findText( getDisplayDeviceInformation() );
if ( %selId == -1 )
OptGraphicsDriverMenu.setFirstSelected();
else
OptGraphicsDriverMenu.setSelected( %selId );
// Setup the graphics quality dropdown menus.
%this-->OptMeshQualityPopup.init( MeshQualityGroup );
%this-->OptTextureQualityPopup.init( TextureQualityGroup );
%this-->OptLightingQualityPopup.init( LightingQualityGroup );
%this-->OptShaderQualityPopup.init( ShaderQualityGroup );
// Setup the anisotropic filtering menu.
%ansioCtrl = %this-->OptAnisotropicPopup;
%ansioCtrl.clear();
%ansioCtrl.add( "Off", 0 );
%ansioCtrl.add( "4X", 4 );
%ansioCtrl.add( "8X", 8 );
%ansioCtrl.add( "16X", 16 );
%ansioCtrl.setSelected( $pref::Video::defaultAnisotropy, false );
// set up the Refresh Rate menu.
%refreshMenu = %this-->OptRefreshSelectMenu;
%refreshMenu.clear();
// %refreshMenu.add("Auto", 60);
%refreshMenu.add("60", 60);
%refreshMenu.add("75", 75);
%refreshMenu.setSelected( getWord( $pref::Video::mode, $WORD::REFRESH ) );
// Audio
//OptAudioHardwareToggle.setStateOn($pref::SFX::useHardware);
//OptAudioHardwareToggle.setActive( true );
%this-->OptAudioVolumeMaster.setValue( $pref::SFX::masterVolume );
%this-->OptAudioVolumeShell.setValue( $pref::SFX::channelVolume[ $GuiAudioType] );
%this-->OptAudioVolumeSim.setValue( $pref::SFX::channelVolume[ $SimAudioType ] );
%this-->OptAudioVolumeMusic.setValue( $pref::SFX::channelVolume[ $MusicAudioType ] );
OptAudioProviderList.clear();
%buffer = sfxGetAvailableDevices();
%count = getRecordCount( %buffer );
for(%i = 0; %i < %count; %i++)
{
%record = getRecord(%buffer, %i);
%provider = getField(%record, 0);
if ( OptAudioProviderList.findText( %provider ) == -1 )
OptAudioProviderList.add( %provider, %i );
}
OptAudioProviderList.sort();
%selId = OptAudioProviderList.findText($pref::SFX::provider);
if ( %selId == -1 )
OptAudioProviderList.setFirstSelected();
else
OptAudioProviderList.setSelected( %selId );
// Populate the Anti-aliasing popup.
%aaMenu = %this-->OptAAQualityPopup;
%aaMenu.clear();
%aaMenu.Add( "Off", 0 );
%aaMenu.Add( "1x", 1 );
%aaMenu.Add( "2x", 2 );
%aaMenu.Add( "4x", 4 );
%aaMenu.setSelected( getWord( $pref::Video::mode, $WORD::AA ) );
OptMouseSensitivity.value = $pref::Input::LinkMouseSensitivity;
// Set the graphics pane to start.
%this-->OptGraphicsButton.performClick();
}
function OptionsDlg::onSleep(%this)
{
// write out the control config into the rw/config.cs file
moveMap.save( "scripts/client/config.cs" );
// saving vehicle mappings into separate config file
vehicleMap.save("scripts/client/config_vehicle.cs");
}
function OptGraphicsDriverMenu::onSelect( %this, %id, %text )
{
// Attempt to keep the same resolution settings:
%resMenu = OptionsDlg-->OptGraphicsResolutionMenu;
%currRes = %resMenu.getText();
// If its empty the use the current.
if ( %currRes $= "" )
%currRes = _makePrettyResString( Canvas.getVideoMode() );
// Fill the resolution list.
optionsDlg.initResMenu();
// Try to select the previous settings:
%selId = %resMenu.findText( %currRes );
if ( %selId == -1 )
%selId = 0;
%resMenu.setSelected( %selId );
OptionsDlg._updateApplyState();
}
function _makePrettyResString( %resString )
{
%width = getWord( %resString, $WORD::RES_X );
%height = getWord( %resString, $WORD::RES_Y );
%aspect = %width / %height;
%aspect = mRound( %aspect * 100 ) * 0.01;
switch$( %aspect )
{
case "1.33":
%aspect = "4:3";
case "1.78":
%aspect = "16:9";
default:
%aspect = "";
}
%outRes = %width @ " x " @ %height;
if ( %aspect !$= "" )
%outRes = %outRes @ " (" @ %aspect @ ")";
return %outRes;
}
function OptionsDlg::initResMenu( %this )
{
// Clear out previous values
%resMenu = %this-->OptGraphicsResolutionMenu;
%resMenu.clear();
// If we are in a browser then we can't change our resolution through
// the options dialog
if (getWebDeployment())
{
%count = 0;
%currRes = getWords(Canvas.getVideoMode(), $WORD::RES_X, $WORD::RES_Y);
%resMenu.add(%currRes, %count);
%count++;
return;
}
// Loop through all and add all valid resolutions
%count = 0;
%resCount = Canvas.getModeCount();
for (%i = 0; %i < %resCount; %i++)
{
%testResString = Canvas.getMode( %i );
%testRes = _makePrettyResString( %testResString );
// Only add to list if it isn't there already.
if (%resMenu.findText(%testRes) == -1)
{
%resMenu.add(%testRes, %i);
%count++;
}
}
%resMenu.sort();
}
function OptionsDlg::applyGraphics( %this, %testNeedApply )
{
%newAdapter = OptGraphicsDriverMenu.getText();
%numAdapters = GFXInit::getAdapterCount();
%newDevice = $pref::Video::displayDevice;
for( %i = 0; %i < %numAdapters; %i ++ )
if( GFXInit::getAdapterName( %i ) $= %newAdapter )
{
%newDevice = GFXInit::getAdapterType( %i );
break;
}
// Change the device.
if ( %newDevice !$= $pref::Video::displayDevice )
{
if ( %testNeedApply )
return true;
$pref::Video::displayDevice = %newDevice;
if( %newAdapter !$= getDisplayDeviceInformation() )
MessageBoxOK( "Change requires restart", "Please restart the game for a display device change to take effect." );
}
// Gather the new video mode.
if ( isFunction("getWebDeployment") && getWebDeployment() )
{
// Under web deployment, we use the custom resolution rather than a Canvas
// defined one.
%newRes = %this-->OptGraphicsResolutionMenu.getText();
}
else
{
%newRes = getWords( Canvas.getMode( %this-->OptGraphicsResolutionMenu.getSelected() ), $WORD::RES_X, $WORD::RES_Y );
}
%newBpp = 32; // ... its not 1997 anymore.
%newFullScreen = %this-->OptGraphicsFullscreenToggle.getValue() ? "true" : "false";
%newRefresh = %this-->OptRefreshSelectMenu.getSelected();
%newVsync = !%this-->OptGraphicsVSyncToggle.getValue();
%newFSAA = %this-->OptAAQualityPopup.getSelected();
// Under web deployment we can't be full screen.
if ( isFunction("getWebDeployment") && getWebDeployment() )
{
%newFullScreen = false;
}
else if ( %newFullScreen $= "false" )
{
// If we're in windowed mode switch the fullscreen check
// if the resolution is bigger than the desktop.
%deskRes = getDesktopResolution();
%deskResX = getWord(%deskRes, $WORD::RES_X);
%deskResY = getWord(%deskRes, $WORD::RES_Y);
if ( getWord( %newRes, $WORD::RES_X ) > %deskResX ||
getWord( %newRes, $WORD::RES_Y ) > %deskResY )
{
%newFullScreen = "true";
%this-->OptGraphicsFullscreenToggle.setStateOn( true );
}
}
// Build the final mode string.
%newMode = %newRes SPC %newFullScreen SPC %newBpp SPC %newRefresh SPC %newFSAA;
// Change the video mode.
if ( %newMode !$= $pref::Video::mode ||
%newVsync != $pref::Video::disableVerticalSync )
{
if ( %testNeedApply )
return true;
$pref::Video::mode = %newMode;
$pref::Video::disableVerticalSync = %newVsync;
configureCanvas();
}
// Test and apply the graphics settings.
if ( %this-->OptMeshQualityPopup.apply( MeshQualityGroup, %testNeedApply ) ) return true;
if ( %this-->OptTextureQualityPopup.apply( TextureQualityGroup, %testNeedApply ) ) return true;
if ( %this-->OptLightingQualityPopup.apply( LightingQualityGroup, %testNeedApply ) ) return true;
if ( %this-->OptShaderQualityPopup.apply( ShaderQualityGroup, %testNeedApply ) ) return true;
// Check the anisotropic filtering.
%level = %this-->OptAnisotropicPopup.getSelected();
if ( %level != $pref::Video::defaultAnisotropy )
{
if ( %testNeedApply )
return true;
$pref::Video::defaultAnisotropy = %level;
}
// If we're applying the state then recheck the
// state to update the apply button.
if ( !%testNeedApply )
%this._updateApplyState();
return false;
}
function OptionsDlg::_updateApplyState( %this )
{
%applyCtrl = %this-->Apply;
%graphicsPane = %this-->OptGraphicsPane;
assert( isObject( %applyCtrl ) );
assert( isObject( %graphicsPane ) );
%applyCtrl.active = %graphicsPane.isVisible() && %this.applyGraphics( true );
}
function OptionsDlg::_autoDetectQuality( %this )
{
%msg = GraphicsQualityAutodetect();
%this.onWake();
if ( %msg !$= "" )
{
MessageBoxOK( "Notice", %msg );
}
}
$RemapCount = 0;
$RemapName[$RemapCount] = "Forward";
$RemapCmd[$RemapCount] = "moveforward";
$RemapCount++;
$RemapName[$RemapCount] = "Backward";
$RemapCmd[$RemapCount] = "movebackward";
$RemapCount++;
$RemapName[$RemapCount] = "Strafe Left";
$RemapCmd[$RemapCount] = "moveleft";
$RemapCount++;
$RemapName[$RemapCount] = "Strafe Right";
$RemapCmd[$RemapCount] = "moveright";
$RemapCount++;
$RemapName[$RemapCount] = "Turn Left";
$RemapCmd[$RemapCount] = "turnLeft";
$RemapCount++;
$RemapName[$RemapCount] = "Turn Right";
$RemapCmd[$RemapCount] = "turnRight";
$RemapCount++;
$RemapName[$RemapCount] = "Look Up";
$RemapCmd[$RemapCount] = "panUp";
$RemapCount++;
$RemapName[$RemapCount] = "Look Down";
$RemapCmd[$RemapCount] = "panDown";
$RemapCount++;
$RemapName[$RemapCount] = "Jump";
$RemapCmd[$RemapCount] = "jump";
$RemapCount++;
$RemapName[$RemapCount] = "Fire Weapon";
$RemapCmd[$RemapCount] = "mouseFire";
$RemapCount++;
$RemapName[$RemapCount] = "Adjust Zoom";
$RemapCmd[$RemapCount] = "setZoomFov";
$RemapCount++;
$RemapName[$RemapCount] = "Toggle Zoom";
$RemapCmd[$RemapCount] = "toggleZoom";
$RemapCount++;
$RemapName[$RemapCount] = "Free Look";
$RemapCmd[$RemapCount] = "toggleFreeLook";
$RemapCount++;
$RemapName[$RemapCount] = "Switch 1st/3rd";
$RemapCmd[$RemapCount] = "toggleFirstPerson";
$RemapCount++;
$RemapName[$RemapCount] = "Chat to Everyone";
$RemapCmd[$RemapCount] = "toggleMessageHud";
$RemapCount++;
$RemapName[$RemapCount] = "Message Hud PageUp";
$RemapCmd[$RemapCount] = "pageMessageHudUp";
$RemapCount++;
$RemapName[$RemapCount] = "Message Hud PageDown";
$RemapCmd[$RemapCount] = "pageMessageHudDown";
$RemapCount++;
$RemapName[$RemapCount] = "Resize Message Hud";
$RemapCmd[$RemapCount] = "resizeMessageHud";
$RemapCount++;
$RemapName[$RemapCount] = "Show Scores";
$RemapCmd[$RemapCount] = "showPlayerList";
$RemapCount++;
$RemapName[$RemapCount] = "Animation - Wave";
$RemapCmd[$RemapCount] = "celebrationWave";
$RemapCount++;
$RemapName[$RemapCount] = "Animation - Salute";
$RemapCmd[$RemapCount] = "celebrationSalute";
$RemapCount++;
$RemapName[$RemapCount] = "Suicide";
$RemapCmd[$RemapCount] = "suicide";
$RemapCount++;
$RemapName[$RemapCount] = "Toggle Camera";
$RemapCmd[$RemapCount] = "toggleCamera";
$RemapCount++;
$RemapName[$RemapCount] = "Drop Camera at Player";
$RemapCmd[$RemapCount] = "dropCameraAtPlayer";
$RemapCount++;
$RemapName[$RemapCount] = "Drop Player at Camera";
$RemapCmd[$RemapCount] = "dropPlayerAtCamera";
$RemapCount++;
$RemapName[$RemapCount] = "Bring up Options Dialog";
$RemapCmd[$RemapCount] = "bringUpOptions";
$RemapCount++;
// adding manageable vehicle mappings to options gui screen
$RemapName[$RemapCount] = "Vehicle Move Forward";
$RemapCmd[$RemapCount] = "moveforward";
$RemapCount++;
$RemapName[$RemapCount] = "Vehicle Move Backward";
$RemapCmd[$RemapCount] = "moveBackward";
$RemapCount++;
$RemapName[$RemapCount] = "Vehicle brake";
$RemapCmd[$RemapCount] = "brake";
$RemapCount++;
$RemapName[$RemapCount] = "Vehicle free look";
$RemapCmd[$RemapCount] = "toggleFreeLook";
$RemapCount++;
$RemapName[$RemapCount] = "Vehicle mouseFire";
$RemapCmd[$RemapCount] = "mouseFire";
$RemapCount++;
$RemapName[$RemapCount] = "Vehicle alt trigger";
$RemapCmd[$RemapCount] = "altTrigger";
$RemapCount++;
function restoreDefaultMappings()
{
moveMap.delete();
vehicleMap.delete();
exec( "scripts/client/default.bind.cs" );
optionsDlg.fillRemapList();
}
function getMapDisplayName( %device, %action )
{
if ( %device $= "keyboard" )
return( %action );
else if ( strstr( %device, "mouse" ) != -1 )
{
// Substitute "mouse" for "button" in the action string:
%pos = strstr( %action, "button" );
if ( %pos != -1 )
{
%mods = getSubStr( %action, 0, %pos );
%object = getSubStr( %action, %pos, 1000 );
%instance = getSubStr( %object, strlen( "button" ), 1000 );
return( %mods @ "mouse" @ ( %instance + 1 ) );
}
else
error( "Mouse input object other than button passed to getDisplayMapName!" );
}
else if ( strstr( %device, "joystick" ) != -1 )
{
// Substitute "joystick" for "button" in the action string:
%pos = strstr( %action, "button" );
if ( %pos != -1 )
{
%mods = getSubStr( %action, 0, %pos );
%object = getSubStr( %action, %pos, 1000 );
%instance = getSubStr( %object, strlen( "button" ), 1000 );
return( %mods @ "joystick" @ ( %instance + 1 ) );
}
else
{
%pos = strstr( %action, "pov" );
if ( %pos != -1 )
{
%wordCount = getWordCount( %action );
%mods = %wordCount > 1 ? getWords( %action, 0, %wordCount - 2 ) @ " " : "";
%object = getWord( %action, %wordCount - 1 );
switch$ ( %object )
{
case "upov": %object = "POV1 up";
case "dpov": %object = "POV1 down";
case "lpov": %object = "POV1 left";
case "rpov": %object = "POV1 right";
case "upov2": %object = "POV2 up";
case "dpov2": %object = "POV2 down";
case "lpov2": %object = "POV2 left";
case "rpov2": %object = "POV2 right";
default: %object = "??";
}
return( %mods @ %object );
}
else
error( "Unsupported Joystick input object passed to getDisplayMapName!" );
}
}
return( "??" );
}
function buildFullMapString( %index )
{
%name = $RemapName[%index];
%cmd = $RemapCmd[%index];
// getting exact type of binding based on Remap name
if(getSubStr(%name,0,7) $= "Vehicle" )
{
%temp = vehicleMap.getBinding( %cmd );
}
else
%temp = moveMap.getBinding( %cmd );
if ( %temp $= "" )
return %name TAB "";
%mapString = "";
%count = getFieldCount( %temp );
for ( %i = 0; %i < %count; %i += 2 )
{
if ( %mapString !$= "" )
%mapString = %mapString @ ", ";
%device = getField( %temp, %i + 0 );
%object = getField( %temp, %i + 1 );
%mapString = %mapString @ getMapDisplayName( %device, %object );
}
return %name TAB %mapString;
}
function OptionsDlg::fillRemapList( %this )
{
%remapList = %this-->OptRemapList;
%remapList.clear();
for ( %i = 0; %i < $RemapCount; %i++ )
%remapList.addRow( %i, buildFullMapString( %i ) );
}
function OptionsDlg::doRemap( %this )
{
%remapList = %this-->OptRemapList;
%selId = %remapList.getSelectedId();
%name = $RemapName[%selId];
//turning on the vehicle mapping flag if selected item is vehicle remapping
if(getSubStr(%name,0,7) $= "Vehicle")
$vehicleMapped = true;
RemapDlg-->OptRemapText.setValue( "Re-bind \"" @ %name @ "\" to..." );
OptRemapInputCtrl.index = %selId;
Canvas.pushDialog( RemapDlg );
}
function redoMapping( %device, %action, %cmd, %oldIndex, %newIndex )
{
//%actionMap.bind( %device, %action, $RemapCmd[%newIndex] );
//performing desired remapping based on flag
if(!$vehicleMapped)
moveMap.bind( %device, %action, %cmd );
else
vehicleMap.bind( %device, %action, %cmd );
%remapList = %this-->OptRemapList;
%remapList.setRowById( %oldIndex, buildFullMapString( %oldIndex ) );
%remapList.setRowById( %newIndex, buildFullMapString( %newIndex ) );
}
function findRemapCmdIndex( %command )
{
for ( %i = 0; %i < $RemapCount; %i++ )
{
if ( %command $= $RemapCmd[%i] )
return( %i );
}
return( -1 );
}
/// This unbinds actions beyond %count associated to the
/// particular moveMap %commmand.
function unbindExtraActions( %command, %count )
{
//get current key binding (checking for vehicle mapping)
if(!$vehicleMapped)
%temp = moveMap.getBinding( %command );
else
%temp = vehicleMap.getBinding( %command );
if ( %temp $= "" )
return;
%count = getFieldCount( %temp ) - ( %count * 2 );
for ( %i = 0; %i < %count; %i += 2 )
{
%device = getField( %temp, %i + 0 );
%action = getField( %temp, %i + 1 );
//performing desired unbinding of mapped key
if(!$vehicleMapped)
moveMap.unbind( %device, %action );
else
vehicleMap.unbind( %device, %action );
}
}
function OptRemapInputCtrl::onInputEvent( %this, %device, %action )
{
Canvas.popDialog( RemapDlg );
// Test for the reserved keystrokes:
if ( %device $= "keyboard" )
{
// Cancel...
if ( %action $= "escape" )
{
// Do nothing...
return;
}
}
%cmd = $RemapCmd[%this.index];
%name = $RemapName[%this.index];
// Grab the friendly display name for this action
// which we'll use when prompting the user below.
%mapName = getMapDisplayName( %device, %action );
// Get the current command this action is mapped to
if(!$vehicleMapped)
%prevMap = moveMap.getCommand( %device, %action );
else
%prevMap = vehicleMap.getCommand( %device, %action );
// If nothing was mapped to the previous command
// mapping then it's easy... just bind it.
if ( %prevMap $= "" )
{
unbindExtraActions( %cmd, 1 );
// performing desired binding (vehicleMap or moveMap)
if(!$vehicleMapped)
moveMap.bind( %device, %action, %cmd );
else
vehicleMap.bind( %device, %action, %cmd );
optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) );
return;
}
// If the previous command is the same as the
// current then they hit the same input as what
// was already assigned.
if ( %prevMap $= %cmd )
{
unbindExtraActions( %cmd, 0 );
//performing desired binding (vehicleMap or moveMap)
if(!$vehicleMapped)
moveMap.bind( %device, %action, %cmd );
else
vehicleMap.bind( %device, %action, %cmd );
optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) );
return;
}
$vehicleMapped = false;
// Look for the index of the previous mapping.
%prevMapIndex = findRemapCmdIndex( %prevMap );
// If we get a negative index then the previous
// mapping was to an item that isn't included in
// the mapping list... so we cannot unmap it.
if ( %prevMapIndex == -1 )
{
MessageBoxOK( "Remap Failed", "\"" @ %mapName @ "\" is already bound to a non-remappable command!" );
return;
}
// Setup the forced remapping callback command.
%callback = "redoMapping(" @ %device @ ", \"" @ %action @ "\", \"" @
%cmd @ "\", " @ %prevMapIndex @ ", " @ %this.index @ ");";
// Warn that we're about to remove the old mapping and
// replace it with another.
%prevCmdName = $RemapName[%prevMapIndex];
MessageBoxYesNo( "Warning",
"\"" @ %mapName @ "\" is already bound to \""
@ %prevCmdName @ "\"!\nDo you wish to replace this mapping?",
%callback, "" );
}
$AudioTestHandle = 0;
// Description to use for playing the volume test sound. This isn't
// played with the description of the channel that has its volume changed
// because we know nothing about the playback state of the channel. If it
// is paused or stopped, the test sound would not play then.
$AudioTestDescription = new SFXDescription()
{
sourceGroup = AudioChannelMaster;
};
function OptAudioUpdateMasterVolume( %volume )
{
if( %volume == $pref::SFX::masterVolume )
return;
sfxSetMasterVolume( %volume );
$pref::SFX::masterVolume = %volume;
if( !isObject( $AudioTestHandle ) )
$AudioTestHandle = sfxPlayOnce( AudioChannel, "art/sound/ui/volumeTest.wav" );
}
function OptAudioUpdateChannelVolume( %description, %volume )
{
%channel = sfxGroupToOldChannel( %description.sourceGroup );
if( %volume == $pref::SFX::channelVolume[ %channel ] )
return;
sfxSetChannelVolume( %channel, %volume );
$pref::SFX::channelVolume[ %channel ] = %volume;
if( !isObject( $AudioTestHandle ) )
{
$AudioTestDescription.volume = %volume;
$AudioTestHandle = sfxPlayOnce( $AudioTestDescription, "art/sound/ui/volumeTest.wav" );
}
}
function OptAudioProviderList::onSelect( %this, %id, %text )
{
// Skip empty provider selections.
if ( %text $= "" )
return;
$pref::SFX::provider = %text;
OptAudioDeviceList.clear();
%buffer = sfxGetAvailableDevices();
%count = getRecordCount( %buffer );
for(%i = 0; %i < %count; %i++)
{
%record = getRecord(%buffer, %i);
%provider = getField(%record, 0);
%device = getField(%record, 1);
if (%provider !$= %text)
continue;
if ( OptAudioDeviceList.findText( %device ) == -1 )
OptAudioDeviceList.add( %device, %i );
}
// Find the previous selected device.
%selId = OptAudioDeviceList.findText($pref::SFX::device);
if ( %selId == -1 )
OptAudioDeviceList.setFirstSelected();
else
OptAudioDeviceList.setSelected( %selId );
}
function OptAudioDeviceList::onSelect( %this, %id, %text )
{
// Skip empty selections.
if ( %text $= "" )
return;
$pref::SFX::device = %text;
if ( !sfxCreateDevice( $pref::SFX::provider,
$pref::SFX::device,
$pref::SFX::useHardware,
-1 ) )
error( "Unable to create SFX device: " @ $pref::SFX::provider
SPC $pref::SFX::device
SPC $pref::SFX::useHardware );
}
function OptMouseSetSensitivity(%value)
{
$pref::Input::LinkMouseSensitivity = %value;
}
/*
function OptAudioHardwareToggle::onClick(%this)
{
if (!sfxCreateDevice($pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1))
error("Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware);
}
*/
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using NServiceKit.Text.Common;
using NServiceKit.Text.Json;
using NServiceKit.Text.Jsv;
#if WINDOWS_PHONE && !WP8
using NServiceKit.Text.WP;
#endif
namespace NServiceKit.Text
{
/// <summary>The js configuration.</summary>
public static class
JsConfig
{
/// <summary>Initializes static members of the NServiceKit.Text.JsConfig class.</summary>
static JsConfig()
{
//In-built default serialization, to Deserialize Color struct do:
//JsConfig<System.Drawing.Color>.SerializeFn = c => c.ToString().Replace("Color ", "").Replace("[", "").Replace("]", "");
//JsConfig<System.Drawing.Color>.DeSerializeFn = System.Drawing.Color.FromName;
Reset();
}
/// <summary>Begins a scope.</summary>
/// <returns>A JsConfigScope.</returns>
public static JsConfigScope BeginScope()
{
return new JsConfigScope();
}
/// <summary>Withs.</summary>
/// <param name="convertObjectTypesIntoStringDictionary">Dictionary of convert object types into
/// strings.</param>
/// <param name="tryToParsePrimitiveTypeValues"> The try to parse primitive type values.</param>
/// <param name="tryToParseNumericType"> Type of the try to parse numeric.</param>
/// <param name="includeNullValues"> The include null values.</param>
/// <param name="excludeTypeInfo"> Information describing the exclude type.</param>
/// <param name="includeTypeInfo"> Information describing the include type.</param>
/// <param name="emitCamelCaseNames"> <see langword="true"/> if the
/// <see cref="ITypeSerializer"/> is configured to take advantage of
/// <see cref="CLSCompliantAttribute"/> specification, to support user-friendly serialized
/// formats, ie emitting camelCasing for JSON and parsing member names and enum values in a case-
/// insensitive manner.</param>
/// <param name="emitLowercaseUnderscoreNames"> <see langword="true"/> if the
/// <see cref="ITypeSerializer"/> is configured to support web- friendly serialized formats, ie
/// emitting lowercase_underscore_casing for JSON.</param>
/// <param name="dateHandler"> The date handler.</param>
/// <param name="timeSpanHandler"> Sets which format to use when serializing
/// TimeSpans.</param>
/// <param name="preferInterfaces"> The prefer interfaces.</param>
/// <param name="throwOnDeserializationError"> Gets or sets a value indicating if the
/// framework should throw serialization exceptions or continue regardless of deserialization
/// errors. If <see langword="true"/> the framework will throw; otherwise, it will parse as many
/// fields as possible. The default is
/// <see langword="false"/>.</param>
/// <param name="typeAttr"> The type attribute.</param>
/// <param name="typeWriter"> The type writer.</param>
/// <param name="typeFinder"> The type finder.</param>
/// <param name="treatEnumAsInteger"> The treat enum as integer.</param>
/// <param name="alwaysUseUtc"> Gets or sets a value indicating if the
/// framework should always convert <see cref="DateTime"/>to UTC format instead of local time.</param>
/// <param name="assumeUtc"> Gets or sets a value indicating if the
/// framework should always assume <see cref="DateTime"/>is in UTC format if Kind is Unspecified.</param>
/// <param name="appendUtcOffset"> Gets or sets whether we should append the
/// Utc offset when we serialize Utc dates. Defaults to no. Only supported for when the
/// JsConfig.DateHandler == JsonDateHandler.TimestampOffset.</param>
/// <param name="escapeUnicode"> Gets or sets a value indicating if
/// unicode symbols should be serialized as "\uXXXX".</param>
/// <param name="includePublicFields"> If set to true, Interface types will be
/// prefered over concrete types when serializing.</param>
/// <param name="maxDepth"> Sets the maximum depth to avoid circular
/// dependencies.</param>
/// <param name="modelFactory"> Set this to enable your own type
/// construction provider. This is helpful for integration with IoC containers where you need to
/// call the container constructor. Return null if you don't know how to construct the type and
/// the parameterless constructor will be used.</param>
/// <param name="excludePropertyReferences"> The exclude property references.</param>
/// <returns>A JsConfigScope.</returns>
public static JsConfigScope With(
bool? convertObjectTypesIntoStringDictionary = null,
bool? tryToParsePrimitiveTypeValues = null,
bool? tryToParseNumericType = null,
bool? includeNullValues = null,
bool? excludeTypeInfo = null,
bool? includeTypeInfo = null,
bool? emitCamelCaseNames = null,
bool? emitLowercaseUnderscoreNames = null,
JsonDateHandler? dateHandler = null,
JsonTimeSpanHandler? timeSpanHandler = null,
bool? preferInterfaces = null,
bool? throwOnDeserializationError = null,
string typeAttr = null,
Func<Type, string> typeWriter = null,
Func<string, Type> typeFinder = null,
bool? treatEnumAsInteger = null,
bool? alwaysUseUtc = null,
bool? assumeUtc = null,
bool? appendUtcOffset = null,
bool? escapeUnicode = null,
bool? includePublicFields = null,
int? maxDepth = null,
EmptyCtorFactoryDelegate modelFactory = null,
string[] excludePropertyReferences = null)
{
return new JsConfigScope {
ConvertObjectTypesIntoStringDictionary = convertObjectTypesIntoStringDictionary ?? sConvertObjectTypesIntoStringDictionary,
TryToParsePrimitiveTypeValues = tryToParsePrimitiveTypeValues ?? sTryToParsePrimitiveTypeValues,
TryToParseNumericType = tryToParseNumericType ?? sTryToParseNumericType,
IncludeNullValues = includeNullValues ?? sIncludeNullValues,
ExcludeTypeInfo = excludeTypeInfo ?? sExcludeTypeInfo,
IncludeTypeInfo = includeTypeInfo ?? sIncludeTypeInfo,
EmitCamelCaseNames = emitCamelCaseNames ?? sEmitCamelCaseNames,
EmitLowercaseUnderscoreNames = emitLowercaseUnderscoreNames ?? sEmitLowercaseUnderscoreNames,
DateHandler = dateHandler ?? sDateHandler,
TimeSpanHandler = timeSpanHandler ?? sTimeSpanHandler,
PreferInterfaces = preferInterfaces ?? sPreferInterfaces,
ThrowOnDeserializationError = throwOnDeserializationError ?? sThrowOnDeserializationError,
TypeAttr = typeAttr ?? sTypeAttr,
TypeWriter = typeWriter ?? sTypeWriter,
TypeFinder = typeFinder ?? sTypeFinder,
TreatEnumAsInteger = treatEnumAsInteger ?? sTreatEnumAsInteger,
AlwaysUseUtc = alwaysUseUtc ?? sAlwaysUseUtc,
AssumeUtc = assumeUtc ?? sAssumeUtc,
AppendUtcOffset = appendUtcOffset ?? sAppendUtcOffset,
EscapeUnicode = escapeUnicode ?? sEscapeUnicode,
IncludePublicFields = includePublicFields ?? sIncludePublicFields,
MaxDepth = maxDepth ?? sMaxDepth,
ModelFactory = modelFactory ?? ModelFactory,
ExcludePropertyReferences = excludePropertyReferences ?? sExcludePropertyReferences
};
}
/// <summary>Dictionary of convert object types into strings.</summary>
private static bool? sConvertObjectTypesIntoStringDictionary;
/// <summary>
/// Gets or sets a value indicating whether the convert object types into string dictionary.
/// </summary>
/// <value>true if convert object types into string dictionary, false if not.</value>
public static bool ConvertObjectTypesIntoStringDictionary
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ConvertObjectTypesIntoStringDictionary: null)
?? sConvertObjectTypesIntoStringDictionary
?? false;
}
set
{
if (!sConvertObjectTypesIntoStringDictionary.HasValue) sConvertObjectTypesIntoStringDictionary = value;
}
}
/// <summary>The try to parse primitive type values.</summary>
private static bool? sTryToParsePrimitiveTypeValues;
/// <summary>
/// Gets or sets a value indicating whether the try to parse primitive type values.
/// </summary>
/// <value>true if try to parse primitive type values, false if not.</value>
public static bool TryToParsePrimitiveTypeValues
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TryToParsePrimitiveTypeValues: null)
?? sTryToParsePrimitiveTypeValues
?? false;
}
set
{
if (!sTryToParsePrimitiveTypeValues.HasValue) sTryToParsePrimitiveTypeValues = value;
}
}
/// <summary>Type of the try to parse numeric.</summary>
private static bool? sTryToParseNumericType;
/// <summary>Gets or sets a value indicating whether the try to parse numeric type.</summary>
/// <value>true if try to parse numeric type, false if not.</value>
public static bool TryToParseNumericType
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TryToParseNumericType : null)
?? sTryToParseNumericType
?? false;
}
set
{
if (!sTryToParseNumericType.HasValue) sTryToParseNumericType = value;
}
}
/// <summary>The include null values.</summary>
private static bool? sIncludeNullValues;
/// <summary>
/// Gets or sets a value indicating whether the null values should be included.
/// </summary>
/// <value>true if include null values, false if not.</value>
public static bool IncludeNullValues
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludeNullValues: null)
?? sIncludeNullValues
?? false;
}
set
{
if (!sIncludeNullValues.HasValue) sIncludeNullValues = value;
}
}
/// <summary>The treat enum as integer.</summary>
private static bool? sTreatEnumAsInteger;
/// <summary>Gets or sets a value indicating whether the treat enum as integer.</summary>
/// <value>true if treat enum as integer, false if not.</value>
public static bool TreatEnumAsInteger
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TreatEnumAsInteger: null)
?? sTreatEnumAsInteger
?? false;
}
set
{
if (!sTreatEnumAsInteger.HasValue) sTreatEnumAsInteger = value;
}
}
/// <summary>Information describing the exclude type.</summary>
private static bool? sExcludeTypeInfo;
/// <summary>Gets or sets a value indicating whether the exclude type information.</summary>
/// <value>true if exclude type information, false if not.</value>
public static bool ExcludeTypeInfo
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ExcludeTypeInfo: null)
?? sExcludeTypeInfo
?? false;
}
set
{
if (!sExcludeTypeInfo.HasValue) sExcludeTypeInfo = value;
}
}
/// <summary>Information describing the include type.</summary>
private static bool? sIncludeTypeInfo;
/// <summary>
/// Gets or sets a value indicating whether the type information should be included.
/// </summary>
/// <value>true if include type information, false if not.</value>
public static bool IncludeTypeInfo
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludeTypeInfo: null)
?? sIncludeTypeInfo
?? false;
}
set
{
if (!sIncludeTypeInfo.HasValue) sIncludeTypeInfo = value;
}
}
/// <summary>The type attribute.</summary>
private static string sTypeAttr;
/// <summary>Gets or sets the type attribute.</summary>
/// <value>The type attribute.</value>
public static string TypeAttr
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeAttr: null)
?? sTypeAttr
?? JsWriter.TypeAttr;
}
set
{
if (sTypeAttr == null) sTypeAttr = value;
JsonTypeAttrInObject = JsonTypeSerializer.GetTypeAttrInObject(value);
JsvTypeAttrInObject = JsvTypeSerializer.GetTypeAttrInObject(value);
}
}
/// <summary>The JSON type attribute in object.</summary>
private static string sJsonTypeAttrInObject;
/// <summary>The default JSON type attribute in object.</summary>
private static readonly string defaultJsonTypeAttrInObject = JsonTypeSerializer.GetTypeAttrInObject(TypeAttr);
/// <summary>Gets or sets the JSON type attribute in object.</summary>
/// <value>The JSON type attribute in object.</value>
internal static string JsonTypeAttrInObject
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.JsonTypeAttrInObject: null)
?? sJsonTypeAttrInObject
?? defaultJsonTypeAttrInObject;
}
set
{
if (sJsonTypeAttrInObject == null) sJsonTypeAttrInObject = value;
}
}
/// <summary>The jsv type attribute in object.</summary>
private static string sJsvTypeAttrInObject;
/// <summary>The default jsv type attribute in object.</summary>
private static readonly string defaultJsvTypeAttrInObject = JsvTypeSerializer.GetTypeAttrInObject(TypeAttr);
/// <summary>Gets or sets the jsv type attribute in object.</summary>
/// <value>The jsv type attribute in object.</value>
internal static string JsvTypeAttrInObject
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.JsvTypeAttrInObject: null)
?? sJsvTypeAttrInObject
?? defaultJsvTypeAttrInObject;
}
set
{
if (sJsvTypeAttrInObject == null) sJsvTypeAttrInObject = value;
}
}
/// <summary>The type writer.</summary>
private static Func<Type, string> sTypeWriter;
/// <summary>Gets or sets the type writer.</summary>
/// <value>The type writer.</value>
public static Func<Type, string> TypeWriter
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeWriter: null)
?? sTypeWriter
?? AssemblyUtils.WriteType;
}
set
{
if (sTypeWriter == null) sTypeWriter = value;
}
}
/// <summary>The type finder.</summary>
private static Func<string, Type> sTypeFinder;
/// <summary>Gets or sets the type finder.</summary>
/// <value>The type finder.</value>
public static Func<string, Type> TypeFinder
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeFinder: null)
?? sTypeFinder
?? AssemblyUtils.FindType;
}
set
{
if (sTypeFinder == null) sTypeFinder = value;
}
}
/// <summary>The date handler.</summary>
private static JsonDateHandler? sDateHandler;
/// <summary>Gets or sets the date handler.</summary>
/// <value>The date handler.</value>
public static JsonDateHandler DateHandler
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.DateHandler: null)
?? sDateHandler
?? JsonDateHandler.TimestampOffset;
}
set
{
if (!sDateHandler.HasValue) sDateHandler = value;
}
}
/// <summary>Sets which format to use when serializing TimeSpans.</summary>
private static JsonTimeSpanHandler? sTimeSpanHandler;
/// <summary>Gets or sets the time span handler.</summary>
/// <value>The time span handler.</value>
public static JsonTimeSpanHandler TimeSpanHandler
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TimeSpanHandler : null)
?? sTimeSpanHandler
?? JsonTimeSpanHandler.DurationFormat;
}
set
{
if (!sTimeSpanHandler.HasValue) sTimeSpanHandler = value;
}
}
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured to take advantage
/// of <see cref="CLSCompliantAttribute"/> specification, to support user-friendly serialized
/// formats, ie emitting camelCasing for JSON and parsing member names and enum values in a case-
/// insensitive manner.
/// </summary>
private static bool? sEmitCamelCaseNames;
/// <summary>Gets or sets a value indicating whether the emit camel case names.</summary>
/// <value>true if emit camel case names, false if not.</value>
public static bool EmitCamelCaseNames
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.EmitCamelCaseNames: null)
?? sEmitCamelCaseNames
?? false;
}
set
{
if (!sEmitCamelCaseNames.HasValue) sEmitCamelCaseNames = value;
}
}
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured to support web-
/// friendly serialized formats, ie emitting lowercase_underscore_casing for JSON.
/// </summary>
private static bool? sEmitLowercaseUnderscoreNames;
/// <summary>
/// Gets or sets a value indicating whether the emit lowercase underscore names.
/// </summary>
/// <value>true if emit lowercase underscore names, false if not.</value>
public static bool EmitLowercaseUnderscoreNames
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.EmitLowercaseUnderscoreNames: null)
?? sEmitLowercaseUnderscoreNames
?? false;
}
set
{
if (!sEmitLowercaseUnderscoreNames.HasValue) sEmitLowercaseUnderscoreNames = value;
}
}
/// <summary>Define how property names are mapped during deserialization.</summary>
private static JsonPropertyConvention propertyConvention;
/// <summary>Gets or sets the property convention.</summary>
/// <value>The property convention.</value>
public static JsonPropertyConvention PropertyConvention
{
get { return propertyConvention; }
set
{
propertyConvention = value;
switch (propertyConvention)
{
case JsonPropertyConvention.ExactMatch:
DeserializeTypeRefJson.PropertyNameResolver = DeserializeTypeRefJson.DefaultPropertyNameResolver;
break;
case JsonPropertyConvention.Lenient:
DeserializeTypeRefJson.PropertyNameResolver = DeserializeTypeRefJson.LenientPropertyNameResolver;
break;
}
}
}
/// <summary>
/// Gets or sets a value indicating if the framework should throw serialization exceptions or
/// continue regardless of deserialization errors. If <see langword="true"/> the framework will
/// throw; otherwise, it will parse as many fields as possible. The default is
/// <see langword="false"/>.
/// </summary>
private static bool? sThrowOnDeserializationError;
/// <summary>
/// Gets or sets a value indicating whether the throw on deserialization error.
/// </summary>
/// <value>true if throw on deserialization error, false if not.</value>
public static bool ThrowOnDeserializationError
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ThrowOnDeserializationError: null)
?? sThrowOnDeserializationError
?? false;
}
set
{
if (!sThrowOnDeserializationError.HasValue) sThrowOnDeserializationError = value;
}
}
/// <summary>
/// Gets or sets a value indicating if the framework should always convert <see cref="DateTime"/>
/// to UTC format instead of local time.
/// </summary>
private static bool? sAlwaysUseUtc;
/// <summary>Gets or sets a value indicating whether the always use UTC.</summary>
/// <value>true if always use utc, false if not.</value>
public static bool AlwaysUseUtc
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.AlwaysUseUtc: null)
?? sAlwaysUseUtc
?? false;
}
set
{
if (!sAlwaysUseUtc.HasValue) sAlwaysUseUtc = value;
}
}
/// <summary>
/// Gets or sets a value indicating if the framework should always assume <see cref="DateTime"/>
/// is in UTC format if Kind is Unspecified.
/// </summary>
private static bool? sAssumeUtc;
/// <summary>Gets or sets a value indicating whether the assume UTC.</summary>
/// <value>true if assume utc, false if not.</value>
public static bool AssumeUtc
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.AssumeUtc : null)
?? sAssumeUtc
?? false;
}
set
{
if (!sAssumeUtc.HasValue) sAssumeUtc = value;
}
}
/// <summary>
/// Gets or sets whether we should append the Utc offset when we serialize Utc dates. Defaults to
/// no. Only supported for when the JsConfig.DateHandler == JsonDateHandler.TimestampOffset.
/// </summary>
private static bool? sAppendUtcOffset;
/// <summary>Gets or sets the append UTC offset.</summary>
/// <value>The append UTC offset.</value>
public static bool? AppendUtcOffset
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.AppendUtcOffset : null)
?? sAppendUtcOffset
?? null;
}
set
{
if (sAppendUtcOffset == null) sAppendUtcOffset = value;
}
}
/// <summary>
/// Gets or sets a value indicating if unicode symbols should be serialized as "\uXXXX".
/// </summary>
private static bool? sEscapeUnicode;
/// <summary>Gets or sets a value indicating whether the escape unicode.</summary>
/// <value>true if escape unicode, false if not.</value>
public static bool EscapeUnicode
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.EscapeUnicode : null)
?? sEscapeUnicode
?? false;
}
set
{
if (!sEscapeUnicode.HasValue) sEscapeUnicode = value;
}
}
/// <summary>The has serialize function.</summary>
internal static HashSet<Type> HasSerializeFn = new HashSet<Type>();
/// <summary>List of types of the treat value as references.</summary>
public static HashSet<Type> TreatValueAsRefTypes = new HashSet<Type>();
/// <summary>The prefer interfaces.</summary>
private static bool? sPreferInterfaces;
/// <summary>
/// If set to true, Interface types will be prefered over concrete types when serializing.
/// </summary>
/// <value>true if prefer interfaces, false if not.</value>
public static bool PreferInterfaces
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.PreferInterfaces: null)
?? sPreferInterfaces
?? false;
}
set
{
if (!sPreferInterfaces.HasValue) sPreferInterfaces = value;
}
}
/// <summary>Treat as reference type.</summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
internal static bool TreatAsRefType(Type valueType)
{
return TreatValueAsRefTypes.Contains(valueType.IsGeneric() ? valueType.GenericTypeDefinition() : valueType);
}
/// <summary>
/// If set to true, Interface types will be prefered over concrete types when serializing.
/// </summary>
private static bool? sIncludePublicFields;
/// <summary>
/// Gets or sets a value indicating whether the public fields should be included.
/// </summary>
/// <value>true if include public fields, false if not.</value>
public static bool IncludePublicFields
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludePublicFields : null)
?? sIncludePublicFields
?? false;
}
set
{
if (!sIncludePublicFields.HasValue) sIncludePublicFields = value;
}
}
/// <summary>Sets the maximum depth to avoid circular dependencies.</summary>
private static int? sMaxDepth;
/// <summary>Gets or sets the depth of the maximum.</summary>
/// <value>The depth of the maximum.</value>
public static int MaxDepth
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.MaxDepth : null)
?? sMaxDepth
?? int.MaxValue;
}
set
{
if (!sMaxDepth.HasValue) sMaxDepth = value;
}
}
/// <summary>
/// Set this to enable your own type construction provider. This is helpful for integration with
/// IoC containers where you need to call the container constructor. Return null if you don't
/// know how to construct the type and the parameterless constructor will be used.
/// </summary>
private static EmptyCtorFactoryDelegate sModelFactory;
/// <summary>Gets or sets the model factory.</summary>
/// <value>The model factory.</value>
public static EmptyCtorFactoryDelegate ModelFactory
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ModelFactory : null)
?? sModelFactory
?? null;
}
set
{
if (sModelFactory != null) sModelFactory = value;
}
}
/// <summary>The exclude property references.</summary>
private static string[] sExcludePropertyReferences;
/// <summary>Gets or sets the exclude property references.</summary>
/// <value>The exclude property references.</value>
public static string[] ExcludePropertyReferences {
get {
return (JsConfigScope.Current != null ? JsConfigScope.Current.ExcludePropertyReferences : null)
?? sExcludePropertyReferences;
}
set {
if (sExcludePropertyReferences != null) sExcludePropertyReferences = value;
}
}
/// <summary>Resets the given cachesForType.</summary>
public static void Reset()
{
foreach (var rawSerializeType in HasSerializeFn.ToArray())
{
Reset(rawSerializeType);
}
sModelFactory = ReflectionExtensions.GetConstructorMethodToCache;
sTryToParsePrimitiveTypeValues = null;
sTryToParseNumericType = null;
sConvertObjectTypesIntoStringDictionary = null;
sIncludeNullValues = null;
sExcludeTypeInfo = null;
sEmitCamelCaseNames = null;
sEmitLowercaseUnderscoreNames = null;
sDateHandler = null;
sTimeSpanHandler = null;
sPreferInterfaces = null;
sThrowOnDeserializationError = null;
sTypeAttr = null;
sJsonTypeAttrInObject = null;
sJsvTypeAttrInObject = null;
sTypeWriter = null;
sTypeFinder = null;
sTreatEnumAsInteger = null;
sAlwaysUseUtc = null;
sAssumeUtc = null;
sAppendUtcOffset = null;
sEscapeUnicode = null;
sIncludePublicFields = null;
HasSerializeFn = new HashSet<Type>();
TreatValueAsRefTypes = new HashSet<Type> { typeof(KeyValuePair<,>) };
PropertyConvention = JsonPropertyConvention.ExactMatch;
sExcludePropertyReferences = null;
}
/// <summary>Resets the given cachesForType.</summary>
/// <param name="cachesForType">Type of the caches for.</param>
public static void Reset(Type cachesForType)
{
typeof(JsConfig<>).MakeGenericType(new[] { cachesForType }).InvokeReset();
}
/// <summary>
/// A Type extension method that executes the reset on a different thread, and waits for the
/// result.
/// </summary>
/// <param name="genericType">The genericType to act on.</param>
internal static void InvokeReset(this Type genericType)
{
#if NETFX_CORE
MethodInfo methodInfo = genericType.GetTypeInfo().GetType().GetMethodInfo("Reset");
methodInfo.Invoke(null, null);
#else
var methodInfo = genericType.GetMethod("Reset", BindingFlags.Static | BindingFlags.Public);
methodInfo.Invoke(null, null);
#endif
}
#if MONOTOUCH
/// <summary>
/// Provide hint to MonoTouch AOT compiler to pre-compile generic classes for all your DTOs.
/// Just needs to be called once in a static constructor.
/// </summary>
[MonoTouch.Foundation.Preserve]
public static void InitForAot() {
}
[MonoTouch.Foundation.Preserve]
public static void RegisterForAot()
{
RegisterTypeForAot<Poco>();
RegisterElement<Poco, string>();
RegisterElement<Poco, bool>();
RegisterElement<Poco, char>();
RegisterElement<Poco, byte>();
RegisterElement<Poco, sbyte>();
RegisterElement<Poco, short>();
RegisterElement<Poco, ushort>();
RegisterElement<Poco, int>();
RegisterElement<Poco, uint>();
RegisterElement<Poco, long>();
RegisterElement<Poco, ulong>();
RegisterElement<Poco, float>();
RegisterElement<Poco, double>();
RegisterElement<Poco, decimal>();
RegisterElement<Poco, bool?>();
RegisterElement<Poco, char?>();
RegisterElement<Poco, byte?>();
RegisterElement<Poco, sbyte?>();
RegisterElement<Poco, short?>();
RegisterElement<Poco, ushort?>();
RegisterElement<Poco, int?>();
RegisterElement<Poco, uint?>();
RegisterElement<Poco, long?>();
RegisterElement<Poco, ulong?>();
RegisterElement<Poco, float?>();
RegisterElement<Poco, double?>();
RegisterElement<Poco, decimal?>();
//RegisterElement<Poco, JsonValue>();
RegisterTypeForAot<DayOfWeek>(); // used by DateTime
// register built in structs
RegisterTypeForAot<Guid>();
RegisterTypeForAot<TimeSpan>();
RegisterTypeForAot<DateTime>();
RegisterTypeForAot<DateTime?>();
RegisterTypeForAot<TimeSpan?>();
RegisterTypeForAot<Guid?>();
}
[MonoTouch.Foundation.Preserve]
public static void RegisterTypeForAot<T>()
{
AotConfig.RegisterSerializers<T>();
}
[MonoTouch.Foundation.Preserve]
static void RegisterQueryStringWriter()
{
var i = 0;
if (QueryStringWriter<Poco>.WriteFn() != null) i++;
}
[MonoTouch.Foundation.Preserve]
internal static int RegisterElement<T, TElement>()
{
var i = 0;
i += AotConfig.RegisterSerializers<TElement>();
AotConfig.RegisterElement<T, TElement, JsonTypeSerializer>();
AotConfig.RegisterElement<T, TElement, JsvTypeSerializer>();
return i;
}
///<summary>
/// Class contains Ahead-of-Time (AOT) explicit class declarations which is used only to workaround "-aot-only" exceptions occured on device only.
/// </summary>
[MonoTouch.Foundation.Preserve(AllMembers=true)]
internal class AotConfig
{
internal static JsReader<JsonTypeSerializer> jsonReader;
internal static JsWriter<JsonTypeSerializer> jsonWriter;
internal static JsReader<JsvTypeSerializer> jsvReader;
internal static JsWriter<JsvTypeSerializer> jsvWriter;
internal static JsonTypeSerializer jsonSerializer;
internal static JsvTypeSerializer jsvSerializer;
static AotConfig()
{
jsonSerializer = new JsonTypeSerializer();
jsvSerializer = new JsvTypeSerializer();
jsonReader = new JsReader<JsonTypeSerializer>();
jsonWriter = new JsWriter<JsonTypeSerializer>();
jsvReader = new JsReader<JsvTypeSerializer>();
jsvWriter = new JsWriter<JsvTypeSerializer>();
}
internal static int RegisterSerializers<T>()
{
var i = 0;
i += Register<T, JsonTypeSerializer>();
if (jsonSerializer.GetParseFn<T>() != null) i++;
if (jsonSerializer.GetWriteFn<T>() != null) i++;
if (jsonReader.GetParseFn<T>() != null) i++;
if (jsonWriter.GetWriteFn<T>() != null) i++;
i += Register<T, JsvTypeSerializer>();
if (jsvSerializer.GetParseFn<T>() != null) i++;
if (jsvSerializer.GetWriteFn<T>() != null) i++;
if (jsvReader.GetParseFn<T>() != null) i++;
if (jsvWriter.GetWriteFn<T>() != null) i++;
//RegisterCsvSerializer<T>();
RegisterQueryStringWriter();
return i;
}
internal static void RegisterCsvSerializer<T>()
{
CsvSerializer<T>.WriteFn();
CsvSerializer<T>.WriteObject(null, null);
CsvWriter<T>.Write(null, default(IEnumerable<T>));
CsvWriter<T>.WriteRow(null, default(T));
}
public static ParseStringDelegate GetParseFn(Type type)
{
var parseFn = JsonTypeSerializer.Instance.GetParseFn(type);
return parseFn;
}
internal static int Register<T, TSerializer>() where TSerializer : ITypeSerializer
{
var i = 0;
if (JsonWriter<T>.WriteFn() != null) i++;
if (JsonWriter.Instance.GetWriteFn<T>() != null) i++;
if (JsonReader.Instance.GetParseFn<T>() != null) i++;
if (JsonReader<T>.Parse(null) != null) i++;
if (JsonReader<T>.GetParseFn() != null) i++;
//if (JsWriter.GetTypeSerializer<JsonTypeSerializer>().GetWriteFn<T>() != null) i++;
if (new List<T>() != null) i++;
if (new T[0] != null) i++;
JsConfig<T>.ExcludeTypeInfo = false;
if (JsConfig<T>.OnDeserializedFn != null) i++;
if (JsConfig<T>.HasDeserializeFn) i++;
if (JsConfig<T>.SerializeFn != null) i++;
if (JsConfig<T>.DeSerializeFn != null) i++;
//JsConfig<T>.SerializeFn = arg => "";
//JsConfig<T>.DeSerializeFn = arg => default(T);
if (TypeConfig<T>.Properties != null) i++;
/*
if (WriteType<T, TSerializer>.Write != null) i++;
if (WriteType<object, TSerializer>.Write != null) i++;
if (DeserializeBuiltin<T>.Parse != null) i++;
if (DeserializeArray<T[], TSerializer>.Parse != null) i++;
DeserializeType<TSerializer>.ExtractType(null);
DeserializeArrayWithElements<T, TSerializer>.ParseGenericArray(null, null);
DeserializeCollection<TSerializer>.ParseCollection<T>(null, null, null);
DeserializeListWithElements<T, TSerializer>.ParseGenericList(null, null, null);
SpecializedQueueElements<T>.ConvertToQueue(null);
SpecializedQueueElements<T>.ConvertToStack(null);
*/
WriteListsOfElements<T, TSerializer>.WriteList(null, null);
WriteListsOfElements<T, TSerializer>.WriteIList(null, null);
WriteListsOfElements<T, TSerializer>.WriteEnumerable(null, null);
WriteListsOfElements<T, TSerializer>.WriteListValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteIListValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteGenericArrayValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteArray(null, null);
TranslateListWithElements<T>.LateBoundTranslateToGenericICollection(null, null);
TranslateListWithConvertibleElements<T, T>.LateBoundTranslateToGenericICollection(null, null);
QueryStringWriter<T>.WriteObject(null, null);
return i;
}
internal static void RegisterElement<T, TElement, TSerializer>() where TSerializer : ITypeSerializer
{
DeserializeDictionary<TSerializer>.ParseDictionary<T, TElement>(null, null, null, null);
DeserializeDictionary<TSerializer>.ParseDictionary<TElement, T>(null, null, null, null);
ToStringDictionaryMethods<T, TElement, TSerializer>.WriteIDictionary(null, null, null, null);
ToStringDictionaryMethods<TElement, T, TSerializer>.WriteIDictionary(null, null, null, null);
// Include List deserialisations from the Register<> method above. This solves issue where List<Guid> properties on responses deserialise to null.
// No idea why this is happening because there is no visible exception raised. Suspect MonoTouch is swallowing an AOT exception somewhere.
DeserializeArrayWithElements<TElement, TSerializer>.ParseGenericArray(null, null);
DeserializeListWithElements<TElement, TSerializer>.ParseGenericList(null, null, null);
// Cannot use the line below for some unknown reason - when trying to compile to run on device, mtouch bombs during native code compile.
// Something about this line or its inner workings is offensive to mtouch. Luckily this was not needed for my List<Guide> issue.
// DeserializeCollection<JsonTypeSerializer>.ParseCollection<TElement>(null, null, null);
TranslateListWithElements<TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
TranslateListWithConvertibleElements<TElement, TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
}
}
#endif
}
#if MONOTOUCH
[MonoTouch.Foundation.Preserve(AllMembers=true)]
internal class Poco
{
public string Dummy { get; set; }
}
#endif
/// <summary>The js configuration.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
public class JsConfig<T>
{
/// <summary>
/// Always emit type info for this type. Takes precedence over ExcludeTypeInfo.
/// </summary>
public static bool IncludeTypeInfo = false;
/// <summary>Never emit type info for this type.</summary>
public static bool ExcludeTypeInfo = false;
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured to take advantage
/// of <see cref="CLSCompliantAttribute"/> specification, to support user-friendly serialized
/// formats, ie emitting camelCasing for JSON and parsing member names and enum values in a case-
/// insensitive manner.
/// </summary>
public static bool EmitCamelCaseNames = false;
/// <summary>List of names of the emit lowercase underscores.</summary>
public static bool EmitLowercaseUnderscoreNames = false;
/// <summary>Define custom serialization fn for BCL Structs.</summary>
private static Func<T, string> serializeFn;
/// <summary>Gets or sets the serialize function.</summary>
/// <value>The serialize function.</value>
public static Func<T, string> SerializeFn
{
get { return serializeFn; }
set
{
serializeFn = value;
if (value != null)
JsConfig.HasSerializeFn.Add(typeof(T));
else
JsConfig.HasSerializeFn.Remove(typeof(T));
ClearFnCaches();
}
}
/// <summary>Opt-in flag to set some Value Types to be treated as a Ref Type.</summary>
/// <value>true if treat value as reference type, false if not.</value>
public static bool TreatValueAsRefType
{
get { return JsConfig.TreatValueAsRefTypes.Contains(typeof(T)); }
set
{
if (value)
JsConfig.TreatValueAsRefTypes.Add(typeof(T));
else
JsConfig.TreatValueAsRefTypes.Remove(typeof(T));
}
}
/// <summary>Whether there is a fn (raw or otherwise)</summary>
/// <value>true if this object has serialize function, false if not.</value>
public static bool HasSerializeFn
{
get { return serializeFn != null || rawSerializeFn != null; }
}
/// <summary>Define custom raw serialization fn.</summary>
private static Func<T, string> rawSerializeFn;
/// <summary>Gets or sets the raw serialize function.</summary>
/// <value>The raw serialize function.</value>
public static Func<T, string> RawSerializeFn
{
get { return rawSerializeFn; }
set
{
rawSerializeFn = value;
if (value != null)
JsConfig.HasSerializeFn.Add(typeof(T));
else
JsConfig.HasSerializeFn.Remove(typeof(T));
ClearFnCaches();
}
}
/// <summary>Define custom serialization hook.</summary>
private static Func<T, T> onSerializingFn;
/// <summary>Gets or sets the on serializing function.</summary>
/// <value>The on serializing function.</value>
public static Func<T, T> OnSerializingFn
{
get { return onSerializingFn; }
set { onSerializingFn = value; }
}
/// <summary>Define custom deserialization fn for BCL Structs.</summary>
public static Func<string, T> DeSerializeFn;
/// <summary>Define custom raw deserialization fn for objects.</summary>
public static Func<string, T> RawDeserializeFn;
/// <summary>Gets a value indicating whether this object has deserialize function.</summary>
/// <value>true if this object has deserialize function, false if not.</value>
public static bool HasDeserializeFn
{
get { return DeSerializeFn != null || RawDeserializeFn != null; }
}
/// <summary>The on deserialized function.</summary>
private static Func<T, T> onDeserializedFn;
/// <summary>Gets or sets the on deserialized function.</summary>
/// <value>The on deserialized function.</value>
public static Func<T, T> OnDeserializedFn
{
get { return onDeserializedFn; }
set { onDeserializedFn = value; }
}
/// <summary>Exclude specific properties of this type from being serialized.</summary>
public static string[] ExcludePropertyNames;
/// <summary>Writes a function.</summary>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
/// <param name="writer">The writer.</param>
/// <param name="obj"> The object.</param>
public static void WriteFn<TSerializer>(TextWriter writer, object obj)
{
if (RawSerializeFn != null)
{
writer.Write(RawSerializeFn((T)obj));
}
else if (SerializeFn != null)
{
var serializer = JsWriter.GetTypeSerializer<TSerializer>();
serializer.WriteString(writer, SerializeFn((T) obj));
}
else
{
var writerFn = JsonWriter.Instance.GetWriteFn<T>();
writerFn(writer, obj);
}
}
/// <summary>Parse function.</summary>
/// <param name="str">The.</param>
/// <returns>An object.</returns>
public static object ParseFn(string str)
{
return DeSerializeFn(str);
}
/// <summary>Parse function.</summary>
/// <param name="serializer">The serializer.</param>
/// <param name="str"> The.</param>
/// <returns>An object.</returns>
internal static object ParseFn(ITypeSerializer serializer, string str)
{
if (RawDeserializeFn != null)
{
return RawDeserializeFn(str);
}
else
{
return DeSerializeFn(serializer.UnescapeString(str));
}
}
/// <summary>Clears the function caches.</summary>
internal static void ClearFnCaches()
{
typeof(JsonWriter<>).MakeGenericType(new[] { typeof(T) }).InvokeReset();
typeof(JsvWriter<>).MakeGenericType(new[] { typeof(T) }).InvokeReset();
}
/// <summary>Resets this object.</summary>
public static void Reset()
{
RawSerializeFn = null;
DeSerializeFn = null;
}
}
/// <summary>Values that represent JsonPropertyConvention.</summary>
public enum JsonPropertyConvention
{
/// <summary>
/// The property names on target types must match property names in the JSON source
/// </summary>
ExactMatch,
/// <summary>
/// The property names on target types may not match the property names in the JSON source
/// </summary>
Lenient
}
/// <summary>Values that represent JsonDateHandler.</summary>
public enum JsonDateHandler
{
/// <summary>An enum constant representing the timestamp offset option.</summary>
TimestampOffset,
/// <summary>An enum constant representing the dcjs compatible option.</summary>
DCJSCompatible,
/// <summary>An enum constant representing the ISO 8601 option.</summary>
ISO8601
}
/// <summary>Values that represent JsonTimeSpanHandler.</summary>
public enum JsonTimeSpanHandler
{
/// <summary>
/// Uses the xsd format like PT15H10M20S
/// </summary>
DurationFormat,
/// <summary>
/// Uses the standard .net ToString method of the TimeSpan class
/// </summary>
StandardFormat
}
}
| |
//Synchronous template
//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 21.01.2016
// Autor Guenther Schindler and Fabio Gruber
// This script prepares ODB++ V8 to load in NBI
// A copy of the job will be made to the tmp directory
// Soldermask layers will be made positive
// Coppyer layers are cut out with drills
// Job opens in NBI Catia
// Prepare Data for real 3D.
//-----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
using System.Diagnostics;
namespace PCBIScript
{
public class PScript : IPCBIScript
{
public PScript()
{
}
private IPCBIWindow Parent;
public void Execute(IPCBIWindow parent)
{
//your code here
this.Parent = parent;
if (MakeWorkingCopy() == DialogResult.OK)
{
RemoveObjectsOutsideProfile(parent);
parent.UIAction.Execute(ID_ActionItem.ID_CHANGE_UNIT_To_MILS); //important for odb string
PrepareFor3D_inNBI(parent);
}
parent.UpdateView();
}
private DialogResult MakeWorkingCopy()
{
DialogResult res = DialogResult.Abort;
string stepName = this.Parent.GetCurrentStep().Name;
string pathForWorkingODB = Path.GetTempPath() + "NBI\\" +Parent.GetJobName()+"_"+ stepName + "\\";
if (Directory.Exists(pathForWorkingODB))
{
Directory.Delete(pathForWorkingODB, true);
System.Threading.Thread.Sleep(400);
}
Parent.SaveJob(pathForWorkingODB, false);
if (!Parent.LoadODBJob(pathForWorkingODB))
MessageBox.Show("Can't create a temporary working copy of ODB-Data.", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
else
{
//res = MessageBox.Show("Continue", "Workingcopy is loaded", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
return DialogResult.OK;
}
return res;
}
private void PrepareFor3D_inNBI(IPCBIWindow Parent)
{
IMatrix matrix = Parent.GetMatrix();
IStep step = Parent.GetCurrentStep();
MakeSolderMaskPositive(matrix);
MakeDrillCutOutOnCopperLayers(Parent, matrix, step);
Parent.UIAction.Execute(ID_ActionItem.ID_CLEAR_SELECTION);
Parent.UIAction.Execute(ID_ActionItem.ID_ALL_LAYER_OFF);
Parent.UIAction.Execute(ID_ActionItem.ID_ALL_SIGNAL_LAYER_ON);
Parent.UpdateView();
Parent.UIAction.Execute(ID_ActionItem.ID_SAVE);
String JobLocation = Parent.GetODBJobDirectory();
string pathNBICatia = @"C:\Program Files (x86)\NativeBoardImport\NBI Catia V5\NBI_Catia_V5.exe";
if (File.Exists(pathNBICatia))
{
try
{
Process.Start(pathNBICatia + "\"" + JobLocation + "\"");
}
catch (Exception ex)
{
PCB_Investigator.Localization.PCBILocalization.ShowMsgBox("Can not open NBI, because "+ex.Message.ToString(), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
private static void MakeDrillCutOutOnCopperLayers(IPCBIWindow Parent, IMatrix matrix, IStep step)
{
IFilter filter = new IFilter(Parent);
int counterDielectirc = 1;
foreach (string layerName in matrix.GetAllDrillLayerNames())
{
ILayer drill_layer = step.GetLayer(layerName);
bool lastWasSignal = false;
foreach (string sigLayer in matrix.GetAllLayerWithThisDrills(layerName))
{
var type = matrix.GetMatrixLayerType(sigLayer);
if (type != MatrixLayerType.Dielectric && !matrix.IsSignalLayer(sigLayer)) //only dielectric und signals
continue;
if ((type == MatrixLayerType.Power_ground || type == MatrixLayerType.Signal))
{
if (lastWasSignal)
{
//if last and current one are signals -> we need a dielectric between both
IODBLayer dielectric = filter.CreateEmptyODBLayer("dielectric_" + counterDielectirc, step.Name);
counterDielectirc++;
if (dielectric != null)
{
AddDrillObjects(filter, drill_layer, MatrixLayerType.Dielectric, dielectric);
matrix.SetMatrixLayerIndex(dielectric.GetLayerName(), matrix.GetRawIndexByName(sigLayer));
matrix.SetMatrixLayerParameter(dielectric.GetLayerName(), MatrixLayerContext.Board, MatrixLayerPolarity.Negative, MatrixLayerType.Dielectric, -1, -1);
matrix.SetLayerHeight(dielectric.GetLayerName(), 5); //value in mils
matrix.UpdateDataAndList(); //update list for correct order
}
else
Debug.WriteLine("error, can't create dielectric...");
}
lastWasSignal = true;
}
else
lastWasSignal = false;
IODBLayer odb_sig_layer = (IODBLayer)step.GetLayer(sigLayer);
if (drill_layer.GetType() == typeof(IODBLayer))
{
AddDrillObjects(filter, drill_layer, type, odb_sig_layer);
drill_layer.EnableLayer(false);
odb_sig_layer.EnableLayer(true);
}
}
}
matrix.UpdateDataAndList();
Parent.UpdateControlsAndResetView();
}
private static void AddDrillObjects(IFilter filter, ILayer drill_layer, MatrixLayerType type, IODBLayer odb_sig_layer)
{
Dictionary<int, int> symbolUsed = new Dictionary<int, int>();
foreach (IODBObject obj in drill_layer.GetAllLayerObjects())
{
#region one drill layer
obj.Select(true);
if (obj.Type == IObjectType.Pad)
{
IPadSpecifics ops = (IPadSpecifics)obj.GetSpecifics();
if (type != MatrixLayerType.Dielectric)
ops.Positive = false;
else
ops.Positive = true;
if (!symbolUsed.ContainsKey(ops.ShapeIndex))
{
int index = IFilter.AddToolFromODBString(odb_sig_layer, ops.ODBSymbol_String);
symbolUsed.Add(ops.ShapeIndex, index);
}
ops.ShapeIndex = symbolUsed[ops.ShapeIndex];
IODBObject pad = filter.CreatePad(odb_sig_layer);
pad.SetSpecifics(ops);
}
else if (obj.Type == IObjectType.Line)
{
ILineSpecifics ops = (ILineSpecifics)obj.GetSpecifics();
if (type != MatrixLayerType.Dielectric)
ops.Positive = false;
else
ops.Positive = true;
if (!symbolUsed.ContainsKey(ops.ShapeIndex))
{
int index = IFilter.AddToolFromODBString(odb_sig_layer, ops.ODBSymbol_String);
symbolUsed.Add(ops.ShapeIndex, index);
}
ops.ShapeIndex = symbolUsed[ops.ShapeIndex];
IODBObject line = filter.CreateLine(odb_sig_layer);
line.SetSpecifics(ops);
}
#endregion
}
}
private static void MakeSolderMaskPositive(IMatrix matrix)
{
foreach (string layerName in matrix.GetAllLayerNames())
{
if (matrix.GetMatrixLayerType(layerName) == MatrixLayerType.Solder_mask && matrix.GetMatrixLayerContext(layerName) == MatrixLayerContext.Board)
{
matrix.MakeLayerPositive(layerName);
}
}
}
public void RemoveObjectsOutsideProfile(IPCBIWindow Parent)
{
IStep step = Parent.GetCurrentStep();
IMatrix matrix = Parent.GetMatrix();
if (step == null) return;
IODBObject profile = step.GetPCBOutlineAsODBObject();
foreach (string layerName in step.GetAllLayerNames())
{
if (matrix.GetMatrixLayerType(layerName) == MatrixLayerType.Component)
continue; //no component layers
ILayer Layer = step.GetLayer(layerName);
if (Layer is IODBLayer)
{
List<IODBObject> objectsToDelete = new List<IODBObject>();
IODBLayer layer = (IODBLayer)Layer;
foreach (IODBObject obj in layer.GetAllLayerObjects())
{
if (profile.IsPointOfSecondObjectIncluded(obj))
{
//inside not delete
}
else
{
objectsToDelete.Add(obj);
}
}
layer.RemoveObjects(objectsToDelete);
}
}
Parent.UpdateView();
}
}
}
| |
namespace EIDSS.FlexibleForms
{
partial class FFDeterminants
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FFDeterminants));
this.treeDeterminant = new DevExpress.XtraTreeList.TreeList();
this.colDeterminantName = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.repositoryItemLookUpEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.repositoryItemCheckedComboBoxEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemCheckedComboBoxEdit();
this.grpSearchParameter = new DevExpress.XtraEditors.GroupControl();
this.lbSearchParameterResults = new DevExpress.XtraEditors.ListBoxControl();
this.pnlSearchParameters = new DevExpress.XtraEditors.PanelControl();
this.cbSearchParameterCriteria = new DevExpress.XtraEditors.ComboBoxEdit();
this.lSearchParameterResults = new DevExpress.XtraEditors.LabelControl();
this.bSearchParameterStart = new DevExpress.XtraEditors.SimpleButton();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
((System.ComponentModel.ISupportInitialize)(this.treeDeterminant)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemCheckedComboBoxEdit1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grpSearchParameter)).BeginInit();
this.grpSearchParameter.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.lbSearchParameterResults)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pnlSearchParameters)).BeginInit();
this.pnlSearchParameters.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.cbSearchParameterCriteria.Properties)).BeginInit();
this.SuspendLayout();
//
// treeDeterminant
//
this.treeDeterminant.AccessibleDescription = null;
this.treeDeterminant.AccessibleName = null;
resources.ApplyResources(this.treeDeterminant, "treeDeterminant");
this.treeDeterminant.BackgroundImage = null;
this.treeDeterminant.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] {
this.colDeterminantName});
this.treeDeterminant.Font = null;
this.treeDeterminant.Name = "treeDeterminant";
this.treeDeterminant.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.repositoryItemLookUpEdit1,
this.repositoryItemCheckedComboBoxEdit1});
this.treeDeterminant.KeyUp += new System.Windows.Forms.KeyEventHandler(this.OnTreeDeterminantKeyUp);
this.treeDeterminant.Click += new System.EventHandler(this.OnTreeDeterminantClick);
//
// colDeterminantName
//
resources.ApplyResources(this.colDeterminantName, "colDeterminantName");
this.colDeterminantName.FieldName = "idfsParameter";
this.colDeterminantName.Name = "colDeterminantName";
this.colDeterminantName.OptionsColumn.AllowEdit = false;
this.colDeterminantName.OptionsColumn.AllowMove = false;
this.colDeterminantName.OptionsColumn.AllowMoveToCustomizationForm = false;
this.colDeterminantName.OptionsColumn.ShowInCustomizationForm = false;
//
// repositoryItemLookUpEdit1
//
this.repositoryItemLookUpEdit1.AccessibleDescription = null;
this.repositoryItemLookUpEdit1.AccessibleName = null;
resources.ApplyResources(this.repositoryItemLookUpEdit1, "repositoryItemLookUpEdit1");
this.repositoryItemLookUpEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("repositoryItemLookUpEdit1.Buttons"))))});
this.repositoryItemLookUpEdit1.Name = "repositoryItemLookUpEdit1";
this.repositoryItemLookUpEdit1.ShowFooter = false;
this.repositoryItemLookUpEdit1.ShowHeader = false;
//
// repositoryItemCheckedComboBoxEdit1
//
this.repositoryItemCheckedComboBoxEdit1.AccessibleDescription = null;
this.repositoryItemCheckedComboBoxEdit1.AccessibleName = null;
resources.ApplyResources(this.repositoryItemCheckedComboBoxEdit1, "repositoryItemCheckedComboBoxEdit1");
this.repositoryItemCheckedComboBoxEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Buttons"))))});
this.repositoryItemCheckedComboBoxEdit1.CloseOnLostFocus = false;
this.repositoryItemCheckedComboBoxEdit1.CloseOnOuterMouseClick = false;
this.repositoryItemCheckedComboBoxEdit1.Mask.AutoComplete = ((DevExpress.XtraEditors.Mask.AutoCompleteType)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.AutoComplete")));
this.repositoryItemCheckedComboBoxEdit1.Mask.BeepOnError = ((bool)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.BeepOnError")));
this.repositoryItemCheckedComboBoxEdit1.Mask.EditMask = resources.GetString("repositoryItemCheckedComboBoxEdit1.Mask.EditMask");
this.repositoryItemCheckedComboBoxEdit1.Mask.IgnoreMaskBlank = ((bool)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.IgnoreMaskBlank")));
this.repositoryItemCheckedComboBoxEdit1.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.MaskType")));
this.repositoryItemCheckedComboBoxEdit1.Mask.PlaceHolder = ((char)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.PlaceHolder")));
this.repositoryItemCheckedComboBoxEdit1.Mask.SaveLiteral = ((bool)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.SaveLiteral")));
this.repositoryItemCheckedComboBoxEdit1.Mask.ShowPlaceHolders = ((bool)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.ShowPlaceHolders")));
this.repositoryItemCheckedComboBoxEdit1.Mask.UseMaskAsDisplayFormat = ((bool)(resources.GetObject("repositoryItemCheckedComboBoxEdit1.Mask.UseMaskAsDisplayFormat")));
this.repositoryItemCheckedComboBoxEdit1.Name = "repositoryItemCheckedComboBoxEdit1";
this.repositoryItemCheckedComboBoxEdit1.ShowButtons = false;
this.repositoryItemCheckedComboBoxEdit1.ValueMember = "Actions";
//
// grpSearchParameter
//
this.grpSearchParameter.AccessibleDescription = null;
this.grpSearchParameter.AccessibleName = null;
resources.ApplyResources(this.grpSearchParameter, "grpSearchParameter");
this.grpSearchParameter.Controls.Add(this.lbSearchParameterResults);
this.grpSearchParameter.Controls.Add(this.pnlSearchParameters);
this.grpSearchParameter.Name = "grpSearchParameter";
//
// lbSearchParameterResults
//
this.lbSearchParameterResults.AccessibleDescription = null;
this.lbSearchParameterResults.AccessibleName = null;
resources.ApplyResources(this.lbSearchParameterResults, "lbSearchParameterResults");
this.lbSearchParameterResults.BackgroundImage = null;
this.lbSearchParameterResults.DisplayMember = "FullPathStr";
this.lbSearchParameterResults.Name = "lbSearchParameterResults";
this.lbSearchParameterResults.ValueMember = "idfsParameterID";
this.lbSearchParameterResults.Click += new System.EventHandler(this.OnLbSearchParameterResultsClick);
//
// pnlSearchParameters
//
this.pnlSearchParameters.AccessibleDescription = null;
this.pnlSearchParameters.AccessibleName = null;
resources.ApplyResources(this.pnlSearchParameters, "pnlSearchParameters");
this.pnlSearchParameters.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.pnlSearchParameters.Controls.Add(this.cbSearchParameterCriteria);
this.pnlSearchParameters.Controls.Add(this.lSearchParameterResults);
this.pnlSearchParameters.Controls.Add(this.bSearchParameterStart);
this.pnlSearchParameters.Controls.Add(this.labelControl1);
this.pnlSearchParameters.Name = "pnlSearchParameters";
//
// cbSearchParameterCriteria
//
resources.ApplyResources(this.cbSearchParameterCriteria, "cbSearchParameterCriteria");
this.cbSearchParameterCriteria.BackgroundImage = null;
this.cbSearchParameterCriteria.EditValue = null;
this.cbSearchParameterCriteria.Name = "cbSearchParameterCriteria";
this.cbSearchParameterCriteria.Properties.AccessibleDescription = null;
this.cbSearchParameterCriteria.Properties.AccessibleName = null;
this.cbSearchParameterCriteria.Properties.AutoHeight = ((bool)(resources.GetObject("cbSearchParameterCriteria.Properties.AutoHeight")));
this.cbSearchParameterCriteria.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("cbSearchParameterCriteria.Properties.Buttons"))))});
this.cbSearchParameterCriteria.Properties.NullValuePrompt = resources.GetString("cbSearchParameterCriteria.Properties.NullValuePrompt");
this.cbSearchParameterCriteria.Properties.NullValuePromptShowForEmptyValue = ((bool)(resources.GetObject("cbSearchParameterCriteria.Properties.NullValuePromptShowForEmptyValue")));
//
// lSearchParameterResults
//
this.lSearchParameterResults.AccessibleDescription = null;
this.lSearchParameterResults.AccessibleName = null;
resources.ApplyResources(this.lSearchParameterResults, "lSearchParameterResults");
this.lSearchParameterResults.Name = "lSearchParameterResults";
//
// bSearchParameterStart
//
this.bSearchParameterStart.AccessibleDescription = null;
this.bSearchParameterStart.AccessibleName = null;
resources.ApplyResources(this.bSearchParameterStart, "bSearchParameterStart");
this.bSearchParameterStart.BackgroundImage = null;
this.bSearchParameterStart.Name = "bSearchParameterStart";
this.bSearchParameterStart.Click += new System.EventHandler(this.OnBSearchParameterStartClick);
//
// labelControl1
//
this.labelControl1.AccessibleDescription = null;
this.labelControl1.AccessibleName = null;
resources.ApplyResources(this.labelControl1, "labelControl1");
this.labelControl1.Name = "labelControl1";
//
// FFDeterminants
//
this.AccessibleDescription = null;
this.AccessibleName = null;
resources.ApplyResources(this, "$this");
this.BackgroundImage = null;
this.Controls.Add(this.grpSearchParameter);
this.Controls.Add(this.treeDeterminant);
this.FormID = "F03";
this.Name = "FFDeterminants";
this.ShowDeleteButton = false;
this.ShowSaveButton = false;
this.Load += new System.EventHandler(this.OnFFDeterminantsLoad);
this.Controls.SetChildIndex(this.treeDeterminant, 0);
this.Controls.SetChildIndex(this.grpSearchParameter, 0);
((System.ComponentModel.ISupportInitialize)(this.treeDeterminant)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemCheckedComboBoxEdit1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grpSearchParameter)).EndInit();
this.grpSearchParameter.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.lbSearchParameterResults)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pnlSearchParameters)).EndInit();
this.pnlSearchParameters.ResumeLayout(false);
this.pnlSearchParameters.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.cbSearchParameterCriteria.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraTreeList.TreeList treeDeterminant;
private DevExpress.XtraTreeList.Columns.TreeListColumn colDeterminantName;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit1;
private DevExpress.XtraEditors.Repository.RepositoryItemCheckedComboBoxEdit repositoryItemCheckedComboBoxEdit1;
private DevExpress.XtraEditors.GroupControl grpSearchParameter;
private DevExpress.XtraEditors.ListBoxControl lbSearchParameterResults;
private DevExpress.XtraEditors.PanelControl pnlSearchParameters;
private DevExpress.XtraEditors.LabelControl lSearchParameterResults;
private DevExpress.XtraEditors.SimpleButton bSearchParameterStart;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.ComboBoxEdit cbSearchParameterCriteria;
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace AnalysisTests {
[TestClass]
public class DatabaseTest {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
[TestMethod, Priority(1)]
public void Invalid2xDatabase() {
using (var db = MockCompletionDB.Create(PythonLanguageVersion.V27,
// __bad_builtin__ is missing str
Tuple.Create("__bad_builtin__", "__builtin__")
)) {
var ptd = db.Database;
Assert.IsNotNull(ptd.GetModule("__builtin__"));
var analyzer = db.MakeAnalyzer();
// String type should have been loaded from the default DB.
Assert.IsNotNull(analyzer.ClassInfos[BuiltinTypeId.Str]);
Assert.IsNotNull(analyzer.ClassInfos[BuiltinTypeId.Bytes]);
}
}
[TestMethod, Priority(1)]
public void Invalid3xDatabase() {
using (var db = MockCompletionDB.Create(PythonLanguageVersion.V33,
// bad_builtins is missing str
Tuple.Create("bad_builtins", "builtins")
)) {
var ptd = db.Database;
Assert.IsNotNull(ptd.GetModule("builtins"));
var analyzer = db.MakeAnalyzer();
// String type should have been loaded from the default DB.
Assert.IsNotNull(analyzer.ClassInfos[BuiltinTypeId.Str]);
// String type is the same as unicode, but not bytes.
Assert.AreNotEqual(analyzer.Types[BuiltinTypeId.Bytes], analyzer.Types[BuiltinTypeId.Str]);
Assert.AreEqual(analyzer.Types[BuiltinTypeId.Unicode], analyzer.Types[BuiltinTypeId.Str]);
// String's module name is 'builtins' and not '__builtin__'
// because we replace the module name based on the version
// despite using the 2.7-based database.
Assert.AreEqual("builtins", analyzer.Types[BuiltinTypeId.Str].DeclaringModule.Name);
}
}
[TestMethod, Priority(1)]
public void LayeredDatabase() {
using (var db1 = MockCompletionDB.Create(PythonLanguageVersion.V27, "os"))
using (var db2 = MockCompletionDB.Create(PythonLanguageVersion.V27, "posixpath")) {
Assert.IsNotNull(db1.Database.GetModule("os"));
Assert.IsNull(db1.Database.GetModule("posixpath"));
var ptd1 = db1.Database;
var ptd2 = ptd1.Clone();
ptd2.LoadDatabase(db2.DBPath);
Assert.IsNull(ptd1.GetModule("posixpath"));
Assert.IsNotNull(ptd2.GetModule("os"));
Assert.IsNotNull(ptd2.GetModule("posixpath"));
Assert.AreSame(ptd1.GetModule("os"), db1.Database.GetModule("os"));
Assert.AreSame(ptd2.GetModule("os"), db1.Database.GetModule("os"));
}
var factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
using (var db1 = MockCompletionDB.Create(PythonLanguageVersion.V27, "os", "posixpath"))
using (var db2 = MockCompletionDB.Create(PythonLanguageVersion.V27, "posixpath")) {
var ptd1 = new PythonTypeDatabase(factory, new[] {
db1.DBPath,
db2.DBPath
});
Assert.IsNotNull(ptd1.GetModule("posixpath"));
Assert.AreNotSame(ptd1.GetModule("posixpath"), db1.Database.GetModule("posixpath"));
Assert.AreNotSame(ptd1.GetModule("posixpath"), db2.Database.GetModule("posixpath"));
var ptd2 = new PythonTypeDatabase(factory, new[] {
db2.DBPath,
db1.DBPath
});
Assert.IsNotNull(ptd2.GetModule("posixpath"));
Assert.AreNotSame(ptd2.GetModule("posixpath"), db1.Database.GetModule("posixpath"));
Assert.AreNotSame(ptd2.GetModule("posixpath"), db2.Database.GetModule("posixpath"));
}
using (var db1 = MockCompletionDB.Create(PythonLanguageVersion.V27, "os", "posixpath"))
using (var db2 = MockCompletionDB.Create(PythonLanguageVersion.V27, "posixpath"))
using (var db3 = MockCompletionDB.Create(PythonLanguageVersion.V27, "ntpath")) {
var ptd = db1.Database;
Assert.AreSame(ptd.GetModule("posixpath"), db1.Database.GetModule("posixpath"));
Assert.AreNotSame(ptd.GetModule("posixpath"), db2.Database.GetModule("posixpath"));
var ptd2 = ptd.Clone();
ptd2.LoadDatabase(db2.DBPath);
Assert.AreNotSame(ptd2.GetModule("posixpath"), ptd.GetModule("posixpath"));
var ptd3 = ptd2.Clone();
ptd3.LoadDatabase(db3.DBPath);
Assert.IsNotNull(ptd3.GetModule("ntpath"));
Assert.IsNull(ptd2.GetModule("ntpath"));
}
}
[TestMethod, Priority(1)]
public void PropertyOfUnknownType() {
using (var db = MockCompletionDB.Create(PythonLanguageVersion.V34, "property_of_unknown_type")) {
var ptd = db.Database;
var module = ptd.GetModule("property_of_unknown_type");
Assert.IsNotNull(module);
var cls = module.GetMember(null, "Class");
Assert.IsInstanceOfType(cls, typeof(IPythonType));
var propObj = ((IPythonType)cls).GetMember(null, "no_return");
Assert.IsInstanceOfType(propObj, typeof(IBuiltinProperty));
var prop = (IBuiltinProperty)propObj;
// The type is unspecified in the DB, so it should be object
Assert.IsNotNull(prop.Type, "Property type should never be null");
Assert.AreEqual(BuiltinTypeId.Object, prop.Type.TypeId, "Property should be of type object");
Assert.AreEqual("property of type object", prop.Description);
// Ensure that we are still getting properties at all
propObj = ((IPythonType)cls).GetMember(null, "with_return");
Assert.IsInstanceOfType(propObj, typeof(IBuiltinProperty));
prop = (IBuiltinProperty)propObj;
Assert.IsNotNull(prop.Type, "Property should not have null type");
Assert.AreEqual("property of type int", prop.Description);
}
}
}
[TestClass]
public class DatabaseTest27 {
static DatabaseTest27() {
AssertListener.Initialize();
PythonTestData.Deploy(includeTestData: false);
}
public virtual PythonVersion Python {
get { return PythonPaths.Python27 ?? PythonPaths.Python27_x64; }
}
[TestMethod, Priority(1)]
public async Task GetSearchPaths() {
Python.AssertInstalled();
var paths = await PythonTypeDatabase.GetUncachedDatabaseSearchPathsAsync(Python.InterpreterPath);
Console.WriteLine("Paths for {0}", Python.InterpreterPath);
foreach (var path in paths) {
Console.WriteLine("{0} {1}", path.Path, path.IsStandardLibrary ? "(stdlib)" : "");
}
// Python.PrefixPath and LibraryPath should be included.
// We can't assume anything else
AssertUtil.ContainsAtLeast(paths.Select(p => p.Path.ToLowerInvariant().TrimEnd('\\')),
Python.PrefixPath.ToLowerInvariant().TrimEnd('\\'),
Path.Combine(Python.PrefixPath, "Lib").ToLowerInvariant().TrimEnd('\\')
);
// All paths should exist
AssertUtil.ArrayEquals(paths.Where(p => !Directory.Exists(p.Path)).ToList(), new PythonLibraryPath[0]);
// Ensure we can round-trip the entries via ToString/Parse
var asStrings = paths.Select(p => p.ToString()).ToList();
var asPaths = asStrings.Select(PythonLibraryPath.Parse).ToList();
var asStrings2 = asPaths.Select(p => p.ToString()).ToList();
AssertUtil.ArrayEquals(asStrings, asStrings2);
AssertUtil.ArrayEquals(paths, asPaths, (o1, o2) => {
PythonLibraryPath p1 = (PythonLibraryPath)o1, p2 = (PythonLibraryPath)o2;
return p1.Path == p2.Path && p1.IsStandardLibrary == p2.IsStandardLibrary;
});
var dbPath = TestData.GetTempPath(randomSubPath: true);
Assert.IsNull(PythonTypeDatabase.GetCachedDatabaseSearchPaths(dbPath),
"Should not have found cached paths in an empty directory");
PythonTypeDatabase.WriteDatabaseSearchPaths(dbPath, paths);
Assert.IsTrue(File.Exists(Path.Combine(dbPath, "database.path")));
var paths2 = PythonTypeDatabase.GetCachedDatabaseSearchPaths(dbPath);
AssertUtil.ArrayEquals(paths, paths2, (o1, o2) => {
PythonLibraryPath p1 = (PythonLibraryPath)o1, p2 = (PythonLibraryPath)o2;
return p1.Path == p2.Path && p1.IsStandardLibrary == p2.IsStandardLibrary;
});
}
[TestMethod, Priority(1)]
public async Task GetExpectedDatabaseModules() {
Python.AssertInstalled();
var db = PythonTypeDatabase.GetDatabaseExpectedModules(
Python.Version.ToVersion(),
await PythonTypeDatabase.GetUncachedDatabaseSearchPathsAsync(Python.InterpreterPath)
).ToList();
var stdlib = db[0];
AssertUtil.ContainsAtLeast(stdlib.Select(mp => mp.FullName),
"os", "ctypes.__init__", "encodings.utf_8", "ntpath"
);
}
}
[TestClass]
public class DatabaseTest25 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python25 ?? PythonPaths.Python25_x64; }
}
}
[TestClass]
public class DatabaseTest26 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python26 ?? PythonPaths.Python26_x64; }
}
}
[TestClass]
public class DatabaseTest30 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python30 ?? PythonPaths.Python30_x64; }
}
}
[TestClass]
public class DatabaseTest31 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python31 ?? PythonPaths.Python31_x64; }
}
}
[TestClass]
public class DatabaseTest32 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python32 ?? PythonPaths.Python32_x64; }
}
}
[TestClass]
public class DatabaseTest33 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python33 ?? PythonPaths.Python33_x64; }
}
}
[TestClass]
public class DatabaseTest34 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python34 ?? PythonPaths.Python34_x64; }
}
}
[TestClass]
public class DatabaseTest35 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.Python35 ?? PythonPaths.Python35_x64; }
}
}
[TestClass]
public class DatabaseTestIPy27 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.IronPython27; }
}
}
[TestClass]
public class DatabaseTestIPy27x64 : DatabaseTest27 {
public override PythonVersion Python {
get { return PythonPaths.IronPython27_x64; }
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !__IOS__ && !WINDOWS_PHONE && !__ANDROID__ && !NETSTANDARD
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
#if WCF_SUPPORTED
using System.ServiceModel;
using System.ServiceModel.Channels;
#endif
using System.Threading;
#if SILVERLIGHT
using System.Windows;
using System.Windows.Threading;
#endif
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
using NLog.LogReceiverService;
/// <summary>
/// Sends log messages to a NLog Receiver Service (using WCF or Web Services).
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/LogReceiverService-target">Documentation on NLog Wiki</seealso>
[Target("LogReceiverService")]
public class LogReceiverWebServiceTarget : Target
{
private readonly LogEventInfoBuffer buffer = new LogEventInfoBuffer(10000, false, 10000);
private bool inCall;
/// <summary>
/// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class.
/// </summary>
public LogReceiverWebServiceTarget()
{
this.Parameters = new List<MethodCallParameter>();
}
/// <summary>
/// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class.
/// </summary>
/// <param name="name">Name of the target.</param>
public LogReceiverWebServiceTarget(string name) : this()
{
this.Name = name;
}
/// <summary>
/// Gets or sets the endpoint address.
/// </summary>
/// <value>The endpoint address.</value>
/// <docgen category='Connection Options' order='10' />
[RequiredParameter]
public virtual string EndpointAddress { get; set; }
#if WCF_SUPPORTED
/// <summary>
/// Gets or sets the name of the endpoint configuration in WCF configuration file.
/// </summary>
/// <value>The name of the endpoint configuration.</value>
/// <docgen category='Connection Options' order='10' />
public string EndpointConfigurationName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use binary message encoding.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool UseBinaryEncoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply)
/// </summary>
/// <docgen category='Connection Options' order='10' />
public bool UseOneWayContract { get; set; }
#endif
/// <summary>
/// Gets or sets the client ID.
/// </summary>
/// <value>The client ID.</value>
/// <docgen category='Payload Options' order='10' />
public Layout ClientId { get; set; }
/// <summary>
/// Gets the list of parameters.
/// </summary>
/// <value>The parameters.</value>
/// <docgen category='Payload Options' order='10' />
[ArrayParameter(typeof(MethodCallParameter), "parameter")]
public IList<MethodCallParameter> Parameters { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to include per-event properties in the payload sent to the server.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeEventProperties { get; set; }
/// <summary>
/// Called when log events are being sent (test hook).
/// </summary>
/// <param name="events">The events.</param>
/// <param name="asyncContinuations">The async continuations.</param>
/// <returns>True if events should be sent, false to stop processing them.</returns>
protected internal virtual bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations)
{
return true;
}
/// <summary>
/// Writes logging event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Logging event to be written out.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.Write((IList<AsyncLogEventInfo>)new[] { logEvent });
}
/// <summary>
/// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents)
///
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
[Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")]
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Write((IList<AsyncLogEventInfo>)logEvents);
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Append" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
// if web service call is being processed, buffer new events and return
// lock is being held here
if (this.inCall)
{
for (int i = 0; i < logEvents.Count; ++i)
{
this.PrecalculateVolatileLayouts(logEvents[i].LogEvent);
this.buffer.Append(logEvents[i]);
}
return;
}
// OptimizeBufferReuse = true, will reuse the input-array on method-exit (so we make clone here)
AsyncLogEventInfo[] logEventsArray = new AsyncLogEventInfo[logEvents.Count];
logEvents.CopyTo(logEventsArray, 0);
var networkLogEvents = this.TranslateLogEvents(logEventsArray);
this.Send(networkLogEvents, logEventsArray, null);
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.SendBufferedEvents(asyncContinuation);
}
private static int AddValueAndGetStringOrdinal(NLogEvents context, Dictionary<string, int> stringTable, string value)
{
int stringIndex;
if (!stringTable.TryGetValue(value, out stringIndex))
{
stringIndex = context.Strings.Count;
stringTable.Add(value, stringIndex);
context.Strings.Add(value);
}
return stringIndex;
}
private NLogEvents TranslateLogEvents(IList<AsyncLogEventInfo> logEvents)
{
if (logEvents.Count == 0 && !LogManager.ThrowExceptions)
{
InternalLogger.Error("LogEvents array is empty, sending empty event...");
return new NLogEvents();
}
string clientID = string.Empty;
if (this.ClientId != null)
{
clientID = this.ClientId.Render(logEvents[0].LogEvent);
}
var networkLogEvents = new NLogEvents
{
ClientName = clientID,
LayoutNames = new StringCollection(),
Strings = new StringCollection(),
BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
};
var stringTable = new Dictionary<string, int>();
for (int i = 0; i < this.Parameters.Count; ++i)
{
networkLogEvents.LayoutNames.Add(this.Parameters[i].Name);
}
if (this.IncludeEventProperties)
{
for (int i = 0; i < logEvents.Count; ++i)
{
var ev = logEvents[i].LogEvent;
this.MergeEventProperties(ev);
if (ev.HasProperties)
{
// add all event-level property names in 'LayoutNames' collection.
foreach (var prop in ev.Properties)
{
string propName = prop.Key as string;
if (propName != null)
{
if (!networkLogEvents.LayoutNames.Contains(propName))
{
networkLogEvents.LayoutNames.Add(propName);
}
}
}
}
}
}
networkLogEvents.Events = new NLogEvent[logEvents.Count];
for (int i = 0; i < logEvents.Count; ++i)
{
AsyncLogEventInfo ev = logEvents[i];
networkLogEvents.Events[i] = this.TranslateEvent(ev.LogEvent, networkLogEvents, stringTable);
}
return networkLogEvents;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Client is disposed asynchronously.")]
private void Send(NLogEvents events, IList<AsyncLogEventInfo> asyncContinuations, AsyncContinuation flushContinuations)
{
if (!this.OnSend(events, asyncContinuations))
{
if (flushContinuations != null)
flushContinuations(null);
return;
}
#if WCF_SUPPORTED
var client = CreateLogReceiver();
client.ProcessLogMessagesCompleted += (sender, e) =>
{
if (e.Error != null)
InternalLogger.Error(e.Error, "Error in send for LogReceiver: {0}", this.Name);
// report error to the callers
for (int i = 0; i < asyncContinuations.Count; ++i)
{
asyncContinuations[i].Continuation(e.Error);
}
if (flushContinuations != null)
flushContinuations(e.Error);
// send any buffered events
this.SendBufferedEvents(null);
};
this.inCall = true;
#if SILVERLIGHT
if (!Deployment.Current.Dispatcher.CheckAccess())
{
Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
}
else
{
client.ProcessLogMessagesAsync(events);
}
#else
client.ProcessLogMessagesAsync(events);
#endif
#else
var client = new SoapLogReceiverClient(this.EndpointAddress);
this.inCall = true;
client.BeginProcessLogMessages(
events,
result =>
{
Exception exception = null;
try
{
client.EndProcessLogMessages(result);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Error in send for LogReceiver: {0}", this.Name);
if (ex.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
exception = ex;
}
// report error to the callers
for (int i = 0; i < asyncContinuations.Count; ++i)
{
asyncContinuations[i].Continuation(exception);
}
if (flushContinuations != null)
flushContinuations(exception);
// send any buffered events
this.SendBufferedEvents(null);
},
null);
#endif
}
#if WCF_SUPPORTED
/// <summary>
/// Creating a new instance of WcfLogReceiverClient
///
/// Inheritors can override this method and provide their own
/// service configuration - binding and endpoint address
/// </summary>
/// <remarks>This method marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use CreateLogReceiver instead. Marked obsolete before v4.3.11 and it may be removed in a future release.")]
protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient()
{
WcfLogReceiverClient client;
if (string.IsNullOrEmpty(this.EndpointConfigurationName))
{
// endpoint not specified - use BasicHttpBinding
Binding binding;
if (this.UseBinaryEncoding)
{
binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
}
else
{
binding = new BasicHttpBinding();
}
client = new WcfLogReceiverClient(UseOneWayContract, binding, new EndpointAddress(this.EndpointAddress));
}
else
{
client = new WcfLogReceiverClient(UseOneWayContract, this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress));
}
client.ProcessLogMessagesCompleted += ClientOnProcessLogMessagesCompleted;
return client;
}
/// <summary>
/// Creating a new instance of IWcfLogReceiverClient
///
/// Inheritors can override this method and provide their own
/// service configuration - binding and endpoint address
/// </summary>
/// <returns></returns>
/// <remarks>virtual is used by endusers</remarks>
protected virtual IWcfLogReceiverClient CreateLogReceiver()
{
#pragma warning disable 612, 618
return this.CreateWcfLogReceiverClient();
#pragma warning restore 612, 618
}
private void ClientOnProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
{
var client = sender as IWcfLogReceiverClient;
if (client != null && client.State == CommunicationState.Opened)
{
try
{
client.Close();
}
catch
{
client.Abort();
}
}
}
#endif
private void SendBufferedEvents(AsyncContinuation flushContinuation)
{
try
{
lock (this.SyncRoot)
{
// clear inCall flag
AsyncLogEventInfo[] bufferedEvents = this.buffer.GetEventsAndClear();
if (bufferedEvents.Length > 0)
{
var networkLogEvents = this.TranslateLogEvents(bufferedEvents);
this.Send(networkLogEvents, bufferedEvents, flushContinuation);
}
else
{
// nothing in the buffer, clear in-call flag
this.inCall = false;
if (flushContinuation != null)
flushContinuation(null);
}
}
}
catch (Exception exception)
{
if (flushContinuation != null)
{
InternalLogger.Error(exception, "Error in flush async for LogReceiver: {0}", this.Name);
if (exception.MustBeRethrown())
throw;
flushContinuation(exception);
}
else
{
InternalLogger.Error(exception, "Error in send async for LogReceiver: {0}", this.Name);
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
}
}
}
private NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary<string, int> stringTable)
{
var nlogEvent = new NLogEvent();
nlogEvent.Id = eventInfo.SequenceID;
nlogEvent.MessageOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.FormattedMessage);
nlogEvent.LevelOrdinal = eventInfo.Level.Ordinal;
nlogEvent.LoggerOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.LoggerName);
nlogEvent.TimeDelta = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc;
for (int i = 0; i < this.Parameters.Count; ++i)
{
var param = this.Parameters[i];
var value = param.Layout.Render(eventInfo);
int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);
nlogEvent.ValueIndexes.Add(stringIndex);
}
// layout names beyond Parameters.Count are per-event property names.
for (int i = this.Parameters.Count; i < context.LayoutNames.Count; ++i)
{
string value;
object propertyValue;
if (eventInfo.HasProperties && eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue))
{
value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture);
}
else
{
value = string.Empty;
}
int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);
nlogEvent.ValueIndexes.Add(stringIndex);
}
if (eventInfo.Exception != null)
{
nlogEvent.ValueIndexes.Add(AddValueAndGetStringOrdinal(context, stringTable, eventInfo.Exception.ToString()));
}
return nlogEvent;
}
}
}
#endif
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapAttributeSet.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
namespace Novell.Directory.Ldap
{
/// <summary>
/// A set of {@link LdapAttribute} objects.
///
/// An <code>LdapAttributeSet</code> is a collection of <code>LdapAttribute</code>
/// classes as returned from an <code>LdapEntry</code> on a search or read
/// operation. <code>LdapAttributeSet</code> may be also used to contruct an entry
/// to be added to a directory. If the <code>add()</code> or <code>addAll()</code>
/// methods are called and one or more of the objects to be added is not
/// an <code>LdapAttribute, ClassCastException</code> is thrown (as discussed in the
/// documentation for <code>java.util.Collection</code>).
///
///
/// </summary>
/// <seealso cref="LdapAttribute">
/// </seealso>
/// <seealso cref="LdapEntry">
/// </seealso>
public class LdapAttributeSet:AbstractSetSupport, System.ICloneable//, SupportClass.SetSupport
{
/// <summary> Returns the number of attributes in this set.
///
/// </summary>
/// <returns> number of attributes in this set.
/// </returns>
public override int Count
{
get
{
return this.map.Count;
}
}
/// <summary> This is the underlying data structure for this set.
/// HashSet is similar to the functionality of this set. The difference
/// is we use the name of an attribute as keys in the Map and LdapAttributes
/// as the values. We also do not declare the map as transient, making the
/// map serializable.
/// </summary>
private System.Collections.Hashtable map;
/// <summary> Constructs an empty set of attributes.</summary>
public LdapAttributeSet():base()
{
map = new System.Collections.Hashtable();
}
// --- methods not defined in Set ---
/// <summary> Returns a deep copy of this attribute set.
///
/// </summary>
/// <returns> A deep copy of this attribute set.
/// </returns>
public override System.Object Clone()
{
try
{
System.Object newObj = base.MemberwiseClone();
System.Collections.IEnumerator i = this.GetEnumerator();
while (i.MoveNext())
{
((LdapAttributeSet) newObj).Add(((LdapAttribute) i.Current).Clone());
}
return newObj;
}
catch (System.Exception ce)
{
throw new System.SystemException("Internal error, cannot create clone");
}
}
/// <summary> Returns the attribute matching the specified attrName.
///
/// For example:
/// <ul>
/// <li><code>getAttribute("cn")</code> returns only the "cn" attribute</li>
/// <li><code>getAttribute("cn;lang-en")</code> returns only the "cn;lang-en"
/// attribute.</li>
/// </ul>
/// In both cases, <code>null</code> is returned if there is no exact match to
/// the specified attrName.
///
/// Note: Novell eDirectory does not currently support language subtypes.
/// It does support the "binary" subtype.
///
/// </summary>
/// <param name="attrName"> The name of an attribute to retrieve, with or without
/// subtype specifications. For example, "cn", "cn;phonetic", and
/// "cn;binary" are valid attribute names.
///
/// </param>
/// <returns> The attribute matching the specified attrName, or <code>null</code>
/// if there is no exact match.
/// </returns>
public virtual LdapAttribute getAttribute(System.String attrName)
{
return (LdapAttribute) map[attrName.ToUpper()];
}
/// <summary> Returns a single best-match attribute, or <code>null</code> if no match is
/// available in the entry.
///
/// Ldap version 3 allows adding a subtype specification to an attribute
/// name. For example, "cn;lang-ja" indicates a Japanese language
/// subtype of the "cn" attribute and "cn;lang-ja-JP-kanji" may be a subtype
/// of "cn;lang-ja". This feature may be used to provide multiple
/// localizations in the same directory. For attributes which do not vary
/// among localizations, only the base attribute may be stored, whereas
/// for others there may be varying degrees of specialization.
///
/// For example, <code>getAttribute(attrName,lang)</code> returns the
/// <code>LdapAttribute</code> that exactly matches attrName and that
/// best matches lang.
///
/// If there are subtypes other than "lang" subtypes included
/// in attrName, for example, "cn;binary", only attributes with all of
/// those subtypes are returned. If lang is <code>null</code> or empty, the
/// method behaves as getAttribute(attrName). If there are no matching
/// attributes, <code>null</code> is returned.
///
///
/// Assume the entry contains only the following attributes:
///
/// <ul>
/// <li>cn;lang-en</li>
/// <li>cn;lang-ja-JP-kanji</li>
/// <li>sn</li>
/// </ul>
///
/// Examples:
/// <ul>
/// <li><code>getAttribute( "cn" )</code> returns <code>null</code>.</li>
/// <li><code>getAttribute( "sn" )</code> returns the "sn" attribute.</li>
/// <li><code>getAttribute( "cn", "lang-en-us" )</code>
/// returns the "cn;lang-en" attribute.</li>
/// <li><code>getAttribute( "cn", "lang-en" )</code>
/// returns the "cn;lang-en" attribute.</li>
/// <li><code>getAttribute( "cn", "lang-ja" )</code>
/// returns <code>null</code>.</li>
/// <li><code>getAttribute( "sn", "lang-en" )</code>
/// returns the "sn" attribute.</li>
/// </ul>
///
/// Note: Novell eDirectory does not currently support language subtypes.
/// It does support the "binary" subtype.
///
/// </summary>
/// <param name="attrName"> The name of an attribute to retrieve, with or without
/// subtype specifications. For example, "cn", "cn;phonetic", and
/// cn;binary" are valid attribute names.
///
/// </param>
/// <param name="lang"> A language specification with optional subtypes
/// appended using "-" as separator. For example, "lang-en", "lang-en-us",
/// "lang-ja", and "lang-ja-JP-kanji" are valid language specification.
///
/// </param>
/// <returns> A single best-match <code>LdapAttribute</code>, or <code>null</code>
/// if no match is found in the entry.
///
/// </returns>
public virtual LdapAttribute getAttribute(System.String attrName, System.String lang)
{
System.String key = attrName + ";" + lang;
return (LdapAttribute) map[key.ToUpper()];
}
/// <summary> Creates a new attribute set containing only the attributes that have
/// the specified subtypes.
///
/// For example, suppose an attribute set contains the following
/// attributes:
///
/// <ul>
/// <li> cn</li>
/// <li> cn;lang-ja</li>
/// <li> sn;phonetic;lang-ja</li>
/// <li> sn;lang-us</li>
/// </ul>
///
/// Calling the <code>getSubset</code> method and passing lang-ja as the
/// argument, the method returns an attribute set containing the following
/// attributes:
///
/// <ul>
/// <li>cn;lang-ja</li>
/// <li>sn;phonetic;lang-ja</li>
/// </ul>
///
/// </summary>
/// <param name="subtype"> Semi-colon delimited list of subtypes to include. For
/// example:
/// <ul>
/// <li> "lang-ja" specifies only Japanese language subtypes</li>
/// <li> "binary" specifies only binary subtypes</li>
/// <li> "binary;lang-ja" specifies only Japanese language subtypes
/// which also are binary</li>
/// </ul>
///
/// Note: Novell eDirectory does not currently support language subtypes.
/// It does support the "binary" subtype.
///
/// </param>
/// <returns> An attribute set containing the attributes that match the
/// specified subtype.
/// </returns>
public virtual LdapAttributeSet getSubset(System.String subtype)
{
// Create a new tempAttributeSet
LdapAttributeSet tempAttributeSet = new LdapAttributeSet();
System.Collections.IEnumerator i = this.GetEnumerator();
// Cycle throught this.attributeSet
while (i.MoveNext())
{
LdapAttribute attr = (LdapAttribute) i.Current;
// Does this attribute have the subtype we are looking for. If
// yes then add it to our AttributeSet, else next attribute
if (attr.hasSubtype(subtype))
tempAttributeSet.Add(attr.Clone());
}
return tempAttributeSet;
}
// --- methods defined in set ---
/// <summary> Returns an iterator over the attributes in this set. The attributes
/// returned from this iterator are not in any particular order.
///
/// </summary>
/// <returns> iterator over the attributes in this set
/// </returns>
public override System.Collections.IEnumerator GetEnumerator()
{
return this.map.Values.GetEnumerator();
}
/// <summary> Returns <code>true</code> if this set contains no elements
///
/// </summary>
/// <returns> <code>true</code> if this set contains no elements
/// </returns>
public override bool IsEmpty()
{
return (this.map.Count == 0);
}
/// <summary> Returns <code>true</code> if this set contains an attribute of the same name
/// as the specified attribute.
///
/// </summary>
/// <param name="attr"> Object of type <code>LdapAttribute</code>
///
/// </param>
/// <returns> true if this set contains the specified attribute
///
/// @throws ClassCastException occurs the specified Object
/// is not of type LdapAttribute.
/// </returns>
public override bool Contains(object attr)
{
LdapAttribute attribute = (LdapAttribute) attr;
return this.map.ContainsKey(attribute.Name.ToUpper());
}
/// <summary> Adds the specified attribute to this set if it is not already present.
/// If an attribute with the same name already exists in the set then the
/// specified attribute will not be added.
///
/// </summary>
/// <param name="attr"> Object of type <code>LdapAttribute</code>
///
/// </param>
/// <returns> true if the attribute was added.
///
/// @throws ClassCastException occurs the specified Object
/// is not of type <code>LdapAttribute</code>.
/// </returns>
public override bool Add(object attr)
{
//We must enforce that attr is an LdapAttribute
LdapAttribute attribute = (LdapAttribute) attr;
System.String name = attribute.Name.ToUpper();
if (this.map.ContainsKey(name))
return false;
else
{
SupportClass.PutElement(this.map, name, attribute);
return true;
}
}
/// <summary> Removes the specified object from this set if it is present.
///
/// If the specified object is of type <code>LdapAttribute</code>, the
/// specified attribute will be removed. If the specified object is of type
/// <code>String</code>, the attribute with a name that matches the string will
/// be removed.
///
/// </summary>
/// <param name="object">LdapAttribute to be removed or <code>String</code> naming
/// the attribute to be removed.
///
/// </param>
/// <returns> true if the object was removed.
///
/// @throws ClassCastException occurs the specified Object
/// is not of type <code>LdapAttribute</code> or of type <code>String</code>.
/// </returns>
public override bool Remove(object object_Renamed)
{
System.String attributeName; //the name is the key to object in the HashMap
if (object_Renamed is System.String)
{
attributeName = ((System.String) object_Renamed);
}
else
{
attributeName = ((LdapAttribute) object_Renamed).Name;
}
if ((System.Object) attributeName == null)
{
return false;
}
return (SupportClass.HashtableRemove(this.map, attributeName.ToUpper()) != null);
}
/// <summary> Removes all of the elements from this set.</summary>
public override void Clear()
{
this.map.Clear();
}
/// <summary> Adds all <code>LdapAttribute</code> objects in the specified collection to
/// this collection.
///
/// </summary>
/// <param name="c"> Collection of <code>LdapAttribute</code> objects.
///
/// @throws ClassCastException occurs when an element in the
/// collection is not of type <code>LdapAttribute</code>.
///
/// </param>
/// <returns> true if this set changed as a result of the call.
/// </returns>
public override bool AddAll(System.Collections.ICollection c)
{
bool setChanged = false;
System.Collections.IEnumerator i = c.GetEnumerator();
while (i.MoveNext())
{
// we must enforce that everything in c is an LdapAttribute
// add will return true if the attribute was added
if (this.Add(i.Current))
{
setChanged = true;
}
}
return setChanged;
}
/// <summary> Returns a string representation of this LdapAttributeSet
///
/// </summary>
/// <returns> a string representation of this LdapAttributeSet
/// </returns>
public override System.String ToString()
{
System.Text.StringBuilder retValue = new System.Text.StringBuilder("LdapAttributeSet: ");
System.Collections.IEnumerator attrs = GetEnumerator();
bool first = true;
while (attrs.MoveNext())
{
if (!first)
{
retValue.Append(" ");
}
first = false;
LdapAttribute attr = (LdapAttribute) attrs.Current;
retValue.Append(attr.ToString());
}
return retValue.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace HarmonyLib
{
/// <summary>A wrapper around a method to use it as a patch (for example a Prefix)</summary>
///
public class HarmonyMethod
{
/// <summary>The original method</summary>
///
public MethodInfo method; // need to be called 'method'
/// <summary>Class/type declaring this patch</summary>
///
public Type declaringType;
/// <summary>Patch method name</summary>
///
public string methodName;
/// <summary>Optional patch <see cref="MethodType"/></summary>
///
public MethodType? methodType;
/// <summary>Array of argument types of the patch method</summary>
///
public Type[] argumentTypes;
/// <summary><see cref="Priority"/> of the patch</summary>
///
public int priority = -1;
/// <summary>Install this patch before patches with these Harmony IDs</summary>
///
public string[] before;
/// <summary>Install this patch after patches with these Harmony IDs</summary>
///
public string[] after;
/// <summary>Reverse patch type, see <see cref="HarmonyReversePatchType"/></summary>
///
public HarmonyReversePatchType? reversePatchType;
/// <summary>Create debug output for this patch</summary>
///
public bool? debug;
/// <summary>Whether to use <see cref="MethodDispatchType.Call"/> (<c>true</c>) or <see cref="MethodDispatchType.VirtualCall"/> (<c>false</c>) mechanics
/// for <see cref="HarmonyDelegate"/>-attributed delegate</summary>
///
public bool nonVirtualDelegate;
/// <summary>Default constructor</summary>
///
public HarmonyMethod()
{
}
void ImportMethod(MethodInfo theMethod)
{
method = theMethod;
if (method is object)
{
var infos = HarmonyMethodExtensions.GetFromMethod(method);
if (infos is object)
Merge(infos).CopyTo(this);
}
}
/// <summary>Creates a patch from a given method</summary>
/// <param name="method">The original method</param>
///
public HarmonyMethod(MethodInfo method)
{
if (method is null)
throw new ArgumentNullException(nameof(method));
ImportMethod(method);
}
/// <summary>Creates a patch from a given method</summary>
/// <param name="method">The original method</param>
/// <param name="priority">The patch <see cref="Priority"/></param>
/// <param name="before">A list of harmony IDs that should come after this patch</param>
/// <param name="after">A list of harmony IDs that should come before this patch</param>
/// <param name="debug">Set to true to generate debug output</param>
///
public HarmonyMethod(MethodInfo method, int priority = -1, string[] before = null, string[] after = null, bool? debug = null)
{
if (method is null)
throw new ArgumentNullException(nameof(method));
ImportMethod(method);
this.priority = priority;
this.before = before;
this.after = after;
this.debug = debug;
}
/// <summary>Creates a patch from a given method</summary>
/// <param name="methodType">The patch class/type</param>
/// <param name="methodName">The patch method name</param>
/// <param name="argumentTypes">The optional argument types of the patch method (for overloaded methods)</param>
///
public HarmonyMethod(Type methodType, string methodName, Type[] argumentTypes = null)
{
var result = AccessTools.Method(methodType, methodName, argumentTypes);
if (result is null)
throw new ArgumentException($"Cannot not find method for type {methodType} and name {methodName} and parameters {argumentTypes?.Description()}");
ImportMethod(result);
}
/// <summary>Gets the names of all internal patch info fields</summary>
/// <returns>A list of field names</returns>
///
public static List<string> HarmonyFields()
{
return AccessTools
.GetFieldNames(typeof(HarmonyMethod))
.Where(s => s != "method")
.ToList();
}
/// <summary>Merges annotations</summary>
/// <param name="attributes">The list of <see cref="HarmonyMethod"/> to merge</param>
/// <returns>The merged <see cref="HarmonyMethod"/></returns>
///
public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
{
var result = new HarmonyMethod();
if (attributes is null) return result;
var resultTrv = Traverse.Create(result);
attributes.ForEach(attribute =>
{
var trv = Traverse.Create(attribute);
HarmonyFields().ForEach(f =>
{
var val = trv.Field(f).GetValue();
// The second half of this if is needed because priority defaults to -1
// This causes the value of a HarmonyPriority attribute to be overriden by the next attribute if it is not merged last
// should be removed by making priority nullable and default to null at some point
if (val is object && (f != nameof(HarmonyMethod.priority) || (int)val != -1))
HarmonyMethodExtensions.SetValue(resultTrv, f, val);
});
});
return result;
}
/// <summary>Returns a string that represents the annotation</summary>
/// <returns>A string representation</returns>
///
public override string ToString()
{
var result = "";
var trv = Traverse.Create(this);
HarmonyFields().ForEach(f =>
{
if (result.Length > 0) result += ", ";
result += $"{f}={trv.Field(f).GetValue()}";
});
return $"HarmonyMethod[{result}]";
}
// used for error reporting
internal string Description()
{
var cName = declaringType is object ? declaringType.FullName : "undefined";
var mName = methodName ?? "undefined";
var tName = methodType.HasValue ? methodType.Value.ToString() : "undefined";
var aName = argumentTypes is object ? argumentTypes.Description() : "undefined";
return $"(class={cName}, methodname={mName}, type={tName}, args={aName})";
}
}
/// <summary>Annotation extensions</summary>
///
public static class HarmonyMethodExtensions
{
internal static void SetValue(Traverse trv, string name, object val)
{
if (val is null) return;
var fld = trv.Field(name);
if (name == nameof(HarmonyMethod.methodType) || name == nameof(HarmonyMethod.reversePatchType))
{
var enumType = Nullable.GetUnderlyingType(fld.GetValueType());
val = Enum.ToObject(enumType, (int)val);
}
_ = fld.SetValue(val);
}
/// <summary>Copies annotation information</summary>
/// <param name="from">The source <see cref="HarmonyMethod"/></param>
/// <param name="to">The destination <see cref="HarmonyMethod"/></param>
///
public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
{
if (to is null) return;
var fromTrv = Traverse.Create(from);
var toTrv = Traverse.Create(to);
HarmonyMethod.HarmonyFields().ForEach(f =>
{
var val = fromTrv.Field(f).GetValue();
if (val is object)
SetValue(toTrv, f, val);
});
}
/// <summary>Clones an annotation</summary>
/// <param name="original">The <see cref="HarmonyMethod"/> to clone</param>
/// <returns>A copied <see cref="HarmonyMethod"/></returns>
///
public static HarmonyMethod Clone(this HarmonyMethod original)
{
var result = new HarmonyMethod();
original.CopyTo(result);
return result;
}
/// <summary>Merges annotations</summary>
/// <param name="master">The master <see cref="HarmonyMethod"/></param>
/// <param name="detail">The detail <see cref="HarmonyMethod"/></param>
/// <returns>A new, merged <see cref="HarmonyMethod"/></returns>
///
public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
{
if (detail is null) return master;
var result = new HarmonyMethod();
var resultTrv = Traverse.Create(result);
var masterTrv = Traverse.Create(master);
var detailTrv = Traverse.Create(detail);
HarmonyMethod.HarmonyFields().ForEach(f =>
{
var baseValue = masterTrv.Field(f).GetValue();
var detailValue = detailTrv.Field(f).GetValue();
// This if is needed because priority defaults to -1
// This causes the value of a HarmonyPriority attribute to be overriden by the next attribute if it is not merged last
// should be removed by making priority nullable and default to null at some point
if (f != nameof(HarmonyMethod.priority) || (int)detailValue != -1)
SetValue(resultTrv, f, detailValue ?? baseValue);
});
return result;
}
static HarmonyMethod GetHarmonyMethodInfo(object attribute)
{
var f_info = attribute.GetType().GetField(nameof(HarmonyAttribute.info), AccessTools.all);
if (f_info is null) return null;
if (f_info.FieldType.FullName != typeof(HarmonyMethod).FullName) return null;
var info = f_info.GetValue(attribute);
return AccessTools.MakeDeepCopy<HarmonyMethod>(info);
}
/// <summary>Gets all annotations on a class/type</summary>
/// <param name="type">The class/type</param>
/// <returns>A list of all <see cref="HarmonyMethod"/></returns>
///
public static List<HarmonyMethod> GetFromType(Type type)
{
return type.GetCustomAttributes(true)
.Select(attr => GetHarmonyMethodInfo(attr))
.Where(info => info is object)
.ToList();
}
/// <summary>Gets merged annotations on a class/type</summary>
/// <param name="type">The class/type</param>
/// <returns>The merged <see cref="HarmonyMethod"/></returns>
///
public static HarmonyMethod GetMergedFromType(Type type)
{
return HarmonyMethod.Merge(GetFromType(type));
}
/// <summary>Gets all annotations on a method</summary>
/// <param name="method">The method/constructor</param>
/// <returns>A list of <see cref="HarmonyMethod"/></returns>
///
public static List<HarmonyMethod> GetFromMethod(MethodBase method)
{
return method.GetCustomAttributes(true)
.Select(attr => GetHarmonyMethodInfo(attr))
.Where(info => info is object)
.ToList();
}
/// <summary>Gets merged annotations on a method</summary>
/// <param name="method">The method/constructor</param>
/// <returns>The merged <see cref="HarmonyMethod"/></returns>
///
public static HarmonyMethod GetMergedFromMethod(MethodBase method)
{
return HarmonyMethod.Merge(GetFromMethod(method));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Hydra.Framework;
using Hydra.Framework.Helpers;
using Hydra.Framework.Java;
using Hydra.Framework.Mapping.CoordinateSystems;
using Hydra.Framework.Conversions;
namespace Hydra.DomainModel
{
//
//**********************************************************************
/// <summary>
/// Device Station Information
/// </summary>
//**********************************************************************
//
[Serializable]
[DataContract(Namespace = CommonConstants.DATA_NAMESPACE)]
public class InternalStationInfo
: AbstractInternalData
{
#region Member Variables
//
//**********************************************************************
/// <summary>
/// Anchor IP Address
/// </summary>
//**********************************************************************
//
[DataMember(Name = "AnchorAddress")]
public string AnchorAddress
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Slot Identifier
/// </summary>
//**********************************************************************
//
[DataMember(Name = "ApflSlotId")]
public int ApflSlotId
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// AP Mac Address
/// </summary>
//**********************************************************************
//
[DataMember(Name = "ApMacAddress")]
public string ApMacAddress
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Interface
/// </summary>
//**********************************************************************
//
[DataMember(Name = "InterfaceStr")]
public string InterfaceStr
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// IP Address
/// </summary>
//**********************************************************************
//
[DataMember(Name = "IpAddress")]
public string IpAddress
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// MAC Address
/// </summary>
//**********************************************************************
//
[DataMember(Name = "MacAddress")]
public string MacAddress
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Policy Manager State
/// </summary>
//**********************************************************************
//
[DataMember(Name = "PolicyManagerState")]
public string PolicyManagerState
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Port Number
/// </summary>
//**********************************************************************
//
[DataMember(Name = "PortNumber")]
public int PortNumber
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Protocol Type
/// </summary>
//**********************************************************************
//
[DataMember(Name = "Protocol")]
public MobileStationProtocolType Protocol
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Security Policy Status
/// </summary>
//**********************************************************************
//
[DataMember(Name = "SecurityPolicyStatus")]
public SecurityPolicyStatusType SecurityPolicyStatus
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// SS Identifier
/// </summary>
//**********************************************************************
//
[DataMember(Name = "SsId")]
public string SSId
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Status
/// </summary>
//**********************************************************************
//
[DataMember(Name = "Status")]
public int Status
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Switch Reference
/// </summary>
//**********************************************************************
//
[DataMember(Name = "SwitchRef")]
public string SwitchRef
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Known Users
/// </summary>
//**********************************************************************
//
[DataMember(Name = "Username")]
public string Username
{
get;
set;
}
#endregion
#region Constructors
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalStationInfo"/> class.
/// </summary>
// **********************************************************************
//
public InternalStationInfo()
: base(InternalLocationServiceType.Internal)
{
}
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="T:InternalStationInfo"/> class.
/// </summary>
/// <param name="anchorAddress">The anchor address.</param>
/// <param name="apflSlotId">The apfl slot id.</param>
/// <param name="apMacAddress">The ap mac address.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="interfaceStr">The interface STR.</param>
/// <param name="ipAddress">The ip address.</param>
/// <param name="macAddress">The mac address.</param>
/// <param name="objectId">The object id.</param>
/// <param name="policyManagerState">State of the policy manager.</param>
/// <param name="portNumber">The port number.</param>
/// <param name="protocol">The protocol.</param>
/// <param name="securityPolicyStatus">The security policy status.</param>
/// <param name="ssId">The ss id.</param>
/// <param name="status">The status.</param>
/// <param name="switchRef">The switch ref.</param>
/// <param name="username">The username.</param>
//**********************************************************************
//
public InternalStationInfo(string anchorAddress, int apflSlotId, string apMacAddress, DateTime changedOn, string interfaceStr, string ipAddress, string macAddress, int objectId,
string policyManagerState, int portNumber, MobileStationProtocolType protocol, SecurityPolicyStatusType securityPolicyStatus, string ssId, int status,
string switchRef, string username)
: base(InternalLocationServiceType.Internal, objectId, changedOn)
{
AnchorAddress = anchorAddress;
ApflSlotId = apflSlotId;
ApMacAddress = apMacAddress;
InterfaceStr = interfaceStr;
IpAddress = ipAddress;
MacAddress = macAddress;
PolicyManagerState = policyManagerState;
PortNumber = portNumber;
Protocol = protocol;
SecurityPolicyStatus = securityPolicyStatus;
SSId = ssId;
Status = status;
SwitchRef = switchRef;
Username = username;
}
#endregion
#region Properties
#endregion
#region Private Methods
#endregion
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Search;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
using BitSet = J2N.Collections.BitSet;
#if TESTFRAMEWORK_MSTEST
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#elif TESTFRAMEWORK_NUNIT
using Test = NUnit.Framework.TestAttribute;
#elif TESTFRAMEWORK_XUNIT
using Test = Lucene.Net.TestFramework.SkippableFactAttribute;
#endif
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Base test class for <see cref="DocIdSet"/>s. </summary>
public abstract class BaseDocIdSetTestCase<T> : LuceneTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
where T : Lucene.Net.Search.DocIdSet
{
public BaseDocIdSetTestCase(BeforeAfterClass beforeAfter)
: base(beforeAfter)
{
}
#else
where T : Lucene.Net.Search.DocIdSet
{
#endif
/// <summary>
/// Create a copy of the given <see cref="BitSet"/> which has <paramref name="length"/> bits. </summary>
public abstract T CopyOf(BitSet bs, int length);
/// <summary>
/// Create a random set which has <paramref name="numBitsSet"/> of its <paramref name="numBits"/> bits set. </summary>
protected static BitSet RandomSet(int numBits, int numBitsSet)
{
if (Debugging.AssertsEnabled) Debugging.Assert(numBitsSet <= numBits);
BitSet set = new BitSet(numBits);
Random random = Random;
if (numBitsSet == numBits)
{
set.Set(0, numBits);
}
else
{
for (int i = 0; i < numBitsSet; ++i)
{
while (true)
{
int o = random.Next(numBits);
if (!set.Get(o))
{
set.Set(o);
break;
}
}
}
}
return set;
}
/// <summary>
/// Same as <see cref="RandomSet(int, int)"/> but given a load factor. </summary>
protected static BitSet RandomSet(int numBits, float percentSet)
{
return RandomSet(numBits, (int)(percentSet * numBits));
}
/// <summary>
/// Test length=0.
/// </summary>
[Test]
public virtual void TestNoBit()
{
BitSet bs = new BitSet(1);
T copy = CopyOf(bs, 0);
AssertEquals(0, bs, copy);
}
/// <summary>
/// Test length=1.
/// </summary>
[Test]
public virtual void Test1Bit()
{
BitSet bs = new BitSet(1);
if (Random.NextBoolean())
{
bs.Set(0);
}
T copy = CopyOf(bs, 1);
AssertEquals(1, bs, copy);
}
/// <summary>
/// Test length=2.
/// </summary>
[Test]
public virtual void Test2Bits()
{
BitSet bs = new BitSet(2);
if (Random.NextBoolean())
{
bs.Set(0);
}
if (Random.NextBoolean())
{
bs.Set(1);
}
T copy = CopyOf(bs, 2);
AssertEquals(2, bs, copy);
}
/// <summary>
/// Compare the content of the set against a <see cref="BitSet"/>.
/// </summary>
[Test]
public virtual void TestAgainstBitSet()
{
int numBits = TestUtil.NextInt32(Random, 100, 1 << 20);
// test various random sets with various load factors
foreach (float percentSet in new float[] { 0f, 0.0001f, (float)Random.NextDouble() / 2, 0.9f, 1f })
{
BitSet set = RandomSet(numBits, percentSet);
T copy = CopyOf(set, numBits);
AssertEquals(numBits, set, copy);
}
// test one doc
BitSet set_ = new BitSet(numBits);
set_.Set(0); // 0 first
T copy_ = CopyOf(set_, numBits);
AssertEquals(numBits, set_, copy_);
set_.Clear(0);
set_.Set(Random.Next(numBits));
copy_ = CopyOf(set_, numBits); // then random index
AssertEquals(numBits, set_, copy_);
// test regular increments
for (int inc = 2; inc < 1000; inc += TestUtil.NextInt32(Random, 1, 100))
{
set_ = new BitSet(numBits);
for (int d = Random.Next(10); d < numBits; d += inc)
{
set_.Set(d);
}
copy_ = CopyOf(set_, numBits);
AssertEquals(numBits, set_, copy_);
}
}
/// <summary>
/// Assert that the content of the <see cref="DocIdSet"/> is the same as the content of the <see cref="BitSet"/>.
/// </summary>
#pragma warning disable xUnit1013
public virtual void AssertEquals(int numBits, BitSet ds1, T ds2)
#pragma warning restore xUnit1013
{
// nextDoc
DocIdSetIterator it2 = ds2.GetIterator();
if (it2 == null)
{
Assert.AreEqual(-1, ds1.NextSetBit(0));
}
else
{
Assert.AreEqual(-1, it2.DocID);
for (int doc = ds1.NextSetBit(0); doc != -1; doc = ds1.NextSetBit(doc + 1))
{
Assert.AreEqual(doc, it2.NextDoc());
Assert.AreEqual(doc, it2.DocID);
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, it2.NextDoc());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, it2.DocID);
}
// nextDoc / advance
it2 = ds2.GetIterator();
if (it2 == null)
{
Assert.AreEqual(-1, ds1.NextSetBit(0));
}
else
{
for (int doc = -1; doc != DocIdSetIterator.NO_MORE_DOCS; )
{
if (Random.NextBoolean())
{
doc = ds1.NextSetBit(doc + 1);
if (doc == -1)
{
doc = DocIdSetIterator.NO_MORE_DOCS;
}
Assert.AreEqual(doc, it2.NextDoc());
Assert.AreEqual(doc, it2.DocID);
}
else
{
int target = doc + 1 + Random.Next(Random.NextBoolean() ? 64 : Math.Max(numBits / 8, 1));
doc = ds1.NextSetBit(target);
if (doc == -1)
{
doc = DocIdSetIterator.NO_MORE_DOCS;
}
Assert.AreEqual(doc, it2.Advance(target));
Assert.AreEqual(doc, it2.DocID);
}
}
}
// bits()
IBits bits = ds2.Bits;
if (bits != null)
{
// test consistency between bits and iterator
it2 = ds2.GetIterator();
for (int previousDoc = -1, doc = it2.NextDoc(); ; previousDoc = doc, doc = it2.NextDoc())
{
int max = doc == DocIdSetIterator.NO_MORE_DOCS ? bits.Length : doc;
for (int i = previousDoc + 1; i < max; ++i)
{
Assert.AreEqual(false, bits.Get(i));
}
if (doc == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
Assert.AreEqual(true, bits.Get(doc));
}
}
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using NPOI.HPSF.Wellknown;
/// <summary>
/// Convenience class representing a Summary Information stream in a
/// Microsoft Office document.
/// @author Rainer Klute
/// <a href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
/// @see DocumentSummaryInformation
/// @since 2002-02-09
/// </summary>
[Serializable]
public class SummaryInformation : SpecialPropertySet
{
/**
* The document name a summary information stream usually has in a POIFS
* filesystem.
*/
public const String DEFAULT_STREAM_NAME = "\x0005SummaryInformation";
public override PropertyIDMap PropertySetIDMap
{
get
{
return PropertyIDMap.SummaryInformationProperties;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SummaryInformation"/> class.
/// </summary>
/// <param name="ps">A property Set which should be Created from a summary
/// information stream.</param>
public SummaryInformation(PropertySet ps): base(ps)
{
if (!IsSummaryInformation)
throw new UnexpectedPropertySetTypeException("Not a "
+ GetType().Name);
}
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
public String Title
{
get { return (String)GetProperty(PropertyIDMap.PID_TITLE); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_TITLE, value);
}
}
/// <summary>
/// Removes the title.
/// </summary>
public void RemoveTitle()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_TITLE);
}
/// <summary>
/// Gets or sets the subject.
/// </summary>
/// <value>The subject.</value>
public String Subject
{
get { return (String)GetProperty(PropertyIDMap.PID_SUBJECT); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_SUBJECT, value);
}
}
/// <summary>
/// Removes the subject.
/// </summary>
public void RemoveSubject()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_SUBJECT);
}
/// <summary>
/// Gets or sets the author.
/// </summary>
/// <value>The author.</value>
public String Author
{
get { return (String)GetProperty(PropertyIDMap.PID_AUTHOR); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_AUTHOR, value);
}
}
/// <summary>
/// Removes the author.
/// </summary>
public void RemoveAuthor()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_AUTHOR);
}
/// <summary>
/// Gets or sets the keywords.
/// </summary>
/// <value>The keywords.</value>
public String Keywords
{
get { return (String)GetProperty(PropertyIDMap.PID_KEYWORDS); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_KEYWORDS, value);
}
}
/// <summary>
/// Removes the keywords.
/// </summary>
public void RemoveKeywords()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_KEYWORDS);
}
/// <summary>
/// Gets or sets the comments.
/// </summary>
/// <value>The comments.</value>
public String Comments
{
get { return (String)GetProperty(PropertyIDMap.PID_COMMENTS); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_COMMENTS, value);
}
}
/// <summary>
/// Removes the comments.
/// </summary>
public void RemoveComments()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_COMMENTS);
}
/// <summary>
/// Gets or sets the template.
/// </summary>
/// <value>The template.</value>
public String Template
{
get { return (String)GetProperty(PropertyIDMap.PID_TEMPLATE); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_TEMPLATE, value);
}
}
/// <summary>
/// Removes the template.
/// </summary>
public void RemoveTemplate()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_TEMPLATE);
}
/// <summary>
/// Gets or sets the last author.
/// </summary>
/// <value>The last author.</value>
public String LastAuthor
{
get{return (String)GetProperty(PropertyIDMap.PID_LASTAUTHOR);}
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_LASTAUTHOR, value);
}
}
/// <summary>
/// Removes the last author.
/// </summary>
public void RemoveLastAuthor()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_LASTAUTHOR);
}
/// <summary>
/// Gets or sets the rev number.
/// </summary>
/// <value>The rev number.</value>
public String RevNumber
{
get { return (String)GetProperty(PropertyIDMap.PID_REVNUMBER); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_REVNUMBER, value);
}
}
/// <summary>
/// Removes the rev number.
/// </summary>
public void RemoveRevNumber()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_REVNUMBER);
}
/// <summary>
/// Returns the Total time spent in editing the document (or 0).
/// </summary>
/// <value>The Total time spent in editing the document or 0 if the {@link
/// SummaryInformation} does not contain this information.</value>
public long EditTime
{
get
{
if (GetProperty(PropertyIDMap.PID_EDITTIME) == null)
return 0;
else
{
DateTime d = (DateTime)GetProperty(PropertyIDMap.PID_EDITTIME);
return Util.DateToFileTime(d);
}
}
set
{
DateTime d = Util.FiletimeToDate(value);
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_EDITTIME, Variant.VT_FILETIME, d);
}
}
/// <summary>
/// Removes the edit time.
/// </summary>
public void RemoveEditTime()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_EDITTIME);
}
/// <summary>
/// Gets or sets the last printed time
/// </summary>
/// <value>The last printed time</value>
/// Returns the last printed time (or <c>null</c>).
public DateTime? LastPrinted
{
get {
return (DateTime?)GetProperty(PropertyIDMap.PID_LASTPRINTED);
}
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_LASTPRINTED, Variant.VT_FILETIME,
value);
}
}
/// <summary>
/// Removes the last printed.
/// </summary>
public void RemoveLastPrinted()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_LASTPRINTED);
}
/// <summary>
/// Gets or sets the create date time.
/// </summary>
/// <value>The create date time.</value>
public DateTime? CreateDateTime
{
get { return (DateTime?)GetProperty(PropertyIDMap.PID_Create_DTM); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_Create_DTM, Variant.VT_FILETIME,
value);
}
}
/// <summary>
/// Removes the create date time.
/// </summary>
public void RemoveCreateDateTime()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_Create_DTM);
}
/// <summary>
/// Gets or sets the last save date time.
/// </summary>
/// <value>The last save date time.</value>
public DateTime? LastSaveDateTime
{
get { return (DateTime?)GetProperty(PropertyIDMap.PID_LASTSAVE_DTM); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_LASTSAVE_DTM,
Variant.VT_FILETIME, value);
}
}
/// <summary>
/// Removes the last save date time.
/// </summary>
public void RemoveLastSaveDateTime()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_LASTSAVE_DTM);
}
/// <summary>
/// Gets or sets the page count or 0 if the {@link SummaryInformation} does
/// not contain a page count.
/// </summary>
/// <value>The page count or 0 if the {@link SummaryInformation} does not
/// contain a page count.</value>
public int PageCount
{
get { return GetPropertyIntValue(PropertyIDMap.PID_PAGECOUNT); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_PAGECOUNT, value);
}
}
/// <summary>
/// Removes the page count.
/// </summary>
public void RemovePageCount()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_PAGECOUNT);
}
/// <summary>
/// Gets or sets the word count or 0 if the {@link SummaryInformation} does
/// not contain a word count.
/// </summary>
/// <value>The word count.</value>
public int WordCount
{
get { return GetPropertyIntValue(PropertyIDMap.PID_WORDCOUNT); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_WORDCOUNT, value);
}
}
/// <summary>
/// Removes the word count.
/// </summary>
public void RemoveWordCount()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_WORDCOUNT);
}
/// <summary>
/// Gets or sets the character count or 0 if the {@link SummaryInformation}
/// does not contain a char count.
/// </summary>
/// <value>The character count.</value>
public int CharCount
{
get{return GetPropertyIntValue(PropertyIDMap.PID_CHARCOUNT);}
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_CHARCOUNT, value);
}
}
/// <summary>
/// Removes the char count.
/// </summary>
public void RemoveCharCount()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_CHARCOUNT);
}
/// <summary>
/// Gets or sets the thumbnail (or <c>null</c>) <strong>when this
/// method is implemented. Please note that the return type is likely To
/// Change!</strong>
/// <strong>Hint To developers:</strong> Drew Varner <Drew.Varner
/// -at- sc.edu> said that this is an image in WMF or Clipboard (BMP?)
/// format. However, we won't do any conversion into any image type but
/// instead just return a byte array.
/// </summary>
/// <value>The thumbnail.</value>
public byte[] Thumbnail
{
get{return (byte[])GetProperty(PropertyIDMap.PID_THUMBNAIL);}
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_THUMBNAIL, /* FIXME: */
Variant.VT_LPSTR, value);
}
}
/// <summary>
/// Removes the thumbnail.
/// </summary>
public void RemoveThumbnail()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_THUMBNAIL);
}
/// <summary>
/// Gets or sets the name of the application.
/// </summary>
/// <value>The name of the application.</value>
public String ApplicationName
{
get { return (String)GetProperty(PropertyIDMap.PID_APPNAME); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_APPNAME, value);
}
}
/// <summary>
/// Removes the name of the application.
/// </summary>
public void RemoveApplicationName()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_APPNAME);
}
/// <summary>
/// Gets or sets a security code which is one of the following values:
/// <ul>
/// <li>0 if the {@link SummaryInformation} does not contain a
/// security field or if there is no security on the document. Use
/// {@link PropertySet#wasNull()} To distinguish between the two
/// cases!</li>
/// <li>1 if the document is password protected</li>
/// <li>2 if the document is Read-only recommended</li>
/// <li>4 if the document is Read-only enforced</li>
/// <li>8 if the document is locked for annotations</li>
/// </ul>
/// </summary>
/// <value>The security code</value>
public int Security
{
get { return GetPropertyIntValue(PropertyIDMap.PID_SECURITY); }
set
{
MutableSection s = (MutableSection)FirstSection;
s.SetProperty(PropertyIDMap.PID_SECURITY, value);
}
}
/// <summary>
/// Removes the security code.
/// </summary>
public void RemoveSecurity()
{
MutableSection s = (MutableSection)FirstSection;
s.RemoveProperty(PropertyIDMap.PID_SECURITY);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using ProtoCore.Exceptions;
using System.Timers;
using ProtoCore.DSASM;
using ProtoCore.Utils;
using ProtoFFI;
using ProtoCore;
using Autodesk.DesignScript.Interfaces;
namespace ProtoLanguage
{
public enum ExecutionMode
{
Parallel,
Serial
}
public class CompileOptions
{
public CompileOptions()
{
DumpIL = false;
DumpByteCode = false;
DumpFunctionResolverLogic = false;
DumpOperatorToMethodByteCode = false;
SuppressBuildOutput = false;
BuildOptWarningAsError = false;
BuildOptErrorAsWarning = false;
IDEDebugMode = false;
WatchTestMode = false;
IncludeDirectories = new List<string>();
// defaults to 6 decimal places
//
FormatToPrintFloatingPoints = "F6";
RootCustomPropertyFilterPathName = @"C:\arxapiharness\Bin\AcDesignScript\CustomPropertyFilter.txt";
CompileToLib = false;
AssocOperatorAsMethod = true;
RootModulePathName = Path.GetFullPath(@".");
staticCycleCheck = true;
dynamicCycleCheck = true;
RecursionChecking = false;
EmitBreakpoints = true;
localDependsOnGlobalSet = false;
LHSGraphNodeUpdate = true;
TempReplicationGuideEmptyFlag = true;
AssociativeToImperativePropagation = true;
SuppressFunctionResolutionWarning = true;
WebRunner = false;
DisableDisposeFunctionDebug = true;
GenerateExprID = true;
IsDeltaExecution = false;
ElementBasedArrayUpdate = true;
}
public bool DumpByteCode { get; set; }
public bool DumpIL { get; private set; }
public bool DumpOperatorToMethodByteCode { get; set; }
public bool SuppressBuildOutput { get; set; }
public bool BuildOptWarningAsError { get; set; }
public bool BuildOptErrorAsWarning { get; set; }
public bool IDEDebugMode { get; set; } //set to true if two way mapping b/w DesignScript and JIL code is needed
public bool WatchTestMode { get; set; } // set to true when running automation tests for expression interpreter
public string FormatToPrintFloatingPoints { get; set; }
public bool CompileToLib { get; set; }
public bool AssocOperatorAsMethod { get; set; }
public string LibPath { get; set; }
public bool staticCycleCheck { get; set; }
public bool dynamicCycleCheck { get; set; }
public bool RecursionChecking { get; set; }
public bool DumpFunctionResolverLogic { get; set; }
public bool EmitBreakpoints { get; set; }
public bool localDependsOnGlobalSet { get; set; }
public bool LHSGraphNodeUpdate { get; set; }
public bool SuppressFunctionResolutionWarning { get; set; }
public bool WebRunner { get; set; }
public bool TempReplicationGuideEmptyFlag { get; set; }
public bool AssociativeToImperativePropagation { get; set; }
public bool DisableDisposeFunctionDebug { get; set; }
public bool GenerateExprID { get; set; }
public bool IsDeltaExecution { get; set; }
public bool ElementBasedArrayUpdate { get; set; }
// This is being moved to Core.Options as this needs to be overridden for the Watch test framework runner
public int kDynamicCycleThreshold = 2000;
public double Tolerance
{
get { return ProtoCore.Utils.MathUtils.Tolerance; }
set { ProtoCore.Utils.MathUtils.Tolerance = value; }
}
public List<string> IncludeDirectories { get; set; }
public string RootModulePathName { get; set; }
private string rootCustomPropertyFilterPathName;
public string RootCustomPropertyFilterPathName
{
get
{
return rootCustomPropertyFilterPathName;
}
set
{
if (value == null)
{
rootCustomPropertyFilterPathName = null;
}
else
{
var fileName = value;
if (System.IO.File.Exists(fileName))
{
rootCustomPropertyFilterPathName = fileName;
System.IO.StreamReader stream = null;
try
{
stream = new System.IO.StreamReader(fileName);
}
catch (System.Exception ex)
{
throw new System.IO.FileLoadException(string.Format("Custom property filter file {0} can't be read. Error Message:{1}", fileName, ex.Message));
}
finally
{
if (stream != null)
{
stream.Dispose();
}
}
}
else
{
//throw new System.IO.FileNotFoundException(string.Format("Custom property filter file {0} does not exists", fileName));
rootCustomPropertyFilterPathName = null;
}
}
}
}
}
public class CompileStateTracker
{
public const int FIRST_CORE_ID = 0;
public int ID { get; private set; }
public bool compileSucceeded { get; set; }
//recurtion
public List<FunctionCounter> recursivePoint { get; set; }
public List<FunctionCounter> funcCounterTable { get; set; }
public bool calledInFunction;
// This flag is set true when we call GraphUtilities.PreloadAssembly to load libraries in Graph UI
public bool IsParsingPreloadedAssembly { get; set; }
// THe ImportModuleHandler owned by the temporary core used in Graph UI precompilation
// needed to detect if the same assembly is not being imported more than once
public ProtoFFI.ImportModuleHandler ImportHandler { get; set; }
// This is set to true when the temporary core is used for precompilation of CBN's in GraphUI
public bool IsParsingCodeBlockNode { get; set; }
// This is the AST node list of default imported libraries needed for Graph Compiler
public ProtoCore.AST.AssociativeAST.CodeBlockNode ImportNodes { get; set; }
// The root AST node obtained from parsing an expression in a Graph node in GraphUI
public List<ProtoCore.AST.Node> AstNodeList { get; set; }
public enum ErrorType
{
OK,
Error,
Warning
}
public struct ErrorEntry
{
public ProtoLanguage.CompileStateTracker.ErrorType Type;
public string FileName;
public string Message;
public ProtoCore.BuildData.WarningID BuildId;
public ProtoCore.RuntimeData.WarningID RuntimeId;
public int Line;
public int Col;
}
public Dictionary<ulong, ulong> codeToLocation = new Dictionary<ulong, ulong>();
public Dictionary<ulong, ErrorEntry> LocationErrorMap = new Dictionary<ulong, ErrorEntry>();
//STop
public Stopwatch StopWatch;
public void StartTimer()
{
StopWatch = new Stopwatch();
StopWatch.Start();
}
public TimeSpan GetCurrentTime()
{
TimeSpan ts = StopWatch.Elapsed;
return ts;
}
public ProtoCore.Lang.FunctionTable FunctionTable { get; set; }
public Script Script { get; set; }
public LangVerify Langverify = new LangVerify();
public Dictionary<Language, ProtoCore.Executive> Executives { get; private set; }
public ProtoCore.Executive CurrentExecutive { get; private set; }
public Stack<ExceptionRegistration> stackActiveExceptionRegistration { get; set; }
public int GlobOffset { get; set; }
public int GlobHeapOffset { get; set; }
public int BaseOffset { get; set; }
public int GraphNodeUID { get; set; }
public Heap Heap { get; set; }
public ProtoCore.Runtime.RuntimeMemory Rmem { get; set; }
public int ClassIndex { get; set; } // Holds the current class scope
public int RunningBlock { get; set; }
public int CodeBlockIndex { get; set; }
public int RuntimeTableIndex { get; set; }
public List<CodeBlock> CodeBlockList { get; set; }
// The Complete Code Block list contains all the code blocks
// unlike the codeblocklist which only stores the outer most code blocks
public List<CodeBlock> CompleteCodeBlockList { get; set; }
public Executable DSExecutable { get; set; }
public List<Instruction> Breakpoints { get; set; }
public CompileOptions Options { get; private set; }
public BuildStatus BuildStatus { get; private set; }
public TypeSystem TypeSystem { get; set; }
// The global class table and function tables
public ClassTable ClassTable { get; set; }
public ProcedureTable ProcTable { get; set; }
public ProcedureNode ProcNode { get; set; }
// The function pointer table
public FunctionPointerTable FunctionPointerTable { get; set; }
//The dynamic string table and function table
public DynamicVariableTable DynamicVariableTable { get; set; }
public DynamicFunctionTable DynamicFunctionTable { get; set; }
public IExecutiveProvider ExecutiveProvider { get; set; }
public Dictionary<string, object> Configurations { get; set; }
//Manages injected context data.
public ContextDataManager ContextDataManager { get; set; }
public ParseMode ParsingMode { get; set; }
public FFIPropertyChangedMonitor FFIPropertyChangedMonitor { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void AddContextData(Dictionary<string, Object> data)
{
if (data == null)
return;
ContextDataManager.GetInstance(this).AddData(data);
}
// Cached replication guides for the current call.
// TODO Jun: Store this in the dynamic table node
public List<List<int>> replicationGuides;
// if CompileToLib is true, this is used to output the asm instruction to the dsASM file
// if CompilerToLib is false, this will be set to Console.Out
public TextWriter AsmOutput;
public int AsmOutputIdents;
public string CurrentDSFileName { get; set; }
// this field is used to store the inferedtype information when the code gen cross one langeage to another
// otherwize the inferedtype information will be lost
public ProtoCore.Type InferedType;
public DebugProperties DebugProps;
//public Stack<List<ProtoCore.AssociativeGraph.GraphNode>> stackNodeExecutedSameTimes { get; set; }
//public Stack<AssociativeGraph.GraphNode> stackExecutingGraphNodes { get; set; }
public Stack<InterpreterProperties> InterpreterProps { get; set; }
// Continuation properties used for Serial mode execution and Debugging of Replicated calls
public ProtoCore.Lang.ContinuationStructure ContinuationStruct { get; set; }
/// <summary>
/// Gets the reason why the execution was last suspended
/// </summary>
public ReasonForExecutionSuspend ReasonForExecutionSuspend { get; internal set; }
public delegate void DisposeDelegate(ProtoLanguage.CompileStateTracker sender);
public event DisposeDelegate Dispose;
public event EventHandler<ExecutionStateEventArgs> ExecutionEvent;
public int ExecutionState { get; set; }
public bool builtInsLoaded { get; set; }
public List<string> LoadedDLLs = new List<string>();
public int deltaCompileStartPC { get; set; }
public void LogErrorInGlobalMap(ProtoLanguage.CompileStateTracker.ErrorType type, string msg, string fileName = null, int line = -1, int col = -1,
ProtoCore.BuildData.WarningID buildId = ProtoCore.BuildData.WarningID.kDefault, ProtoCore.RuntimeData.WarningID runtimeId = ProtoCore.RuntimeData.WarningID.kDefault)
{
ulong location = (((ulong)line) << 32 | ((uint)col));
ProtoLanguage.CompileStateTracker.ErrorEntry newError = new ProtoLanguage.CompileStateTracker.ErrorEntry
{
Type = type,
FileName = fileName,
Message = msg,
Line = line,
Col = col,
BuildId = buildId,
RuntimeId = runtimeId
};
if (this.LocationErrorMap.ContainsKey(location))
{
ProtoLanguage.CompileStateTracker.ErrorEntry error = this.LocationErrorMap[location];
// If there is a warning, replace it with an error
if (error.Type == ProtoLanguage.CompileStateTracker.ErrorType.Warning && type == ProtoLanguage.CompileStateTracker.ErrorType.Error)
{
this.LocationErrorMap[location] = newError;
}
}
else
{
this.LocationErrorMap.Add(location, newError);
}
}
public void NotifyExecutionEvent(ExecutionStateEventArgs.State state)
{
switch (state)
{
case ExecutionStateEventArgs.State.kExecutionBegin:
Validity.Assert(ExecutionState == (int)ExecutionStateEventArgs.State.kInvalid, "Invalid Execution state being notified.");
break;
case ExecutionStateEventArgs.State.kExecutionEnd:
if (ExecutionState == (int)ExecutionStateEventArgs.State.kInvalid) //execution never begun.
return;
break;
case ExecutionStateEventArgs.State.kExecutionBreak:
Validity.Assert(ExecutionState == (int)ExecutionStateEventArgs.State.kExecutionBegin || ExecutionState == (int)ExecutionStateEventArgs.State.kExecutionResume, "Invalid Execution state being notified.");
break;
case ExecutionStateEventArgs.State.kExecutionResume:
Validity.Assert(ExecutionState == (int)ExecutionStateEventArgs.State.kExecutionBreak, "Invalid Execution state being notified.");
break;
default:
Validity.Assert(false, "Invalid Execution state being notified.");
break;
}
ExecutionState = (int)state;
if (null != ExecutionEvent)
ExecutionEvent(this, new ExecutionStateEventArgs(state));
}
public class CodeBlockCompilationSnapshot
{
public CodeBlockCompilationSnapshot(int codeBlocKId, int graphNodeCount, int endPC)
{
CodeBlockId = codeBlocKId;
GraphNodeCount = graphNodeCount;
InstructionCount = endPC;
}
public static List<CodeBlockCompilationSnapshot> CaptureCoreCompileState(Core core)
{
List<CodeBlockCompilationSnapshot> snapShots = new List<CodeBlockCompilationSnapshot>();
if (core.CodeBlockList != null)
{
foreach (var codeBlock in core.CodeBlockList)
{
int codeBlockId = codeBlock.codeBlockId;
InstructionStream istream = core.CodeBlockList[codeBlockId].instrStream;
int graphCount = istream.dependencyGraph.GraphList.Count;
int instructionCount = istream.instrList.Count;
snapShots.Add(new CodeBlockCompilationSnapshot(codeBlockId, graphCount, instructionCount));
}
}
return snapShots;
}
public int CodeBlockId { get; set;}
public int GraphNodeCount { get; set;}
public int InstructionCount { get; set;}
}
public void ResetDeltaCompileFromSnapshot(List<CodeBlockCompilationSnapshot> snapShots)
{
if (snapShots == null)
throw new ArgumentNullException("snapshots");
foreach (var snapShot in snapShots)
{
InstructionStream istream = CodeBlockList[snapShot.CodeBlockId].instrStream;
int instrCount = istream.instrList.Count - snapShot.InstructionCount;
if (instrCount > 0)
{
istream.instrList.RemoveRange(snapShot.InstructionCount, instrCount);
}
int graphNodeCount = istream.dependencyGraph.GraphList.Count - snapShot.GraphNodeCount;
if (graphNodeCount > 0)
{
istream.dependencyGraph.GraphList.RemoveRange(snapShot.GraphNodeCount, graphNodeCount);
}
}
}
/// <summary>
/// Reset properties for recompilation
/// Generated instructions for imported libraries are preserved.
/// This means they are just reloaded, not regenerated
/// </summary>
private void ResetDeltaCompile()
{
if (CodeBlockList.Count > 0)
{
// Preserve only the instructions of libraries that were previously loaded
// Other instructions need to be removed and regenerated
int instrCount = CodeBlockList[0].instrStream.instrList.Count;
// Remove from these indices
int from = deltaCompileStartPC;
int count = instrCount - deltaCompileStartPC;
CodeBlockList[0].instrStream.instrList.RemoveRange(from, count);
// Remove graphnodes from this range
// TODO Jun: Optimize this - determine which graphnodes need to be removed during compilation
int removeGraphnodesFrom = ProtoCore.DSASM.Constants.kInvalidIndex;
for (int n = 0; n < CodeBlockList[0].instrStream.dependencyGraph.GraphList.Count; ++n)
{
ProtoCore.AssociativeGraph.GraphNode graphNode = CodeBlockList[0].instrStream.dependencyGraph.GraphList[n];
if (graphNode.updateBlock.startpc >= deltaCompileStartPC)
{
removeGraphnodesFrom = n;
break;
}
}
if (ProtoCore.DSASM.Constants.kInvalidIndex != removeGraphnodesFrom)
{
count = CodeBlockList[0].instrStream.dependencyGraph.GraphList.Count - removeGraphnodesFrom;
int classIndex = CodeBlockList[0].instrStream.dependencyGraph.GraphList[removeGraphnodesFrom].classIndex;
int procIndex = CodeBlockList[0].instrStream.dependencyGraph.GraphList[removeGraphnodesFrom].procIndex;
// TODO Jun: Find the better way to remove the graphnodes from the nodemap
// Does getting the classindex and proindex of the first node sufficient?
CodeBlockList[0].instrStream.dependencyGraph.RemoveNodesFromScope(classIndex, procIndex);
// Remove the graphnodes from them main list
CodeBlockList[0].instrStream.dependencyGraph.GraphList.RemoveRange(removeGraphnodesFrom, count);
}
else
{
// @keyu: This is for the first run. Just simply remove
// global graph node from the map to avoid they are marked
// as dirty at the next run.
CodeBlockList[0].instrStream.dependencyGraph.RemoveNodesFromScope(Constants.kInvalidIndex, Constants.kInvalidIndex);
}
}
}
// @keyu: ResetDeltaExection() resets everything so that the core will
// compile new code and execute it, but in some cases we dont want to
// compile code, just re-execute the existing code, therefore only some
// states need to be reset.
public void ResetForExecution()
{
ExecMode = ProtoCore.DSASM.InterpreterMode.kNormal;
ExecutionState = (int)ExecutionStateEventArgs.State.kInvalid;
RunningBlock = 0;
}
// Comment Jun:
// The core is reused on delta execution
// These are properties that need to be reset on subsequent executions
// All properties require reset except for the runtime memory
public void ResetForDeltaExecution()
{
compileSucceeded = false;
ClassIndex = ProtoCore.DSASM.Constants.kInvalidIndex;
watchClassScope = ProtoCore.DSASM.Constants.kInvalidIndex;
watchFunctionScope = ProtoCore.DSASM.Constants.kInvalidIndex;
watchBaseOffset = 0;
watchStack = new List<StackValue>();
watchSymbolList = new List<SymbolNode>();
watchFramePointer = ProtoCore.DSASM.Constants.kInvalidIndex;
ID = FIRST_CORE_ID;
//recurtion
recursivePoint = new List<FunctionCounter>();
funcCounterTable = new List<FunctionCounter>();
calledInFunction = false;
//GlobOffset = 0;
GlobHeapOffset = 0;
BaseOffset = 0;
GraphNodeUID = 0;
RunningBlock = 0;
//CodeBlockList = new List<DSASM.CodeBlock>();
CompleteCodeBlockList = new List<ProtoCore.DSASM.CodeBlock>();
DSExecutable = new ProtoCore.DSASM.Executable();
AssocNode = null;
//
//
// Comment Jun: Delta execution should not reset the class tables as they are preserved
//
// FunctionTable = new Lang.FunctionTable();
// ClassTable = new DSASM.ClassTable();
// TypeSystem = new TypeSystem();
// TypeSystem.SetClassTable(ClassTable);
// ProcNode = null;
// ProcTable = new DSASM.ProcedureTable(ProtoCore.DSASM.Constants.kGlobalScope);
//
// CodeBlockList = new List<DSASM.CodeBlock>();
//
//
// CodeBlockIndex = 0;
// RuntimeTableIndex = 0;
//
//Initialize the function pointer table
FunctionPointerTable = new ProtoCore.DSASM.FunctionPointerTable();
//Initialize the dynamic string table and dynamic function table
DynamicVariableTable = new ProtoCore.DSASM.DynamicVariableTable();
DynamicFunctionTable = new ProtoCore.DSASM.DynamicFunctionTable();
replicationGuides = new List<List<int>>();
ExceptionHandlingManager = new ExceptionHandlingManager();
startPC = ProtoCore.DSASM.Constants.kInvalidIndex;
if (Options.SuppressBuildOutput)
{
// don't log any of the build related messages
// just accumulate them in relevant containers with
// BuildStatus object
//
BuildStatus = new BuildStatus(this, false, false, false);
}
else
{
BuildStatus = new BuildStatus(this, Options.BuildOptWarningAsError, null, Options.BuildOptErrorAsWarning);
}
SSASubscript = 0;
ExpressionUID = 0;
ModifierBlockUID = 0;
ModifierStateSubscript = 0;
ExprInterpreterExe = null;
ExecMode = ProtoCore.DSASM.InterpreterMode.kNormal;
assocCodegen = null;
FunctionCallDepth = 0;
// Default execution log is Console.Out.
this.ExecutionLog = Console.Out;
ExecutionState = (int)ExecutionStateEventArgs.State.kInvalid; //not yet started
DebugProps = new DebugProperties();
InterpreterProps = new Stack<InterpreterProperties>();
stackActiveExceptionRegistration = new Stack<ExceptionRegistration>();
ExecutiveProvider = new ExecutiveProvider();
ParsingMode = ProtoCore.ParseMode.Normal;
// Reset PC dictionary containing PC to line/col map
if (codeToLocation != null)
codeToLocation.Clear();
if (LocationErrorMap != null)
LocationErrorMap.Clear();
if (AstNodeList != null)
AstNodeList.Clear();
ResetDeltaCompile();
}
public void ResetForPrecompilation()
{
compileSucceeded = false;
GraphNodeUID = 0;
CodeBlockIndex = 0;
RuntimeTableIndex = 0;
//Initialize the dynamic string table and dynamic function table
DynamicVariableTable = new ProtoCore.DSASM.DynamicVariableTable();
DynamicFunctionTable = new ProtoCore.DSASM.DynamicFunctionTable();
// If the previous compilation for import resulted in a build error,
// ignore it and continue compiling other import statements
/*if (BuildStatus.ErrorCount > 0)
{
ImportHandler = null;
CodeBlockList.Clear();
CompleteCodeBlockList.Clear();
}*/
if (Options.SuppressBuildOutput)
{
// don't log any of the build related messages
// just accumulate them in relevant containers with
// BuildStatus object
//
BuildStatus = new BuildStatus(this, false, false, false);
}
else
{
BuildStatus = new BuildStatus(this, Options.BuildOptWarningAsError);
}
if (AstNodeList != null)
AstNodeList.Clear();
ExpressionUID = 0;
}
private void ResetAll(CompileOptions options)
{
compileSucceeded = false;
ProtoCore.Utils.Validity.AssertExpiry();
Options = options;
Executives = new Dictionary<ProtoCore.Language, ProtoCore.Executive>();
FunctionTable = new ProtoCore.Lang.FunctionTable();
ClassIndex = ProtoCore.DSASM.Constants.kInvalidIndex;
Heap = new ProtoCore.DSASM.Heap();
Rmem = new ProtoCore.Runtime.RuntimeMemory(Heap);
watchClassScope = ProtoCore.DSASM.Constants.kInvalidIndex;
watchFunctionScope = ProtoCore.DSASM.Constants.kInvalidIndex;
watchBaseOffset = 0;
watchStack = new List<StackValue>();
watchSymbolList = new List<SymbolNode>();
watchFramePointer = ProtoCore.DSASM.Constants.kInvalidIndex;
ID = FIRST_CORE_ID;
//recurtion
recursivePoint = new List<FunctionCounter>();
funcCounterTable = new List<FunctionCounter>();
calledInFunction = false;
GlobOffset = 0;
GlobHeapOffset = 0;
BaseOffset = 0;
GraphNodeUID = 0;
RunningBlock = 0;
CodeBlockIndex = 0;
RuntimeTableIndex = 0;
CodeBlockList = new List<ProtoCore.DSASM.CodeBlock>();
CompleteCodeBlockList = new List<ProtoCore.DSASM.CodeBlock>();
DSExecutable = new ProtoCore.DSASM.Executable();
AssocNode = null;
// TODO Jun/Luke type system refactoring
// Initialize the globalClass table and type system
ClassTable = new ProtoCore.DSASM.ClassTable();
TypeSystem = new TypeSystem();
TypeSystem.SetClassTable(ClassTable);
ProcNode = null;
ProcTable = new ProtoCore.DSASM.ProcedureTable(ProtoCore.DSASM.Constants.kGlobalScope);
//Initialize the function pointer table
FunctionPointerTable = new ProtoCore.DSASM.FunctionPointerTable();
//Initialize the dynamic string table and dynamic function table
DynamicVariableTable = new ProtoCore.DSASM.DynamicVariableTable();
DynamicFunctionTable = new ProtoCore.DSASM.DynamicFunctionTable();
replicationGuides = new List<List<int>>();
ExceptionHandlingManager = new ExceptionHandlingManager();
startPC = ProtoCore.DSASM.Constants.kInvalidIndex;
deltaCompileStartPC = ProtoCore.DSASM.Constants.kInvalidIndex;
if (options.SuppressBuildOutput)
{
// don't log any of the build related messages
// just accumulate them in relevant containers with
// BuildStatus object
//
BuildStatus = new BuildStatus(this, false, false, false);
}
else
{
BuildStatus = new BuildStatus(this, Options.BuildOptWarningAsError, null, Options.BuildOptErrorAsWarning);
}
SSASubscript = 0;
ExpressionUID = 0;
ModifierBlockUID = 0;
ModifierStateSubscript = 0;
ExprInterpreterExe = null;
ExecMode = ProtoCore.DSASM.InterpreterMode.kNormal;
assocCodegen = null;
FunctionCallDepth = 0;
// Default execution log is Console.Out.
this.ExecutionLog = Console.Out;
ExecutionState = (int)ExecutionStateEventArgs.State.kInvalid; //not yet started
DebugProps = new DebugProperties();
//stackNodeExecutedSameTimes = new Stack<List<AssociativeGraph.GraphNode>>();
//stackExecutingGraphNodes = new Stack<AssociativeGraph.GraphNode>();
InterpreterProps = new Stack<InterpreterProperties>();
stackActiveExceptionRegistration = new Stack<ExceptionRegistration>();
ExecutiveProvider = new ExecutiveProvider();
Configurations = new Dictionary<string, object>();
ContinuationStruct = new ProtoCore.Lang.ContinuationStructure();
ParsingMode = ProtoCore.ParseMode.Normal;
IsParsingPreloadedAssembly = false;
IsParsingCodeBlockNode = false;
ImportHandler = null;
deltaCompileStartPC = 0;
builtInsLoaded = false;
//FFIPropertyChangedMonitor = new FFIPropertyChangedMonitor(this);
}
// The unique subscript for SSA temporaries
// TODO Jun: Organize these variables in core into proper enums/classes/struct
public int SSASubscript { get; set; }
public int ExpressionUID { get; set; }
public int ModifierBlockUID { get; set; }
public int ModifierStateSubscript { get; set; }
public ExceptionHandlingManager ExceptionHandlingManager { get; set; }
private int tempVarId = 0;
private int tempLanguageId = 0;
// TODO Jun: Cleansify me - i dont need to be here
public ProtoCore.AST.AssociativeAST.AssociativeNode AssocNode { get; set; }
public int startPC { get; set; }
//
// TODO Jun: This is the expression interpreters executable.
// It must be moved to its own core, whre each core is an instance of a compiler+interpreter
//
public Executable ExprInterpreterExe { get; set; }
public ProtoCore.DSASM.InterpreterMode ExecMode { get; set; }
public List<SymbolNode> watchSymbolList { get; set; }
public int watchClassScope { get; set; }
public int watchFunctionScope { get; set; }
public int watchBaseOffset { get; set; }
public List<StackValue> watchStack { get; set; }
public int watchFramePointer { get; set; }
public ProtoCore.CodeGen assocCodegen { get; set; }
// this one is to address the issue that when the execution control is in a language block
// which is further inside a function, the compiler feprun is false,
// when inspecting value in that language block or the function, debugger will assume the function index is -1,
// name look up will fail beacuse all the local variables inside
// that language block and fucntion has non-zero function index
public int FunctionCallDepth { get; set; }
public System.IO.TextWriter ExecutionLog { get; set; }
protected void OnDispose()
{
if (Dispose != null)
{
Dispose(this);
}
}
public void Cleanup()
{
OnDispose();
ProtoFFI.CLRModuleType.ClearTypes();
}
public void InitializeContextGlobals(Dictionary<string, object> context)
{
int globalBlock = 0;
foreach (KeyValuePair<string, object> global in context)
{
int stackIndex = CodeBlockList[globalBlock].symbolTable.IndexOf(global.Key);
if (global.Value.GetType() != typeof(Double) && global.Value.GetType() != typeof(Int32))
throw new NotImplementedException("Context that's aren't double are not yet supported @TODO: Jun,Sharad,Luke ASAP");
double dValue = Convert.ToDouble(global.Value);
StackValue svData = StackUtils.BuildDouble(dValue);
Rmem.SetGlobalStackData(stackIndex, svData);
}
}
public CompileStateTracker(CompileOptions options)
{
ResetAll(options);
}
public SymbolNode GetSymbolInFunction(string name, int classScope, int functionScope, CodeBlock codeBlock)
{
Debug.Assert(functionScope != Constants.kGlobalScope);
if (Constants.kGlobalScope == functionScope)
{
return null;
}
int symbolIndex = Constants.kInvalidIndex;
if (classScope != Constants.kGlobalScope)
{
//Search local variable for the class member function
symbolIndex = ClassTable.ClassNodes[classScope].symbols.IndexOf(name, classScope, functionScope);
if (symbolIndex != Constants.kInvalidIndex)
{
return ClassTable.ClassNodes[classScope].symbols.symbolList[symbolIndex];
}
//Search class members
symbolIndex = ClassTable.ClassNodes[classScope].symbols.IndexOf(name, classScope, Constants.kGlobalScope);
if (symbolIndex != Constants.kInvalidIndex)
{
return ClassTable.ClassNodes[classScope].symbols.symbolList[symbolIndex];
}
}
while (symbolIndex == Constants.kInvalidIndex &&
codeBlock != null &&
codeBlock.blockType != CodeBlockType.kFunction)
{
symbolIndex = codeBlock.symbolTable.IndexOf(name, classScope, functionScope);
if (symbolIndex != Constants.kInvalidIndex)
{
return codeBlock.symbolTable.symbolList[symbolIndex];
}
else
{
codeBlock = codeBlock.parent;
}
}
if (symbolIndex == Constants.kInvalidIndex &&
codeBlock != null &&
codeBlock.blockType == CodeBlockType.kFunction)
{
symbolIndex = codeBlock.symbolTable.IndexOf(name, classScope, functionScope);
if (symbolIndex != Constants.kInvalidIndex)
{
return codeBlock.symbolTable.symbolList[symbolIndex];
}
}
return null;
}
public SymbolNode GetFirstVisibleSymbol(string name, int classscope, int function, CodeBlock codeblock)
{
//
//
Debug.Assert(null != codeblock);
if (null == codeblock)
{
return null;
}
int symbolIndex = ProtoCore.DSASM.Constants.kInvalidIndex;
bool stillInsideFunction = function != ProtoCore.DSASM.Constants.kInvalidIndex;
ProtoCore.DSASM.CodeBlock searchBlock = codeblock;
// TODO(Jiong): Code Duplication, Consider moving this if else block inside the while loop
if (stillInsideFunction)
{
symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, function);
if (function != ProtoCore.DSASM.Constants.kInvalidIndex &&
searchBlock.procedureTable != null &&
searchBlock.procedureTable.procList.Count > function && // Note: This check assumes we can not define functions inside a fucntion
symbolIndex == ProtoCore.DSASM.Constants.kInvalidIndex)
symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, ProtoCore.DSASM.Constants.kInvalidIndex);
}
else
{
symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, ProtoCore.DSASM.Constants.kInvalidIndex);
}
while (ProtoCore.DSASM.Constants.kInvalidIndex == symbolIndex)
{
// if the search block is of type function, it means our search has gone out of the function itself
// so, we should ignore the given function index and only search its parent block's global variable
if (searchBlock.blockType == ProtoCore.DSASM.CodeBlockType.kFunction)
stillInsideFunction = false;
searchBlock = searchBlock.parent;
if (null != searchBlock)
{
// Continue searching
if (stillInsideFunction)
{
// we are still inside a function, first search the local variable defined in this function
// if not found, then search the enclosing block by specifying the function index as -1
symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, function);
// this check is to avoid unnecessary search
// for example if we have a for loop inside an imperative block which is further inside a function
// when we are searching inside the for loop or language block, there is no need to search twice
// we need to search twice only when we are searching directly inside the function,
if (function != ProtoCore.DSASM.Constants.kInvalidIndex &&
searchBlock.procedureTable != null &&
searchBlock.procedureTable.procList.Count > function && // Note: This check assumes we can not define functions inside a fucntion
symbolIndex == ProtoCore.DSASM.Constants.kInvalidIndex)
symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, ProtoCore.DSASM.Constants.kInvalidIndex);
}
else
{
symbolIndex = searchBlock.symbolTable.IndexOf(name, classscope, ProtoCore.DSASM.Constants.kInvalidIndex);
}
}
else
{
// End of nested blocks
/*
// Not found? Look at the class scope
if (ProtoCore.DSASM.Constants.kInvalidIndex != classscope)
{
// Look at the class members and base class members
bool hasSymbol = false;
ProtoCore.DSASM.AddressType addrType = DSASM.AddressType.Invalid;
ProtoCore.DSASM.ClassNode cnode = classTable.list[classscope];
symbolIndex = cnode.GetFirstVisibleSymbol(name, classscope, function, out hasSymbol, out addrType);
if (ProtoCore.DSASM.Constants.kInvalidIndex != symbolIndex)
{
if (addrType == DSASM.AddressType.StaticMemVarIndex)
{
return codeBlockList[0].symbolTable.symbolList[symbolIndex];
}
else
{
return classTable.list[classscope].symbols.symbolList[symbolIndex];
}
}
// Look at the class constructors and functions
symbolIndex = classTable.list[classscope].symbols.IndexOf(name, classscope, function);
if (ProtoCore.DSASM.Constants.kInvalidIndex != symbolIndex)
{
return classTable.list[classscope].symbols.symbolList[symbolIndex];
}
}
// Not found? Look at the global scope
symbolIndex = searchBlock.symbolTable.IndexOf(name, ProtoCore.DSASM.Constants.kInvalidIndex, ProtoCore.DSASM.Constants.kGlobalScope);
if (ProtoCore.DSASM.Constants.kInvalidIndex == symbolIndex)
{
return null;
}
break;
* */
return null;
}
}
return searchBlock.symbolTable.symbolList[symbolIndex];
}
public bool IsFunctionCodeBlock(CodeBlock cblock)
{
// Determine if the immediate block is a function block
// Construct blocks are ignored
Debug.Assert(null != cblock);
while (null != cblock)
{
if (ProtoCore.DSASM.CodeBlockType.kFunction == cblock.blockType)
{
return true;
}
else if (ProtoCore.DSASM.CodeBlockType.kLanguage == cblock.blockType)
{
return false;
}
cblock = cblock.parent;
}
return false;
}
public ProcedureNode GetFirstVisibleProcedure(string name, List<ProtoCore.Type> argTypeList, CodeBlock codeblock)
{
Debug.Assert(null != codeblock);
if (null == codeblock)
{
return null;
}
ProtoCore.DSASM.CodeBlock searchBlock = codeblock;
while (null != searchBlock)
{
if (null == searchBlock.procedureTable)
{
searchBlock = searchBlock.parent;
continue;
}
// The class table is passed just to check for coercion values
int procIndex = searchBlock.procedureTable.IndexOf(name, argTypeList, ClassTable);
if (ProtoCore.DSASM.Constants.kInvalidIndex != procIndex)
{
return searchBlock.procedureTable.procList[procIndex];
}
searchBlock = searchBlock.parent;
}
return null;
}
public ProtoCore.DSASM.CodeBlock GetCodeBlock(List<ProtoCore.DSASM.CodeBlock> blockList, int blockId)
{
ProtoCore.DSASM.CodeBlock codeblock = null;
codeblock = blockList.Find(x => x.codeBlockId == blockId);
if (codeblock == null)
{
foreach (ProtoCore.DSASM.CodeBlock block in blockList)
{
codeblock = GetCodeBlock(block.children, blockId);
if (codeblock != null)
{
break;
}
}
}
return codeblock;
}
//public StackValue Bounce(int exeblock, int entry, ProtoCore.Runtime.Context context, ProtoCore.DSASM.StackFrame stackFrame, int locals = 0, ProtoCore.DebugServices.EventSink sink = null)
//{
// if (stackFrame != null)
// {
// ProtoCore.DSASM.StackValue svThisPtr = stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kThisPtr);
// int ci = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kClass).opdata;
// int fi = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFunction).opdata;
// int returnAddr = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kReturnAddress).opdata;
// int blockDecl = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFunctionBlock).opdata;
// int blockCaller = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFunctionCallerBlock).opdata;
// ProtoCore.DSASM.StackFrameType callerFrameType = (ProtoCore.DSASM.StackFrameType)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kCallerStackFrameType).opdata;
// ProtoCore.DSASM.StackFrameType frameType = (ProtoCore.DSASM.StackFrameType)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kStackFrameType).opdata;
// Validity.Assert(frameType == StackFrameType.kTypeLanguage);
// int depth = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kStackFrameDepth).opdata;
// int framePointer = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFramePointer).opdata;
// List<StackValue> registers = stackFrame.GetRegisters();
// Rmem.PushStackFrame(svThisPtr, ci, fi, returnAddr, blockDecl, blockCaller, callerFrameType, frameType, depth + 1, framePointer, registers, locals, 0);
// }
// ProtoCore.Language id = DSExecutable.instrStreamList[exeblock].language;
// CurrentExecutive = Executives[id];
// ProtoCore.DSASM.StackValue sv = Executives[id].Execute(exeblock, entry, context, sink);
// return sv;
//}
//public StackValue Bounce(int exeblock, int entry, ProtoCore.Runtime.Context context, List<Instruction> breakpoints, ProtoCore.DSASM.StackFrame stackFrame, int locals = 0,
// ProtoCore.DSASM.Executive exec = null, ProtoCore.DebugServices.EventSink sink = null, bool fepRun = false)
//{
// if (stackFrame != null)
// {
// ProtoCore.DSASM.StackValue svThisPtr = stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kThisPtr);
// int ci = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kClass).opdata;
// int fi = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFunction).opdata;
// int returnAddr = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kReturnAddress).opdata;
// int blockDecl = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFunctionBlock).opdata;
// int blockCaller = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFunctionCallerBlock).opdata;
// ProtoCore.DSASM.StackFrameType callerFrameType = (ProtoCore.DSASM.StackFrameType)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kCallerStackFrameType).opdata;
// ProtoCore.DSASM.StackFrameType frameType = (ProtoCore.DSASM.StackFrameType)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kStackFrameType).opdata;
// Validity.Assert(frameType == StackFrameType.kTypeLanguage);
// int depth = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kStackFrameDepth).opdata;
// int framePointer = (int)stackFrame.GetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFramePointer).opdata;
// List<StackValue> registers = stackFrame.GetRegisters();
// DebugProps.SetUpBounce(exec, blockCaller, returnAddr);
// Rmem.PushStackFrame(svThisPtr, ci, fi, returnAddr, blockDecl, blockCaller, callerFrameType, frameType, depth + 1, framePointer, registers, locals, 0);
// }
// ProtoCore.Language id = DSExecutable.instrStreamList[exeblock].language;
// CurrentExecutive = Executives[id];
// ProtoCore.DSASM.StackValue sv = Executives[id].Execute(exeblock, entry, context, breakpoints, sink, fepRun);
// return sv;
//}
private void BfsBuildSequenceTable(CodeBlock codeBlock, SymbolTable[] runtimeSymbols)
{
if (ProtoCore.DSASM.CodeBlockType.kLanguage == codeBlock.blockType
|| ProtoCore.DSASM.CodeBlockType.kFunction == codeBlock.blockType
|| ProtoCore.DSASM.CodeBlockType.kConstruct == codeBlock.blockType)
{
Debug.Assert(codeBlock.symbolTable.runtimeIndex < RuntimeTableIndex);
runtimeSymbols[codeBlock.symbolTable.runtimeIndex] = codeBlock.symbolTable;
}
foreach (ProtoCore.DSASM.CodeBlock child in codeBlock.children)
{
BfsBuildSequenceTable(child, runtimeSymbols);
}
}
private void BfsBuildProcedureTable(CodeBlock codeBlock, ProcedureTable[] procTable)
{
if (ProtoCore.DSASM.CodeBlockType.kLanguage == codeBlock.blockType || ProtoCore.DSASM.CodeBlockType.kFunction == codeBlock.blockType)
{
Debug.Assert(codeBlock.procedureTable.runtimeIndex < RuntimeTableIndex);
procTable[codeBlock.procedureTable.runtimeIndex] = codeBlock.procedureTable;
}
foreach (ProtoCore.DSASM.CodeBlock child in codeBlock.children)
{
BfsBuildProcedureTable(child, procTable);
}
}
private void BfsBuildInstructionStreams(CodeBlock codeBlock, InstructionStream[] istreamList)
{
if (null != codeBlock)
{
if (ProtoCore.DSASM.CodeBlockType.kLanguage == codeBlock.blockType || ProtoCore.DSASM.CodeBlockType.kFunction == codeBlock.blockType)
{
Debug.Assert(codeBlock.codeBlockId < CodeBlockIndex);
istreamList[codeBlock.codeBlockId] = codeBlock.instrStream;
}
foreach (ProtoCore.DSASM.CodeBlock child in codeBlock.children)
{
BfsBuildInstructionStreams(child, istreamList);
}
}
}
public void GenerateExprExe()
{
// TODO Jun: Determine if we really need another executable for the expression interpreter
Validity.Assert(null == ExprInterpreterExe);
ExprInterpreterExe = new ProtoCore.DSASM.Executable();
// Copy all tables
ExprInterpreterExe.classTable = DSExecutable.classTable;
ExprInterpreterExe.procedureTable = DSExecutable.procedureTable;
ExprInterpreterExe.runtimeSymbols = DSExecutable.runtimeSymbols;
ExprInterpreterExe.isSingleAssocBlock = DSExecutable.isSingleAssocBlock;
// Copy all instruction streams
// TODO Jun: What method to copy all? Use that
ExprInterpreterExe.instrStreamList = new InstructionStream[DSExecutable.instrStreamList.Length];
for (int i = 0; i < DSExecutable.instrStreamList.Length; ++i)
{
if (null != DSExecutable.instrStreamList[i])
{
ExprInterpreterExe.instrStreamList[i] = new InstructionStream(DSExecutable.instrStreamList[i].language, this);
for (int j = 0; j < DSExecutable.instrStreamList[i].instrList.Count; ++j)
{
ExprInterpreterExe.instrStreamList[i].instrList.Add(DSExecutable.instrStreamList[i].instrList[j]);
}
}
}
}
public void GenerateExprExeInstructions(int blockScope)
{
// Append the expression instruction at the end of the current block
for (int n = 0; n < ExprInterpreterExe.iStreamCanvas.instrList.Count; ++n)
{
ExprInterpreterExe.instrStreamList[blockScope].instrList.Add(ExprInterpreterExe.iStreamCanvas.instrList[n]);
}
}
public void GenerateExecutable()
{
Debug.Assert(CodeBlockList.Count >= 0);
// Retrieve the class table directly since it is a global table
DSExecutable.classTable = ClassTable;
// Build the runtime symbols
DSExecutable.runtimeSymbols = new ProtoCore.DSASM.SymbolTable[RuntimeTableIndex];
for (int n = 0; n < CodeBlockList.Count; ++n)
{
BfsBuildSequenceTable(CodeBlockList[n], DSExecutable.runtimeSymbols);
}
// Build the runtime procedure table
DSExecutable.procedureTable = new ProtoCore.DSASM.ProcedureTable[RuntimeTableIndex];
for (int n = 0; n < CodeBlockList.Count; ++n)
{
BfsBuildProcedureTable(CodeBlockList[n], DSExecutable.procedureTable);
}
// Build the executable instruction streams
DSExecutable.instrStreamList = new ProtoCore.DSASM.InstructionStream[CodeBlockIndex];
for (int n = 0; n < CodeBlockList.Count; ++n)
{
BfsBuildInstructionStreams(CodeBlockList[n], DSExecutable.instrStreamList);
}
// Single associative block means the first instruction is an immediate bounce
// This variable is only used by the mirror to determine if the GetValue()
// block parameter needs to be incremented or not in order to get the correct global variable
if (DSExecutable.isSingleAssocBlock)
{
DSExecutable.isSingleAssocBlock = (ProtoCore.DSASM.OpCode.BOUNCE == CodeBlockList[0].instrStream.instrList[0].opCode) ? true : false;
}
// Properties directly accessed by the runtime from core, should now be accessed from the executable
DSExecutable.CodeBlockList = new List<CodeBlock>(CodeBlockList);
DSExecutable.FunctionTable = FunctionTable;
DSExecutable.CompleteCodeBlockList = CompleteCodeBlockList;
DSExecutable.DynamicVariableTable = DynamicVariableTable;
DSExecutable.DynamicFunctionTable = DynamicFunctionTable;
DSExecutable.FunctionPointerTable = FunctionPointerTable;
GenerateExprExe();
}
public string GenerateTempVar()
{
tempVarId++;
return ProtoCore.DSASM.Constants.kTempVar + tempVarId.ToString();
}
public string GenerateTempPropertyVar()
{
tempVarId++;
return ProtoCore.DSASM.Constants.kTempPropertyVar + tempVarId.ToString();
}
public string GenerateTempLangageVar()
{
tempLanguageId++;
return ProtoCore.DSASM.Constants.kTempLangBlock + tempLanguageId.ToString();
}
public bool IsTempVar(String varName)
{
if (String.IsNullOrEmpty(varName))
{
return false;
}
return varName[0] == '%';
}
public string GetModifierBlockTemp(string modifierName)
{
// The naming convention for auto-generated modifier block states begins with a '%'
// followed by "<Constants.kTempModifierStateNamePrefix>_<modifier_block_name>_<index>
string modStateTemp = ProtoCore.DSASM.Constants.kTempModifierStateNamePrefix + modifierName + ModifierStateSubscript.ToString();
++ModifierStateSubscript;
return modStateTemp;
}
public List<int> GetAncestorBlockIdsOfBlock(int blockId)
{
if (blockId >= this.CompleteCodeBlockList.Count || blockId < 0)
{
return new List<int>();
}
CodeBlock thisBlock = this.CompleteCodeBlockList[blockId];
var ancestors = new List<int>();
CodeBlock codeBlock = thisBlock.parent;
while (codeBlock != null)
{
ancestors.Add(codeBlock.codeBlockId);
codeBlock = codeBlock.parent;
}
return ancestors;
}
public int GetCurrentBlockId()
{
int constructBlockId = this.Rmem.CurrentConstructBlockId;
if (constructBlockId == Constants.kInvalidIndex)
return DebugProps.CurrentBlockId;
CodeBlock constructBlock = GetCodeBlock(CodeBlockList, constructBlockId);
while (null != constructBlock && constructBlock.blockType == CodeBlockType.kConstruct)
{
constructBlock = constructBlock.parent;
}
if (null != constructBlock)
constructBlockId = constructBlock.codeBlockId;
if (constructBlockId != DebugProps.CurrentBlockId)
return DebugProps.CurrentBlockId;
else
return this.Rmem.CurrentConstructBlockId;
}
public ProtoCore.AssociativeGraph.GraphNode GetExecutingGraphNode()
{
foreach (var prop in this.InterpreterProps)
{
if (prop.executingGraphNode != null)
{
return prop.executingGraphNode;
}
}
return null;
}
public bool IsEvalutingPropertyChanged()
{
foreach (var prop in this.InterpreterProps)
{
if (prop.updateStatus == ProtoCore.AssociativeEngine.UpdateStatus.kPropertyChangedUpdate)
{
return true;
}
}
return false;
}
}
}
| |
// <copyright file="TelemetrySpan.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Trace
{
/// <summary>
/// Span represents a single operation within a trace.
/// </summary>
/// <remarks>TelemetrySpan is a wrapper around <see cref="Activity"/> class.</remarks>
public class TelemetrySpan : IDisposable
{
internal static readonly TelemetrySpan NoopInstance = new TelemetrySpan(null);
internal readonly Activity Activity;
internal TelemetrySpan(Activity activity)
{
this.Activity = activity;
}
/// <summary>
/// Gets the span context.
/// </summary>
public SpanContext Context
{
get
{
if (this.Activity == null)
{
return default;
}
else
{
return new SpanContext(this.Activity.Context);
}
}
}
/// <summary>
/// Gets a value indicating whether this span will be recorded.
/// </summary>
public bool IsRecording
{
get
{
return this.Activity != null && this.Activity.IsAllDataRequested;
}
}
/// <summary>
/// Gets the identity of the parent span id, if any.
/// </summary>
public ActivitySpanId ParentSpanId
{
get
{
if (this.Activity == null)
{
return default;
}
else
{
return this.Activity.ParentSpanId;
}
}
}
/// <summary>
/// Sets the status of the span execution.
/// </summary>
/// <param name="value">Status to be set.</param>
public void SetStatus(Status value)
{
this.Activity?.SetStatus(value);
}
/// <summary>
/// Updates the <see cref="TelemetrySpan"/> name.
///
/// If used, this will override the name provided via StartSpan method overload.
/// Upon this update, any sampling behavior based on <see cref="TelemetrySpan"/> name will depend on the
/// implementation.
/// </summary>
/// <param name="name">Name of the span.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan UpdateName(string name)
{
if (this.Activity != null)
{
this.Activity.DisplayName = name;
}
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="value">Attribute value.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, string value)
{
this.SetAttributeInternal(key, value);
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="value">Attribute value.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, int value)
{
this.SetAttributeInternal(key, value);
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="value">Attribute value.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, bool value)
{
this.SetAttributeInternal(key, value);
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="value">Attribute value.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, double value)
{
this.SetAttributeInternal(key, value);
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="values">Attribute values.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, string[] values)
{
this.SetAttributeInternal(key, values);
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="values">Attribute values.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, int[] values)
{
this.SetAttributeInternal(key, values);
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="values">Attribute values.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, bool[] values)
{
this.SetAttributeInternal(key, values);
return this;
}
/// <summary>
/// Sets a new attribute on the span.
/// </summary>
/// <param name="key">Attribute key.</param>
/// <param name="values">Attribute values.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan SetAttribute(string key, double[] values)
{
this.SetAttributeInternal(key, values);
return this;
}
/// <summary>
/// Adds a single Event to the <see cref="TelemetrySpan"/>.
/// </summary>
/// <param name="name">Name of the event.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan AddEvent(string name)
{
this.AddEventInternal(name);
return this;
}
/// <summary>
/// Adds a single Event to the <see cref="TelemetrySpan"/>.
/// </summary>
/// <param name="name">Name of the event.</param>
/// <param name="timestamp">Timestamp of the event.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan AddEvent(string name, DateTimeOffset timestamp)
{
this.AddEventInternal(name, timestamp);
return this;
}
/// <summary>
/// Adds a single Event to the <see cref="TelemetrySpan"/>.
/// </summary>
/// <param name="name">Name of the event.</param>
/// <param name="attributes">Attributes for the event.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan AddEvent(string name, SpanAttributes attributes)
{
this.AddEventInternal(name, default, attributes?.Attributes);
return this;
}
/// <summary>
/// Adds a single Event to the <see cref="TelemetrySpan"/>.
/// </summary>
/// <param name="name">Name of the event.</param>
/// <param name="timestamp">Timestamp of the event.</param>
/// <param name="attributes">Attributes for the event.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan AddEvent(string name, DateTimeOffset timestamp, SpanAttributes attributes)
{
this.AddEventInternal(name, timestamp, attributes?.Attributes);
return this;
}
/// <summary>
/// End the span.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void End()
{
this.Activity?.Stop();
}
/// <summary>
/// End the span.
/// </summary>
/// <param name="endTimestamp">End timestamp.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void End(DateTimeOffset endTimestamp)
{
this.Activity?.SetEndTime(endTimestamp.UtcDateTime);
this.Activity?.Stop();
}
/// <summary>
/// Record Exception.
/// </summary>
/// <param name="ex">Exception to be recorded.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TelemetrySpan RecordException(Exception ex)
{
if (ex == null)
{
return this;
}
return this.RecordException(ex.GetType().Name, ex.Message, ex.ToInvariantString());
}
/// <summary>
/// Record Exception.
/// </summary>
/// <param name="type">Type of the exception to be recorded.</param>
/// <param name="message">Message of the exception to be recorded.</param>
/// <param name="stacktrace">Stacktrace of the exception to be recorded.</param>
/// <returns>The <see cref="TelemetrySpan"/> instance for chaining.</returns>
public TelemetrySpan RecordException(string type, string message, string stacktrace)
{
SpanAttributes attributes = new SpanAttributes();
if (!string.IsNullOrWhiteSpace(type))
{
attributes.Add(SemanticConventions.AttributeExceptionType, type);
}
if (!string.IsNullOrWhiteSpace(stacktrace))
{
attributes.Add(SemanticConventions.AttributeExceptionStacktrace, stacktrace);
}
if (!string.IsNullOrWhiteSpace(message))
{
attributes.Add(SemanticConventions.AttributeExceptionMessage, message);
}
if (attributes.Attributes.Count != 0)
{
this.AddEvent(SemanticConventions.AttributeExceptionEventName, attributes);
}
return this;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Marks the span as current.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Activate()
{
Activity.Current = this.Activity;
}
/// <summary>
/// Releases the unmanaged resources used by this class and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
this.Activity?.Dispose();
}
private void SetAttributeInternal(string key, object value)
{
if (this.IsRecording)
{
this.Activity.SetTag(key, value);
}
}
private void AddEventInternal(string name, DateTimeOffset timestamp = default, ActivityTagsCollection tags = null)
{
if (this.IsRecording)
{
this.Activity.AddEvent(new ActivityEvent(name, timestamp, tags));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace fxpa
{
public partial class DOATransparentLabel : UserControl
// A Label that can be translucent to the background
{
#region Local Variables
public enum ShapeBorderStyles
{
ShapeBSNone,
ShapeBSFixedSingle,
};
private ShapeBorderStyles _borderStyle = ShapeBorderStyles.ShapeBSNone;
private System.Drawing.Color _backColor = Color.Black;
private System.Drawing.Color _borderColor = Color.White;
private int _radius = 20;
private int _opacity = 125;
private string _text = "doaTransparentLabel";
// Local Variables for text
public enum TextAlignment
{
Left,
Center,
Right
};
public enum MoveType
{
None,
RightToLeft,
DownToUp,
LeftToRight,
UpToDown
}
protected TextAlignment _textAlign = TextAlignment.Center;
protected MoveType _moving = MoveType.None;
protected bool _isSelected = false;
private System.Drawing.Color _dimmedColor = Color.LightGray;
// Work Variables
protected int pointX = 0;
protected int pointY = 0;
protected Rectangle iRect = new Rectangle();
protected Rectangle txtRect = new Rectangle();
#endregion
#region Constructor
public DOATransparentLabel()
{
InitializeComponent();
base.BackColor = Color.Transparent;
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
SetStyle(ControlStyles.Opaque, false);
UpdateStyles();
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
//
// timer1
//
this.timer1.Enabled = false;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
this.timer1.Interval = 100;
}
#endregion
#region Properties
[DefaultValue(typeof(Color), "Black")]
public new Color BackColor
// Gets or sets the background color of the control.
{
get { return _backColor; }
set { _backColor = value; Invalidate();}
}
[
Bindable(true),
Category("Appearance"),
DefaultValue(ShapeBorderStyles.ShapeBSNone),
Description("Style of border to be drawn around control")
]
public ShapeBorderStyles ShapeBorderStyle
{
get { return _borderStyle; }
set { _borderStyle = value; this.Invalidate(); }
}
[DefaultValue(typeof(Color), "White"), Category("Appearance"), Description("The border color of the control.")]
/// Gets or sets the outer border color of the control.
public Color BorderColor
{
get { return _borderColor; }
set {_borderColor = value; Invalidate();}
}
[
Bindable(true),
Category("Appearance"),
DefaultValue(125),
Description("The alpha value used to blend the control's background. Valid values are 0 through 255.")
]
public int Opacity
{
get { return _opacity; }
set { _opacity = value; this.Invalidate(); }
}
[
Bindable(true),
Category("Layout"),
DefaultValue(20),
Description("Radius of rounded borders")
]
public int Radius
{
get { return _radius; }
set { _radius = value; this.Invalidate(); }
}
[
Bindable(true),
Category("Appearance"),
DefaultValue("DOATransparentLabel"),
Description("Text in the DOATransparentLabel")
]
public String Caption
{
get { return _text; }
set { _text = value; this.Invalidate(); }
}
public override Font Font
{
get { return base.Font; }
set { base.Font = value; this.Invalidate(); }
}
public override Color ForeColor
{
get { return base.ForeColor; }
set { base.ForeColor = value; this.Invalidate(); }
}
[
Bindable(true),
Category("Appearance"),
Description("Dimmed Color"),
]
public Color DimmedColor
{
get { return _dimmedColor; }
set { _dimmedColor = value; this.Invalidate(); }
}
[
Bindable(true),
Category("Behavior"),
Description("Text movement"),
DefaultValue(MoveType.None)
]
public MoveType Moving
{
get { return _moving; }
set { _moving = value; this.Invalidate(); }
}
[
Bindable(true),
Category("Appearance"),
Description("Text alignment (Left, Right or Center), only with Moving None"),
DefaultValue(TextAlignment.Center)
]
public TextAlignment TextAlign
{
get { return _textAlign; }
set { _textAlign = value; this.Invalidate(); }
}
[
Bindable(true),
Category("Behavior"),
Description("Active the text movement"),
DefaultValue(false)
]
public bool MovingActive
{
get { return this.timer1.Enabled; }
set
{
if (value == false) _moving = MoveType.None;
this.timer1.Enabled = value;
this.Invalidate();
}
}
#endregion
#region Methods
protected override void OnPaint(PaintEventArgs e)
{
SmoothingMode sm = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
if (_borderStyle == ShapeBorderStyles.ShapeBSFixedSingle)
DrawBorder(e.Graphics);
DrawLabelBackground(e.Graphics);
DrawText(e);
e.Graphics.SmoothingMode = sm;
}
private void DrawBorder(Graphics g)
{
Rectangle rect = this.ClientRectangle;
rect.Width--;
rect.Height--;
using (GraphicsPath bp = GetPath(rect, _radius))
{
using (Pen p = new Pen(_borderColor))
{
g.DrawPath(p, bp);
}
}
}
private void DrawLabelBackground(Graphics g)
{
Rectangle rect = this.ClientRectangle;
iRect = rect;
rect.X++;
rect.Y++;
rect.Width -= 2;
rect.Height -= 2;
using (GraphicsPath bb = GetPath(rect, _radius))
{
using (Brush br = new SolidBrush(Color.FromArgb(_opacity, _backColor)))
{
g.FillPath(br, bb);
}
}
}
protected GraphicsPath GetPath(Rectangle rc, int r)
// Build the path with the round corners in the rectangle
// r is the radious of rounded corner.
{
int x = rc.X, y = rc.Y, w = rc.Width, h = rc.Height;
r = r << 1;
GraphicsPath path = new GraphicsPath();
if (r > 0)
// If the radious of rounded corner is greater than one side then
// do the side rounded
{
if (r > h) { r = h; }; //Rounded
if (r > w) { r = w; }; //Rounded
path.AddArc(x, y, r, r, 180, 90); //Upper left corner
path.AddArc(x + w - r, y, r, r, 270, 90); //Upper right corner
path.AddArc(x + w - r, y + h - r, r, r, 0, 90); //Lower right corner
path.AddArc(x, y + h - r, r, r, 90, 90); //Lower left corner
path.CloseFigure();
}
else
// If the radious of rounded corner is zero then the path is a rectangle
{
path.AddRectangle(rc);
}
return path;
}
protected void DrawText(PaintEventArgs pe)
{
//This is a workaround to get MeasureString to work properly
//pe.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
SizeF sz = pe.Graphics.MeasureString(_text, base.Font);
switch (_moving)
{
case MoveType.None:
NoMove();
break;
case MoveType.RightToLeft:
MoveRightToLeft();
break;
case MoveType.DownToUp:
MoveDownToUp();
break;
case MoveType.LeftToRight:
MoveLeftToRight();
break;
case MoveType.UpToDown:
MoveUpToDown();
break;
}
//Rectangle bounds for the text
txtRect = new Rectangle(this.pointX, this.pointY,
(int)sz.Width + 1, (int)sz.Height);
//If the mouse is passing over the text it is selected and will be dimmed
//otherwise nothing.
Brush brText = new SolidBrush(base.ForeColor);
Brush brTextDimmed = new SolidBrush(_dimmedColor);
if (_isSelected)
pe.Graphics.DrawString(_text,
base.Font,
brTextDimmed,
txtRect);
else
pe.Graphics.DrawString(_text,
base.Font,
brText,
txtRect);
}
protected void NoMove()
{
//Align text
switch (_textAlign)
{
case TextAlignment.Left:
pointX = (int)this.iRect.X;
break;
case TextAlignment.Center:
pointX = (this.iRect.Width - this.txtRect.Width) / 2;
break;
case TextAlignment.Right:
pointX = (this.iRect.Width - this.txtRect.Width);
break;
}
pointY = (this.iRect.Height - this.txtRect.Height) / 2;
}
protected void MoveRightToLeft()
{
if (pointX < -this.txtRect.Width)
{ pointX = this.iRect.X + this.iRect.Width; }
else
{ pointX -= 2; }
pointY = (this.iRect.Height - this.txtRect.Height) / 2;
}
protected void MoveDownToUp()
{
pointX = (this.iRect.Width - this.txtRect.Width) / 2;
if (pointY < -this.txtRect.Height)
{ pointY = (int)this.iRect.Y + this.iRect.Height; }
else
{ pointY -= 2; }
}
protected void MoveLeftToRight()
{
if (pointX > this.iRect.X + this.iRect.Width)
{ pointX = this.iRect.X - this.txtRect.Width; }
else
{ pointX += 2; }
pointY = (this.iRect.Height - this.txtRect.Height) / 2;
}
protected void MoveUpToDown()
{
pointX = (this.iRect.Width - this.txtRect.Width) / 2;
if (pointY > this.iRect.Y + this.iRect.Height)
{ pointY = (int)this.iRect.Y - this.iRect.Height; }
else
{ pointY += 2; }
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
_isSelected = true;
this.Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_isSelected = false;
this.Invalidate();
}
private void timer1_Tick(object sender, System.EventArgs e)
{
this.Invalidate();
this.Update();
}
}
#endregion
}
| |
// 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.
using Microsoft.Azure.Batch.Conventions.Files.Utilities;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Batch.Conventions.Files
{
/// <summary>
/// Represents persistent storage for the outputs of an Azure Batch task.
/// </summary>
/// <remarks>
/// Task outputs refer to output data logically associated with a specific task, rather than
/// the job as a whole. For example, in a movie rendering job, if a task rendered a single frame,
/// that frame would be a task output. Logs and other diagnostic information such as intermediate
/// files may also be persisted as task outputs (see <see cref="TaskOutputKind"/> for a way to
/// categorise these so that clients can distinguish between the main output and auxiliary data).
/// </remarks>
public class TaskOutputStorage
{
private readonly StoragePath _storagePath;
/// <summary>
/// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a task id and
/// a URL representing the job output container.
/// </summary>
/// <param name="jobOutputContainerUri">The URL in Azure storage of the blob container to
/// use for outputs associated with this job. This URL must contain a SAS (Shared Access
/// Signature) granting access to the container, or the container must be public.</param>
/// <param name="taskId">The id of the Azure Batch task.</param>
/// <remarks>The container must already exist; the TaskOutputStorage class does not create
/// it for you.</remarks>
public TaskOutputStorage(Uri jobOutputContainerUri, string taskId)
: this(CloudBlobContainerUtils.GetContainerReference(jobOutputContainerUri), taskId, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a storage account,
/// job id, and task id.
/// </summary>
/// <param name="storageAccount">The storage account linked to the Azure Batch account.</param>
/// <param name="jobId">The id of the Azure Batch job containing the task.</param>
/// <param name="taskId">The id of the Azure Batch task.</param>
/// <remarks>The job output container must already exist; the TaskOutputStorage class does not create
/// it for you.</remarks>
public TaskOutputStorage(CloudStorageAccount storageAccount, string jobId, string taskId)
: this(CloudBlobContainerUtils.GetContainerReference(storageAccount, jobId), taskId, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a task id and
/// a URL representing the job output container.
/// </summary>
/// <param name="jobOutputContainerUri">The URL in Azure storage of the blob container to
/// use for outputs associated with this job. This URL must contain a SAS (Shared Access
/// Signature) granting access to the container, or the container must be public.</param>
/// <param name="taskId">The id of the Azure Batch task.</param>
/// <param name="storageRetryPolicy">The retry policy for storage requests.</param>
/// <remarks>The container must already exist; the TaskOutputStorage class does not create
/// it for you.</remarks>
public TaskOutputStorage(Uri jobOutputContainerUri, string taskId, IRetryPolicy storageRetryPolicy)
: this(CloudBlobContainerUtils.GetContainerReference(jobOutputContainerUri), taskId, storageRetryPolicy)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a storage account,
/// job id, and task id.
/// </summary>
/// <param name="storageAccount">The storage account linked to the Azure Batch account.</param>
/// <param name="jobId">The id of the Azure Batch job containing the task.</param>
/// <param name="taskId">The id of the Azure Batch task.</param>
/// <param name="storageRetryPolicy">The retry policy for storage requests.</param>
/// <remarks>The job output container must already exist; the TaskOutputStorage class does not create
/// it for you.</remarks>
public TaskOutputStorage(CloudStorageAccount storageAccount, string jobId, string taskId, IRetryPolicy storageRetryPolicy)
: this(CloudBlobContainerUtils.GetContainerReference(storageAccount, jobId), taskId, storageRetryPolicy)
{
}
private TaskOutputStorage(CloudBlobContainer jobOutputContainer, string taskId, IRetryPolicy storageRetryPolicy)
{
if (jobOutputContainer == null)
{
throw new ArgumentNullException(nameof(jobOutputContainer));
}
Validate.IsNotNullOrEmpty(taskId, nameof(taskId));
if (storageRetryPolicy != null)
{
jobOutputContainer.ServiceClient.DefaultRequestOptions.RetryPolicy = storageRetryPolicy;
}
_storagePath = new StoragePath.TaskStoragePath(jobOutputContainer, taskId);
}
/// <summary>
/// Saves the specified file to persistent storage.
/// </summary>
/// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to
/// store this file, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param>
/// <param name="relativePath">The path of the file to save, relative to the current directory.
/// If the file is in a subdirectory of the current directory, the relative path will be preserved
/// in blob storage.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>If the file is outside the current directory, traversals up the directory tree are removed.
/// For example, a <paramref name="relativePath"/> of "..\ProcessEnv.cmd" would be treated as "ProcessEnv.cmd"
/// for the purposes of creating a blob name.</remarks>
/// <exception cref="ArgumentNullException">The <paramref name="kind"/> or <paramref name="relativePath"/> argument is null.</exception>
/// <exception cref="ArgumentException">The <paramref name="relativePath"/> argument is an absolute path, or is empty.</exception>
public async Task SaveAsync(
TaskOutputKind kind,
string relativePath,
CancellationToken cancellationToken = default(CancellationToken)
)
=> await SaveAsyncImpl(kind, new DirectoryInfo(Environment.CurrentDirectory), relativePath, cancellationToken);
internal async Task SaveAsyncImpl(
TaskOutputKind kind,
DirectoryInfo baseFolder,
string relativePath,
CancellationToken cancellationToken = default(CancellationToken)
)
=> await _storagePath.SaveAsync(kind, baseFolder, relativePath, cancellationToken);
/// <summary>
/// Saves the specified file to persistent storage.
/// </summary>
/// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to
/// store this file, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param>
/// <param name="sourcePath">The path of the file to save.</param>
/// <param name="destinationRelativePath">The blob name under which to save the file. This may include a
/// relative component, such as "pointclouds/pointcloud_0001.txt".</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="kind"/>, <paramref name="sourcePath"/>, or <paramref name="destinationRelativePath"/> argument is null.</exception>
/// <exception cref="ArgumentException">The <paramref name="sourcePath"/> or <paramref name="destinationRelativePath"/> argument is empty.</exception>
public async Task SaveAsync(
TaskOutputKind kind,
string sourcePath,
string destinationRelativePath,
CancellationToken cancellationToken = default(CancellationToken)
)
=> await _storagePath.SaveAsync(kind, sourcePath, destinationRelativePath, cancellationToken);
/// <summary>
/// Saves the specified text to persistent storage, without requiring you to create a local file.
/// </summary>
/// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to
/// store this data, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param>
/// <param name="text">The text to save.</param>
/// <param name="destinationRelativePath">The blob name under which to save the text. This may include a
/// relative component, such as "records/widget42.json".</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="kind"/>, <paramref name="text"/>, or <paramref name="destinationRelativePath"/> argument is null.</exception>
/// <exception cref="ArgumentException">The <paramref name="destinationRelativePath"/> argument is empty.</exception>
public async Task SaveTextAsync(
TaskOutputKind kind,
string text,
string destinationRelativePath,
CancellationToken cancellationToken = default(CancellationToken)
)
=> await _storagePath.SaveTextAsync(kind, text, destinationRelativePath, cancellationToken);
/// <summary>
/// Lists the task outputs of the specified kind.
/// </summary>
/// <param name="kind">A <see cref="TaskOutputKind"/> representing the category of outputs to
/// list, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param>
/// <returns>A list of persisted task outputs of the specified kind.</returns>
/// <remarks>The list is retrieved lazily from Azure blob storage when it is enumerated.</remarks>
public IEnumerable<OutputFileReference> ListOutputs(TaskOutputKind kind)
=> _storagePath.List(kind);
/// <summary>
/// Retrieves a task output from Azure blob storage by kind and path.
/// </summary>
/// <param name="kind">A <see cref="TaskOutputKind"/> representing the category of the output to
/// retrieve, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param>
/// <param name="filePath">The path under which the output was persisted in blob storage.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A reference to the requested file in Azure blob storage.</returns>
public async Task<OutputFileReference> GetOutputAsync(
TaskOutputKind kind,
string filePath,
CancellationToken cancellationToken = default(CancellationToken)
)
=> await _storagePath.GetOutputAsync(kind, filePath, cancellationToken);
/// <summary>
/// Saves the specified file to persistent storage as a <see cref="TaskOutputKind.TaskLog"/>,
/// and tracks subsequent appends to the file and appends them to the persistent copy too.
/// </summary>
/// <param name="relativePath">The path of the file to save, relative to the current directory.
/// If the file is in a subdirectory of the current directory, the relative path will be preserved
/// in blob storage.</param>
/// <returns>An <see cref="ITrackedSaveOperation"/> which will save a file to blob storage and will periodically flush file
/// appends to the blob until disposed. When disposed, all remaining appends are flushed to
/// blob storage, and further tracking of file appends is stopped.</returns>
/// <remarks>
/// <para>Tracking supports only appends. That is, while a file is being tracked, any data added
/// at the end is appended to the persistent storage. Changes to data that has already been uploaded
/// will not be reflected to the persistent store. This method is therefore intended for use only
/// with files such as (non-rotating) log files where data is only added at the end of the file.
/// If the entire contents of a file can change, use <see cref="SaveAsync(TaskOutputKind, string, CancellationToken)"/>
/// and call it periodically or after each change.</para>
/// <para>If the file is outside the current directory, traversals up the directory tree are removed.
/// For example, a <paramref name="relativePath"/> of "..\ProcessEnv.cmd" would be treated as "ProcessEnv.cmd"
/// for the purposes of creating a blob name.</para>
/// </remarks>
/// <exception cref="ArgumentNullException">The <paramref name="relativePath"/> argument is null.</exception>
/// <exception cref="ArgumentException">The <paramref name="relativePath"/> argument is an absolute path, or is empty.</exception>
public async Task<ITrackedSaveOperation> SaveTrackedAsync(string relativePath)
=> await _storagePath.SaveTrackedAsync(TaskOutputKind.TaskLog, relativePath, TrackedFile.DefaultFlushInterval);
/// <summary>
/// Saves the specified file to persistent storage, and tracks subsequent appends to the file
/// and appends them to the persistent copy too.
/// </summary>
/// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to
/// store this file, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param>
/// <param name="sourcePath">The path of the file to save.</param>
/// <param name="destinationRelativePath">The blob name under which to save the file. This may include a
/// relative component, such as "pointclouds/pointcloud_0001.txt".</param>
/// <param name="flushInterval">The interval at which to flush appends to persistent storage.</param>
/// <returns>An <see cref="ITrackedSaveOperation"/> which will save a file to blob storage and will periodically flush file
/// appends to the blob until disposed. When disposed, all remaining appends are flushed to
/// blob storage, and further tracking of file appends is stopped.</returns>
/// <remarks>
/// <para>Tracking supports only appends. That is, while a file is being tracked, any data added
/// at the end is appended to the persistent storage. Changes to data that has already been uploaded
/// will not be reflected to the persistent store. This method is therefore intended for use only
/// with files such as (non-rotating) log files where data is only added at the end of the file.
/// If the entire contents of a file can change, use <see cref="SaveAsync(TaskOutputKind, string, string, CancellationToken)"/>
/// and call it periodically or after each change.</para>
/// </remarks>
/// <exception cref="ArgumentNullException">The <paramref name="kind"/>, <paramref name="sourcePath"/>, or <paramref name="destinationRelativePath"/> argument is null.</exception>
/// <exception cref="ArgumentException">The <paramref name="sourcePath"/> or <paramref name="destinationRelativePath"/> argument is empty.</exception>
public async Task<ITrackedSaveOperation> SaveTrackedAsync(
TaskOutputKind kind,
string sourcePath,
string destinationRelativePath,
TimeSpan flushInterval
)
=> await _storagePath.SaveTrackedAsync(kind, sourcePath, destinationRelativePath, flushInterval);
}
}
| |
//
// Copyright 2013 Google
//
// 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 Google.OrTools.ConstraintSolver;
using Google.OrTools.Graph;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System;
public class SpeakerScheduling
{
public class FlowAssign : NetDecisionBuilder
{
public FlowAssign(IntVar[] vars, int first_slot, IntVar last_slot_var)
{
vars_ = vars;
first_slot_ = first_slot;
last_slot_var_ = last_slot_var;
}
public override Decision Next(Solver solver)
{
int large = 100000;
int number_of_variables = vars_.Length;
long last_slot = last_slot_var_.Max();
// Lets build a bipartite graph with equal number of nodes left and right.
// Variables will be on the left, slots on the right.
// We will add dummy variables when needed.
// Arcs will have a cost x is slot x is possible for a variable, a large
// number otherwise. For dummy variables, the cost will be 0 always.
LinearSumAssignment matching = new LinearSumAssignment();
for (int speaker = 0; speaker < number_of_variables; ++speaker)
{
IntVar var = vars_[speaker];
for (int value = first_slot_; value <= last_slot; ++value)
{
if (var.Contains(value))
{
matching.AddArcWithCost(speaker, value - first_slot_, value);
}
else
{
matching.AddArcWithCost(speaker, value - first_slot_, large);
}
}
}
// The Matching algorithms expect the same number of left and right nodes.
// So we fill the rest with dense zero-cost arcs.
for (int dummy = number_of_variables;
dummy <= last_slot - first_slot_; ++dummy) {
for (int value = first_slot_; value <= last_slot; ++value)
{
matching.AddArcWithCost(dummy, value - first_slot_, 0);
}
}
if (matching.Solve() == LinearSumAssignment.OPTIMAL &&
matching.OptimalCost() < large) // No violated arcs.
{
for (int speaker = 0; speaker < number_of_variables; ++speaker)
{
vars_[speaker].SetValue(matching.RightMate(speaker) + first_slot_);
}
} else {
solver.Fail();
}
return null;
}
private IntVar[] vars_;
private int first_slot_;
private IntVar last_slot_var_;
}
private static void Solve(int first_slot)
{
Console.WriteLine("----------------------------------------------------");
Solver solver = new Solver("SpeakerScheduling");
// the slots each speaker is available
int[][] speaker_availability = {
new int[] {1,3,4,6,7,10,12,13,14,15,16,18,19,20,21,22,23,24,25,33,34,35,36,37,38,39,40,41,43,44,45,46,47,48,49,50,51,52,54,55,56,57,58,59},
new int[] {1,2,7,8,10,11,16,17,18,21,22,23,24,25,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,52,53,54,55,56,57,58,59,60},
new int[] {5,6,7,10,12,14,16,17,21,22,23,24,33,35,37,38,39,40,41,42,43,44,45,46,51,53,55,56,57,58,59},
new int[] {1,2,3,4,5,6,7,11,13,14,15,16,20,24,25,33,34,35,37,38,39,40,41,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,59,60},
new int[] {4,7,8,9,16,17,19,20,21,22,23,24,25,33,34,35,36,37,38,39,40,41,42,43,49,50,51,53,55,56,57,58,59,60},
new int[] {4,7,9,11,12,13,14,15,16,17,18,22,23,24,33,34,35,36,38,39,42,44,46,48,49,51,53,54,55,56,57},
new int[] {1,2,3,4,5,6,7,33,34,35,36,37,38,39,40,41,42,54,55,56,57,58,59,60},
new int[] {1,3,11,14,15,16,17,21,22,23,24,25,33,35,36,37,39,40,41,42,43,44,45,47,48,49,51,52,53,54,55,56,57,58,59,60},
new int[] {1,2,3,4,5,7,8,9,10,11,13,18,19,20,21,22,23,24,25,33,34,35,36,37,38,39,40,41,42,43,44,45,46,50,51,52,53,54,55,56,57,59,60},
new int[] {24,33,34,35,36,37,38,39,40,41,42,43,45,49,50,51,52,53,54,55,56,57,58,59,60},
new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,22,23,24,25,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,50,51,52,53,55,56,57,58,59,60},
new int[] {3,4,5,6,13,15,16,17,18,19,21,22,24,25,33,34,35,36,37,39,40,41,42,43,44,45,47,52,53,55,57,58,59,60},
new int[] {4,5,6,8,11,12,13,14,17,19,20,22,23,24,25,33,34,35,36,37,39,40,41,42,43,47,48,49,50,51,52,55,56,57},
new int[] {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60},
new int[] {12,25,33,35,36,37,39,41,42,43,48,51,52,53,54,57,59,60},
new int[] {4,8,16,17,19,23,25,33,34,35,37,41,44,45,47,48,49,50},
new int[] {3,23,24,25,33,35,36,37,38,39,40,42,43,44,49,50,53,54,55,56,57,58,60},
new int[] {7,13,19,20,22,23,24,25,33,34,35,38,40,41,42,44,45,46,47,48,49,52,53,54,58,59,60}
};
// how long each talk lasts for each speaker
int[] durations = { 1, 2, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int sum_of_durations = durations.Sum();
int number_of_speakers = durations.Length;
// calculate the total number of slots (maximum in the availability array)
// (and add the max durations)
int last_slot = (from s in Enumerable.Range(0, number_of_speakers)
select speaker_availability[s].Max()).Max();
Console.WriteLine(
"Scheduling {0} speakers, for a total of {1} slots, during [{2}..{3}]",
number_of_speakers, sum_of_durations, first_slot, last_slot);
// Start variable for all talks.
IntVar[] starts = new IntVar[number_of_speakers];
// We store the possible starts for all talks filtered from the
// duration and the speaker availability.
int[][] possible_starts = new int[number_of_speakers][];
for (int speaker = 0; speaker < number_of_speakers; ++speaker)
{
int duration = durations[speaker];
// Let's filter the possible starts.
List<int> filtered_starts = new List<int>();
int availability = speaker_availability[speaker].Length;
for (int index = 0; index < availability; ++index)
{
bool ok = true;
int slot = speaker_availability[speaker][index];
if (slot < first_slot)
{
continue;
}
for (int offset = 1; offset < durations[speaker]; ++offset)
{
if (index + offset >= availability ||
speaker_availability[speaker][index + offset] != slot + offset)
{
// discontinuity.
ok = false;
break;
}
}
if (ok)
{
filtered_starts.Add(slot);
}
possible_starts[speaker] = filtered_starts.ToArray();
}
starts[speaker] =
solver.MakeIntVar(possible_starts[speaker], "start[" + speaker + "]");
}
List<IntVar>[] contributions_per_slot =
new List<IntVar>[last_slot + 1];
for (int slot = first_slot; slot <= last_slot; ++slot)
{
contributions_per_slot[slot] = new List<IntVar>();
}
for (int speaker = 0; speaker < number_of_speakers; ++speaker)
{
int duration = durations[speaker];
IntVar start_var = starts[speaker];
foreach (int start in possible_starts[speaker])
{
for (int offset = 0; offset < duration; ++offset)
{
contributions_per_slot[start + offset].Add(start_var.IsEqual(start));
}
}
}
// Force the schedule to be consistent.
for (int slot = first_slot; slot <= last_slot; ++slot)
{
solver.Add(
solver.MakeSumLessOrEqual(contributions_per_slot[slot].ToArray(), 1));
}
// Add minimum start info.
for (int speaker = 0; speaker < number_of_speakers; ++speaker)
{
solver.Add(starts[speaker] >= first_slot);
}
// Creates makespan.
IntVar[] end_times = new IntVar[number_of_speakers];
for (int speaker = 0; speaker < number_of_speakers; speaker++)
{
end_times[speaker] = (starts[speaker] + (durations[speaker] - 1)).Var();
}
IntVar last_slot_var = end_times.Max().VarWithName("last_slot");
// Add trivial bound to objective.
last_slot_var.SetMin(first_slot + sum_of_durations - 1);
// Redundant scheduling constraint.
IntervalVar[] intervals =
solver.MakeFixedDurationIntervalVarArray(starts, durations, "intervals");
DisjunctiveConstraint disjunctive =
solver.MakeDisjunctiveConstraint(intervals, "disjunctive");
solver.Add(disjunctive);
//
// Search
//
List<IntVar> short_talks = new List<IntVar>();
List<IntVar> long_talks = new List<IntVar>();
for (int speaker = 0; speaker < number_of_speakers; ++speaker)
{
if (durations[speaker] == 1)
{
short_talks.Add(starts[speaker]);
}
else
{
long_talks.Add(starts[speaker]);
}
}
OptimizeVar objective_monitor = solver.MakeMinimize(last_slot_var, 1);
DecisionBuilder long_phase =
solver.MakePhase(long_talks.ToArray(),
Solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
Solver.ASSIGN_MIN_VALUE);
DecisionBuilder short_phase =
new FlowAssign(short_talks.ToArray(), first_slot, last_slot_var);
DecisionBuilder obj_phase =
solver.MakePhase(last_slot_var,
Solver.CHOOSE_FIRST_UNBOUND,
Solver.ASSIGN_MIN_VALUE);
DecisionBuilder main_phase =
solver.Compose(long_phase, short_phase, obj_phase);
solver.NewSearch(main_phase, objective_monitor);
while (solver.NextSolution())
{
Console.WriteLine("\nLast used slot: " + (last_slot_var.Value()));
Console.WriteLine("Speakers (start..end):");
for (int s = 0; s < number_of_speakers; s++)
{
long sstart = starts[s].Value();
Console.WriteLine(" - speaker {0,2}: {1,2}..{2,2}", (s + 1),
sstart, (sstart + durations[s] - 1));
}
}
Console.WriteLine("\nSolutions: {0}", solver.Solutions());
Console.WriteLine("WallTime: {0}ms", solver.WallTime());
Console.WriteLine("Failures: {0}", solver.Failures());
Console.WriteLine("Branches: {0} ", solver.Branches());
solver.EndSearch();
}
public static void Main(String[] args)
{
int start = 1;
if (args.Length == 1)
{
start = int.Parse(args[0]);
}
Stopwatch s = new Stopwatch();
s.Start();
for (int i = start; i < 40; i++)
{
Solve(i);
}
s.Stop();
Console.WriteLine("Finished in " + s.ElapsedMilliseconds + " ms");
}
}
| |
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Runtime.InteropServices;
namespace PixelFarm.VectorMath
{
public class JsonIgnoreAttribute : Attribute
{
}
/// <summary>
/// Represents a 3D vector using three double-precision floating-point numbers.
/// </summary>
//[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3 : IEquatable<Vector3>
{
/// <summary>
/// The X component of the Vector3.
/// </summary>
public double x;
/// <summary>
/// The Y component of the Vector3.
/// </summary>
public double y;
/// <summary>
/// The Z component of the Vector3.
/// </summary>
public double z;
/// <summary>
/// Constructs a new Vector3.
/// </summary>
/// <param name="x">The x component of the Vector3.</param>
/// <param name="y">The y component of the Vector3.</param>
/// <param name="z">The z component of the Vector3.</param>
public Vector3(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
/// <summary>
/// Constructs a new instance from the given Vector2d.
/// </summary>
/// <param name="v">The Vector2d to copy components from.</param>
public Vector3(Vector2 v, double z = 0)
{
x = v.x;
y = v.y;
this.z = z;
}
/// <summary>
/// Constructs a new instance from the given Vector3d.
/// </summary>
/// <param name="v">The Vector3d to copy components from.</param>
public Vector3(Vector3 v)
{
x = v.x;
y = v.y;
z = v.z;
}
public Vector3(Vector3Float v)
{
x = v.x;
y = v.y;
z = v.z;
}
public Vector3(double[] doubleArray)
{
x = doubleArray[0];
y = doubleArray[1];
z = doubleArray[2];
}
/// <summary>
/// Constructs a new instance from the given Vector4d.
/// </summary>
/// <param name="v">The Vector4d to copy components from.</param>
public Vector3(Vector4 v)
{
x = v.x;
y = v.y;
z = v.z;
}
public double this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
return 0;
}
}
set
{
switch (index)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
default:
throw new Exception();
}
}
}
/// <summary>
/// Gets the length (magnitude) of the vector.
/// </summary>
/// <see cref="LengthFast"/>
/// <seealso cref="LengthSquared"/>
[JsonIgnoreAttribute]
public double Length
{
get
{
return System.Math.Sqrt(x * x + y * y + z * z);
}
}
/// <summary>
/// Gets the square of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property avoids the costly square root operation required by the Length property. This makes it more suitable
/// for comparisons.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthFast"/>
[JsonIgnoreAttribute]
public double LengthSquared
{
get
{
return x * x + y * y + z * z;
}
}
/// <summary>
/// Returns a normalized Vector of this.
/// </summary>
/// <returns></returns>
public Vector3 GetNormal()
{
Vector3 temp = this;
temp.Normalize();
return temp;
}
/// <summary>
/// Scales the Vector3d to unit length.
/// </summary>
public void Normalize()
{
double scale = 1.0 / this.Length;
x *= scale;
y *= scale;
z *= scale;
}
public double[] ToArray()
{
return new double[] { x, y, z };
}
/// <summary>
/// Defines a unit-length Vector3d that points towards the X-axis.
/// </summary>
public static readonly Vector3 UnitX = new Vector3(1, 0, 0);
/// <summary>
/// Defines a unit-length Vector3d that points towards the Y-axis.
/// </summary>
public static readonly Vector3 UnitY = new Vector3(0, 1, 0);
/// <summary>
/// /// Defines a unit-length Vector3d that points towards the Z-axis.
/// </summary>
public static readonly Vector3 UnitZ = new Vector3(0, 0, 1);
/// <summary>
/// Defines a zero-length Vector3.
/// </summary>
public static readonly Vector3 Zero = new Vector3(0, 0, 0);
/// <summary>
/// Defines an instance with all components set to 1.
/// </summary>
public static readonly Vector3 One = new Vector3(1, 1, 1);
/// <summary>
/// Defines an instance with all components set to positive infinity.
/// </summary>
public static readonly Vector3 PositiveInfinity = new Vector3(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity);
/// <summary>
/// Defines an instance with all components set to negative infinity.
/// </summary>
public static readonly Vector3 NegativeInfinity = new Vector3(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity);
/// <summary>
/// Defines the size of the Vector3d struct in bytes.
/// </summary>
public static readonly int SizeInBytes = Marshal.SizeOf(new Vector3());
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <returns>Result of operation.</returns>
public static Vector3 Add(Vector3 a, Vector3 b)
{
Add(ref a, ref b, out a);
return a;
}
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <param name="result">Result of operation.</param>
public static void Add(ref Vector3 a, ref Vector3 b, out Vector3 result)
{
result = new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
public static Vector3 Subtract(Vector3 a, Vector3 b)
{
Subtract(ref a, ref b, out a);
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
public static void Subtract(ref Vector3 a, ref Vector3 b, out Vector3 result)
{
result = new Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3 Multiply(Vector3 vector, double scale)
{
Multiply(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector3 vector, double scale, out Vector3 result)
{
result = new Vector3(vector.x * scale, vector.y * scale, vector.z * scale);
}
/// <summary>
/// Multiplies a vector by the components a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3 Multiply(Vector3 vector, Vector3 scale)
{
Multiply(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector3 vector, ref Vector3 scale, out Vector3 result)
{
result = new Vector3(vector.x * scale.x, vector.y * scale.y, vector.z * scale.z);
}
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3 Divide(Vector3 vector, double scale)
{
Divide(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector3 vector, double scale, out Vector3 result)
{
Multiply(ref vector, 1 / scale, out result);
}
/// <summary>
/// Divides a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3 Divide(Vector3 vector, Vector3 scale)
{
Divide(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Divide a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector3 vector, ref Vector3 scale, out Vector3 result)
{
result = new Vector3(vector.x / scale.x, vector.y / scale.y, vector.z / scale.z);
}
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise minimum</returns>
public static Vector3 ComponentMin(Vector3 a, Vector3 b)
{
a.x = a.x < b.x ? a.x : b.x;
a.y = a.y < b.y ? a.y : b.y;
a.z = a.z < b.z ? a.z : b.z;
return a;
}
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise minimum</param>
public static void ComponentMin(ref Vector3 a, ref Vector3 b, out Vector3 result)
{
result.x = a.x < b.x ? a.x : b.x;
result.y = a.y < b.y ? a.y : b.y;
result.z = a.z < b.z ? a.z : b.z;
}
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise maximum</returns>
public static Vector3 ComponentMax(Vector3 a, Vector3 b)
{
a.x = a.x > b.x ? a.x : b.x;
a.y = a.y > b.y ? a.y : b.y;
a.z = a.z > b.z ? a.z : b.z;
return a;
}
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise maximum</param>
public static void ComponentMax(ref Vector3 a, ref Vector3 b, out Vector3 result)
{
result.x = a.x > b.x ? a.x : b.x;
result.y = a.y > b.y ? a.y : b.y;
result.z = a.z > b.z ? a.z : b.z;
}
/// <summary>
/// Returns the Vector3d with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3</returns>
public static Vector3 Min(Vector3 left, Vector3 right)
{
return left.LengthSquared < right.LengthSquared ? left : right;
}
/// <summary>
/// Returns the Vector3d with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3</returns>
public static Vector3 Max(Vector3 left, Vector3 right)
{
return left.LengthSquared >= right.LengthSquared ? left : right;
}
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <returns>The clamped vector</returns>
public static Vector3 Clamp(Vector3 vec, Vector3 min, Vector3 max)
{
vec.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x;
vec.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y;
vec.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z;
return vec;
}
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <param name="result">The clamped vector</param>
public static void Clamp(ref Vector3 vec, ref Vector3 min, ref Vector3 max, out Vector3 result)
{
result.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x;
result.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y;
result.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z;
}
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector3 Normalize(Vector3 vec)
{
double scale = 1.0 / vec.Length;
vec.x *= scale;
vec.y *= scale;
vec.z *= scale;
return vec;
}
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void Normalize(ref Vector3 vec, out Vector3 result)
{
double scale = 1.0 / vec.Length;
result.x = vec.x * scale;
result.y = vec.y * scale;
result.z = vec.z * scale;
}
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The dot product of the two inputs</returns>
public static double Dot(Vector3 left, Vector3 right)
{
return left.x * right.x + left.y * right.y + left.z * right.z;
}
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <param name="result">The dot product of the two inputs</param>
public static void Dot(ref Vector3 left, ref Vector3 right, out double result)
{
result = left.x * right.x + left.y * right.y + left.z * right.z;
}
/// <summary>
/// Caclulate the cross (vector) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The cross product of the two inputs</returns>
public static Vector3 Cross(Vector3 left, Vector3 right)
{
Vector3 result;
Cross(ref left, ref right, out result);
return result;
}
/// <summary>
/// Caclulate the cross (vector) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The cross product of the two inputs</returns>
/// <param name="result">The cross product of the two inputs</param>
public static void Cross(ref Vector3 left, ref Vector3 right, out Vector3 result)
{
result = new Vector3(left.y * right.z - left.z * right.y,
left.z * right.x - left.x * right.z,
left.x * right.y - left.y * right.x);
}
/// <summary>
/// Checks if 3 points are collinear (all lie on the same line).
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="epsilon"></param>
/// <returns></returns>
public static bool Collinear(Vector3 a, Vector3 b, Vector3 c, double epsilon = .000001)
{
// Return true if a, b, and c all lie on the same line.
return Math.Abs(Cross(b - a, c - a).Length) < epsilon;
}
public static Vector3 GetPerpendicular(Vector3 a, Vector3 b)
{
if (!Collinear(a, b, Zero))
{
return Vector3.Cross(a, b);
}
else
{
Vector3 zOne = new Vector3(0, 0, 100000);
if (!Collinear(a, b, zOne))
{
return Vector3.Cross(a - zOne, b - zOne);
}
else
{
Vector3 xOne = new Vector3(1000000, 0, 0);
return Vector3.Cross(a - xOne, b - xOne);
}
}
}
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns>
public static Vector3 Lerp(Vector3 a, Vector3 b, double blend)
{
a.x = blend * (b.x - a.x) + a.x;
a.y = blend * (b.y - a.y) + a.y;
a.z = blend * (b.z - a.z) + a.z;
return a;
}
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param>
public static void Lerp(ref Vector3 a, ref Vector3 b, double blend, out Vector3 result)
{
result.x = blend * (b.x - a.x) + a.x;
result.y = blend * (b.y - a.y) + a.y;
result.z = blend * (b.z - a.z) + a.z;
}
/// <summary>
/// Interpolate 3 Vectors using Barycentric coordinates
/// </summary>
/// <param name="a">First input Vector</param>
/// <param name="b">Second input Vector</param>
/// <param name="c">Third input Vector</param>
/// <param name="u">First Barycentric Coordinate</param>
/// <param name="v">Second Barycentric Coordinate</param>
/// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns>
public static Vector3 BaryCentric(Vector3 a, Vector3 b, Vector3 c, double u, double v)
{
return a + u * (b - a) + v * (c - a);
}
/// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary>
/// <param name="a">First input Vector.</param>
/// <param name="b">Second input Vector.</param>
/// <param name="c">Third input Vector.</param>
/// <param name="u">First Barycentric Coordinate.</param>
/// <param name="v">Second Barycentric Coordinate.</param>
/// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param>
public static void BaryCentric(ref Vector3 a, ref Vector3 b, ref Vector3 c, double u, double v, out Vector3 result)
{
result = a; // copy
Vector3 temp = b; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, u, out temp);
Add(ref result, ref temp, out result);
temp = c; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, v, out temp);
Add(ref result, ref temp, out result);
}
/// <summary>Transform a direction vector by the given Matrix
/// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored.
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3 TransformVector(Vector3 vec, Matrix4X4 mat)
{
return new Vector3(
Vector3.Dot(vec, new Vector3(mat.Column0)),
Vector3.Dot(vec, new Vector3(mat.Column1)),
Vector3.Dot(vec, new Vector3(mat.Column2)));
}
/// <summary>Transform a direction vector by the given Matrix
/// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored.
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void TransformVector(ref Vector3 vec, ref Matrix4X4 mat, out Vector3 result)
{
result.x = vec.x * mat.Row0.x +
vec.y * mat.Row1.x +
vec.z * mat.Row2.x;
result.y = vec.x * mat.Row0.y +
vec.y * mat.Row1.y +
vec.z * mat.Row2.y;
result.z = vec.x * mat.Row0.z +
vec.y * mat.Row1.z +
vec.z * mat.Row2.z;
}
/// <summary>Transform a Normal by the given Matrix</summary>
/// <remarks>
/// This calculates the inverse of the given matrix, use TransformNormalInverse if you
/// already have the inverse to avoid this extra calculation
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed normal</returns>
public static Vector3 TransformNormal(Vector3 norm, Matrix4X4 mat)
{
mat.Invert();
return TransformNormalInverse(norm, mat);
}
/// <summary>Transform a Normal by the given Matrix</summary>
/// <remarks>
/// This calculates the inverse of the given matrix, use TransformNormalInverse if you
/// already have the inverse to avoid this extra calculation
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed normal</param>
public static void TransformNormal(ref Vector3 norm, ref Matrix4X4 mat, out Vector3 result)
{
Matrix4X4 Inverse = Matrix4X4.Invert(mat);
Vector3.TransformNormalInverse(ref norm, ref Inverse, out result);
}
/// <summary>Transform a Normal by the (transpose of the) given Matrix</summary>
/// <remarks>
/// This version doesn't calculate the inverse matrix.
/// Use this version if you already have the inverse of the desired transform to hand
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="invMat">The inverse of the desired transformation</param>
/// <returns>The transformed normal</returns>
public static Vector3 TransformNormalInverse(Vector3 norm, Matrix4X4 invMat)
{
return new Vector3(
Vector3.Dot(norm, new Vector3(invMat.Row0)),
Vector3.Dot(norm, new Vector3(invMat.Row1)),
Vector3.Dot(norm, new Vector3(invMat.Row2)));
}
/// <summary>Transform a Normal by the (transpose of the) given Matrix</summary>
/// <remarks>
/// This version doesn't calculate the inverse matrix.
/// Use this version if you already have the inverse of the desired transform to hand
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="invMat">The inverse of the desired transformation</param>
/// <param name="result">The transformed normal</param>
public static void TransformNormalInverse(ref Vector3 norm, ref Matrix4X4 invMat, out Vector3 result)
{
result.x = norm.x * invMat.Row0.x +
norm.y * invMat.Row0.y +
norm.z * invMat.Row0.z;
result.y = norm.x * invMat.Row1.x +
norm.y * invMat.Row1.y +
norm.z * invMat.Row1.z;
result.z = norm.x * invMat.Row2.x +
norm.y * invMat.Row2.y +
norm.z * invMat.Row2.z;
}
/// <summary>Transform a Position by the given Matrix</summary>
/// <param name="pos">The position to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed position</returns>
public static Vector3 TransformPosition(Vector3 pos, Matrix4X4 mat)
{
return new Vector3(
Vector3.Dot(pos, new Vector3(mat.Column0)) + mat.Row3.x,
Vector3.Dot(pos, new Vector3(mat.Column1)) + mat.Row3.y,
Vector3.Dot(pos, new Vector3(mat.Column2)) + mat.Row3.z);
}
/// <summary>Transform a Position by the given Matrix</summary>
/// <param name="pos">The position to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed position</param>
public static void TransformPosition(ref Vector3 pos, ref Matrix4X4 mat, out Vector3 result)
{
result.x = pos.x * mat.Row0.x +
pos.y * mat.Row1.x +
pos.z * mat.Row2.x +
mat.Row3.x;
result.y = pos.x * mat.Row0.y +
pos.y * mat.Row1.y +
pos.z * mat.Row2.y +
mat.Row3.y;
result.z = pos.x * mat.Row0.z +
pos.y * mat.Row1.z +
pos.z * mat.Row2.z +
mat.Row3.z;
}
/// <summary>
/// Transform all the vectors in the array by the given Matrix.
/// </summary>
/// <param name="boundsVerts"></param>
/// <param name="rotationQuaternion"></param>
public static void Transform(Vector3[] vecArray, Matrix4X4 mat)
{
for (int i = 0; i < vecArray.Length; i++)
{
vecArray[i] = Transform(vecArray[i], mat);
}
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3 Transform(Vector3 vec, Matrix4X4 mat)
{
Vector3 result;
Transform(ref vec, ref mat, out result);
return result;
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void Transform(ref Vector3 vec, ref Matrix4X4 mat, out Vector3 result)
{
Vector4 v4 = new Vector4(vec.x, vec.y, vec.z, 1.0);
Vector4.Transform(ref v4, ref mat, out v4);
result = v4.Xyz;
}
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <returns>The result of the operation.</returns>
public static Vector3 Transform(Vector3 vec, Quaternion quat)
{
Vector3 result;
Transform(ref vec, ref quat, out result);
return result;
}
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <param name="result">The result of the operation.</param>
public static void Transform(ref Vector3 vec, ref Quaternion quat, out Vector3 result)
{
// Since vec.W == 0, we can optimize quat * vec * quat^-1 as follows:
// vec + 2.0 * cross(quat.xyz, cross(quat.xyz, vec) + quat.w * vec)
Vector3 xyz = quat.Xyz, temp, temp2;
Vector3.Cross(ref xyz, ref vec, out temp);
Vector3.Multiply(ref vec, quat.W, out temp2);
Vector3.Add(ref temp, ref temp2, out temp);
Vector3.Cross(ref xyz, ref temp, out temp);
Vector3.Multiply(ref temp, 2, out temp);
Vector3.Add(ref vec, ref temp, out result);
}
/// <summary>
/// Transform all the vectors in the array by the quaternion rotation.
/// </summary>
/// <param name="boundsVerts"></param>
/// <param name="rotationQuaternion"></param>
public static void Transform(Vector3[] vecArray, Quaternion rotationQuaternion)
{
for (int i = 0; i < vecArray.Length; i++)
{
vecArray[i] = Transform(vecArray[i], rotationQuaternion);
}
}
/// <summary>
/// Transform a Vector3d by the given Matrix, and project the resulting Vector4 back to a Vector3
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3 TransformPerspective(Vector3 vec, Matrix4X4 mat)
{
Vector3 result;
TransformPerspective(ref vec, ref mat, out result);
return result;
}
/// <summary>Transform a Vector3d by the given Matrix, and project the resulting Vector4d back to a Vector3d</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void TransformPerspective(ref Vector3 vec, ref Matrix4X4 mat, out Vector3 result)
{
Vector4 v = new Vector4(vec);
Vector4.Transform(ref v, ref mat, out v);
result.x = v.x / v.w;
result.y = v.y / v.w;
result.z = v.z / v.w;
}
/// <summary>
/// Calculates the angle (in radians) between two vectors.
/// </summary>
/// <param name="first">The first vector.</param>
/// <param name="second">The second vector.</param>
/// <returns>Angle (in radians) between the vectors.</returns>
/// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks>
public static double CalculateAngle(Vector3 first, Vector3 second)
{
return System.Math.Acos((Vector3.Dot(first, second)) / (first.Length * second.Length));
}
/// <summary>Calculates the angle (in radians) between two vectors.</summary>
/// <param name="first">The first vector.</param>
/// <param name="second">The second vector.</param>
/// <param name="result">Angle (in radians) between the vectors.</param>
/// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks>
public static void CalculateAngle(ref Vector3 first, ref Vector3 second, out double result)
{
double temp;
Vector3.Dot(ref first, ref second, out temp);
result = System.Math.Acos(temp / (first.Length * second.Length));
}
/// <summary>
/// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance.
/// </summary>
[JsonIgnoreAttribute]
public Vector2 Xy { get { return new Vector2(x, y); } set { x = value.x; y = value.y; } }
/// <summary>
/// Adds two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3 operator +(Vector3 left, Vector3 right)
{
left.x += right.x;
left.y += right.y;
left.z += right.z;
return left;
}
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3 operator -(Vector3 left, Vector3 right)
{
left.x -= right.x;
left.y -= right.y;
left.z -= right.z;
return left;
}
/// <summary>
/// Negates an instance.
/// </summary>
/// <param name="vec">The instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3 operator -(Vector3 vec)
{
vec.x = -vec.x;
vec.y = -vec.y;
vec.z = -vec.z;
return vec;
}
/// <summary>
/// Component wise multiply two vectors together, x*x, y*y, z*z.
/// </summary>
/// <param name="vecA"></param>
/// <param name="vecB"></param>
/// <returns></returns>
public static Vector3 operator *(Vector3 vecA, Vector3 vecB)
{
vecA.x *= vecB.x;
vecA.y *= vecB.y;
vecA.z *= vecB.z;
return vecA;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="vec">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3 operator *(Vector3 vec, double scale)
{
vec.x *= scale;
vec.y *= scale;
vec.z *= scale;
return vec;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="scale">The scalar.</param>
/// <param name="vec">The instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3 operator *(double scale, Vector3 vec)
{
vec.x *= scale;
vec.y *= scale;
vec.z *= scale;
return vec;
}
/// <summary>
/// Creates a new vector which is the numerator devided by each component of the vector.
/// </summary>
/// <param name="numerator"></param>
/// <param name="vec"></param>
/// <returns>The result of the calculation.</returns>
public static Vector3 operator /(double numerator, Vector3 vec)
{
return new Vector3((numerator / vec.x), (numerator / vec.y), (numerator / vec.z));
}
/// <summary>
/// Divides an instance by a scalar.
/// </summary>
/// <param name="vec">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3 operator /(Vector3 vec, double scale)
{
double mult = 1 / scale;
vec.x *= mult;
vec.y *= mult;
vec.z *= mult;
return vec;
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Vector3 left, Vector3 right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equa lright; false otherwise.</returns>
public static bool operator !=(Vector3 left, Vector3 right)
{
return !left.Equals(right);
}
/// <summary>
/// Returns a System.String that represents the current Vector3.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("[{0}, {1}, {2}]", x, y, z);
}
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return new { x, y, z }.GetHashCode();
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Vector3))
return false;
return this.Equals((Vector3)obj);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal within an error range.
/// </summary>
/// <param name="OtherVector"></param>
/// <param name="ErrorValue"></param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public bool Equals(Vector3 OtherVector, double ErrorValue)
{
if ((x < OtherVector.x + ErrorValue && x > OtherVector.x - ErrorValue) &&
(y < OtherVector.y + ErrorValue && y > OtherVector.y - ErrorValue) &&
(z < OtherVector.z + ErrorValue && z > OtherVector.z - ErrorValue))
{
return true;
}
return false;
}
/// <summary>Indicates whether the current vector is equal to another vector.</summary>
/// <param name="other">A vector to compare with this vector.</param>
/// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns>
public bool Equals(Vector3 other)
{
return
x == other.x &&
y == other.y &&
z == other.z;
}
public static double ComponentMax(Vector3 vector3)
{
return Math.Max(vector3.x, Math.Max(vector3.y, vector3.z));
}
public static double ComponentMin(Vector3 vector3)
{
return Math.Min(vector3.x, Math.Min(vector3.y, vector3.z));
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET
// Copyright (C) Rick Brewster, Chris Crosetto, Dennis Dietrich, Tom Jackson,
// Michael Kelsey, Brandon Ortiz, Craig Taylor, Chris Trevino,
// and Luke Walker
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved.
// See src/setup/License.rtf for complete licensing and attribution information.
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Copied for Paint.NET PCX Plugin
// Copyright (C) Joshua Bell
/////////////////////////////////////////////////////////////////////////////////
// Based on: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/colorquant.asp
//Bizhawk says: adapted from https://github.com/inexorabletash/PcxFileType/blob/master/Quantize
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
namespace BizHawk.Client.EmuHawk
{
/// <summary>
/// Quantize using an Octree
/// </summary>
unsafe class OctreeQuantizer : Quantizer
{
/// <summary>
/// Stores the tree
/// </summary>
private Octree _octree;
/// <summary>
/// Maximum allowed color depth
/// </summary>
private int _maxColors;
/// <summary>
/// Construct the octree quantizer
/// </summary>
/// <remarks>
/// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
/// the second pass quantizes a color based on the nodes in the tree
/// </remarks>
/// <param name="maxColors">The maximum number of colors to return</param>
/// <param name="maxColorBits">The number of significant bits</param>
public OctreeQuantizer(int maxColors, int maxColorBits)
: base(false)
{
if (maxColors > 255)
throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256");
if ((maxColorBits < 1) |(maxColorBits > 8))
throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8");
_octree = new Octree(maxColorBits);
_maxColors = maxColors;
}
/// <summary>
/// Process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected override void InitialQuantizePixel(int pixel)
{
_octree.AddColor(pixel);
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <returns>The quantized value</returns>
protected override byte QuantizePixel(int pixel)
{
byte paletteIndex = (byte)_maxColors; // The color at [_maxColors] is set to transparent
// Get the palette index if this non-transparent
int a = (pixel>>24)&0xFF;
#if HANDLE_TRANSPARENCY
if (a > 0)
#endif
{
paletteIndex = (byte)_octree.GetPaletteIndex(pixel);
}
return paletteIndex;
}
/// <summary>
/// Retrieve the palette for the quantized image
/// </summary>
/// <param name="original">Any old palette, this is overrwritten</param>
/// <returns>The new color palette</returns>
protected override ColorPalette GetPalette(ColorPalette original)
{
// First off convert the octree to _maxColors colors
List<Color> palette = _octree.Palletize(_maxColors - 1);
// Then convert the palette based on those colors
for (int index = 0; index < palette.Count; index++)
{
original.Entries[index] = palette[index];
}
#if ORIGINAL_CODE
for (int i = palette.Count; i < original.Entries.Length; ++i)
{
original.Entries[i] = Color.FromArgb(255, 0, 0, 0);
}
// Add the transparent color
original.Entries[_maxColors] = Color.FromArgb(0, 0, 0, 0);
#else // PCX Plugin
// For PCX: Pad with transparency
for (int i = palette.Count; i < original.Entries.Length; ++i)
original.Entries[i] = Color.Transparent;
#endif
return original;
}
/// <summary>
/// Class which does the actual quantization
/// </summary>
private class Octree
{
/// <summary>
/// Construct the octree
/// </summary>
/// <param name="maxColorBits">The maximum number of significant bits in the image</param>
public Octree(int maxColorBits)
{
_maxColorBits = maxColorBits;
_leafCount = 0;
_reducibleNodes = new OctreeNode[9];
_root = new OctreeNode(0, _maxColorBits, this);
_previousColor = 0;
_previousNode = null;
}
/// <summary>
/// Add a given color value to the octree
/// </summary>
/// <param name="pixel"></param>
public void AddColor(int pixel)
{
// Check if this request is for the same color as the last
if (_previousColor == pixel)
{
// If so, check if I have a previous node setup. This will only ocurr if the first color in the image
// happens to be black, with an alpha component of zero.
if (null == _previousNode)
{
_previousColor = pixel;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
else
{
// Just update the previous node
_previousNode.Increment(pixel);
}
}
else
{
_previousColor = pixel;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
}
/// <summary>
/// Reduce the depth of the tree
/// </summary>
public void Reduce()
{
int index;
// Find the deepest level containing at least one reducible node
for (index = _maxColorBits - 1; (index > 0) && (null == _reducibleNodes[index]); index--)
{
// intentionally blank
}
// Reduce the node most recently added to the list at level 'index'
OctreeNode node = _reducibleNodes[index];
_reducibleNodes[index] = node.NextReducible;
// Decrement the leaf count after reducing the node
_leafCount -= node.Reduce();
// And just in case I've reduced the last color to be added, and the next color to
// be added is the same, invalidate the previousNode...
_previousNode = null;
}
/// <summary>
/// Get/Set the number of leaves in the tree
/// </summary>
public int Leaves
{
get
{
return _leafCount;
}
set
{
_leafCount = value;
}
}
/// <summary>
/// Return the array of reducible nodes
/// </summary>
protected OctreeNode[] ReducibleNodes
{
get
{
return _reducibleNodes;
}
}
/// <summary>
/// Keep track of the previous node that was quantized
/// </summary>
/// <param name="node">The node last quantized</param>
protected void TrackPrevious(OctreeNode node)
{
_previousNode = node;
}
private Color[] _palette;
private PaletteTable paletteTable;
/// <summary>
/// Convert the nodes in the octree to a palette with a maximum of colorCount colors
/// </summary>
/// <param name="colorCount">The maximum number of colors</param>
/// <returns>A list with the palettized colors</returns>
public List<Color> Palletize(int colorCount)
{
while (Leaves > colorCount)
{
Reduce();
}
// Now palettize the nodes
List<Color> palette = new List<Color>(Leaves);
int paletteIndex = 0;
_root.ConstructPalette(palette, ref paletteIndex);
// And return the palette
this._palette = palette.ToArray();
this.paletteTable = null;
return palette;
}
/// <summary>
/// Get the palette index for the passed color
/// </summary>
/// <param name="pixel"></param>
/// <returns></returns>
public int GetPaletteIndex(int pixel)
{
int ret = -1;
ret = _root.GetPaletteIndex(pixel, 0);
if (ret < 0)
{
if (this.paletteTable == null)
{
this.paletteTable = new PaletteTable(this._palette);
}
ret = this.paletteTable.FindClosestPaletteIndex(Color.FromArgb(pixel));
}
return ret;
}
/// <summary>
/// Mask used when getting the appropriate pixels for a given node
/// </summary>
private static int[] mask = new int[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
/// <summary>
/// The root of the octree
/// </summary>
private OctreeNode _root;
/// <summary>
/// Number of leaves in the tree
/// </summary>
private int _leafCount;
/// <summary>
/// Array of reducible nodes
/// </summary>
private OctreeNode[] _reducibleNodes;
/// <summary>
/// Maximum number of significant bits in the image
/// </summary>
private int _maxColorBits;
/// <summary>
/// Store the last node quantized
/// </summary>
private OctreeNode _previousNode;
/// <summary>
/// Cache the previous color quantized
/// </summary>
private int _previousColor;
/// <summary>
/// Class which encapsulates each node in the tree
/// </summary>
protected class OctreeNode
{
/// <summary>
/// Construct the node
/// </summary>
/// <param name="level">The level in the tree = 0 - 7</param>
/// <param name="colorBits">The number of significant color bits in the image</param>
/// <param name="octree">The tree to which this node belongs</param>
public OctreeNode(int level, int colorBits, Octree octree)
{
// Construct the new node
_leaf = (level == colorBits);
_red = 0;
_green = 0;
_blue = 0;
_pixelCount = 0;
// If a leaf, increment the leaf count
if (_leaf)
{
octree.Leaves++;
_nextReducible = null;
_children = null;
}
else
{
// Otherwise add this to the reducible nodes
_nextReducible = octree.ReducibleNodes[level];
octree.ReducibleNodes[level] = this;
_children = new OctreeNode[8];
}
}
/// <summary>
/// Add a color into the tree
/// </summary>
/// <param name="pixel">The color</param>
/// <param name="colorBits">The number of significant color bits</param>
/// <param name="level">The level in the tree</param>
/// <param name="octree">The tree to which this node belongs</param>
public void AddColor(int pixel, int colorBits, int level, Octree octree)
{
// Update the color information if this is a leaf
if (_leaf)
{
Increment(pixel);
// Setup the previous node
octree.TrackPrevious(this);
}
else
{
// Go to the next level down in the tree
int shift = 7 - level;
int b = pixel & 0xFF;
int g = (pixel >> 8) & 0xFF;
int r = (pixel >> 16) & 0xFF;
int index = ((r & mask[level]) >> (shift - 2)) |
((g & mask[level]) >> (shift - 1)) |
((b & mask[level]) >> (shift));
OctreeNode child = _children[index];
if (null == child)
{
// Create a new child node & store in the array
child = new OctreeNode(level + 1, colorBits, octree);
_children[index] = child;
}
// Add the color to the child node
child.AddColor(pixel, colorBits, level + 1, octree);
}
}
/// <summary>
/// Get/Set the next reducible node
/// </summary>
public OctreeNode NextReducible
{
get
{
return _nextReducible;
}
set
{
_nextReducible = value;
}
}
/// <summary>
/// Return the child nodes
/// </summary>
public OctreeNode[] Children
{
get
{
return _children;
}
}
/// <summary>
/// Reduce this node by removing all of its children
/// </summary>
/// <returns>The number of leaves removed</returns>
public int Reduce()
{
int children = 0;
_red = 0;
_green = 0;
_blue = 0;
// Loop through all children and add their information to this node
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
{
_red += _children[index]._red;
_green += _children[index]._green;
_blue += _children[index]._blue;
_pixelCount += _children[index]._pixelCount;
++children;
_children[index] = null;
}
}
// Now change this to a leaf node
_leaf = true;
// Return the number of nodes to decrement the leaf count by
return(children - 1);
}
/// <summary>
/// Traverse the tree, building up the color palette
/// </summary>
/// <param name="palette">The palette</param>
/// <param name="paletteIndex">The current palette index</param>
public void ConstructPalette(List<Color> palette, ref int paletteIndex)
{
if (_leaf)
{
// Consume the next palette index
_paletteIndex = paletteIndex++;
// And set the color of the palette entry
int r = _red / _pixelCount;
int g = _green / _pixelCount;
int b = _blue / _pixelCount;
palette.Add(Color.FromArgb(r, g, b));
}
else
{
// Loop through children looking for leaves
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
{
_children[index].ConstructPalette(palette, ref paletteIndex);
}
}
}
}
/// <summary>
/// Return the palette index for the passed color
/// </summary>
public int GetPaletteIndex(int pixel, int level)
{
int paletteIndex = _paletteIndex;
if (!_leaf)
{
int shift = 7 - level;
int b = pixel & 0xFF;
int g = (pixel >> 8) & 0xFF;
int r = (pixel >> 16) & 0xFF;
int index = ((r & mask[level]) >> (shift - 2)) |
((g & mask[level]) >> (shift - 1)) |
((b & mask[level]) >> (shift));
if (null != _children[index])
{
paletteIndex = _children[index].GetPaletteIndex(pixel, level + 1);
}
else
{
paletteIndex = -1;
}
}
return paletteIndex;
}
/// <summary>
/// Increment the pixel count and add to the color information
/// </summary>
public void Increment(int pixel)
{
++_pixelCount;
int b = pixel&0xFF;
int g = (pixel>>8) & 0xFF;
int r = (pixel >> 16) & 0xFF;
_red += r;
_green += g;
_blue += b;
}
/// <summary>
/// Flag indicating that this is a leaf node
/// </summary>
private bool _leaf;
/// <summary>
/// Number of pixels in this node
/// </summary>
private int _pixelCount;
/// <summary>
/// Red component
/// </summary>
private int _red;
/// <summary>
/// Green Component
/// </summary>
private int _green;
/// <summary>
/// Blue component
/// </summary>
private int _blue;
/// <summary>
/// Pointers to any child nodes
/// </summary>
private OctreeNode[] _children;
/// <summary>
/// Pointer to next reducible node
/// </summary>
private OctreeNode _nextReducible;
/// <summary>
/// The index of this node in the palette
/// </summary>
private int _paletteIndex;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.Formula.Functions;
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
public class AVEDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.avedev(values);
}
}
public class AVERAGE : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return MathX.average(values);
}
}
public class DEVSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.devsq(values);
}
}
public class SUM : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.sum(values);
}
}
public class LARGE : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthLargest(values, k);
}
}
public class MAX : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.max(values) : 0;
}
}
public class MIN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.min(values) : 0;
}
}
public class MEDIAN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.median(values);
}
}
public class PRODUCT : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.product(values);
}
}
public class SMALL : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthSmallest(values, k);
}
}
public class STDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.stdev(values);
}
}
public class SUMSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.sumsq(values);
}
}
public class VAR : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.var(values);
}
};
public class VARP : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.varp(values);
}
};
public class SubtotalInstance : AggregateFunction
{
private AggregateFunction _func;
public SubtotalInstance(AggregateFunction func)
{
_func = func;
}
protected internal override double Evaluate(double[] values)
{
return _func.Evaluate(values);
}
/**
* ignore nested subtotals.
*/
public override bool IsSubtotalCounted
{
get
{
return false;
}
}
}
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
public abstract class AggregateFunction : MultiOperandNumericFunction
{
public static Function SubtotalInstance(Function func)
{
AggregateFunction arg = (AggregateFunction)func;
return new SubtotalInstance(arg);
}
internal class ValueCollector : MultiOperandNumericFunction
{
private static ValueCollector instance = new ValueCollector();
public ValueCollector() :
base(false, false)
{
}
public static double[] CollectValues(params ValueEval[] operands)
{
return instance.GetNumberArray(operands);
}
protected internal override double Evaluate(double[] values)
{
throw new InvalidOperationException("should not be called");
}
}
protected AggregateFunction()
: base(false, false)
{
}
public static readonly Function AVEDEV = new AVEDEV();
public static readonly Function AVERAGE = new AVERAGE();
public static readonly Function DEVSQ = new DEVSQ();
public static readonly Function LARGE = new LARGE();
public static readonly Function MAX = new MAX();
public static readonly Function MEDIAN = new MEDIAN();
public static readonly Function MIN = new MIN();
public static readonly Function PRODUCT = new PRODUCT();
public static readonly Function SMALL = new SMALL();
public static readonly Function STDEV = new STDEV();
public static readonly Function SUM = new SUM();
public static readonly Function SUMSQ = new SUMSQ();
public static readonly Function VAR = new VAR();
public static readonly Function VARP = new VARP();
}
}
| |
namespace YAMP
{
using System;
using System.IO;
using YAMP.Exceptions;
/// <summary>
/// A special kind of matrix which is a range (vector).
/// </summary>
public sealed class RangeValue : MatrixValue
{
#region Fields
int count;
#endregion
#region ctor
/// <summary>
/// Creates a new range value with the specified steps.
/// </summary>
/// <param name="start">The starting value.</param>
/// <param name="end">The ending value.</param>
/// <param name="step">The step value.</param>
public RangeValue(double start, double end, double step)
{
Start = start;
End = end;
Step = step;
count = 1 + (int)Math.Floor((end - start) / step);
DimensionX = 1;
DimensionY = count;
if (count < 0)
throw new YAMPRangeInvalidException("negative number of entries has been detected");
if (count >= Int32.MaxValue / 10)
throw new YAMPRangeInvalidException("too many entries have been found");
}
/// <summary>
/// Creates a new range value from some point to the end of the matrix.
/// </summary>
/// <param name="start">The starting value.</param>
/// <param name="step">The step value.</param>
public RangeValue (double start, double step) : this(start, start, step)
{
All = true;
}
/// <summary>
/// Standard operator - Start at 1, Step 1 and till the end of the matrix.
/// </summary>
public RangeValue () : this(1, 1)
{
}
#endregion
#region Properties
/// <summary>
/// Gets the specified step size.
/// </summary>
public double Step { get; private set; }
/// <summary>
/// Gets the specified offset.
/// </summary>
public double Start { get; private set; }
/// <summary>
/// Gets the specified tail.
/// </summary>
public double End { get; private set; }
/// <summary>
/// Gets a boolean to indicate whether all elements (of the
/// target object) should be used.
/// </summary>
public bool All { get; private set; }
#endregion
#region Methods
/// <summary>
/// Clones the given range.
/// </summary>
/// <returns>A new matrix value (range).</returns>
public override MatrixValue Clone()
{
var m = new MatrixValue(DimensionY, DimensionX);
for (var j = 1; j <= DimensionY; j++)
for (var i = 1; i <= DimensionX; i++)
m[j, i] = this[j, i].Clone();
return m;
}
ScalarValue GetValue(int i)
{
return new ScalarValue(Start + (i - 1) * Step);
}
/// <summary>
/// Gets or sets an entry in the range.
/// </summary>
/// <param name="j">The 1-based row-index.</param>
/// <param name="i">The 1-based column-index.</param>
/// <returns>The value behind the index.</returns>
public override ScalarValue this[int j, int i]
{
get
{
if (i > DimensionX || i < 1 || j > DimensionY || j < 1)
throw new ArgumentOutOfRangeException("Access in Matrix out of bounds.");
var index = new MatrixIndex();
index.Column = i;
index.Row = j;
if (ContainsIndex(index))
return GetIndex(index);
if(i == 1)
return GetValue(j);
return ScalarValue.Zero;
}
set
{
base[j, i] = value;
}
}
#endregion
#region Serialization
/// <summary>
/// Tries to serialize the contents into bytes.
/// </summary>
/// <returns>The raw data.</returns>
public override byte[] Serialize()
{
var content = base.Serialize();
using (var ms = new MemoryStream())
{
ms.Write(content, 0, content.Length);
var start = BitConverter.GetBytes(Start);
var end = BitConverter.GetBytes(End);
var step = BitConverter.GetBytes(Step);
var all = BitConverter.GetBytes(All);
ms.Write(start, 0, start.Length);
ms.Write(end, 0, end.Length);
ms.Write(step, 0, step.Length);
ms.Write(all, 0, all.Length);
content = ms.ToArray();
}
return content;
}
/// <summary>
/// Tries to create a new instance from the given bytes.
/// </summary>
/// <param name="content">The binary content.</param>
/// <returns>The new instance.</returns>
public override Value Deserialize(byte[] content)
{
var R = new RangeValue();
R.DimensionY = BitConverter.ToInt32(content, 0);
R.DimensionX = BitConverter.ToInt32(content, 4);
var count = BitConverter.ToInt32(content, 8);
var pos = 12;
for (var i = 0; i < count; i++)
{
var row = BitConverter.ToInt32(content, pos);
var col = BitConverter.ToInt32(content, pos + 4);
var re = BitConverter.ToDouble(content, pos + 8);
var im = BitConverter.ToDouble(content, pos + 16);
R[row, col] = new ScalarValue(re, im);
pos += 24;
}
R.Start = BitConverter.ToDouble(content, content.Length - 25);
R.End = BitConverter.ToDouble(content, content.Length - 17);
R.Step = BitConverter.ToDouble(content, content.Length - 9);
R.All = BitConverter.ToBoolean(content, content.Length - 1);
return R;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.Xml
{
using System;
//
// XmlCharCheckingReaderWithNS
//
internal partial class XmlCharCheckingReader : XmlWrappingReader
{
public override async Task<bool> ReadAsync()
{
switch (_state)
{
case State.Initial:
_state = State.Interactive;
if (base.reader.ReadState == ReadState.Initial)
{
goto case State.Interactive;
}
break;
case State.Error:
return false;
case State.InReadBinary:
await FinishReadBinaryAsync().ConfigureAwait(false);
_state = State.Interactive;
goto case State.Interactive;
case State.Interactive:
if (!await base.reader.ReadAsync().ConfigureAwait(false))
{
return false;
}
break;
default:
Debug.Assert(false);
return false;
}
XmlNodeType nodeType = base.reader.NodeType;
if (!_checkCharacters)
{
switch (nodeType)
{
case XmlNodeType.Comment:
if (_ignoreComments)
{
return await ReadAsync().ConfigureAwait(false);
}
break;
case XmlNodeType.Whitespace:
if (_ignoreWhitespace)
{
return await ReadAsync().ConfigureAwait(false);
}
break;
case XmlNodeType.ProcessingInstruction:
if (_ignorePis)
{
return await ReadAsync().ConfigureAwait(false);
}
break;
case XmlNodeType.DocumentType:
if (_dtdProcessing == DtdProcessing.Prohibit)
{
Throw(ResXml.Xml_DtdIsProhibitedEx, string.Empty);
}
else if (_dtdProcessing == DtdProcessing.Ignore)
{
return await ReadAsync().ConfigureAwait(false);
}
break;
}
return true;
}
else
{
switch (nodeType)
{
case XmlNodeType.Element:
if (_checkCharacters)
{
// check element name
ValidateQName(base.reader.Prefix, base.reader.LocalName);
// check values of attributes
if (base.reader.MoveToFirstAttribute())
{
do
{
ValidateQName(base.reader.Prefix, base.reader.LocalName);
CheckCharacters(base.reader.Value);
} while (base.reader.MoveToNextAttribute());
base.reader.MoveToElement();
}
}
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
if (_checkCharacters)
{
CheckCharacters(await base.reader.GetValueAsync().ConfigureAwait(false));
}
break;
case XmlNodeType.EntityReference:
if (_checkCharacters)
{
// check name
ValidateQName(base.reader.Name);
}
break;
case XmlNodeType.ProcessingInstruction:
if (_ignorePis)
{
return await ReadAsync().ConfigureAwait(false);
}
if (_checkCharacters)
{
ValidateQName(base.reader.Name);
CheckCharacters(base.reader.Value);
}
break;
case XmlNodeType.Comment:
if (_ignoreComments)
{
return await ReadAsync().ConfigureAwait(false);
}
if (_checkCharacters)
{
CheckCharacters(base.reader.Value);
}
break;
case XmlNodeType.DocumentType:
if (_dtdProcessing == DtdProcessing.Prohibit)
{
Throw(ResXml.Xml_DtdIsProhibitedEx, string.Empty);
}
else if (_dtdProcessing == DtdProcessing.Ignore)
{
return await ReadAsync().ConfigureAwait(false);
}
if (_checkCharacters)
{
ValidateQName(base.reader.Name);
CheckCharacters(base.reader.Value);
string str;
str = base.reader.GetAttribute("SYSTEM");
if (str != null)
{
CheckCharacters(str);
}
str = base.reader.GetAttribute("PUBLIC");
if (str != null)
{
int i;
if ((i = _xmlCharType.IsPublicId(str)) >= 0)
{
Throw(ResXml.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(str, i));
}
}
}
break;
case XmlNodeType.Whitespace:
if (_ignoreWhitespace)
{
return await ReadAsync().ConfigureAwait(false);
}
if (_checkCharacters)
{
CheckWhitespace(await base.reader.GetValueAsync().ConfigureAwait(false));
}
break;
case XmlNodeType.SignificantWhitespace:
if (_checkCharacters)
{
CheckWhitespace(await base.reader.GetValueAsync().ConfigureAwait(false));
}
break;
case XmlNodeType.EndElement:
if (_checkCharacters)
{
ValidateQName(base.reader.Prefix, base.reader.LocalName);
}
break;
default:
break;
}
_lastNodeType = nodeType;
return true;
}
}
public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
if (_state != State.InReadBinary)
{
// forward ReadBase64Chunk calls into the base (wrapped) reader if possible, i.e. if it can read binary and we
// should not check characters
if (base.CanReadBinaryContent && (!_checkCharacters))
{
_readBinaryHelper = null;
_state = State.InReadBinary;
return await base.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
}
else
{
// forward calls into wrapped reader
if (_readBinaryHelper == null)
{
return await base.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = State.Interactive;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// turn on InReadBinary in again and return
_state = State.InReadBinary;
return readCount;
}
public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
if (_state != State.InReadBinary)
{
// forward ReadBinHexChunk calls into the base (wrapped) reader if possible, i.e. if it can read chunks and we
// should not check characters
if (base.CanReadBinaryContent && (!_checkCharacters))
{
_readBinaryHelper = null;
_state = State.InReadBinary;
return await base.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
}
else
{
// forward calls into wrapped reader
if (_readBinaryHelper == null)
{
return await base.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = State.Interactive;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// turn on InReadBinary in again and return
_state = State.InReadBinary;
return readCount;
}
public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
if (ReadState != ReadState.Interactive)
{
return 0;
}
if (_state != State.InReadBinary)
{
// forward ReadBase64Chunk calls into the base (wrapped) reader if possible, i.e. if it can read binary and we
// should not check characters
if (base.CanReadBinaryContent && (!_checkCharacters))
{
_readBinaryHelper = null;
_state = State.InReadBinary;
return await base.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
}
else
{
// forward calls into wrapped reader
if (_readBinaryHelper == null)
{
return await base.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = State.Interactive;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// turn on InReadBinary in again and return
_state = State.InReadBinary;
return readCount;
}
public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
if (ReadState != ReadState.Interactive)
{
return 0;
}
if (_state != State.InReadBinary)
{
// forward ReadBinHexChunk calls into the base (wrapped) reader if possible, i.e. if it can read chunks and we
// should not check characters
if (base.CanReadBinaryContent && (!_checkCharacters))
{
_readBinaryHelper = null;
_state = State.InReadBinary;
return await base.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
}
else
{
// forward calls into wrapped reader
if (_readBinaryHelper == null)
{
return await base.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = State.Interactive;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// turn on InReadBinary in again and return
_state = State.InReadBinary;
return readCount;
}
private async Task FinishReadBinaryAsync()
{
_state = State.Interactive;
if (_readBinaryHelper != null)
{
await _readBinaryHelper.FinishAsync().ConfigureAwait(false);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Physics;
using Microsoft.MixedReality.Toolkit.Utilities;
using System.Collections;
using Unity.Profiling;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// This class allows for HoloLens 1 style input, using a far gaze ray
/// for focus with hand and gesture-based input and interaction across it.
/// </summary>
/// <remarks>
/// <para>GGV stands for gaze, gesture, and voice.
/// This pointer's position is given by hand position (grip pose),
/// and the input focus is given by head gaze.</para>
/// </remarks>
[AddComponentMenu("Scripts/MRTK/SDK/GGVPointer")]
public class GGVPointer : InputSystemGlobalHandlerListener,
IMixedRealityPointer,
IMixedRealityInputHandler,
IMixedRealityInputHandler<MixedRealityPose>,
IMixedRealitySourceStateHandler
{
[Header("Pointer")]
[SerializeField]
private MixedRealityInputAction selectAction = MixedRealityInputAction.None;
[SerializeField]
private MixedRealityInputAction poseAction = MixedRealityInputAction.None;
private IMixedRealityGazeProvider gazeProvider;
private Vector3 sourcePosition;
private bool isSelectPressed;
private Handedness lastControllerHandedness;
#region IMixedRealityPointer
private IMixedRealityController controller;
/// <inheritdoc />
public IMixedRealityController Controller
{
get { return controller; }
set
{
controller = value;
if (controller != null && this != null)
{
gameObject.name = $"{Controller.ControllerHandedness}_GGVPointer";
pointerName = gameObject.name;
InputSourceParent = controller.InputSource;
}
}
}
private uint pointerId;
/// <inheritdoc />
public uint PointerId
{
get
{
if (pointerId == 0)
{
pointerId = CoreServices.InputSystem.FocusProvider.GenerateNewPointerId();
}
return pointerId;
}
}
private string pointerName = string.Empty;
/// <inheritdoc />
public string PointerName
{
get { return pointerName; }
set
{
pointerName = value;
if (this != null)
{
gameObject.name = value;
}
}
}
/// <inheritdoc />
public IMixedRealityInputSource InputSourceParent { get; private set; }
/// <inheritdoc />
public IMixedRealityCursor BaseCursor { get; set; }
/// <inheritdoc />
public ICursorModifier CursorModifier { get; set; }
/// <inheritdoc />
public bool IsInteractionEnabled => IsActive;
/// <inheritdoc />
public bool IsActive { get; set; }
/// <inheritdoc />
public bool IsFocusLocked { get; set; }
/// <inheritdoc />
public bool IsTargetPositionLockedOnFocusLock { get; set; }
public RayStep[] Rays { get; protected set; } = { new RayStep(Vector3.zero, Vector3.forward) };
public LayerMask[] PrioritizedLayerMasksOverride { get; set; }
public IMixedRealityFocusHandler FocusTarget { get; set; }
/// <inheritdoc />
public IPointerResult Result { get; set; }
/// <inheritdoc />
public virtual SceneQueryType SceneQueryType { get; set; } = SceneQueryType.SimpleRaycast;
/// <inheritdoc />
public float SphereCastRadius
{
get => throw new System.NotImplementedException();
set => throw new System.NotImplementedException();
}
private static bool Equals(IMixedRealityPointer left, IMixedRealityPointer right)
{
return left != null && left.Equals(right);
}
/// <inheritdoc />
bool IEqualityComparer.Equals(object left, object right)
{
return left.Equals(right);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((IMixedRealityPointer)obj);
}
private bool Equals(IMixedRealityPointer other)
{
return other != null && PointerId == other.PointerId && string.Equals(PointerName, other.PointerName);
}
/// <inheritdoc />
int IEqualityComparer.GetHashCode(object obj)
{
return obj.GetHashCode();
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = 0;
hashCode = (hashCode * 397) ^ (int)PointerId;
hashCode = (hashCode * 397) ^ (PointerName != null ? PointerName.GetHashCode() : 0);
return hashCode;
}
}
private static readonly ProfilerMarker OnPostSceneQueryPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnPostSceneQuery");
/// <inheritdoc />
public void OnPostSceneQuery()
{
using (OnPostSceneQueryPerfMarker.Auto())
{
if (isSelectPressed && IsInteractionEnabled)
{
CoreServices.InputSystem.RaisePointerDragged(this, MixedRealityInputAction.None, Controller.ControllerHandedness);
}
}
}
private static readonly ProfilerMarker OnPreSceneQueryPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnPreSceneQuery");
/// <inheritdoc />
public void OnPreSceneQuery()
{
using (OnPreSceneQueryPerfMarker.Auto())
{
Vector3 newGazeOrigin = gazeProvider.GazePointer.Rays[0].Origin;
Vector3 endPoint = newGazeOrigin + (gazeProvider.GazePointer.Rays[0].Direction * CoreServices.InputSystem.FocusProvider.GlobalPointingExtent);
Rays[0].UpdateRayStep(ref newGazeOrigin, ref endPoint);
}
}
/// <inheritdoc />
public void OnPreCurrentPointerTargetChange() { }
/// <inheritdoc />
public void Reset()
{
Controller = null;
BaseCursor = null;
IsActive = false;
IsFocusLocked = false;
}
/// <inheritdoc />
public virtual Vector3 Position => sourcePosition;
/// <inheritdoc />
public virtual Quaternion Rotation
{
get
{
// Previously we were simply returning the InternalGazeProvider rotation here.
// This caused issues when the head rotated, but the hand stayed where it was.
// Now we're returning a rotation based on the vector from the camera position
// to the hand. This rotation is not affected by rotating your head.
Vector3 look = Position - CameraCache.Main.transform.position;
// If the input source is at the same position as the camera, assume it's the camera and return the InternalGazeProvider rotation.
// This prevents passing Vector3.zero into Quaternion.LookRotation, which isn't possible and causes a console log.
if (look == Vector3.zero)
{
return Quaternion.LookRotation(gazeProvider.GazePointer.Rays[0].Direction);
}
return Quaternion.LookRotation(look);
}
}
#endregion
#region IMixedRealityInputHandler Implementation
private static readonly ProfilerMarker OnInputUpPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnInputUp");
/// <inheritdoc />
public void OnInputUp(InputEventData eventData)
{
using (OnInputUpPerfMarker.Auto())
{
if (eventData.SourceId == InputSourceParent.SourceId)
{
if (eventData.MixedRealityInputAction == selectAction)
{
isSelectPressed = false;
if (IsInteractionEnabled)
{
BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor;
if (c != null)
{
c.SourceDownIds.Remove(eventData.SourceId);
}
CoreServices.InputSystem.RaisePointerClicked(this, selectAction, 0, Controller.ControllerHandedness);
CoreServices.InputSystem.RaisePointerUp(this, selectAction, Controller.ControllerHandedness);
// For GGV, the gaze pointer does not set this value itself.
// See comment in OnInputDown for more details.
gazeProvider.GazePointer.IsFocusLocked = false;
}
}
}
}
}
private static readonly ProfilerMarker OnInputDownPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnInputDown");
/// <inheritdoc />
public void OnInputDown(InputEventData eventData)
{
using (OnInputDownPerfMarker.Auto())
{
if (eventData.SourceId == InputSourceParent.SourceId)
{
if (eventData.MixedRealityInputAction == selectAction)
{
isSelectPressed = true;
lastControllerHandedness = Controller.ControllerHandedness;
if (IsInteractionEnabled)
{
BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor;
if (c != null)
{
c.SourceDownIds.Add(eventData.SourceId);
}
CoreServices.InputSystem.RaisePointerDown(this, selectAction, Controller.ControllerHandedness);
// For GGV, the gaze pointer does not set this value itself as it does not receive input
// events from the hands. Because this value is important for certain gaze behavior,
// such as positioning the gaze cursor, it is necessary to set it here.
gazeProvider.GazePointer.IsFocusLocked = (gazeProvider.GazePointer.Result?.Details.Object != null);
}
}
}
}
}
#endregion IMixedRealityInputHandler Implementation
#region MonoBehaviour Implementation
protected override void OnEnable()
{
base.OnEnable();
gazeProvider = CoreServices.InputSystem.GazeProvider;
BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor;
if (c != null)
{
c.VisibleSourcesCount++;
}
}
protected override void OnDisable()
{
base.OnDisable();
if (gazeProvider != null)
{
BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor;
if (c != null)
{
c.VisibleSourcesCount--;
}
}
}
#endregion MonoBehaviour Implementation
#region InputSystemGlobalHandlerListener Implementation
/// <inheritdoc />
protected override void RegisterHandlers()
{
CoreServices.InputSystem?.RegisterHandler<IMixedRealityInputHandler>(this);
CoreServices.InputSystem?.RegisterHandler<IMixedRealityInputHandler<MixedRealityPose>>(this);
CoreServices.InputSystem?.RegisterHandler<IMixedRealitySourceStateHandler>(this);
}
/// <inheritdoc />
protected override void UnregisterHandlers()
{
CoreServices.InputSystem?.UnregisterHandler<IMixedRealityInputHandler>(this);
CoreServices.InputSystem?.UnregisterHandler<IMixedRealityInputHandler<MixedRealityPose>>(this);
CoreServices.InputSystem?.UnregisterHandler<IMixedRealitySourceStateHandler>(this);
}
#endregion InputSystemGlobalHandlerListener Implementation
#region IMixedRealitySourceStateHandler
/// <inheritdoc />
public void OnSourceDetected(SourceStateEventData eventData) { }
private static readonly ProfilerMarker OnSourceLostPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnSourceLost");
/// <inheritdoc />
public void OnSourceLost(SourceStateEventData eventData)
{
using (OnSourceLostPerfMarker.Auto())
{
if (eventData.SourceId == InputSourceParent.SourceId)
{
BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor;
if (c != null)
{
c.SourceDownIds.Remove(eventData.SourceId);
}
if (isSelectPressed)
{
// Raise OnInputUp if pointer is lost while select is pressed
CoreServices.InputSystem.RaisePointerUp(this, selectAction, lastControllerHandedness);
// For GGV, the gaze pointer does not set this value itself.
// See comment in OnInputDown for more details.
gazeProvider.GazePointer.IsFocusLocked = false;
}
// Destroy the pointer since nobody else is destroying us
GameObjectExtensions.DestroyGameObject(gameObject);
}
}
}
#endregion IMixedRealitySourceStateHandler
#region IMixedRealityInputHandler<MixedRealityPose>
private static readonly ProfilerMarker OnInputChangedPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnInputChanged");
/// <inheritdoc />
public void OnInputChanged(InputEventData<MixedRealityPose> eventData)
{
using (OnInputChangedPerfMarker.Auto())
{
if (eventData.SourceId == Controller?.InputSource.SourceId &&
eventData.Handedness == Controller?.ControllerHandedness &&
eventData.MixedRealityInputAction == poseAction)
{
sourcePosition = eventData.InputData.Position;
}
}
}
#endregion IMixedRealityInputHandler<MixedRealityPose>
}
}
| |
//
// CryptographyContext.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
namespace MimeKit.Cryptography {
/// <summary>
/// An abstract cryptography context.
/// </summary>
/// <remarks>
/// Generally speaking, applications should not use a <see cref="CryptographyContext"/>
/// directly, but rather via higher level APIs such as <see cref="MultipartSigned"/>,
/// <see cref="MultipartEncrypted"/> and <see cref="ApplicationPkcs7Mime"/>.
/// </remarks>
public abstract class CryptographyContext : IDisposable
{
static ConstructorInfo SecureMimeContextConstructor;
static ConstructorInfo OpenPgpContextConstructor;
static readonly object mutex = new object ();
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CryptographyContext"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="CryptographyContext"/>.
/// </remarks>
protected CryptographyContext ()
{
}
/// <summary>
/// Gets the signature protocol.
/// </summary>
/// <remarks>
/// <para>The signature protocol is used by <see cref="MultipartSigned"/>
/// in order to determine what the protocol parameter of the Content-Type
/// header should be.</para>
/// </remarks>
/// <value>The signature protocol.</value>
public abstract string SignatureProtocol { get; }
/// <summary>
/// Gets the encryption protocol.
/// </summary>
/// <remarks>
/// <para>The encryption protocol is used by <see cref="MultipartEncrypted"/>
/// in order to determine what the protocol parameter of the Content-Type
/// header should be.</para>
/// </remarks>
/// <value>The encryption protocol.</value>
public abstract string EncryptionProtocol { get; }
/// <summary>
/// Gets the key exchange protocol.
/// </summary>
/// <remarks>
/// <para>The key exchange protocol is really only used for PGP.</para>
/// </remarks>
/// <value>The key exchange protocol.</value>
public abstract string KeyExchangeProtocol { get; }
#if NOT_YET
/// <summary>
/// Gets or sets a value indicating whether this <see cref="MimeKit.Cryptography.CryptographyContext"/> allows online
/// certificate retrieval.
/// </summary>
/// <value><c>true</c> if online certificate retrieval should be allowed; otherwise, <c>false</c>.</value>
public bool AllowOnlineCertificateRetrieval { get; set; }
/// <summary>
/// Gets or sets the online certificate retrieval timeout.
/// </summary>
/// <value>The online certificate retrieval timeout.</value>
public TimeSpan OnlineCertificateRetrievalTimeout { get; set; }
#endif
/// <summary>
/// Checks whether or not the specified protocol is supported by the <see cref="CryptographyContext"/>.
/// </summary>
/// <remarks>
/// Used in order to make sure that the protocol parameter value specified in either a multipart/signed
/// or multipart/encrypted part is supported by the supplied cryptography context.
/// </remarks>
/// <returns><c>true</c> if the protocol is supported; otherwise <c>false</c></returns>
/// <param name="protocol">The protocol.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="protocol"/> is <c>null</c>.
/// </exception>
public abstract bool Supports (string protocol);
/// <summary>
/// Gets the string name of the digest algorithm for use with the micalg parameter of a multipart/signed part.
/// </summary>
/// <remarks>
/// Maps the <see cref="DigestAlgorithm"/> to the appropriate string identifier
/// as used by the micalg parameter value of a multipart/signed Content-Type
/// header.
/// </remarks>
/// <returns>The micalg value.</returns>
/// <param name="micalg">The digest algorithm.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="micalg"/> is out of range.
/// </exception>
public abstract string GetDigestAlgorithmName (DigestAlgorithm micalg);
/// <summary>
/// Gets the digest algorithm from the micalg parameter value in a multipart/signed part.
/// </summary>
/// <remarks>
/// Maps the micalg parameter value string back to the appropriate <see cref="DigestAlgorithm"/>.
/// </remarks>
/// <returns>The digest algorithm.</returns>
/// <param name="micalg">The micalg parameter value.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="micalg"/> is <c>null</c>.
/// </exception>
public abstract DigestAlgorithm GetDigestAlgorithm (string micalg);
/// <summary>
/// Cryptographically signs the content.
/// </summary>
/// <remarks>
/// Cryptographically signs the content using the specified signer and digest algorithm.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance
/// containing the detached signature data.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="content">The content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="digestAlgo"/> is out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
public abstract MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content);
/// <summary>
/// Verifies the specified content using the detached signatureData.
/// </summary>
/// <remarks>
/// Verifies the specified content using the detached signatureData.
/// </remarks>
/// <returns>A list of digital signatures.</returns>
/// <param name="content">The content.</param>
/// <param name="signatureData">The signature data.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signatureData"/> is <c>null</c>.</para>
/// </exception>
public abstract DigitalSignatureCollection Verify (Stream content, Stream signatureData);
/// <summary>
/// Encrypts the specified content for the specified recipients.
/// </summary>
/// <remarks>
/// Encrypts the specified content for the specified recipients.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance
/// containing the encrypted data.</returns>
/// <param name="recipients">The recipients.</param>
/// <param name="content">The content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A certificate could not be found for one or more of the <paramref name="recipients"/>.
/// </exception>
public abstract MimePart Encrypt (IEnumerable<MailboxAddress> recipients, Stream content);
/// <summary>
/// Decrypts the specified encryptedData.
/// </summary>
/// <remarks>
/// Decrypts the specified encryptedData.
/// </remarks>
/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
/// <param name="encryptedData">The encrypted data.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="encryptedData"/> is <c>null</c>.
/// </exception>
public abstract MimeEntity Decrypt (Stream encryptedData);
/// <summary>
/// Imports the public certificates or keys from the specified stream.
/// </summary>
/// <remarks>
/// Imports the public certificates or keys from the specified stream.
/// </remarks>
/// <param name="stream">The raw certificate or key data.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// Importing keys is not supported by this cryptography context.
/// </exception>
public abstract void Import (Stream stream);
/// <summary>
/// Exports the keys for the specified mailboxes.
/// </summary>
/// <remarks>
/// Exports the keys for the specified mailboxes.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported keys.</returns>
/// <param name="mailboxes">The mailboxes.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="mailboxes"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="mailboxes"/> was empty.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// Exporting keys is not supported by this cryptography context.
/// </exception>
public abstract MimePart Export (IEnumerable<MailboxAddress> mailboxes);
/// <summary>
/// Releases the unmanaged resources used by the <see cref="CryptographyContext"/> and
/// optionally releases the managed resources.
/// </summary>
/// <remarks>
/// Releases the unmanaged resources used by the <see cref="CryptographyContext"/> and
/// optionally releases the managed resources.
/// </remarks>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only the unmanaged resources.</param>
protected virtual void Dispose (bool disposing)
{
}
/// <summary>
/// Releases all resources used by the <see cref="MimeKit.Cryptography.CryptographyContext"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="MimeKit.Cryptography.CryptographyContext"/>. The
/// <see cref="Dispose()"/> method leaves the <see cref="MimeKit.Cryptography.CryptographyContext"/> in an unusable state. After
/// calling <see cref="Dispose()"/>, you must release all references to the <see cref="MimeKit.Cryptography.CryptographyContext"/> so
/// the garbage collector can reclaim the memory that the <see cref="MimeKit.Cryptography.CryptographyContext"/> was occupying.</remarks>
public void Dispose ()
{
Dispose (true);
}
/// <summary>
/// Creates a new <see cref="CryptographyContext"/> for the specified protocol.
/// </summary>
/// <remarks>
/// <para>Creates a new <see cref="CryptographyContext"/> for the specified protocol.</para>
/// <para>The default <see cref="CryptographyContext"/> types can over overridden by calling
/// the <see cref="Register"/> method with the preferred type.</para>
/// </remarks>
/// <returns>The <see cref="CryptographyContext"/> for the protocol.</returns>
/// <param name="protocol">The protocol.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="protocol"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// There are no supported <see cref="CryptographyContext"/>s that support
/// the specified <paramref name="protocol"/>.
/// </exception>
public static CryptographyContext Create (string protocol)
{
if (protocol == null)
throw new ArgumentNullException ("protocol");
protocol = protocol.ToLowerInvariant ();
lock (mutex) {
switch (protocol) {
case "application/x-pkcs7-signature":
case "application/pkcs7-signature":
case "application/x-pkcs7-mime":
case "application/pkcs7-mime":
case "application/x-pkcs7-keys":
case "application/pkcs7-keys":
if (SecureMimeContextConstructor != null)
return (CryptographyContext) SecureMimeContextConstructor.Invoke (new object[0]);
if (!SqliteCertificateDatabase.IsAvailable)
throw new NotSupportedException ("You need to subclass MimeKit.Cryptography.SecureMimeContext and then register it with MimeKit.Cryptography.CryptographyContext.Register().");
return new DefaultSecureMimeContext ();
case "application/x-pgp-signature":
case "application/pgp-signature":
case "application/x-pgp-encrypted":
case "application/pgp-encrypted":
case "application/x-pgp-keys":
case "application/pgp-keys":
if (OpenPgpContextConstructor != null)
return (CryptographyContext) OpenPgpContextConstructor.Invoke (new object[0]);
throw new NotSupportedException ("You need to subclass MimeKit.Cryptography.GnuPGContext and then register it with MimeKit.Cryptography.CryptographyContext.Register().");
default:
throw new NotSupportedException ();
}
}
}
/// <summary>
/// Registers a default <see cref="SecureMimeContext"/> or <see cref="OpenPgpContext"/>.
/// </summary>
/// <remarks>
/// Registers the specified type as the default <see cref="SecureMimeContext"/> or
/// <see cref="OpenPgpContext"/>.
/// </remarks>
/// <param name="type">A custom subclass of <see cref="SecureMimeContext"/> or
/// <see cref="OpenPgpContext"/>.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="type"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="type"/> is not a subclass of
/// <see cref="SecureMimeContext"/> or <see cref="OpenPgpContext"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="type"/> does not have a parameterless constructor.</para>
/// </exception>
public static void Register (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
var ctor = type.GetConstructor (new Type[0]);
if (ctor == null)
throw new ArgumentException ("The specified type must have a parameterless constructor.", "type");
if (type.IsSubclassOf (typeof (SecureMimeContext))) {
lock (mutex) {
SecureMimeContextConstructor = ctor;
}
} else if (type.IsSubclassOf (typeof (OpenPgpContext))) {
lock (mutex) {
OpenPgpContextConstructor = ctor;
}
} else {
throw new ArgumentException ("The specified type must be a subclass of SecureMimeContext or OpenPgpContext.", "type");
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CameraMetadataValue.cs" company="Google">
//
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
using System;
using System.Runtime.InteropServices;
using GoogleARCoreInternal;
using UnityEngine;
/// <summary>
/// Struct to contain camera metadata's value. When querying data from the struct, caller is
/// responsible for making sure the querying data type matches the ValueType.
///
/// For example: if ValueType is typeof(byte), caller should only use
/// CameraMetadataValue.AsByte() to access the value.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct CameraMetadataValue
{
[FieldOffset(0)]
private NdkCameraMetadataType m_Type;
[FieldOffset(4)]
private sbyte m_ByteValue;
[FieldOffset(4)]
private int m_IntValue;
[FieldOffset(4)]
private long m_LongValue;
[FieldOffset(4)]
private float m_FloatValue;
[FieldOffset(4)]
private double m_DoubleValue;
[FieldOffset(4)]
private CameraMetadataRational m_RationalValue;
/// <summary>
/// Constructs CameraMetadataValue using sbyte. This constructor only sets the sbyte field
/// in the struct, leaving the rest of the data to default value.
/// </summary>
/// <param name="byteValue">The byte value set to the struct.</param>
public CameraMetadataValue(sbyte byteValue)
{
m_IntValue = 0;
m_LongValue = 0;
m_FloatValue = 0;
m_DoubleValue = 0;
m_RationalValue = new CameraMetadataRational();
m_Type = NdkCameraMetadataType.Byte;
m_ByteValue = byteValue;
}
/// <summary>
/// Constructs CameraMetadataValue using int. This constructor only sets the int field
/// in the struct, leaving the rest of the data to default value.
/// </summary>
/// <param name="intValue">The int value set to the struct.</param>
public CameraMetadataValue(int intValue)
{
m_ByteValue = 0;
m_LongValue = 0;
m_FloatValue = 0;
m_DoubleValue = 0;
m_RationalValue = new CameraMetadataRational();
m_Type = NdkCameraMetadataType.Int32;
m_IntValue = intValue;
}
/// <summary>
/// Constructs CameraMetadataValue using long. This constructor only sets the long field
/// in the struct, leaving the rest of the data to default value.
/// </summary>
/// <param name="longValue">The long value set to the struct.</param>
public CameraMetadataValue(long longValue)
{
m_ByteValue = 0;
m_IntValue = 0;
m_FloatValue = 0;
m_DoubleValue = 0;
m_RationalValue = new CameraMetadataRational();
m_Type = NdkCameraMetadataType.Int64;
m_LongValue = longValue;
}
/// <summary>
/// Constructs CameraMetadataValue using float. This constructor only sets the float field
/// in the struct, leaving the rest of the data to default value.
/// </summary>
/// <param name="floatValue">The float value set to the struct.</param>
public CameraMetadataValue(float floatValue)
{
m_ByteValue = 0;
m_IntValue = 0;
m_LongValue = 0;
m_DoubleValue = 0;
m_RationalValue = new CameraMetadataRational();
m_Type = NdkCameraMetadataType.Float;
m_FloatValue = floatValue;
}
/// <summary>
/// Constructs CameraMetadataValue using double. This constructor only sets the double field
/// in the struct, leaving the rest of the data to default value.
/// </summary>
/// <param name="doubleValue">The double value set to the struct.</param>
public CameraMetadataValue(double doubleValue)
{
m_ByteValue = 0;
m_IntValue = 0;
m_LongValue = 0;
m_FloatValue = 0;
m_RationalValue = new CameraMetadataRational();
m_Type = NdkCameraMetadataType.Double;
m_DoubleValue = doubleValue;
}
/// <summary>
/// Constructs CameraMetadataValue using CameraMetadataRational. This constructor only sets
/// the CameraMetadataRational field in the struct, leaving the rest of the data to default
/// value.
/// </summary>
/// <param name="rationalValue">The CameraMetadataRational value set to the struct.</param>
public CameraMetadataValue(CameraMetadataRational rationalValue)
{
m_ByteValue = 0;
m_IntValue = 0;
m_LongValue = 0;
m_FloatValue = 0;
m_DoubleValue = 0;
m_Type = NdkCameraMetadataType.Rational;
m_RationalValue = rationalValue;
}
/// <summary>
/// Gets the Type of the CameraMetadataValue. This Type must be used to call the proper
/// query function.
/// </summary>
public Type ValueType
{
get
{
switch (m_Type)
{
case NdkCameraMetadataType.Byte:
return typeof(Byte);
case NdkCameraMetadataType.Int32:
return typeof(int);
case NdkCameraMetadataType.Float:
return typeof(float);
case NdkCameraMetadataType.Int64:
return typeof(long);
case NdkCameraMetadataType.Double:
return typeof(double);
case NdkCameraMetadataType.Rational:
return typeof(CameraMetadataRational);
default:
return null;
}
}
}
/// <summary>
/// Gets sbyte value from the struct. This function checks if the querying type matches the
/// internal type field, and logs error if the types do not match.
/// </summary>
/// <returns>Returns sbyte value stored in the struct.</returns>
public sbyte AsByte()
{
if (m_Type != NdkCameraMetadataType.Byte)
{
LogError(NdkCameraMetadataType.Byte);
}
return m_ByteValue;
}
/// <summary>
/// Gets int value from the struct. This function checks if the querying type matches the
/// internal type field, and logs error if the types do not match.
/// </summary>
/// <returns>Returns int value stored in the struct.</returns>
public int AsInt()
{
if (m_Type != NdkCameraMetadataType.Int32)
{
LogError(NdkCameraMetadataType.Int32);
}
return m_IntValue;
}
/// <summary>
/// Gets float value from the struct. This function checks if the querying type matches the
/// internal type field, and logs error if the types do not match.
/// </summary>
/// <returns>Returns float value stored in the struct.</returns>
public float AsFloat()
{
if (m_Type != NdkCameraMetadataType.Float)
{
LogError(NdkCameraMetadataType.Float);
}
return m_FloatValue;
}
/// <summary>
/// Gets long value from the struct. This function checks if the querying type matches the
/// internal type field, and logs error if the types do not match.
/// </summary>
/// <returns>Returns long value stored in the struct.</returns>
public long AsLong()
{
if (m_Type != NdkCameraMetadataType.Int64)
{
LogError(NdkCameraMetadataType.Int64);
}
return m_LongValue;
}
/// <summary>
/// Gets double value from the struct. This function checks if the querying type matches the
/// internal type field, and logs error if the types do not match.
/// </summary>
/// <returns>Returns double value stored in the struct.</returns>
public double AsDouble()
{
if (m_Type != NdkCameraMetadataType.Double)
{
LogError(NdkCameraMetadataType.Double);
}
return m_DoubleValue;
}
/// <summary>
/// Gets CameraMetadataRational value from the struct. This function checks if the querying
/// type matches the internal type field, and logs error if the types do not match.
/// </summary>
/// <returns>Returns CameraMetadataRational value stored in the struct.</returns>
public CameraMetadataRational AsRational()
{
if (m_Type != NdkCameraMetadataType.Rational)
{
LogError(NdkCameraMetadataType.Rational);
}
return m_RationalValue;
}
private void LogError(NdkCameraMetadataType requestedType)
{
ARDebug.LogErrorFormat(
"Error getting value from CameraMetadataType due to type mismatch. " +
"requested type = {0}, internal type = {1}\n" +
"Are you sure you are querying the correct type?", requestedType, m_Type);
}
}
/// <summary>
/// CameraMetadataRational follows the layout of ACameraMetadata_rational struct in NDK.
/// Please refer to NdkCameraMetadata.h for documentation:
/// https://developer.android.com/ndk/reference/ndk_camera_metadata_8h.html .
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CameraMetadataRational
{
/// <summary>
/// The numerator of the metadata rational.
/// </summary>
public int Numerator;
/// <summary>
/// The denominator of the metadata rational.
/// </summary>
public int Denominator;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Diagnostics;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
using IOPath = System.IO.Path;
namespace System.ComponentModel.Composition.Hosting
{
[DebuggerTypeProxy(typeof(DirectoryCatalogDebuggerProxy))]
public partial class DirectoryCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged, ICompositionElement
{
private readonly Lock _thisLock = new Lock();
private readonly ICompositionElement _definitionOrigin = null;
private ComposablePartCatalogCollection _catalogCollection;
private Dictionary<string, AssemblyCatalog> _assemblyCatalogs;
private volatile bool _isDisposed = false;
private string _path;
private string _fullPath;
private string _searchPattern;
private ReadOnlyCollection<string> _loadedFiles;
private readonly ReflectionContext _reflectionContext = null;
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
/// in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space, or
/// contains one or more implementation-specific invalid characters.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path)
: this(path, "*.dll")
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
/// in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="reflectionContext">
/// The <see cref="ReflectionContext"/> a context used by the catalog when
/// interpreting the types to inject attributes into the type definition.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space, or
/// contains one or more implementation-specific invalid characters.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/> or
/// <paramref name="reflectionContext"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path, ReflectionContext reflectionContext)
: this(path, "*.dll", reflectionContext)
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
/// in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="definitionOrigin">
/// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space, or
/// contains one or more implementation-specific invalid characters.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/> or
/// <paramref name="definitionOrigin"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path, ICompositionElement definitionOrigin)
: this(path, "*.dll", definitionOrigin)
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the given searchPattern
/// over the files in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="reflectionContext">
/// The <see cref="ReflectionContext"/> a context used by the catalog when
/// interpreting the types to inject attributes into the type definition.
/// </param>
/// <param name="definitionOrigin">
/// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space
/// does not contain a valid pattern.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/> or
/// <paramref name="reflectionContext"/> is <see langword="null"/> or
/// <paramref name="definitionOrigin"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path, ReflectionContext reflectionContext, ICompositionElement definitionOrigin)
: this(path, "*.dll", reflectionContext, definitionOrigin)
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
/// in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="searchPattern">
/// Any valid searchPattern that <see cref="Directory.GetFiles(string, string)"/> will accept.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space, or
/// contains one or more implementation-specific invalid characters. Or <paramref name="searchPattern"/>
/// does not contain a valid pattern.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path, string searchPattern)
{
Requires.NotNullOrEmpty(path, "path");
Requires.NotNullOrEmpty(searchPattern, "searchPattern");
_definitionOrigin = this;
Initialize(path, searchPattern);
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
/// in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="definitionOrigin">
/// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space, or
/// contains one or more implementation-specific invalid characters. Or <paramref name="searchPattern"/>
/// does not contain a valid pattern.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// <paramref name="definitionOrigin"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path, string searchPattern, ICompositionElement definitionOrigin)
{
Requires.NotNullOrEmpty(path, "path");
Requires.NotNullOrEmpty(searchPattern, "searchPattern");
Requires.NotNull(definitionOrigin, nameof(definitionOrigin));
_definitionOrigin = definitionOrigin;
Initialize(path, searchPattern);
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the given searchPattern
/// over the files in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="searchPattern">
/// Any valid searchPattern that <see cref="Directory.GetFiles(string, string)"/> will accept.
/// </param>
/// <param name="reflectionContext">
/// The <see cref="ReflectionContext"/> a context used by the catalog when
/// interpreting the types to inject attributes into the type definition.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space, or
/// contains one or more implementation-specific invalid characters. Or <paramref name="searchPattern"/>
/// does not contain a valid pattern.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>
/// or <paramref name="searchPattern"/> is <see langword="null"/>.
/// or <paramref name="reflectionContext"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path, string searchPattern, ReflectionContext reflectionContext)
{
Requires.NotNullOrEmpty(path, "path");
Requires.NotNullOrEmpty(searchPattern, "searchPattern");
Requires.NotNull(reflectionContext, "reflectionContext");
_reflectionContext = reflectionContext;
_definitionOrigin = this;
Initialize(path, searchPattern);
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the given searchPattern
/// over the files in the given directory path.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="searchPattern">
/// Any valid searchPattern that <see cref="Directory.GetFiles(string, string)"/> will accept.
/// </param>
/// <param name="reflectionContext">
/// The <see cref="ReflectionContext"/> a context used by the catalog when
/// interpreting the types to inject attributes into the type definition.
/// </param>
/// <param name="definitionOrigin">
/// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is a zero-length string, contains only white space, or
/// contains one or more implementation-specific invalid characters. Or <paramref name="searchPattern"/>
/// does not contain a valid pattern.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>
/// or <paramref name="searchPattern"/> is <see langword="null"/>.
/// or <paramref name="reflectionContext"/> is <see langword="null"/>.
/// or <paramref name="definitionOrigin"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
/// be less than 260 characters.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public DirectoryCatalog(string path, string searchPattern, ReflectionContext reflectionContext, ICompositionElement definitionOrigin)
{
Requires.NotNullOrEmpty(path, "path");
Requires.NotNullOrEmpty(searchPattern, "searchPattern");
Requires.NotNull(reflectionContext, "reflectionContext");
Requires.NotNull(definitionOrigin, "definitionOrigin");
_reflectionContext = reflectionContext;
_definitionOrigin = definitionOrigin;
Initialize(path, searchPattern);
}
/// <summary>
/// Translated absolute path of the path passed into the constructor of <see cref="DirectoryCatalog"/>.
/// </summary>
public string FullPath
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return _fullPath;
}
}
/// <summary>
/// Set of files that have currently been loaded into the catalog.
/// </summary>
public ReadOnlyCollection<string> LoadedFiles
{
get
{
Contract.Ensures(Contract.Result<ReadOnlyCollection<string>>() != null);
using (new ReadLock(_thisLock))
{
return _loadedFiles;
}
}
}
/// <summary>
/// Path passed into the constructor of <see cref="DirectoryCatalog"/>.
/// </summary>
public string Path
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return _path;
}
}
/// <summary>
/// SearchPattern passed into the constructor of <see cref="DirectoryCatalog"/>, or the default *.dll.
/// </summary>
public string SearchPattern
{
get
{
return _searchPattern;
}
}
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
/// <summary>
/// Notify when the contents of the Catalog has changing.
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (!_isDisposed)
{
bool disposeLock = false;
ComposablePartCatalogCollection catalogs = null;
try
{
using (new WriteLock(_thisLock))
{
if (!_isDisposed)
{
disposeLock = true;
catalogs = _catalogCollection;
_catalogCollection = null;
_assemblyCatalogs = null;
_isDisposed = true;
}
}
}
finally
{
if (catalogs != null)
{
catalogs.Dispose();
}
if (disposeLock)
{
_thisLock.Dispose();
}
}
}
}
}
finally
{
base.Dispose(disposing);
}
}
public override IEnumerator<ComposablePartDefinition> GetEnumerator()
{
return _catalogCollection.SelectMany(catalog => catalog as IEnumerable<ComposablePartDefinition>).GetEnumerator();
}
/// <summary>
/// Returns the export definitions that match the constraint defined by the specified definition.
/// </summary>
/// <param name="definition">
/// The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="ExportDefinition"/> objects to return.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
/// <see cref="ExportDefinition"/> objects and their associated
/// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
/// by <paramref name="definition"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="definition"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="DirectoryCatalog"/> has been disposed of.
/// </exception>
public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
{
ThrowIfDisposed();
Requires.NotNull(definition, nameof(definition));
return _catalogCollection.SelectMany(catalog => catalog.GetExports(definition));
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
{
EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
if (changedEvent != null)
{
changedEvent(this, e);
}
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
{
EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
if (changingEvent != null)
{
changingEvent(this, e);
}
}
/// <summary>
/// Refreshes the <see cref="ComposablePartDefinition"/>s with the latest files in the directory that match
/// the searchPattern. If any files have been added they will be added to the catalog and if any files were
/// removed they will be removed from the catalog. For files that have been removed keep in mind that the
/// assembly cannot be unloaded from the process so <see cref="ComposablePartDefinition"/>s for those files
/// will simply be removed from the catalog.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
/// <see cref="Assembly.Load(AssemblyName)"/> can throw.
/// </summary>
/// <exception cref="DirectoryNotFoundException">
/// The specified path has been removed since object construction.
/// </exception>
public void Refresh()
{
ThrowIfDisposed();
Assumes.NotNull(_loadedFiles);
List<Tuple<string, AssemblyCatalog>> catalogsToAdd;
List<Tuple<string, AssemblyCatalog>> catalogsToRemove;
ComposablePartDefinition[] addedDefinitions;
ComposablePartDefinition[] removedDefinitions;
object changeReferenceObject;
string[] afterFiles;
string[] beforeFiles;
while (true)
{
afterFiles = GetFiles();
using (new ReadLock(_thisLock))
{
changeReferenceObject = _loadedFiles;
beforeFiles = _loadedFiles.ToArray();
}
DiffChanges(beforeFiles, afterFiles, out catalogsToAdd, out catalogsToRemove);
// Don't go any further if there's no work to do
if (catalogsToAdd.Count == 0 && catalogsToRemove.Count == 0)
{
return;
}
// Notify listeners to give them a preview before completeting the changes
addedDefinitions = catalogsToAdd
.SelectMany(cat => cat.Item2 as IEnumerable<ComposablePartDefinition>)
.ToArray<ComposablePartDefinition>();
removedDefinitions = catalogsToRemove
.SelectMany(cat => cat.Item2 as IEnumerable<ComposablePartDefinition>)
.ToArray<ComposablePartDefinition>();
using (var atomicComposition = new AtomicComposition())
{
var changingArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, atomicComposition);
OnChanging(changingArgs);
// if the change went through then write the catalog changes
using (new WriteLock(_thisLock))
{
if (changeReferenceObject != _loadedFiles)
{
// Someone updated the list while we were diffing so we need to try the diff again
continue;
}
foreach (var catalogToAdd in catalogsToAdd)
{
_assemblyCatalogs.Add(catalogToAdd.Item1, catalogToAdd.Item2);
_catalogCollection.Add(catalogToAdd.Item2);
}
foreach (var catalogToRemove in catalogsToRemove)
{
_assemblyCatalogs.Remove(catalogToRemove.Item1);
_catalogCollection.Remove(catalogToRemove.Item2);
}
_loadedFiles = afterFiles.ToReadOnlyCollection();
// Lastly complete any changes added to the atomicComposition during the change event
atomicComposition.Complete();
// Break out of the while(true)
break;
} // WriteLock
} // AtomicComposition
} // while (true)
var changedArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, null);
OnChanged(changedArgs);
}
/// <summary>
/// Returns a string representation of the directory catalog.
/// </summary>
/// <returns>
/// A <see cref="String"/> containing the string representation of the <see cref="DirectoryCatalog"/>.
/// </returns>
public override string ToString()
{
return GetDisplayName();
}
private AssemblyCatalog CreateAssemblyCatalogGuarded(string assemblyFilePath)
{
Exception exception = null;
try
{
return (_reflectionContext != null)
? new AssemblyCatalog(assemblyFilePath, _reflectionContext, this)
: new AssemblyCatalog(assemblyFilePath, this);
}
catch (FileNotFoundException ex)
{ // Files should always exists but don't blow up here if they don't
exception = ex;
}
catch (FileLoadException ex)
{ // File was found but could not be loaded
exception = ex;
}
catch (BadImageFormatException ex)
{ // Dlls that contain native code are not loaded, but do not invalidate the Directory
exception = ex;
}
catch (ReflectionTypeLoadException ex)
{ // Dlls that have missing Managed dependencies are not loaded, but do not invalidate the Directory
exception = ex;
}
CompositionTrace.AssemblyLoadFailed(this, assemblyFilePath, exception);
return null;
}
private void DiffChanges(string[] beforeFiles, string[] afterFiles,
out List<Tuple<string, AssemblyCatalog>> catalogsToAdd,
out List<Tuple<string, AssemblyCatalog>> catalogsToRemove)
{
catalogsToAdd = new List<Tuple<string, AssemblyCatalog>>();
catalogsToRemove = new List<Tuple<string, AssemblyCatalog>>();
IEnumerable<string> filesToAdd = afterFiles.Except(beforeFiles);
foreach (string file in filesToAdd)
{
AssemblyCatalog catalog = CreateAssemblyCatalogGuarded(file);
if (catalog != null)
{
catalogsToAdd.Add(new Tuple<string, AssemblyCatalog>(file, catalog));
}
}
IEnumerable<string> filesToRemove = beforeFiles.Except(afterFiles);
using (new ReadLock(_thisLock))
{
foreach (string file in filesToRemove)
{
AssemblyCatalog catalog;
if (_assemblyCatalogs.TryGetValue(file, out catalog))
{
catalogsToRemove.Add(new Tuple<string, AssemblyCatalog>(file, catalog));
}
}
}
}
private string GetDisplayName()
{
return string.Format(CultureInfo.CurrentCulture,
"{0} (Path=\"{1}\")", // NOLOC
GetType().Name,
_path);
}
private string[] GetFiles()
{
string[] files = Directory.GetFiles(_fullPath, _searchPattern);
return Array.ConvertAll<string, string>(files, (file) => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? file.ToUpperInvariant() : file);
}
private static string GetFullPath(string path)
{
var fullPath = IOPath.GetFullPath(path);
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? fullPath.ToUpperInvariant() : fullPath;
}
private void Initialize(string path, string searchPattern)
{
_path = path;
_fullPath = GetFullPath(path);
_searchPattern = searchPattern;
_assemblyCatalogs = new Dictionary<string, AssemblyCatalog>();
_catalogCollection = new ComposablePartCatalogCollection(null, null, null);
_loadedFiles = GetFiles().ToReadOnlyCollection();
foreach (string file in _loadedFiles)
{
AssemblyCatalog assemblyCatalog = null;
assemblyCatalog = CreateAssemblyCatalogGuarded(file);
if (assemblyCatalog != null)
{
_assemblyCatalogs.Add(file, assemblyCatalog);
_catalogCollection.Add(assemblyCatalog);
}
}
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
/// <summary>
/// Gets the display name of the directory catalog.
/// </summary>
/// <value>
/// A <see cref="String"/> containing a human-readable display name of the <see cref="DirectoryCatalog"/>.
/// </value>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
string ICompositionElement.DisplayName
{
get { return GetDisplayName(); }
}
/// <summary>
/// Gets the composition element from which the directory catalog originated.
/// </summary>
/// <value>
/// This property always returns <see langword="null"/>.
/// </value>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
ICompositionElement ICompositionElement.Origin
{
get { return null; }
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ResourceProperty.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Provides a type to describe properties on resources.
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services.Providers
{
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
/// <summary>Use this class to describe a property on a resource.</summary>
[DebuggerDisplay("{kind}: {name}")]
public class ResourceProperty
{
#region Private fields.
/// <summary>The name of this property.</summary>
private readonly string name;
/// <summary>The kind of resource Type that this property refers to.
/// For e.g. for collection properties, this would return the resource type,
/// and not the collection type that this property refers to.</summary>
private readonly ResourceType propertyResourceType;
/// <summary>The kind of property this is in relation to the resource.</summary>
private ResourcePropertyKind kind;
/// <summary> Is true, if this property is a actual clr property on the property type. In this case,
/// astoria service will do reflection over the property type and get/set value for this property.
/// False means that astoria service needs to go through the IDataServiceQueryProvider contract to get/set value for this provider.</summary>
private bool canReflectOnInstanceTypeProperty;
/// <summary>Is true, if the resource property is set to readonly i.e. fully initialized and validated. No more changes can be made,
/// once the resource property is set to readonly.</summary>
private bool isReadOnly;
/// <summary>MIME type for the property, if it's a primitive value.</summary>
private string mimeType;
#endregion Private fields.
/// <summary>
/// Initializes a new ResourceProperty instance for an open property.
/// </summary>
/// <param name="name">Property name for the property.</param>
/// <param name="kind">Property kind.</param>
/// <param name="propertyResourceType">The type of the resource that this property refers to</param>
public ResourceProperty(
string name,
ResourcePropertyKind kind,
ResourceType propertyResourceType)
{
WebUtil.CheckStringArgumentNull(name, "name");
WebUtil.CheckArgumentNull(propertyResourceType, "propertyResourceType");
ValidatePropertyParameters(kind, propertyResourceType);
this.kind = kind;
this.name = name;
this.propertyResourceType = propertyResourceType;
this.canReflectOnInstanceTypeProperty = true;
}
#region Properties
/// <summary>Indicates whether this property can be accessed through reflection on the declaring resource instance type.</summary>
/// <remarks>A 'true' value here typically indicates astoria service will use reflection to get the property info on the declaring ResourceType.InstanceType.
/// 'false' means that astoria service will go through IDataServiceQueryProvider interface to get/set this property's value.</remarks>
public bool CanReflectOnInstanceTypeProperty
{
get
{
return this.canReflectOnInstanceTypeProperty;
}
set
{
this.ThrowIfSealed();
this.canReflectOnInstanceTypeProperty = value;
}
}
/// <summary>
/// The resource type that is property refers to [For collection,
/// this will return the element of the collection, and not the
/// collection].
/// </summary>
public ResourceType ResourceType
{
[DebuggerStepThrough]
get { return this.propertyResourceType; }
}
/// <summary>The property name.</summary>
public string Name
{
[DebuggerStepThrough]
get { return this.name; }
}
/// <summary>MIME type for the property, if it's a primitive value; null if none specified.</summary>
public string MimeType
{
[DebuggerStepThrough]
get
{
return this.mimeType;
}
set
{
this.ThrowIfSealed();
if (String.IsNullOrEmpty(value))
{
throw new InvalidOperationException(Strings.ResourceProperty_MimeTypeAttributeEmpty(this.Name));
}
if (this.ResourceType.ResourceTypeKind != ResourceTypeKind.Primitive)
{
throw new InvalidOperationException(Strings.ResourceProperty_MimeTypeAttributeOnNonPrimitive(this.Name, this.ResourceType.FullName));
}
if (!WebUtil.IsValidMimeType(value))
{
throw new InvalidOperationException(Strings.ResourceProperty_MimeTypeNotValid(value, this.Name));
}
this.mimeType = value;
}
}
/// <summary>The kind of property this is in relation to the resource.</summary>
public ResourcePropertyKind Kind
{
[DebuggerStepThrough]
get
{
return this.kind;
}
[DebuggerStepThrough]
internal set
{
Debug.Assert(!this.isReadOnly, "Kind - the resource property cannot be readonly");
this.kind = value;
}
}
/// <summary>
/// PlaceHolder to hold custom state information about resource property.
/// </summary>
public object CustomState
{
get;
set;
}
/// <summary>
/// Returns true, if this resource property has been set to read only. Otherwise returns false.
/// </summary>
public bool IsReadOnly
{
get { return this.isReadOnly; }
}
/// <summary>The kind of type this property has in relation to the data service.</summary>
internal ResourceTypeKind TypeKind
{
get
{
return this.ResourceType.ResourceTypeKind;
}
}
/// <summary>The type of the property.</summary>
internal Type Type
{
get
{
if (this.Kind == ResourcePropertyKind.ResourceSetReference)
{
return typeof(System.Collections.Generic.IEnumerable<>).MakeGenericType(this.propertyResourceType.InstanceType);
}
else
{
return this.propertyResourceType.InstanceType;
}
}
}
#endregion Properties
#region Methods
/// <summary>
/// Sets the resource property to readonly. Once this method is called, no more changes can be made to resource property.
/// </summary>
public void SetReadOnly()
{
// If its already set to readonly, do no-op
if (this.isReadOnly)
{
return;
}
this.ResourceType.SetReadOnly();
this.isReadOnly = true;
}
/// <summary>
/// return true if this property is of the given kind
/// </summary>
/// <param name="checkKind">flag which needs to be checked on the current property kind</param>
/// <returns>true if the current property is of the given kind</returns>
internal bool IsOfKind(ResourcePropertyKind checkKind)
{
return ResourceProperty.IsOfKind(this.kind, checkKind);
}
/// <summary>
/// return true if the given property kind is of the given kind
/// </summary>
/// <param name="propertyKind">kind of the property</param>
/// <param name="kind">flag which needs to be checked on property kind</param>
/// <returns>true if the kind flag is set on the given property kind</returns>
private static bool IsOfKind(ResourcePropertyKind propertyKind, ResourcePropertyKind kind)
{
return ((propertyKind & kind) == kind);
}
/// <summary>
/// Validates that the given property kind is valid
/// </summary>
/// <param name="kind">property kind to check</param>
/// <param name="parameterName">name of the parameter</param>
private static void CheckResourcePropertyKind(ResourcePropertyKind kind, string parameterName)
{
// For open properties, resource property instance is created only for nav properties.
if (kind != ResourcePropertyKind.ResourceReference &&
kind != ResourcePropertyKind.ResourceSetReference &&
kind != ResourcePropertyKind.ComplexType &&
kind != ResourcePropertyKind.Primitive &&
kind != (ResourcePropertyKind.Primitive | ResourcePropertyKind.Key) &&
kind != (ResourcePropertyKind.Primitive | ResourcePropertyKind.ETag))
{
throw new ArgumentException(Strings.InvalidEnumValue(kind.GetType().Name), parameterName);
}
}
/// <summary>
/// Validate the parameters of the resource property constructor.
/// </summary>
/// <param name="kind">kind of the resource property.</param>
/// <param name="propertyResourceType">resource type that this property refers to.</param>
private static void ValidatePropertyParameters(ResourcePropertyKind kind, ResourceType propertyResourceType)
{
CheckResourcePropertyKind(kind, "kind");
if (IsOfKind(kind, ResourcePropertyKind.ResourceReference) || IsOfKind(kind, ResourcePropertyKind.ResourceSetReference))
{
if (propertyResourceType.ResourceTypeKind != ResourceTypeKind.EntityType)
{
throw new ArgumentException(Strings.ResourceProperty_PropertyKindAndResourceTypeKindMismatch("kind", "propertyResourceType"));
}
}
if (IsOfKind(kind, ResourcePropertyKind.Primitive))
{
if (propertyResourceType.ResourceTypeKind != ResourceTypeKind.Primitive)
{
throw new ArgumentException(Strings.ResourceProperty_PropertyKindAndResourceTypeKindMismatch("kind", "propertyResourceType"));
}
}
if (IsOfKind(kind, ResourcePropertyKind.ComplexType))
{
if (propertyResourceType.ResourceTypeKind != ResourceTypeKind.ComplexType)
{
throw new ArgumentException(Strings.ResourceProperty_PropertyKindAndResourceTypeKindMismatch("kind", "propertyResourceType"));
}
}
if (IsOfKind(kind, ResourcePropertyKind.Key) && Nullable.GetUnderlyingType(propertyResourceType.InstanceType) != null)
{
throw new ArgumentException(Strings.ResourceProperty_KeyPropertiesCannotBeNullable);
}
}
/// <summary>
/// Checks if the resource type is sealed. If not, it throws an InvalidOperationException.
/// </summary>
private void ThrowIfSealed()
{
if (this.isReadOnly)
{
throw new InvalidOperationException(Strings.ResourceProperty_Sealed(this.Name));
}
}
#endregion Methods
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Tracing;
using System.Reflection;
using System.Security;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
// Stops compiler from warning about unknown warnings
#pragma warning disable 1634, 1691
namespace System.Management.Automation
{
/// <summary>
/// Manager for JobSourceAdapters for invocation and management of specific Job types.
/// </summary>
public sealed class JobManager
{
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
/// <summary>
/// Collection of registered JobSourceAdapters.
/// </summary>
private readonly Dictionary<string, JobSourceAdapter> _sourceAdapters =
new Dictionary<string, JobSourceAdapter>();
private readonly object _syncObject = new object();
/// <summary>
/// Collection of job IDs that are valid for reuse.
/// </summary>
private static readonly Dictionary<Guid, KeyValuePair<int, string>> s_jobIdsForReuse = new Dictionary<Guid, KeyValuePair<int, string>>();
private static readonly object s_syncObject = new object();
/// <summary>
/// Creates a JobManager instance.
/// </summary>
internal JobManager()
{
}
/// <summary>
/// Returns true if the type is already registered.
/// </summary>
/// <param name="typeName">Type to check.</param>
/// <returns>Whether the type is registered already.</returns>
public bool IsRegistered(string typeName)
{
if (string.IsNullOrEmpty(typeName))
{
return false;
}
lock (_syncObject)
{
return _sourceAdapters.ContainsKey(typeName);
}
}
/// <summary>
/// Adds a new JobSourceAdapter to the JobManager instance.
/// After addition, creating a NewJob with a JobDefinition
/// indicating the JobSourceAdapter derivative type will function.
/// </summary>
/// <param name="jobSourceAdapterType">The derivative JobSourceAdapter type to
/// register.</param>
/// <exception cref="InvalidOperationException">Throws when there is no public
/// default constructor on the type.</exception>
internal void RegisterJobSourceAdapter(Type jobSourceAdapterType)
{
Dbg.Assert(typeof(JobSourceAdapter).IsAssignableFrom(jobSourceAdapterType), "BaseType of any type being registered with the JobManager should be JobSourceAdapter.");
Dbg.Assert(jobSourceAdapterType != typeof(JobSourceAdapter), "JobSourceAdapter abstract type itself should never be registered.");
Dbg.Assert(jobSourceAdapterType != null, "JobSourceAdapterType should never be called with null value.");
object instance = null;
ConstructorInfo constructor = jobSourceAdapterType.GetConstructor(Type.EmptyTypes);
if (!constructor.IsPublic)
{
string message = string.Format(CultureInfo.CurrentCulture,
RemotingErrorIdStrings.JobManagerRegistrationConstructorError,
jobSourceAdapterType.FullName);
throw new InvalidOperationException(message);
}
try
{
instance = constructor.Invoke(null);
}
catch (MemberAccessException exception)
{
_tracer.TraceException(exception);
throw;
}
catch (TargetInvocationException exception)
{
_tracer.TraceException(exception);
throw;
}
catch (TargetParameterCountException exception)
{
_tracer.TraceException(exception);
throw;
}
catch (NotSupportedException exception)
{
_tracer.TraceException(exception);
throw;
}
catch (SecurityException exception)
{
_tracer.TraceException(exception);
throw;
}
if (instance != null)
{
lock (_syncObject)
{
_sourceAdapters.Add(jobSourceAdapterType.Name, (JobSourceAdapter)instance);
}
}
}
/// <summary>
/// Returns a token that allows a job to be constructed with a specific id and instanceId.
/// The original job must have been saved using "SaveJobIdForReconstruction" in the JobSourceAdapter.
/// </summary>
/// <param name="instanceId">The instance id desired.</param>
/// <param name="typeName">The requesting type name for JobSourceAdapter implementation.</param>
/// <returns>Token for job creation.</returns>
internal static JobIdentifier GetJobIdentifier(Guid instanceId, string typeName)
{
lock (s_syncObject)
{
KeyValuePair<int, string> keyValuePair;
if (s_jobIdsForReuse.TryGetValue(instanceId, out keyValuePair) && keyValuePair.Value.Equals(typeName))
return new JobIdentifier(keyValuePair.Key, instanceId);
return null;
}
}
/// <summary>
/// Saves the Id information for a job so that it can be constructed at a later time by a JobSourceAdapter
/// with the same type.
/// </summary>
/// <param name="instanceId">The instance id to save.</param>
/// <param name="id">The session specific id to save.</param>
/// <param name="typeName">The type name for the JobSourceAdapter implementation doing the save.</param>
internal static void SaveJobId(Guid instanceId, int id, string typeName)
{
lock (s_syncObject)
{
if (s_jobIdsForReuse.ContainsKey(instanceId)) return;
s_jobIdsForReuse.Add(instanceId, new KeyValuePair<int, string>(id, typeName));
}
}
#region NewJob
/// <summary>
/// Creates a new job of the appropriate type given by JobDefinition passed in.
/// </summary>
/// <param name="definition">JobDefinition defining the command.</param>
/// <returns>Job2 object of the appropriate type specified by the definition.</returns>
/// <exception cref="InvalidOperationException">If JobSourceAdapter type specified
/// in definition is not registered.</exception>
/// <exception cref="Exception">JobSourceAdapter implementation exception thrown on error.
/// </exception>
public Job2 NewJob(JobDefinition definition)
{
if (definition == null)
{
throw new ArgumentNullException(nameof(definition));
}
JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition);
Job2 newJob;
#pragma warning disable 56500
try
{
newJob = sourceAdapter.NewJob(definition);
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
// sourceAdapter.NewJob returned unknown error.
_tracer.TraceException(exception);
throw;
}
#pragma warning restore 56500
return newJob;
}
/// <summary>
/// Creates a new job of the appropriate type given by JobDefinition passed in.
/// </summary>
/// <param name="specification">JobInvocationInfo defining the command.</param>
/// <returns>Job2 object of the appropriate type specified by the definition.</returns>
/// <exception cref="InvalidOperationException">If JobSourceAdapter type specified
/// in definition is not registered.</exception>
/// <exception cref="Exception">JobSourceAdapter implementation exception thrown on error.
/// </exception>
public Job2 NewJob(JobInvocationInfo specification)
{
if (specification == null)
{
throw new ArgumentNullException(nameof(specification));
}
if (specification.Definition == null)
{
throw new ArgumentException(RemotingErrorIdStrings.NewJobSpecificationError, nameof(specification));
}
JobSourceAdapter sourceAdapter = GetJobSourceAdapter(specification.Definition);
Job2 newJob = null;
#pragma warning disable 56500
try
{
newJob = sourceAdapter.NewJob(specification);
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
// sourceAdapter.NewJob returned unknown error.
_tracer.TraceException(exception);
throw;
}
#pragma warning restore 56500
return newJob;
}
#endregion NewJob
#region Persist Job
/// <summary>
/// Saves the job to a persisted store.
/// </summary>
/// <param name="job">Job2 type job to persist.</param>
/// <param name="definition">Job definition containing source adapter information.</param>
public void PersistJob(Job2 job, JobDefinition definition)
{
if (job == null)
{
throw new PSArgumentNullException(nameof(job));
}
if (definition == null)
{
throw new PSArgumentNullException(nameof(definition));
}
JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition);
try
{
sourceAdapter.PersistJob(job);
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
// sourceAdapter.NewJob returned unknown error.
_tracer.TraceException(exception);
throw;
}
}
#endregion
/// <summary>
/// Helper method, finds source adapter if registered, otherwise throws
/// an InvalidOperationException.
/// </summary>
/// <param name="adapterTypeName">The name of the JobSourceAdapter derivative desired.</param>
/// <returns>The JobSourceAdapter instance.</returns>
/// <exception cref="InvalidOperationException">If JobSourceAdapter type specified
/// is not found.</exception>
private JobSourceAdapter AssertAndReturnJobSourceAdapter(string adapterTypeName)
{
JobSourceAdapter adapter;
lock (_syncObject)
{
if (!_sourceAdapters.TryGetValue(adapterTypeName, out adapter))
{
throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound);
}
}
return adapter;
}
/// <summary>
/// Helper method to find and return the job source adapter if currently loaded or
/// otherwise load the associated module and the requested source adapter.
/// </summary>
/// <param name="definition">JobDefinition supplies the JobSourceAdapter information.</param>
/// <returns>JobSourceAdapter.</returns>
private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition)
{
string adapterTypeName;
if (!string.IsNullOrEmpty(definition.JobSourceAdapterTypeName))
{
adapterTypeName = definition.JobSourceAdapterTypeName;
}
else if (definition.JobSourceAdapterType != null)
{
adapterTypeName = definition.JobSourceAdapterType.Name;
}
else
{
throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound);
}
JobSourceAdapter adapter;
bool adapterFound = false;
lock (_syncObject)
{
adapterFound = _sourceAdapters.TryGetValue(adapterTypeName, out adapter);
}
if (!adapterFound)
{
if (!string.IsNullOrEmpty(definition.ModuleName))
{
// Attempt to load the module.
Exception ex = null;
try
{
InitialSessionState iss = InitialSessionState.CreateDefault2();
iss.Commands.Clear();
iss.Formats.Clear();
iss.Commands.Add(new SessionStateCmdletEntry("Import-Module", typeof(Microsoft.PowerShell.Commands.ImportModuleCommand), null));
using (PowerShell powerShell = PowerShell.Create(iss))
{
powerShell.AddCommand("Import-Module");
powerShell.AddParameter("Name", definition.ModuleName);
powerShell.Invoke();
if (powerShell.ErrorBuffer.Count > 0)
{
ex = powerShell.ErrorBuffer[0].Exception;
}
}
}
catch (RuntimeException e)
{
ex = e;
}
catch (InvalidOperationException e)
{
ex = e;
}
catch (ScriptCallDepthException e)
{
ex = e;
}
catch (SecurityException e)
{
ex = e;
}
if (ex != null)
{
throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound, ex);
}
// Now try getting the job source adapter again.
adapter = AssertAndReturnJobSourceAdapter(adapterTypeName);
}
else
{
throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound);
}
}
return adapter;
}
#region GetJobs
/// <summary>
/// Get list of all jobs.
/// </summary>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="jobSourceAdapterTypes">Job source adapter type names.</param>
/// <returns>Collection of jobs.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
internal List<Job2> GetJobs(
Cmdlet cmdlet,
bool writeErrorOnException,
bool writeObject,
string[] jobSourceAdapterTypes)
{
return GetFilteredJobs(null, FilterType.None, cmdlet, writeErrorOnException, writeObject, false, jobSourceAdapterTypes);
}
/// <summary>
/// Get list of jobs that matches the specified names.
/// </summary>
/// <param name="name">Names to match, can support
/// wildcard if the store supports.</param>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="recurse"></param>
/// <param name="jobSourceAdapterTypes">Job source adapter type names.</param>
/// <returns>Collection of jobs that match the specified
/// criteria.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
internal List<Job2> GetJobsByName(
string name,
Cmdlet cmdlet,
bool writeErrorOnException,
bool writeObject,
bool recurse,
string[] jobSourceAdapterTypes)
{
return GetFilteredJobs(name, FilterType.Name, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes);
}
/// <summary>
/// Get list of jobs that run the specified command.
/// </summary>
/// <param name="command">Command to match.</param>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="recurse"></param>
/// <param name="jobSourceAdapterTypes">Job source adapter type names.</param>
/// <returns>Collection of jobs that match the specified
/// criteria.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
internal List<Job2> GetJobsByCommand(
string command,
Cmdlet cmdlet,
bool writeErrorOnException,
bool writeObject,
bool recurse,
string[] jobSourceAdapterTypes)
{
return GetFilteredJobs(command, FilterType.Command, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes);
}
/// <summary>
/// Get list of jobs that are in the specified state.
/// </summary>
/// <param name="state">State to match.</param>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="recurse"></param>
/// <param name="jobSourceAdapterTypes">Job source adapter type names.</param>
/// <returns>Collection of jobs with the specified
/// state.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
internal List<Job2> GetJobsByState(
JobState state,
Cmdlet cmdlet,
bool writeErrorOnException,
bool writeObject,
bool recurse,
string[] jobSourceAdapterTypes)
{
return GetFilteredJobs(state, FilterType.State, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes);
}
/// <summary>
/// Get list of jobs based on the adapter specific
/// filter parameters.
/// </summary>
/// <param name="filter">Dictionary containing name value
/// pairs for adapter specific filters.</param>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="recurse"></param>
/// <returns>Collection of jobs that match the
/// specified criteria.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
internal List<Job2> GetJobsByFilter(Dictionary<string, object> filter, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse)
{
return GetFilteredJobs(filter, FilterType.Filter, cmdlet, writeErrorOnException, writeObject, recurse, null);
}
/// <summary>
/// Get a filtered list of jobs based on adapter name.
/// </summary>
/// <param name="id">Job id.</param>
/// <param name="name">Adapter name.</param>
/// <returns></returns>
internal bool IsJobFromAdapter(Guid id, string name)
{
lock (_syncObject)
{
foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values)
{
if (sourceAdapter.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return (sourceAdapter.GetJobByInstanceId(id, false) != null);
}
}
}
return false;
}
/// <summary>
/// Get a filtered list of jobs based on filter type.
/// </summary>
/// <param name="filter">Object to use for filtering.</param>
/// <param name="filterType">Type of filter, specifies which "get" from
/// JobSourceAdapter to call, and dictates the type for filter.</param>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="recurse"></param>
/// <param name="jobSourceAdapterTypes">Job source adapter type names.</param>
/// <returns>Filtered list of jobs.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
private List<Job2> GetFilteredJobs(
object filter,
FilterType filterType,
Cmdlet cmdlet,
bool writeErrorOnException,
bool writeObject,
bool recurse,
string[] jobSourceAdapterTypes)
{
Diagnostics.Assert(cmdlet != null, "Cmdlet should be passed to JobManager");
List<Job2> allJobs = new List<Job2>();
lock (_syncObject)
{
foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values)
{
List<Job2> jobs = null;
// Filter search based on job source adapter types if provided.
if (!CheckTypeNames(sourceAdapter, jobSourceAdapterTypes))
{
continue;
}
#pragma warning disable 56500
try
{
jobs = CallJobFilter(sourceAdapter, filter, filterType, recurse);
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
// sourceAdapter.GetJobsByFilter() threw unknown exception.
_tracer.TraceException(exception);
WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobsError", sourceAdapter);
}
#pragma warning restore 56500
if (jobs == null) continue;
allJobs.AddRange(jobs);
}
}
if (writeObject)
{
foreach (Job2 job in allJobs)
{
cmdlet.WriteObject(job);
}
}
return allJobs;
}
/// <summary>
/// Compare sourceAdapter name with the provided source adapter type
/// name list.
/// </summary>
/// <param name="sourceAdapter"></param>
/// <param name="jobSourceAdapterTypes"></param>
/// <returns></returns>
private static bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAdapterTypes)
{
// If no type names were specified then allow all adapter types.
if (jobSourceAdapterTypes == null ||
jobSourceAdapterTypes.Length == 0)
{
return true;
}
string sourceAdapterName = GetAdapterName(sourceAdapter);
Diagnostics.Assert(sourceAdapterName != null, "Source adapter should have name or type.");
// Look for name match allowing wildcards.
foreach (string typeName in jobSourceAdapterTypes)
{
WildcardPattern typeNamePattern = WildcardPattern.Get(typeName, WildcardOptions.IgnoreCase);
if (typeNamePattern.IsMatch(sourceAdapterName))
{
return true;
}
}
return false;
}
private static string GetAdapterName(JobSourceAdapter sourceAdapter)
{
return (!string.IsNullOrEmpty(sourceAdapter.Name) ?
sourceAdapter.Name :
sourceAdapter.GetType().ToString());
}
/// <summary>
/// Gets a filtered list of jobs from the given JobSourceAdapter.
/// </summary>
/// <param name="sourceAdapter">JobSourceAdapter to query.</param>
/// <param name="filter">Filter object.</param>
/// <param name="filterType">Filter type.</param>
/// <param name="recurse"></param>
/// <returns>List of jobs from sourceAdapter filtered on filterType.</returns>
/// <exception cref="Exception">Throws exception on error from JobSourceAdapter
/// implementation.</exception>
private static List<Job2> CallJobFilter(JobSourceAdapter sourceAdapter, object filter, FilterType filterType, bool recurse)
{
List<Job2> jobs = new List<Job2>();
IList<Job2> matches;
switch (filterType)
{
case FilterType.Command:
matches = sourceAdapter.GetJobsByCommand((string)filter, recurse);
break;
case FilterType.Filter:
matches = sourceAdapter.GetJobsByFilter((Dictionary<string, object>)filter, recurse);
break;
case FilterType.Name:
matches = sourceAdapter.GetJobsByName((string)filter, recurse);
break;
case FilterType.State:
matches = sourceAdapter.GetJobsByState((JobState)filter, recurse);
break;
case FilterType.None:
default:
matches = sourceAdapter.GetJobs();
break;
}
if (matches != null)
{
jobs.AddRange(matches);
}
return jobs;
}
/// <summary>
/// Get job specified by the session specific id provided.
/// </summary>
/// <param name="id">Session specific job id.</param>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="recurse"></param>
/// <returns>Job that match the specified criteria.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
internal Job2 GetJobById(int id, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse)
{
return GetJobThroughId<int>(Guid.Empty, id, cmdlet, writeErrorOnException, writeObject, recurse);
}
/// <summary>
/// Get job that has the specified id.
/// </summary>
/// <param name="instanceId">Guid to match.</param>
/// <param name="cmdlet">Cmdlet requesting this, for error processing.</param>
/// <param name="writeErrorOnException"></param>
/// <param name="writeObject"></param>
/// <param name="recurse"></param>
/// <returns>Job with the specified guid.</returns>
/// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from
/// JobSourceAdapter implementation.</exception>
internal Job2 GetJobByInstanceId(Guid instanceId, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse)
{
return GetJobThroughId<Guid>(instanceId, 0, cmdlet, writeErrorOnException, writeObject, recurse);
}
private Job2 GetJobThroughId<T>(Guid guid, int id, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse)
{
Diagnostics.Assert(cmdlet != null, "Cmdlet should always be passed to JobManager");
Job2 job = null;
lock (_syncObject)
{
foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values)
{
try
{
if (typeof(T) == typeof(Guid))
{
Diagnostics.Assert(id == 0, "id must be zero when invoked with guid");
job = sourceAdapter.GetJobByInstanceId(guid, recurse);
}
else if (typeof(T) == typeof(int))
{
Diagnostics.Assert(guid == Guid.Empty, "Guid must be empty when used with int");
job = sourceAdapter.GetJobBySessionId(id, recurse);
}
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
// sourceAdapter.GetJobByInstanceId threw unknown exception.
_tracer.TraceException(exception);
WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter);
}
if (job == null) continue;
if (writeObject)
{
cmdlet.WriteObject(job);
}
return job;
}
}
return null;
}
/// <summary>
/// Gets or creates a Job2 object with the given definition name, path
/// and definition type if specified, that can be run via the StartJob()
/// method.
/// </summary>
/// <param name="definitionName">Job definition name.</param>
/// <param name="definitionPath">Job definition file path.</param>
/// <param name="definitionType">JobSourceAdapter type that contains the job definition.</param>
/// <param name="cmdlet">Cmdlet making call.</param>
/// <param name="writeErrorOnException">Whether to write jobsourceadapter errors.</param>
/// <returns>List of matching Job2 objects.</returns>
internal List<Job2> GetJobToStart(
string definitionName,
string definitionPath,
string definitionType,
Cmdlet cmdlet,
bool writeErrorOnException)
{
List<Job2> jobs = new List<Job2>();
WildcardPattern typeNamePattern = (definitionType != null) ?
WildcardPattern.Get(definitionType, WildcardOptions.IgnoreCase) : null;
lock (_syncObject)
{
foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values)
{
try
{
if (typeNamePattern != null)
{
string sourceAdapterName = GetAdapterName(sourceAdapter);
if (!typeNamePattern.IsMatch(sourceAdapterName))
{
continue;
}
}
Job2 job = sourceAdapter.NewJob(definitionName, definitionPath);
if (job != null)
{
jobs.Add(job);
}
if (typeNamePattern != null)
{
// Adapter type found, can quit.
break;
}
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
_tracer.TraceException(exception);
WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter);
}
}
}
return jobs;
}
private static void WriteErrorOrWarning(bool writeErrorOnException, Cmdlet cmdlet, Exception exception, string identifier, JobSourceAdapter sourceAdapter)
{
try
{
if (writeErrorOnException)
{
cmdlet.WriteError(new ErrorRecord(exception, identifier, ErrorCategory.OpenError, sourceAdapter));
}
else
{
// Write a warning
string message = string.Format(CultureInfo.CurrentCulture,
RemotingErrorIdStrings.JobSourceAdapterError,
exception.Message,
sourceAdapter.Name);
cmdlet.WriteWarning(message);
}
}
catch (Exception)
{
// if this call is not made from a cmdlet thread or if
// the cmdlet is closed this will thrown an exception
// it is fine to eat that exception
}
}
/// <summary>
/// Returns a List of adapter names currently loaded.
/// </summary>
/// <param name="adapterTypeNames">Adapter names to filter on.</param>
/// <returns>List of names.</returns>
internal List<string> GetLoadedAdapterNames(string[] adapterTypeNames)
{
List<string> adapterNames = new List<string>();
lock (_syncObject)
{
foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values)
{
if (CheckTypeNames(sourceAdapter, adapterTypeNames))
{
adapterNames.Add(GetAdapterName(sourceAdapter));
}
}
}
return adapterNames;
}
#endregion GetJobs
#region RemoveJob
/// <summary>
/// Remove a job from the appropriate store.
/// </summary>
/// <param name="sessionJobId">Session specific Job ID to remove.</param>
/// <param name="cmdlet"></param>
/// <param name="writeErrorOnException"></param>
internal void RemoveJob(int sessionJobId, Cmdlet cmdlet, bool writeErrorOnException)
{
Job2 job = GetJobById(sessionJobId, cmdlet, writeErrorOnException, false, false);
RemoveJob(job, cmdlet, false);
}
/// <summary>
/// Remove a job from the appropriate store.
/// </summary>
/// <param name="job">Job object to remove.</param>
/// <param name="cmdlet"></param>
/// <param name="writeErrorOnException"></param>
/// <param name="throwExceptions">If true, will throw all JobSourceAdapter exceptions to caller.
/// This is needed if RemoveJob is being called from an event handler in Receive-Job.</param>
/// <returns>True if job is found.</returns>
internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, bool throwExceptions = false)
{
bool jobFound = false;
lock (_syncObject)
{
foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values)
{
Job2 foundJob = null;
#pragma warning disable 56500
try
{
foundJob = sourceAdapter.GetJobByInstanceId(job.InstanceId, true);
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
// sourceAdapter.GetJobByInstanceId() threw unknown exception.
_tracer.TraceException(exception);
if (throwExceptions) throw;
WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", sourceAdapter);
}
#pragma warning restore 56500
if (foundJob == null) continue;
jobFound = true;
RemoveJobIdForReuse(foundJob);
#pragma warning disable 56500
try
{
sourceAdapter.RemoveJob(job);
}
catch (Exception exception)
{
// Since we are calling into 3rd party code
// catching Exception is allowed. In all
// other cases the appropriate exception
// needs to be caught.
// sourceAdapter.RemoveJob() threw unknown exception.
_tracer.TraceException(exception);
if (throwExceptions) throw;
WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterRemoveJobError", sourceAdapter);
}
#pragma warning restore 56500
}
}
if (!jobFound && throwExceptions)
{
var message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository,
"Job repository", job.InstanceId.ToString());
throw new ArgumentException(message);
}
return jobFound;
}
private void RemoveJobIdForReuse(Job job)
{
Hashtable duplicateDetector = new Hashtable();
duplicateDetector.Add(job.Id, job.Id);
RemoveJobIdForReuseHelper(duplicateDetector, job);
}
private void RemoveJobIdForReuseHelper(Hashtable duplicateDetector, Job job)
{
lock (s_syncObject)
{
s_jobIdsForReuse.Remove(job.InstanceId);
}
foreach (Job child in job.ChildJobs)
{
if (duplicateDetector.ContainsKey(child.Id))
{
continue;
}
duplicateDetector.Add(child.Id, child.Id);
RemoveJobIdForReuse(child);
}
}
#endregion RemoveJob
/// <summary>
/// Filters available for GetJob, used internally to centralize Exception handling.
/// </summary>
private enum FilterType
{
/// <summary>
/// Use no filter.
/// </summary>
None,
/// <summary>
/// Filter on command (string).
/// </summary>
Command,
/// <summary>
/// Filter on custom dictionary (dictionary(string, object)).
/// </summary>
Filter,
/// <summary>
/// Filter on name (string).
/// </summary>
Name,
/// <summary>
/// Filter on job state (JobState).
/// </summary>
State
}
}
}
| |
namespace Host.UnitTests.Serialization.Json
{
using System;
using System.Globalization;
using System.IO;
using System.Text;
using Crest.Host.Serialization.Json;
using FluentAssertions;
using Xunit;
public class JsonStreamWriterTests : IDisposable
{
private readonly MemoryStream stream = new MemoryStream();
private readonly JsonStreamWriter writer;
protected JsonStreamWriterTests()
{
this.writer = new JsonStreamWriter(this.stream);
}
public void Dispose()
{
this.stream.Dispose();
}
private string GetString<T>(Action<T> write, T value)
{
this.stream.SetLength(0);
write(value);
this.writer.Flush();
return Encoding.UTF8.GetString(this.stream.ToArray());
}
public sealed class WriteBoolean : JsonStreamWriterTests
{
[Fact]
public void ShouldWriteFalse()
{
string result = this.GetString(this.writer.WriteBoolean, false);
result.Should().Be("false");
}
[Fact]
public void ShouldWriteTrue()
{
string result = this.GetString(this.writer.WriteBoolean, true);
result.Should().Be("true");
}
}
public sealed class WriteChar : JsonStreamWriterTests
{
[Fact]
public void ShouldOutputTheChar()
{
string result = this.GetString(this.writer.WriteChar, 'T');
result.Should().Be("\"T\"");
}
}
public sealed class WriteDateTime : JsonStreamWriterTests
{
// This tests the methods required by the base method to rent/commit
// the buffer work. DateTime is chosen as it's simple and also
// writes a smaller value than the buffer size requested.
[Fact]
public void ShouldTheValue()
{
var dateTime = new DateTime(2017, 1, 2, 13, 14, 15, DateTimeKind.Utc);
string result = this.GetString(this.writer.WriteDateTime, dateTime);
result.Should().Be("\"2017-01-02T13:14:15Z\"");
}
}
public sealed class WriteDecimal : JsonStreamWriterTests
{
[Fact]
public void ShouldWriteTheNumber()
{
string result = this.GetString(this.writer.WriteDecimal, 123.4m);
result.Should().BeEquivalentTo("123.4");
}
}
public sealed class WriteDouble : JsonStreamWriterTests
{
[Theory]
[InlineData(double.NaN)]
[InlineData(double.NegativeInfinity)]
[InlineData(double.PositiveInfinity)]
public void ShouldNotAllowInvalidJsonValues(double value)
{
// JSON numbers can't be all the valid values of our good old
// IEEE double precision floating point number :(
this.writer.Invoking(w => w.WriteDouble(value))
.Should().Throw<ArgumentOutOfRangeException>();
}
[Fact]
public void ShouldWriteTheNumber()
{
string result = this.GetString(this.writer.WriteDouble, 123.4);
result.Should().BeEquivalentTo("123.4");
}
}
public sealed class WriteInt64 : JsonStreamWriterTests
{
[Theory]
[InlineData(long.MinValue)]
[InlineData(0)]
[InlineData(long.MaxValue)]
public void ShouldWriteIntegerLimits(long value)
{
string result = this.GetString(this.writer.WriteInt64, value);
result.Should().Be(value.ToString(CultureInfo.InvariantCulture));
}
}
public sealed class WriteNull : JsonStreamWriterTests
{
[Fact]
public void ShouldWriteNull()
{
this.writer.WriteNull();
this.writer.Flush();
string result = Encoding.UTF8.GetString(this.stream.ToArray());
result.Should().Be("null");
}
}
public sealed class WriteSingle : JsonStreamWriterTests
{
[Theory]
[InlineData(float.NaN)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
public void ShouldNotAllowInvalidJsonValues(float value)
{
// See remarks in WriteDouble tests
this.writer.Invoking(w => w.WriteSingle(value))
.Should().Throw<ArgumentOutOfRangeException>();
}
[Fact]
public void ShouldWriteTheNumber()
{
string result = this.GetString(this.writer.WriteSingle, 123.4f);
result.Should().BeEquivalentTo("123.4");
}
}
public sealed class WriteString : JsonStreamWriterTests
{
[Fact]
public void ShouldOutputLongStrings()
{
// This tests the buffer gets flushed when it's full
string longString = new string('a', 2000);
string result = this.GetString(this.writer.WriteString, longString);
// Remove the surrounding quotes
result.Substring(1, result.Length - 2)
.Should().Be(longString);
}
[Fact]
public void ShouldOutputTheString()
{
string result = this.GetString(this.writer.WriteString, @"Test\Data");
result.Should().Be(@"""Test\\Data""");
}
}
public sealed class WriteUInt64 : JsonStreamWriterTests
{
[Theory]
[InlineData(0)]
[InlineData(ulong.MaxValue)]
public void ShouldWriteIntegerLimits(ulong value)
{
string stringValue = this.GetString(this.writer.WriteUInt64, value);
stringValue.Should().Be(value.ToString(CultureInfo.InvariantCulture));
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using Microsoft.Web.Administration;
using WebsitePanel.Providers.Common;
using WebsitePanel.Server.Utils;
using System;
using System.Linq;
using CertEnrollInterop;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using WebsitePanel.Providers.Web.Iis.Common;
using System.Security;
using WebsitePanel.Providers.Web.Iis.WebObjects;
namespace WebsitePanel.Providers.Web.Iis
{
public class SSLModuleService : ConfigurationModuleService
{
public void GenerateCsr(SSLCertificate cert)
{
// Create all the objects that will be required
CX509CertificateRequestPkcs10 pkcs10 = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509CertificateRequestPkcs10", true)) as CX509CertificateRequestPkcs10;
CX509PrivateKey privateKey = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey", true)) as CX509PrivateKey;
CCspInformation csp = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformation", true)) as CCspInformation;
CCspInformations csPs = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformations", true)) as CCspInformations;
CX500DistinguishedName dn = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX500DistinguishedName", true)) as CX500DistinguishedName;
CX509Enrollment enroll = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment;
CObjectIds objectIds = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectIds", true)) as CObjectIds;
CObjectId objectId = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectId", true)) as CObjectId;
CX509ExtensionKeyUsage extensionKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionKeyUsage", true)) as CX509ExtensionKeyUsage;
CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionEnhancedKeyUsage", true)) as CX509ExtensionEnhancedKeyUsage;
try
{
// Initialize the csp object using the desired Cryptograhic Service Provider (CSP)
csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider");
// Add this CSP object to the CSP collection object
csPs.Add(csp);
// Provide key container name, key length and key spec to the private key object
privateKey.Length = cert.CSRLength;
privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
privateKey.ExportPolicy =
X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG
| X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_ARCHIVING_FLAG
| X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_ARCHIVING_FLAG
| X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
privateKey.MachineContext = true;
// Provide the CSP collection object (in this case containing only 1 CSP object)
// to the private key object
privateKey.CspInformations = csPs;
// Create the actual key pair
privateKey.Create();
// Initialize the PKCS#10 certificate request object based on the private key.
// Using the context, indicate that this is a user certificate request and don't
// provide a template name
pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
cert.PrivateKey = privateKey.ToString();
// Key Usage Extension
extensionKeyUsage.InitializeEncode(
CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE |
CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE |
CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE |
CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE
);
pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage);
// Enhanced Key Usage Extension
objectId.InitializeFromName(CertEnrollInterop.CERTENROLL_OBJECTID.XCN_OID_PKIX_KP_SERVER_AUTH);
objectIds.Add(objectId);
x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds);
pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage);
// Encode the name in using the Distinguished Name object
string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country);
dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE);
// enable SMIME capabilities
pkcs10.SmimeCapabilities = true;
// Assing the subject name by using the Distinguished Name object initialized above
pkcs10.Subject = dn;
// Create enrollment request
enroll.InitializeFromRequest(pkcs10);
enroll.CertificateFriendlyName = cert.FriendlyName;
cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER);
}
catch (Exception ex)
{
Log.WriteError("Error creating CSR", ex);
}
}
public SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website)
{
CX509Enrollment response = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment;
try
{
response.Initialize(X509CertificateEnrollmentContext.ContextMachine);
response.InstallResponse(
InstallResponseRestrictionFlags.AllowUntrustedRoot,
cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER,
null
);
SSLCertificate servercert = (from c in GetServerCertificates()
where c.FriendlyName == cert.FriendlyName
select c).Single();
cert.SerialNumber = servercert.SerialNumber;
cert.ValidFrom = servercert.ValidFrom;
cert.ExpiryDate = servercert.ExpiryDate;
cert.Hash = servercert.Hash;
cert.DistinguishedName = servercert.DistinguishedName;
if (cert.IsRenewal && CheckCertificate(website))
{
DeleteCertificate(GetCurrentSiteCertificate(website), website);
}
AddBinding(cert, website);
}
catch (Exception ex)
{
Log.WriteError("Error adding SSL certificate", ex);
cert.Success = false;
}
return cert;
}
public List<SSLCertificate> GetServerCertificates()
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
//
var certificates = new List<SSLCertificate>();
//
try
{
store.Open(OpenFlags.ReadOnly);
//
certificates = (from X509Certificate2 cert in store.Certificates
let hostname = cert.GetNameInfo(X509NameType.SimpleName, false)
select new SSLCertificate()
{
FriendlyName = cert.FriendlyName,
Hostname = hostname,
Hash = cert.GetCertHash(),
SerialNumber = cert.SerialNumber,
ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()),
ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()),
DistinguishedName = cert.Subject
}).ToList();
}
catch (Exception ex)
{
Log.WriteError(
String.Format("SSLModuleService is unable to get certificates from X509Store('{0}', '{1}') and complete GetServerCertificates call", store.Name, store.Location), ex);
// Re-throw exception
throw;
}
finally
{
store.Close();
}
//
return certificates;
}
public SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
//
SSLCertificate newcert = null, oldcert = null;
// Ensure we perform operations safely and preserve the original state during all manipulations
if (CheckCertificate(website))
oldcert = GetCurrentSiteCertificate(website);
//
X509Certificate2 x509Cert = new X509Certificate2(certificate, password);
#region Step 1: Register X.509 certificate in the store
// Trying to keep X.509 store open as less as possible
try
{
store.Open(OpenFlags.ReadWrite);
//
store.Add(x509Cert);
}
catch (Exception ex)
{
Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex);
// Re-throw error
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 2: Instantiate a copy of new X.509 certificate
try
{
//
store.Open(OpenFlags.ReadWrite);
//
newcert = new SSLCertificate
{
Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false),
FriendlyName = x509Cert.FriendlyName,
CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()),
Installed = true,
DistinguishedName = x509Cert.Subject,
Hash = x509Cert.GetCertHash(),
SerialNumber = x509Cert.SerialNumber,
ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()),
ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()),
};
}
catch (Exception ex)
{
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log error
Log.WriteError("SSLModuleService could not instantiate a copy of new X.509 certificate. All previous changes have been rolled back.", ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 3: Remove old certificate from the web site if any
try
{
store.Open(OpenFlags.ReadWrite);
// Check if certificate already exists, remove it.
if (oldcert != null)
DeleteCertificate(oldcert, website);
}
catch (Exception ex)
{
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log the error
Log.WriteError(
String.Format("SSLModuleService could not remove existing certificate from '{0}' web site. All changes have been rolled back.", website.Name), ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 4: Register new certificate with HTTPS binding on the web site
try
{
store.Open(OpenFlags.ReadWrite);
//
AddBinding(newcert, website);
}
catch (Exception ex)
{
// Install old certificate back if any
if (oldcert != null)
InstallCertificate(oldcert, website);
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log the error
Log.WriteError(
String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site. All changes have been rolled back.", website.Name), ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
//
return newcert;
}
public byte[] ExportPfx(string serialNumber, string password)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, false)[0];
byte[] exported = cert.Export(X509ContentType.Pfx, password);
return exported;
}
public void AddBinding(SSLCertificate certificate, WebSite website)
{
using (ServerManager srvman = GetServerManager())
{
// Not sure why do we need to work with X.509 store here, so commented it out and lets see what happens
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
//
List<ServerBinding> bindings = new List<ServerBinding>();
// Retrieve existing site bindings to figure out what do we have here
WebObjectsModuleService webObjSvc = new WebObjectsModuleService();
bindings.AddRange(webObjSvc.GetSiteBindings(srvman, website.SiteId));
// Look for dedicated ip
bool dedicatedIp = bindings.Exists(binding => String.IsNullOrEmpty(binding.Host) && binding.IP != "*");
//
string bindingInformation;
//
bindingInformation = dedicatedIp ? string.Format("{0}:443:", website.SiteIPAddress)
: string.Format("{0}:443:{1}", website.SiteIPAddress, certificate.Hostname);
//
srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, certificate.Hash, store.Name);
//
store.Close();
//
srvman.CommitChanges();
}
}
public void RemoveBinding(SSLCertificate certificate, WebSite website)
{
using (ServerManager sm = GetServerManager())
{
Site site = sm.Sites[website.SiteId];
Binding sslbind = (from b in site.Bindings
where b.Protocol == "https"
select b).Single();
site.Bindings.Remove(sslbind);
sm.CommitChanges();
}
}
public SSLCertificate FindByFriendlyname(string name)
{
throw new NotImplementedException("Method not implemented");
}
public ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website)
{
ResultObject result = new ResultObject();
try
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.MaxAllowed);
X509Certificate2 cert =
store.Certificates.Find(X509FindType.FindBySerialNumber, certificate.SerialNumber, false)[0];
store.Remove(cert);
store.Close();
RemoveBinding(certificate, website);
result.IsSuccess = true;
}
catch (Exception ex)
{
result.IsSuccess = false;
result.AddError("", ex);
}
return result;
}
public SSLCertificate ImportCertificate(WebSite website)
{
SSLCertificate certificate = new SSLCertificate { Success = false };
try
{
using (ServerManager sm = GetServerManager())
{
Site site = sm.Sites[website.SiteId];
Binding sslbind = (from b in site.Bindings
where b.Protocol == "https"
select b).Single();
certificate.Hash = sslbind.CertificateHash;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.MaxAllowed);
X509Certificate2 x509Cert = (from X509Certificate2 c in store.Certificates
where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(certificate.Hash)
select c).Single();
store.Close();
certificate.Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false);
certificate.FriendlyName = x509Cert.FriendlyName;
certificate.CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString());
certificate.Installed = true;
certificate.DistinguishedName = x509Cert.Subject;
certificate.Hash = x509Cert.GetCertHash();
certificate.SerialNumber = x509Cert.SerialNumber;
certificate.ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString());
certificate.ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString());
certificate.Success = true;
}
}
catch (Exception ex)
{
certificate.Success = false;
certificate.Certificate = ex.ToString();
}
return certificate;
}
//Checks to see if the site has a certificate
public bool CheckCertificate(WebSite website)
{
using (var sm = GetServerManager())
{
//
Site site = sm.Sites[website.SiteId];
// Just exit from the loop if https binding found
foreach (Binding bind in site.Bindings.Where(bind => bind.Protocol == "https"))
return true;
//
return false;
}
}
public SSLCertificate GetCurrentSiteCertificate(WebSite website)
{
using (ServerManager sm = GetServerManager())
{
Site site = sm.Sites[website.SiteId];
Binding sslbind = (from b in site.Bindings
where b.Protocol == "https"
select b).Single();
byte[] currentHash = sslbind.CertificateHash;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 oldcertificate = (from X509Certificate2 c in store.Certificates
where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(currentHash)
select c).Single();
store.Close();
SSLCertificate certificate = new SSLCertificate();
certificate.Hash = oldcertificate.GetCertHash();
certificate.SerialNumber = oldcertificate.SerialNumber;
return certificate;
}
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Returns information about Amazon EBS snapshots available to the user.
/// </summary>
/// <remarks>
/// Information returned includes volume ID, status, start time, progress,
/// owner ID, volume size, and description. Snapshots available to the user
/// include public snapshots available for any user to launch, private
/// snapshots owned by the user making the request, and private snapshots
/// owned by other users for which the user granted explicit create
/// volume permissions.
///
/// The create volume permissions fall into 3 categories:
///
/// public
///
/// The owner of the snapshot granted create volume permissions for the
/// snapshot to the all group. All users have create volume permissions
/// for these snapshots.
///
/// explicit
///
/// The owner of the snapshot granted create volume permissions to a
/// specific user.
///
/// implicit
///
/// A user has implicit create volume permissions for all snapshots he
/// or she owns.
///
/// The list of snapshots returned can be modified by specifying
/// snapshot IDs, snapshot owners, or users with create volume permissions.
///
/// If no options are specified, Amazon EC2 returns all snapshots for
/// which the user has create volume permissions.
///
/// If you specify one or more snapshot IDs, only snapshots that have
/// the specified IDs are returned. If you specify an invalid snapshot ID,
/// a fault is returned. If you specify a snapshot ID for which you do not
/// have access, it will not be included in the returned results.
///
/// If you specify one or more snapshot owners, only snapshots from the
/// specified owners and for which you have access are returned. The
/// results can include the AWS Account IDs of the specified owners,
/// amazon for snapshots owned by Amazon or self for snapshots that you own.
///
/// If you specify a list of restorable users, only users that
/// have create snapshot permissions for the snapshots are returned.
/// You can specify AWS Account IDs (if you own the snapshot(s)), self for
/// snapshots for which you own or have explicit permissions, or all for
/// public snapshots.
/// </remarks>
[XmlRootAttribute(IsNullable = false)]
public class DescribeSnapshotsRequest : EC2Request
{
private List<string> snapshotIdField;
private string ownerField;
private string restorableByField;
private List<Filter> filterField;
/// <summary>
/// One or more snapshot IDs.
/// </summary>
[XmlElementAttribute(ElementName = "SnapshotId")]
public List<string> SnapshotId
{
get
{
if (this.snapshotIdField == null)
{
this.snapshotIdField = new List<string>();
}
return this.snapshotIdField;
}
set { this.snapshotIdField = value; }
}
/// <summary>
/// Sets snapshot IDs.
/// </summary>
/// <param name="list">The ID of the Amazon EBS snapshot.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeSnapshotsRequest WithSnapshotId(params string[] list)
{
foreach (string item in list)
{
SnapshotId.Add(item);
}
return this;
}
/// <summary>
/// Checks if SnapshotId property is set
/// </summary>
/// <returns>true if SnapshotId property is set</returns>
public bool IsSetSnapshotId()
{
return (SnapshotId.Count > 0);
}
/// <summary>
/// Owner of the snapshots to return.
/// Valid Values: self |amazon | AWS Account ID
/// </summary>
[XmlElementAttribute(ElementName = "Owner")]
public string Owner
{
get { return this.ownerField; }
set { this.ownerField = value; }
}
/// <summary>
/// Sets the owner of the snapshots to return.
/// </summary>
/// <param name="owner">Returns snapshots owned by the specified
/// owner. Valid Values: self | amazon | AWS Account ID</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeSnapshotsRequest WithOwner(string owner)
{
this.ownerField = owner;
return this;
}
/// <summary>
/// Checks if Owner property is set
/// </summary>
/// <returns>true if Owner property is set</returns>
public bool IsSetOwner()
{
return this.ownerField != null;
}
/// <summary>
/// Account ID of a user that can create volumes from the snapshot.
/// </summary>
[XmlElementAttribute(ElementName = "RestorableBy")]
public string RestorableBy
{
get { return this.restorableByField; }
set { this.restorableByField = value; }
}
/// <summary>
/// Sets the Account ID of a user that can create volumes from the snapshot.
/// </summary>
/// <param name="restorableBy">Account ID of a user that can create volumes
/// from the snapshot.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeSnapshotsRequest WithRestorableBy(string restorableBy)
{
this.restorableByField = restorableBy;
return this;
}
/// <summary>
/// Checks if RestorableBy property is set
/// </summary>
/// <returns>true if RestorableBy property is set</returns>
public bool IsSetRestorableBy()
{
return this.restorableByField != null;
}
/// <summary>
/// A list of filters used to match system-defined properties and user-defined tags associated with
/// the specified Snapshots.
/// For a complete reference to the available filter keys for this operation, see the
/// Amazon EC2 API reference.
/// </summary>
[XmlElementAttribute(ElementName = "Filter")]
public List<Filter> Filter
{
get
{
if (this.filterField == null)
{
this.filterField = new List<Filter>();
}
return this.filterField;
}
set { this.filterField = value; }
}
/// <summary>
/// Sets filters used to match system-defined properties and user-defined tags associated with
/// the specified Snapshots.
/// </summary>
/// <param name="list">A list of filters used to match system-defined properties and user-defined tags associated with
/// the specified Snapshots.
/// For a complete reference to the available filter keys for this operation, see the
/// Amazon EC2 API reference.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeSnapshotsRequest WithFilter(params Filter[] list)
{
foreach (Filter item in list)
{
Filter.Add(item);
}
return this;
}
/// <summary>
/// Checks if Filter property is set
/// </summary>
/// <returns>true if Filter property is set</returns>
public bool IsSetFilter()
{
return (Filter.Count > 0);
}
}
}
| |
/*
* Copyright 2006 Jeremias Maerki in part, and ZXing Authors in part
*
* 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.
*/
/*
* This file has been modified from its original form in Barcode4J.
*/
using System;
#if SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NETFX_CORE
using System.Numerics;
#else
using BigIntegerLibrary;
#endif
using System.Text;
using ZXing.Common;
namespace ZXing.PDF417.Internal
{
/// <summary>
/// PDF417 high-level encoder following the algorithm described in ISO/IEC 15438:2001(E) in
/// annex P.
/// </summary>
internal static class PDF417HighLevelEncoder
{
/// <summary>
/// code for Text compaction
/// </summary>
private const int TEXT_COMPACTION = 0;
/// <summary>
/// code for Byte compaction
/// </summary>
private const int BYTE_COMPACTION = 1;
/// <summary>
/// code for Numeric compaction
/// </summary>
private const int NUMERIC_COMPACTION = 2;
/// <summary>
/// Text compaction submode Alpha
/// </summary>
private const int SUBMODE_ALPHA = 0;
/// <summary>
/// Text compaction submode Lower
/// </summary>
private const int SUBMODE_LOWER = 1;
/// <summary>
/// Text compaction submode Mixed
/// </summary>
private const int SUBMODE_MIXED = 2;
/// <summary>
/// Text compaction submode Punctuation
/// </summary>
private const int SUBMODE_PUNCTUATION = 3;
/// <summary>
/// mode latch to Text Compaction mode
/// </summary>
private const int LATCH_TO_TEXT = 900;
/// <summary>
/// mode latch to Byte Compaction mode (number of characters NOT a multiple of 6)
/// </summary>
private const int LATCH_TO_BYTE_PADDED = 901;
/// <summary>
/// mode latch to Numeric Compaction mode
/// </summary>
private const int LATCH_TO_NUMERIC = 902;
/// <summary>
/// mode shift to Byte Compaction mode
/// </summary>
private const int SHIFT_TO_BYTE = 913;
/// <summary>
/// mode latch to Byte Compaction mode (number of characters a multiple of 6)
/// </summary>
private const int LATCH_TO_BYTE = 924;
/// <summary>
/// identifier for a user defined Extended Channel Interpretation (ECI)
/// </summary>
private const int ECI_USER_DEFINED = 925;
/// <summary>
/// identifier for a general purpose ECO format
/// </summary>
private const int ECI_GENERAL_PURPOSE = 926;
/// <summary>
/// identifier for an ECI of a character set of code page
/// </summary>
private const int ECI_CHARSET = 927;
/// <summary>
/// Raw code table for text compaction Mixed sub-mode
/// </summary>
private static readonly sbyte[] TEXT_MIXED_RAW =
{
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 38, 13, 9, 44, 58,
35, 45, 46, 36, 47, 43, 37, 42, 61, 94, 0, 32, 0, 0, 0
};
/// <summary>
/// Raw code table for text compaction: Punctuation sub-mode
/// </summary>
private static readonly sbyte[] TEXT_PUNCTUATION_RAW =
{
59, 60, 62, 64, 91, 92, 93, 95, 96, 126, 33, 13, 9, 44, 58,
10, 45, 46, 36, 47, 34, 124, 42, 40, 41, 63, 123, 125, 39, 0
};
private static readonly sbyte[] MIXED = new sbyte[128];
private static readonly sbyte[] PUNCTUATION = new sbyte[128];
internal static Encoding DEFAULT_ENCODING;
static PDF417HighLevelEncoder()
{
//Construct inverse lookups
for (int idx = 0; idx < MIXED.Length; idx++)
MIXED[idx] = -1;
for (sbyte i = 0; i < TEXT_MIXED_RAW.Length; i++)
{
sbyte b = TEXT_MIXED_RAW[i];
if (b > 0)
{
MIXED[b] = i;
}
}
for (int idx = 0; idx < PUNCTUATION.Length; idx++)
PUNCTUATION[idx] = -1;
for (sbyte i = 0; i < TEXT_PUNCTUATION_RAW.Length; i++)
{
sbyte b = TEXT_PUNCTUATION_RAW[i];
if (b > 0)
{
PUNCTUATION[b] = i;
}
}
#if WindowsCE
try
{
DEFAULT_ENCODING = Encoding.GetEncoding("CP437");
}
catch (PlatformNotSupportedException)
{
// WindowsCE doesn't support all encodings. But it is device depended.
// So we try here the some different ones
DEFAULT_ENCODING = Encoding.GetEncoding(1252);
}
#elif !SILVERLIGHT || WINDOWS
DEFAULT_ENCODING = Encoding.GetEncoding("CP437");
#else
// Silverlight supports only UTF-8 and UTF-16 out-of-the-box
DEFAULT_ENCODING = Encoding.GetEncoding("UTF-8");
#endif
}
/// <summary>
/// Performs high-level encoding of a PDF417 message using the algorithm described in annex P
/// of ISO/IEC 15438:2001(E). If byte compaction has been selected, then only byte compaction
/// is used.
///
/// <param name="msg">the message</param>
/// <returns>the encoded message (the char values range from 0 to 928)</returns>
/// </summary>
internal static String encodeHighLevel(String msg, Compaction compaction, Encoding encoding, bool disableEci)
{
//the codewords 0..928 are encoded as Unicode characters
var sb = new StringBuilder(msg.Length);
if (!DEFAULT_ENCODING.Equals(encoding) && !disableEci)
{
CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding.WebName);
if (eci != null)
{
encodingECI(eci.Value, sb);
}
}
int len = msg.Length;
int p = 0;
int textSubMode = SUBMODE_ALPHA;
// User selected encoding mode
byte[] bytes = null; //Fill later and only if needed
if (compaction == Compaction.TEXT)
{
encodeText(msg, p, len, sb, textSubMode);
}
else if (compaction == Compaction.BYTE)
{
bytes = encoding.GetBytes(msg);
encodeBinary(bytes, p, bytes.Length, BYTE_COMPACTION, sb);
}
else if (compaction == Compaction.NUMERIC)
{
sb.Append((char) LATCH_TO_NUMERIC);
encodeNumeric(msg, p, len, sb);
}
else
{
int encodingMode = TEXT_COMPACTION; //Default mode, see 4.4.2.1
while (p < len)
{
int n = determineConsecutiveDigitCount(msg, p);
if (n >= 13)
{
sb.Append((char) LATCH_TO_NUMERIC);
encodingMode = NUMERIC_COMPACTION;
textSubMode = SUBMODE_ALPHA; //Reset after latch
encodeNumeric(msg, p, n, sb);
p += n;
}
else
{
int t = determineConsecutiveTextCount(msg, p);
if (t >= 5 || n == len)
{
if (encodingMode != TEXT_COMPACTION)
{
sb.Append((char) LATCH_TO_TEXT);
encodingMode = TEXT_COMPACTION;
textSubMode = SUBMODE_ALPHA; //start with submode alpha after latch
}
textSubMode = encodeText(msg, p, t, sb, textSubMode);
p += t;
}
else
{
if (bytes == null)
{
bytes = encoding.GetBytes(msg);
}
int b = determineConsecutiveBinaryCount(msg, bytes, p);
if (b == 0)
{
b = 1;
}
if (b == 1 && encodingMode == TEXT_COMPACTION)
{
//Switch for one byte (instead of latch)
encodeBinary(bytes, p, 1, TEXT_COMPACTION, sb);
}
else
{
//Mode latch performed by encodeBinary()
encodeBinary(bytes, p, b, encodingMode, sb);
encodingMode = BYTE_COMPACTION;
textSubMode = SUBMODE_ALPHA; //Reset after latch
}
p += b;
}
}
}
}
return sb.ToString();
}
/// <summary>
/// Encode parts of the message using Text Compaction as described in ISO/IEC 15438:2001(E),
/// chapter 4.4.2.
///
/// <param name="msg">the message</param>
/// <param name="startpos">the start position within the message</param>
/// <param name="count">the number of characters to encode</param>
/// <param name="sb">receives the encoded codewords</param>
/// <param name="initialSubmode">should normally be SUBMODE_ALPHA</param>
/// <returns>the text submode in which this method ends</returns>
/// </summary>
private static int encodeText(String msg,
int startpos,
int count,
StringBuilder sb,
int initialSubmode)
{
StringBuilder tmp = new StringBuilder(count);
int submode = initialSubmode;
int idx = 0;
while (true)
{
char ch = msg[startpos + idx];
switch (submode)
{
case SUBMODE_ALPHA:
if (isAlphaUpper(ch))
{
if (ch == ' ')
{
tmp.Append((char) 26); //space
}
else
{
tmp.Append((char) (ch - 65));
}
}
else
{
if (isAlphaLower(ch))
{
submode = SUBMODE_LOWER;
tmp.Append((char) 27); //ll
continue;
}
else if (isMixed(ch))
{
submode = SUBMODE_MIXED;
tmp.Append((char) 28); //ml
continue;
}
else
{
tmp.Append((char) 29); //ps
tmp.Append((char) PUNCTUATION[ch]);
break;
}
}
break;
case SUBMODE_LOWER:
if (isAlphaLower(ch))
{
if (ch == ' ')
{
tmp.Append((char) 26); //space
}
else
{
tmp.Append((char) (ch - 97));
}
}
else
{
if (isAlphaUpper(ch))
{
tmp.Append((char) 27); //as
tmp.Append((char) (ch - 65));
//space cannot happen here, it is also in "Lower"
break;
}
else if (isMixed(ch))
{
submode = SUBMODE_MIXED;
tmp.Append((char) 28); //ml
continue;
}
else
{
tmp.Append((char) 29); //ps
tmp.Append((char) PUNCTUATION[ch]);
break;
}
}
break;
case SUBMODE_MIXED:
if (isMixed(ch))
{
tmp.Append((char) MIXED[ch]);
}
else
{
if (isAlphaUpper(ch))
{
submode = SUBMODE_ALPHA;
tmp.Append((char) 28); //al
continue;
}
else if (isAlphaLower(ch))
{
submode = SUBMODE_LOWER;
tmp.Append((char) 27); //ll
continue;
}
else
{
if (startpos + idx + 1 < count)
{
char next = msg[startpos + idx + 1];
if (isPunctuation(next))
{
submode = SUBMODE_PUNCTUATION;
tmp.Append((char) 25); //pl
continue;
}
}
tmp.Append((char) 29); //ps
tmp.Append((char) PUNCTUATION[ch]);
}
}
break;
default: //SUBMODE_PUNCTUATION
if (isPunctuation(ch))
{
tmp.Append((char) PUNCTUATION[ch]);
}
else
{
submode = SUBMODE_ALPHA;
tmp.Append((char) 29); //al
continue;
}
break;
}
idx++;
if (idx >= count)
{
break;
}
}
char h = (char) 0;
int len = tmp.Length;
for (int i = 0; i < len; i++)
{
bool odd = (i%2) != 0;
if (odd)
{
h = (char) ((h*30) + tmp[i]);
sb.Append(h);
}
else
{
h = tmp[i];
}
}
if ((len%2) != 0)
{
sb.Append((char) ((h*30) + 29)); //ps
}
return submode;
}
/// <summary>
/// Encode parts of the message using Byte Compaction as described in ISO/IEC 15438:2001(E),
/// chapter 4.4.3. The Unicode characters will be converted to binary using the cp437
/// codepage.
///
/// <param name="bytes">the message converted to a byte array</param>
/// <param name="startpos">the start position within the message</param>
/// <param name="count">the number of bytes to encode</param>
/// <param name="startmode">the mode from which this method starts</param>
/// <param name="sb">receives the encoded codewords</param>
/// </summary>
private static void encodeBinary(byte[] bytes,
int startpos,
int count,
int startmode,
StringBuilder sb)
{
if (count == 1 && startmode == TEXT_COMPACTION)
{
sb.Append((char) SHIFT_TO_BYTE);
}
else
{
bool sixpack = ((count % 6) == 0);
if (sixpack)
{
sb.Append((char)LATCH_TO_BYTE);
}
else
{
sb.Append((char)LATCH_TO_BYTE_PADDED);
}
}
int idx = startpos;
// Encode sixpacks
if (count >= 6)
{
char[] chars = new char[5];
while ((startpos + count - idx) >= 6)
{
long t = 0;
for (int i = 0; i < 6; i++)
{
t <<= 8;
t += bytes[idx + i] & 0xff;
}
for (int i = 0; i < 5; i++)
{
chars[i] = (char) (t%900);
t /= 900;
}
for (int i = chars.Length - 1; i >= 0; i--)
{
sb.Append(chars[i]);
}
idx += 6;
}
}
//Encode rest (remaining n<5 bytes if any)
for (int i = idx; i < startpos + count; i++)
{
int ch = bytes[i] & 0xff;
sb.Append((char) ch);
}
}
private static void encodeNumeric(String msg, int startpos, int count, StringBuilder sb)
{
#if SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NETFX_CORE
int idx = 0;
StringBuilder tmp = new StringBuilder(count/3 + 1);
BigInteger num900 = new BigInteger(900);
BigInteger num0 = new BigInteger(0);
while (idx < count - 1)
{
tmp.Length = 0;
int len = Math.Min(44, count - idx);
String part = '1' + msg.Substring(startpos + idx, len);
#if SILVERLIGHT4 || SILVERLIGHT5
BigInteger bigint = BigIntegerExtensions.Parse(part);
#else
BigInteger bigint = BigInteger.Parse(part);
#endif
do
{
BigInteger c = bigint%num900;
tmp.Append((char) c);
bigint = BigInteger.Divide(bigint, num900);
} while (!bigint.Equals(num0));
//Reverse temporary string
for (int i = tmp.Length - 1; i >= 0; i--)
{
sb.Append(tmp[i]);
}
idx += len;
}
#else
int idx = 0;
StringBuilder tmp = new StringBuilder(count / 3 + 1);
BigInteger num900 = new BigInteger(900);
BigInteger num0 = new BigInteger(0);
while (idx < count - 1)
{
tmp.Length = 0;
int len = Math.Min(44, count - idx);
String part = '1' + msg.Substring(startpos + idx, len);
BigInteger bigint = BigInteger.Parse(part);
do
{
BigInteger c = BigInteger.Modulo(bigint, num900);
tmp.Append((char)c.GetHashCode());
bigint = BigInteger.Division(bigint, num900);
} while (!bigint.Equals(num0));
//Reverse temporary string
for (int i = tmp.Length - 1; i >= 0; i--)
{
sb.Append(tmp[i]);
}
idx += len;
}
#endif
}
private static bool isDigit(char ch)
{
return ch >= '0' && ch <= '9';
}
private static bool isAlphaUpper(char ch)
{
return ch == ' ' || (ch >= 'A' && ch <= 'Z');
}
private static bool isAlphaLower(char ch)
{
return ch == ' ' || (ch >= 'a' && ch <= 'z');
}
private static bool isMixed(char ch)
{
return MIXED[ch] != -1;
}
private static bool isPunctuation(char ch)
{
return PUNCTUATION[ch] != -1;
}
private static bool isText(char ch)
{
return ch == '\t' || ch == '\n' || ch == '\r' || (ch >= 32 && ch <= 126);
}
/// <summary>
/// Determines the number of consecutive characters that are encodable using numeric compaction.
///
/// <param name="msg">the message</param>
/// <param name="startpos">the start position within the message</param>
/// <returns>the requested character count</returns>
/// </summary>
private static int determineConsecutiveDigitCount(String msg, int startpos)
{
int count = 0;
int len = msg.Length;
int idx = startpos;
if (idx < len)
{
char ch = msg[idx];
while (isDigit(ch) && idx < len)
{
count++;
idx++;
if (idx < len)
{
ch = msg[idx];
}
}
}
return count;
}
/// <summary>
/// Determines the number of consecutive characters that are encodable using text compaction.
///
/// <param name="msg">the message</param>
/// <param name="startpos">the start position within the message</param>
/// <returns>the requested character count</returns>
/// </summary>
private static int determineConsecutiveTextCount(String msg, int startpos)
{
int len = msg.Length;
int idx = startpos;
while (idx < len)
{
char ch = msg[idx];
int numericCount = 0;
while (numericCount < 13 && isDigit(ch) && idx < len)
{
numericCount++;
idx++;
if (idx < len)
{
ch = msg[idx];
}
}
if (numericCount >= 13)
{
return idx - startpos - numericCount;
}
if (numericCount > 0)
{
//Heuristic: All text-encodable chars or digits are binary encodable
continue;
}
ch = msg[idx];
//Check if character is encodable
if (!isText(ch))
{
break;
}
idx++;
}
return idx - startpos;
}
/// <summary>
/// Determines the number of consecutive characters that are encodable using binary compaction.
///
/// <param name="msg">the message</param>
/// <param name="bytes">the message converted to a byte array</param>
/// <param name="startpos">the start position within the message</param>
/// <returns>the requested character count</returns>
/// </summary>
private static int determineConsecutiveBinaryCount(String msg, byte[] bytes, int startpos)
{
int len = msg.Length;
int idx = startpos;
while (idx < len)
{
char ch = msg[idx];
int numericCount = 0;
while (numericCount < 13 && isDigit(ch))
{
numericCount++;
//textCount++;
int i = idx + numericCount;
if (i >= len)
{
break;
}
ch = msg[i];
}
if (numericCount >= 13)
{
return idx - startpos;
}
int textCount = 0;
while (textCount < 5 && isText(ch))
{
textCount++;
int i = idx + textCount;
if (i >= len)
{
break;
}
ch = msg[i];
}
if (textCount >= 5)
{
return idx - startpos;
}
ch = msg[idx];
//Check if character is encodable
//Sun returns a ASCII 63 (?) for a character that cannot be mapped. Let's hope all
//other VMs do the same
if (bytes[idx] == 63 && ch != '?')
{
throw new WriterException("Non-encodable character detected: " + ch + " (Unicode: " + (int) ch + ')');
}
idx++;
}
return idx - startpos;
}
private static void encodingECI(int eci, StringBuilder sb)
{
if (eci >= 0 && eci < 900)
{
sb.Append((char) ECI_CHARSET);
sb.Append((char) eci);
}
else if (eci < 810900)
{
sb.Append((char) ECI_GENERAL_PURPOSE);
sb.Append((char) (eci/900 - 1));
sb.Append((char) (eci%900));
}
else if (eci < 811800)
{
sb.Append((char) ECI_USER_DEFINED);
sb.Append((char) (810900 - eci));
}
else
{
throw new WriterException("ECI number not in valid range from 0..811799, but was " + eci);
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Xml
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Collections;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Text;
using System.Runtime.Serialization;
using System.Globalization;
public delegate void OnXmlDictionaryReaderClose(XmlDictionaryReader reader);
public abstract class XmlDictionaryReader : XmlReader
{
internal const int MaxInitialArrayLength = 65535;
static public XmlDictionaryReader CreateDictionaryReader(XmlReader reader)
{
if (reader == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
if (dictionaryReader == null)
{
dictionaryReader = new XmlWrappedReader(reader, null);
}
return dictionaryReader;
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
return CreateBinaryReader(buffer, 0, buffer.Length, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
return CreateBinaryReader(buffer, offset, count, dictionary, quotas, session, null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(buffer, offset, count, dictionary, quotas, session, onClose);
return reader;
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
return CreateBinaryReader(stream, dictionary, quotas, session, null);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(stream, dictionary, quotas, session, onClose);
return reader;
}
static public XmlDictionaryReader CreateTextReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
return CreateTextReader(buffer, 0, buffer.Length, quotas);
}
static public XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateTextReader(buffer, offset, count, null, quotas, null);
}
static public XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count,
Encoding encoding,
XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose)
{
XmlUTF8TextReader reader = new XmlUTF8TextReader();
reader.SetInput(buffer, offset, count, encoding, quotas, onClose);
return reader;
}
static public XmlDictionaryReader CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateTextReader(stream, null, quotas, null);
}
static public XmlDictionaryReader CreateTextReader(Stream stream, Encoding encoding,
XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose)
{
XmlUTF8TextReader reader = new XmlUTF8TextReader();
reader.SetInput(stream, encoding, quotas, onClose);
return reader;
}
static public XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas)
{
if (encoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding");
return CreateMtomReader(stream, new Encoding[1] { encoding }, quotas);
}
static public XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(stream, encodings, null, quotas);
}
static public XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(stream, encodings, contentType, quotas, int.MaxValue, null);
}
static public XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType,
XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
{
XmlMtomReader reader = new XmlMtomReader();
reader.SetInput(stream, encodings, contentType, quotas, maxBufferSize, onClose);
return reader;
}
static public XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas)
{
if (encoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding");
return CreateMtomReader(buffer, offset, count, new Encoding[1] { encoding }, quotas);
}
static public XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(buffer, offset, count, encodings, null, quotas);
}
static public XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(buffer, offset, count, encodings, contentType, quotas, int.MaxValue, null);
}
static public XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType,
XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
{
XmlMtomReader reader = new XmlMtomReader();
reader.SetInput(buffer, offset, count, encodings, contentType, quotas, maxBufferSize, onClose);
return reader;
}
#if NO
static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding)
{
return XmlMtomWriter.IsUTF8Encoding(encoding) ? new XmlUTF8TextReader(buffer, offset, count)
: CreateReader(new MemoryStream(buffer, offset, count), encoding);
}
#endif
public virtual bool CanCanonicalize
{
get
{
return false;
}
}
public virtual XmlDictionaryReaderQuotas Quotas
{
get
{
return XmlDictionaryReaderQuotas.Max;
}
}
public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void MoveToStartElement()
{
if (!IsStartElement())
XmlExceptionHelper.ThrowStartElementExpected(this);
}
public virtual void MoveToStartElement(string name)
{
if (!IsStartElement(name))
XmlExceptionHelper.ThrowStartElementExpected(this, name);
}
public virtual void MoveToStartElement(string localName, string namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual void MoveToStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual bool IsLocalName(string localName)
{
return this.LocalName == localName;
}
public virtual bool IsLocalName(XmlDictionaryString localName)
{
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName");
return IsLocalName(localName.Value);
}
public virtual bool IsNamespaceUri(string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
return this.NamespaceURI == namespaceUri;
}
public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
return IsNamespaceUri(namespaceUri.Value);
}
public virtual void ReadFullStartElement()
{
MoveToStartElement();
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this);
Read();
}
public virtual void ReadFullStartElement(string name)
{
MoveToStartElement(name);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, name);
Read();
}
public virtual void ReadFullStartElement(string localName, string namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadFullStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
Read();
}
public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return IsStartElement(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual int IndexOfLocalName(string[] localNames, string namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames");
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
if (this.NamespaceURI == namespaceUri)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
string value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value)
{
return i;
}
}
}
return -1;
}
public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames");
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
if (this.NamespaceURI == namespaceUri.Value)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
XmlDictionaryString value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value.Value)
{
return i;
}
}
}
return -1;
}
public virtual string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual bool TryGetBase64ContentLength(out int length)
{
length = 0;
return false;
}
public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual byte[] ReadContentAsBase64()
{
return ReadContentAsBase64(Quotas.MaxArrayLength, MaxInitialArrayLength);
}
internal byte[] ReadContentAsBase64(int maxByteArrayContentLength, int maxInitialCount)
{
int length;
if (TryGetBase64ContentLength(out length))
{
if (length > maxByteArrayContentLength)
XmlExceptionHelper.ThrowMaxArrayLengthExceeded(this, maxByteArrayContentLength);
if (length <= maxInitialCount)
{
byte[] buffer = new byte[length];
int read = 0;
while (read < length)
{
int actual = ReadContentAsBase64(buffer, read, length - read);
if (actual == 0)
XmlExceptionHelper.ThrowBase64DataExpected(this);
read += actual;
}
return buffer;
}
}
return ReadContentAsBytes(true, maxByteArrayContentLength);
}
public override string ReadContentAsString()
{
return ReadContentAsString(Quotas.MaxStringContentLength);
}
protected string ReadContentAsString(int maxStringContentLength)
{
StringBuilder sb = null;
string result = string.Empty;
bool done = false;
while (true)
{
switch (this.NodeType)
{
case XmlNodeType.Attribute:
result = this.Value;
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
// merge text content
string value = this.Value;
if (result.Length == 0)
{
result = value;
}
else
{
if (sb == null)
sb = new StringBuilder(result);
if (sb.Length > maxStringContentLength - value.Length)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
sb.Append(value);
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (this.CanResolveEntity)
{
this.ResolveEntity();
break;
}
goto default;
case XmlNodeType.Element:
case XmlNodeType.EndElement:
default:
done = true;
break;
}
if (done)
break;
if (this.AttributeCount != 0)
ReadAttributeValue();
else
Read();
}
if (sb != null)
result = sb.ToString();
if (result.Length > maxStringContentLength)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
return result;
}
public override string ReadString()
{
return ReadString(Quotas.MaxStringContentLength);
}
protected string ReadString(int maxStringContentLength)
{
if (this.ReadState != ReadState.Interactive)
return string.Empty;
if (this.NodeType != XmlNodeType.Element)
MoveToElement();
if (this.NodeType == XmlNodeType.Element)
{
if (this.IsEmptyElement)
return string.Empty;
if (!Read())
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidOperation)));
if (this.NodeType == XmlNodeType.EndElement)
return string.Empty;
}
StringBuilder sb = null;
string result = string.Empty;
while (IsTextNode(this.NodeType))
{
string value = this.Value;
if (result.Length == 0)
{
result = value;
}
else
{
if (sb == null)
sb = new StringBuilder(result);
if (sb.Length > maxStringContentLength - value.Length)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
sb.Append(value);
}
if (!Read())
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidOperation)));
}
if (sb != null)
result = sb.ToString();
if (result.Length > maxStringContentLength)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
return result;
}
public virtual byte[] ReadContentAsBinHex()
{
return ReadContentAsBinHex(Quotas.MaxArrayLength);
}
protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength)
{
return ReadContentAsBytes(false, maxByteArrayContentLength);
}
byte[] ReadContentAsBytes(bool base64, int maxByteArrayContentLength)
{
byte[][] buffers = new byte[32][];
byte[] buffer;
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
int count = 384;
int bufferCount = 0;
int totalRead = 0;
while (true)
{
buffer = new byte[count];
buffers[bufferCount++] = buffer;
int read = 0;
while (read < buffer.Length)
{
int actual;
if (base64)
actual = ReadContentAsBase64(buffer, read, buffer.Length - read);
else
actual = ReadContentAsBinHex(buffer, read, buffer.Length - read);
if (actual == 0)
break;
read += actual;
}
if (totalRead > maxByteArrayContentLength - read)
XmlExceptionHelper.ThrowMaxArrayLengthExceeded(this, maxByteArrayContentLength);
totalRead += read;
if (read < buffer.Length)
break;
count = count * 2;
}
buffer = new byte[totalRead];
int offset = 0;
for (int i = 0; i < bufferCount - 1; i++)
{
Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length);
offset += buffers[i].Length;
}
Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset);
return buffer;
}
protected bool IsTextNode(XmlNodeType nodeType)
{
return nodeType == XmlNodeType.Text ||
nodeType == XmlNodeType.Whitespace ||
nodeType == XmlNodeType.SignificantWhitespace ||
nodeType == XmlNodeType.CDATA ||
nodeType == XmlNodeType.Attribute;
}
public virtual int ReadContentAsChars(char[] chars, int offset, int count)
{
int read = 0;
while (true)
{
XmlNodeType nodeType = this.NodeType;
if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement)
break;
if (IsTextNode(nodeType))
{
read = ReadValueChunk(chars, offset, count);
if (read > 0)
break;
if (nodeType == XmlNodeType.Attribute /* || inAttributeText */)
break;
if (!Read())
break;
}
else
{
if (!Read())
break;
}
}
return read;
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
if (type == typeof(Guid[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
Guid[] guids = new Guid[values.Length];
for (int i = 0; i < values.Length; i++)
guids[i] = XmlConverter.ToGuid(values[i]);
return guids;
}
if (type == typeof(UniqueId[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
UniqueId[] uniqueIds = new UniqueId[values.Length];
for (int i = 0; i < values.Length; i++)
uniqueIds[i] = XmlConverter.ToUniqueId(values[i]);
return uniqueIds;
}
return base.ReadContentAs(type, namespaceResolver);
}
public virtual string ReadContentAsString(string[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("strings");
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
string value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value == s)
{
index = i;
return value;
}
}
return s;
}
public virtual string ReadContentAsString(XmlDictionaryString[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("strings");
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
XmlDictionaryString value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value.Value == s)
{
index = i;
return value.Value;
}
}
return s;
}
public override decimal ReadContentAsDecimal()
{
return XmlConverter.ToDecimal(ReadContentAsString());
}
public override Single ReadContentAsFloat()
{
return XmlConverter.ToSingle(ReadContentAsString());
}
public virtual UniqueId ReadContentAsUniqueId()
{
return XmlConverter.ToUniqueId(ReadContentAsString());
}
public virtual Guid ReadContentAsGuid()
{
return XmlConverter.ToGuid(ReadContentAsString());
}
public virtual TimeSpan ReadContentAsTimeSpan()
{
return XmlConverter.ToTimeSpan(ReadContentAsString());
}
public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri)
{
string prefix;
XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName);
namespaceUri = LookupNamespace(prefix);
if (namespaceUri == null)
XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix);
}
/* string, bool, int, long, float, double, decimal, DateTime, base64, binhex, uniqueID, object, list*/
public override string ReadElementContentAsString()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
string value;
if (isEmptyElement)
{
Read();
value = string.Empty;
}
else
{
ReadStartElement();
value = ReadContentAsString();
ReadEndElement();
}
return value;
}
public override bool ReadElementContentAsBoolean()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
bool value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToBoolean(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsBoolean();
ReadEndElement();
}
return value;
}
public override int ReadElementContentAsInt()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
int value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt32(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsInt();
ReadEndElement();
}
return value;
}
public override long ReadElementContentAsLong()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
long value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt64(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsLong();
ReadEndElement();
}
return value;
}
public override float ReadElementContentAsFloat()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
float value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToSingle(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsFloat();
ReadEndElement();
}
return value;
}
public override double ReadElementContentAsDouble()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
double value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDouble(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDouble();
ReadEndElement();
}
return value;
}
public override decimal ReadElementContentAsDecimal()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
decimal value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDecimal(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDecimal();
ReadEndElement();
}
return value;
}
public override DateTime ReadElementContentAsDateTime()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
DateTime value;
if (isEmptyElement)
{
Read();
try
{
value = DateTime.Parse(string.Empty, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsDateTime();
ReadEndElement();
}
return value;
}
public virtual UniqueId ReadElementContentAsUniqueId()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
UniqueId value;
if (isEmptyElement)
{
Read();
try
{
value = new UniqueId(string.Empty);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsUniqueId();
ReadEndElement();
}
return value;
}
[SuppressMessage("Reliability", "Reliability113", Justification = "Catching expected exceptions inline instead of calling Fx.CreateGuid to minimize code change")]
public virtual Guid ReadElementContentAsGuid()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
Guid value;
if (isEmptyElement)
{
Read();
try
{
value = Guid.Empty;
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsGuid();
ReadEndElement();
}
return value;
}
public virtual TimeSpan ReadElementContentAsTimeSpan()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
TimeSpan value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToTimeSpan(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsTimeSpan();
ReadEndElement();
}
return value;
}
public virtual byte[] ReadElementContentAsBase64()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = new byte[0];
}
else
{
ReadStartElement();
buffer = ReadContentAsBase64();
ReadEndElement();
}
return buffer;
}
public virtual byte[] ReadElementContentAsBinHex()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = new byte[0];
}
else
{
ReadStartElement();
buffer = ReadContentAsBinHex();
ReadEndElement();
}
return buffer;
}
public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri)
{
localName = this.LocalName;
namespaceUri = this.NamespaceURI;
}
public virtual bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
{
localName = null;
return false;
}
public virtual bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString namespaceUri)
{
namespaceUri = null;
return false;
}
public virtual bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
{
value = null;
return false;
}
void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
public virtual bool IsStartArray(out Type type)
{
type = null;
return false;
}
public virtual bool TryGetArrayLength(out int count)
{
count = 0;
return false;
}
// Boolean
public virtual bool[] ReadBooleanArray(string localName, string namespaceUri)
{
return BooleanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual bool[] ReadBooleanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return BooleanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsBoolean();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int16
public virtual Int16[] ReadInt16Array(string localName, string namespaceUri)
{
return Int16ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int16[] ReadInt16Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int16ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int16[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
int i = ReadElementContentAsInt();
if (i < Int16.MinValue || i > Int16.MaxValue)
XmlExceptionHelper.ThrowConversionOverflow(this, i.ToString(NumberFormatInfo.CurrentInfo), "Int16");
array[offset + actual] = (Int16)i;
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int32
public virtual Int32[] ReadInt32Array(string localName, string namespaceUri)
{
return Int32ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int32[] ReadInt32Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int32ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int32[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsInt();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int64
public virtual Int64[] ReadInt64Array(string localName, string namespaceUri)
{
return Int64ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int64[] ReadInt64Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int64ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int64[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsLong();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Single
public virtual float[] ReadSingleArray(string localName, string namespaceUri)
{
return SingleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual float[] ReadSingleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return SingleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsFloat();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Double
public virtual double[] ReadDoubleArray(string localName, string namespaceUri)
{
return DoubleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual double[] ReadDoubleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DoubleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDouble();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Decimal
public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri)
{
return DecimalArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual decimal[] ReadDecimalArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DecimalArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDecimal();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// DateTime
public virtual DateTime[] ReadDateTimeArray(string localName, string namespaceUri)
{
return DateTimeArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual DateTime[] ReadDateTimeArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDateTime();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Guid
public virtual Guid[] ReadGuidArray(string localName, string namespaceUri)
{
return GuidArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Guid[] ReadGuidArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GuidArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsGuid();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// TimeSpan
public virtual TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri)
{
return TimeSpanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual TimeSpan[] ReadTimeSpanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return TimeSpanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsTimeSpan();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo
{
XmlReader reader;
XmlNamespaceManager nsMgr;
public XmlWrappedReader(XmlReader reader, XmlNamespaceManager nsMgr)
{
this.reader = reader;
this.nsMgr = nsMgr;
}
public override int AttributeCount
{
get
{
return reader.AttributeCount;
}
}
public override string BaseURI
{
get
{
return reader.BaseURI;
}
}
public override bool CanReadBinaryContent
{
get { return reader.CanReadBinaryContent; }
}
public override bool CanReadValueChunk
{
get { return reader.CanReadValueChunk; }
}
public override void Close()
{
reader.Close();
nsMgr = null;
}
public override int Depth
{
get
{
return reader.Depth;
}
}
public override bool EOF
{
get
{
return reader.EOF;
}
}
public override string GetAttribute(int index)
{
return reader.GetAttribute(index);
}
public override string GetAttribute(string name)
{
return reader.GetAttribute(name);
}
public override string GetAttribute(string name, string namespaceUri)
{
return reader.GetAttribute(name, namespaceUri);
}
public override bool HasValue
{
get
{
return reader.HasValue;
}
}
public override bool IsDefault
{
get
{
return reader.IsDefault;
}
}
public override bool IsEmptyElement
{
get
{
return reader.IsEmptyElement;
}
}
public override bool IsStartElement(string name)
{
return reader.IsStartElement(name);
}
public override bool IsStartElement(string localName, string namespaceUri)
{
return reader.IsStartElement(localName, namespaceUri);
}
public override string LocalName
{
get
{
return reader.LocalName;
}
}
public override string LookupNamespace(string namespaceUri)
{
return reader.LookupNamespace(namespaceUri);
}
public override void MoveToAttribute(int index)
{
reader.MoveToAttribute(index);
}
public override bool MoveToAttribute(string name)
{
return reader.MoveToAttribute(name);
}
public override bool MoveToAttribute(string name, string namespaceUri)
{
return reader.MoveToAttribute(name, namespaceUri);
}
public override bool MoveToElement()
{
return reader.MoveToElement();
}
public override bool MoveToFirstAttribute()
{
return reader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return reader.MoveToNextAttribute();
}
public override string Name
{
get
{
return reader.Name;
}
}
public override string NamespaceURI
{
get
{
return reader.NamespaceURI;
}
}
public override XmlNameTable NameTable
{
get
{
return reader.NameTable;
}
}
public override XmlNodeType NodeType
{
get
{
return reader.NodeType;
}
}
public override string Prefix
{
get
{
return reader.Prefix;
}
}
public override char QuoteChar
{
get
{
return reader.QuoteChar;
}
}
public override bool Read()
{
return reader.Read();
}
public override bool ReadAttributeValue()
{
return reader.ReadAttributeValue();
}
public override string ReadElementString(string name)
{
return reader.ReadElementString(name);
}
public override string ReadElementString(string localName, string namespaceUri)
{
return reader.ReadElementString(localName, namespaceUri);
}
public override string ReadInnerXml()
{
return reader.ReadInnerXml();
}
public override string ReadOuterXml()
{
return reader.ReadOuterXml();
}
public override void ReadStartElement(string name)
{
reader.ReadStartElement(name);
}
public override void ReadStartElement(string localName, string namespaceUri)
{
reader.ReadStartElement(localName, namespaceUri);
}
public override void ReadEndElement()
{
reader.ReadEndElement();
}
public override string ReadString()
{
return reader.ReadString();
}
public override ReadState ReadState
{
get
{
return reader.ReadState;
}
}
public override void ResolveEntity()
{
reader.ResolveEntity();
}
public override string this[int index]
{
get
{
return reader[index];
}
}
public override string this[string name]
{
get
{
return reader[name];
}
}
public override string this[string name, string namespaceUri]
{
get
{
return reader[name, namespaceUri];
}
}
public override string Value
{
get
{
return reader.Value;
}
}
public override string XmlLang
{
get
{
return reader.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return reader.XmlSpace;
}
}
public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count)
{
return reader.ReadElementContentAsBase64(buffer, offset, count);
}
public override int ReadContentAsBase64(byte[] buffer, int offset, int count)
{
return reader.ReadContentAsBase64(buffer, offset, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count)
{
return reader.ReadElementContentAsBinHex(buffer, offset, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int offset, int count)
{
return reader.ReadContentAsBinHex(buffer, offset, count);
}
public override int ReadValueChunk(char[] chars, int offset, int count)
{
return reader.ReadValueChunk(chars, offset, count);
}
public override Type ValueType
{
get
{
return reader.ValueType;
}
}
public override Boolean ReadContentAsBoolean()
{
return reader.ReadContentAsBoolean();
}
public override DateTime ReadContentAsDateTime()
{
return reader.ReadContentAsDateTime();
}
public override Decimal ReadContentAsDecimal()
{
// return reader.ReadContentAsDecimal();
return (Decimal)reader.ReadContentAs(typeof(Decimal), null);
}
public override Double ReadContentAsDouble()
{
return reader.ReadContentAsDouble();
}
public override Int32 ReadContentAsInt()
{
return reader.ReadContentAsInt();
}
public override Int64 ReadContentAsLong()
{
return reader.ReadContentAsLong();
}
public override Single ReadContentAsFloat()
{
return reader.ReadContentAsFloat();
}
public override string ReadContentAsString()
{
return reader.ReadContentAsString();
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
return reader.ReadContentAs(type, namespaceResolver);
}
public bool HasLineInfo()
{
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo == null)
return false;
return lineInfo.HasLineInfo();
}
public int LineNumber
{
get
{
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LineNumber;
}
}
public int LinePosition
{
get
{
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LinePosition;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using FT = MS.Internal.Xml.XPath.Function.FunctionType;
namespace MS.Internal.Xml.XPath
{
internal sealed class QueryBuilder
{
// Note: Up->Down, Down->Up:
// For operators order is normal: 1 + 2 --> Operator+(1, 2)
// For paths order is reversed: a/b -> ChildQuery_B(input: ChildQuery_A(input: ContextQuery()))
// Input flags. We pass them Up->Down.
// Using them upper query set states which controls how inner query will be built.
private enum Flags
{
None = 0x00,
SmartDesc = 0x01,
PosFilter = 0x02, // Node has this flag set when it has position predicate applied to it
Filter = 0x04, // Subtree we compiling will be filtered. i.e. Flag not set on rightmost filter.
}
// Output props. We return them Down->Up.
// These are properties of Query tree we have built already.
// These properties are closely related to QueryProps exposed by Query node itself.
// They have the following difference:
// QueryProps describe property of node they are (belong like Reverse)
// these Props describe accumulated properties of the tree (like nonFlat)
private enum Props
{
None = 0x00,
PosFilter = 0x01, // This filter or inner filter was positional: foo[1] or foo[1][true()]
HasPosition = 0x02, // Expression may ask position() of the context
HasLast = 0x04, // Expression may ask last() of the context
NonFlat = 0x08, // Some nodes may be descendent of others
}
// comment are approximate. This is my best understanding:
private string _query;
private bool _allowVar;
private bool _allowKey;
private bool _allowCurrent;
private bool _needContext;
private BaseAxisQuery _firstInput; // Input of the leftmost predicate. Set by leftmost predicate, used in rightmost one
private void Reset()
{
_parseDepth = 0;
_needContext = false;
}
private Query ProcessAxis(Axis root, Flags flags, out Props props)
{
Query result = null;
if (root.Prefix.Length > 0)
{
_needContext = true;
}
_firstInput = null;
Query qyInput;
{
if (root.Input != null)
{
Flags inputFlags = Flags.None;
if ((flags & Flags.PosFilter) == 0)
{
Axis input = root.Input as Axis;
if (input != null)
{
if (
root.TypeOfAxis == Axis.AxisType.Child &&
input.TypeOfAxis == Axis.AxisType.DescendantOrSelf && input.NodeType == XPathNodeType.All
)
{
Query qyGrandInput;
if (input.Input != null)
{
qyGrandInput = ProcessNode(input.Input, Flags.SmartDesc, out props);
}
else
{
qyGrandInput = new ContextQuery();
props = Props.None;
}
result = new DescendantQuery(qyGrandInput, root.Name, root.Prefix, root.NodeType, false, input.AbbrAxis);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
props |= Props.NonFlat;
return result;
}
}
if (root.TypeOfAxis == Axis.AxisType.Descendant || root.TypeOfAxis == Axis.AxisType.DescendantOrSelf)
{
inputFlags |= Flags.SmartDesc;
}
}
qyInput = ProcessNode(root.Input, inputFlags, out props);
}
else
{
qyInput = new ContextQuery();
props = Props.None;
}
}
switch (root.TypeOfAxis)
{
case Axis.AxisType.Ancestor:
result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, false);
props |= Props.NonFlat;
break;
case Axis.AxisType.AncestorOrSelf:
result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, true);
props |= Props.NonFlat;
break;
case Axis.AxisType.Child:
if ((props & Props.NonFlat) != 0)
{
result = new CacheChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
else
{
result = new ChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
break;
case Axis.AxisType.Parent:
result = new ParentQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Descendant:
if ((flags & Flags.SmartDesc) != 0)
{
result = new DescendantOverDescendantQuery(qyInput, false, root.Name, root.Prefix, root.NodeType, /*abbrAxis:*/false);
}
else
{
result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, false, /*abbrAxis:*/false);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
}
props |= Props.NonFlat;
break;
case Axis.AxisType.DescendantOrSelf:
if ((flags & Flags.SmartDesc) != 0)
{
result = new DescendantOverDescendantQuery(qyInput, true, root.Name, root.Prefix, root.NodeType, root.AbbrAxis);
}
else
{
result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, true, root.AbbrAxis);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
}
props |= Props.NonFlat;
break;
case Axis.AxisType.Preceding:
result = new PrecedingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
props |= Props.NonFlat;
break;
case Axis.AxisType.Following:
result = new FollowingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
props |= Props.NonFlat;
break;
case Axis.AxisType.FollowingSibling:
result = new FollSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
break;
case Axis.AxisType.PrecedingSibling:
result = new PreSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Attribute:
result = new AttributeQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Self:
result = new XPathSelfQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Namespace:
if ((root.NodeType == XPathNodeType.All || root.NodeType == XPathNodeType.Element || root.NodeType == XPathNodeType.Attribute) && root.Prefix.Length == 0)
{
result = new NamespaceQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
else
{
result = new EmptyQuery();
}
break;
default:
throw XPathException.Create(SR.Xp_NotSupported, _query);
}
return result;
}
private static bool CanBeNumber(Query q)
{
return (
q.StaticType == XPathResultType.Any ||
q.StaticType == XPathResultType.Number
);
}
private Query ProcessFilter(Filter root, Flags flags, out Props props)
{
bool first = ((flags & Flags.Filter) == 0);
Props propsCond;
Query cond = ProcessNode(root.Condition, Flags.None, out propsCond);
if (
CanBeNumber(cond) ||
(propsCond & (Props.HasPosition | Props.HasLast)) != 0
)
{
propsCond |= Props.HasPosition;
flags |= Flags.PosFilter;
}
// We don't want DescendantOverDescendant pattern to be recognized here (in case descendent::foo[expr]/descendant::bar)
// So we clean this flag here:
flags &= ~Flags.SmartDesc;
// Suggestion: Instead it would be nice to wrap descendent::foo[expr] into special query that will flatten it -- i.e.
// remove all nodes that are descendant of other nodes. This is very easy because for sorted nodesets all children
// follow its parent. One step caching. This can be easily done by rightmost DescendantQuery itself.
// Interesting note! Can we guarantee that DescendantOverDescendant returns flat nodeset? This definitely true if it's input is flat.
Query qyInput = ProcessNode(root.Input, flags | Flags.Filter, out props);
if (root.Input.Type != AstNode.AstType.Filter)
{
// Props.PosFilter is for nested filters only.
// We clean it here to avoid cleaning it in all other ast nodes.
props &= ~Props.PosFilter;
}
if ((propsCond & Props.HasPosition) != 0)
{
// this condition is positional rightmost filter should be aware of this.
props |= Props.PosFilter;
}
/*merging predicates*/
{
FilterQuery qyFilter = qyInput as FilterQuery;
if (qyFilter != null && (propsCond & Props.HasPosition) == 0 && qyFilter.Condition.StaticType != XPathResultType.Any)
{
Query prevCond = qyFilter.Condition;
if (prevCond.StaticType == XPathResultType.Number)
{
prevCond = new LogicalExpr(Operator.Op.EQ, new NodeFunctions(FT.FuncPosition, null), prevCond);
}
cond = new BooleanExpr(Operator.Op.AND, prevCond, cond);
qyInput = qyFilter.qyInput;
}
}
if ((props & Props.PosFilter) != 0 && qyInput is DocumentOrderQuery)
{
qyInput = ((DocumentOrderQuery)qyInput).input;
}
if (_firstInput == null)
{
_firstInput = qyInput as BaseAxisQuery;
}
bool merge = (qyInput.Properties & QueryProps.Merge) != 0;
bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0;
if ((propsCond & Props.HasPosition) != 0)
{
if (reverse)
{
qyInput = new ReversePositionQuery(qyInput);
}
else if ((propsCond & Props.HasLast) != 0)
{
qyInput = new ForwardPositionQuery(qyInput);
}
}
if (first && _firstInput != null)
{
if (merge && (props & Props.PosFilter) != 0)
{
qyInput = new FilterQuery(qyInput, cond, /*noPosition:*/false);
Query parent = _firstInput.qyInput;
if (!(parent is ContextQuery))
{ // we don't need to wrap filter with MergeFilterQuery when cardinality is parent <: ?
_firstInput.qyInput = new ContextQuery();
_firstInput = null;
return new MergeFilterQuery(parent, qyInput);
}
_firstInput = null;
return qyInput;
}
_firstInput = null;
}
return new FilterQuery(qyInput, cond, /*noPosition:*/(propsCond & Props.HasPosition) == 0);
}
private Query ProcessOperator(Operator root, out Props props)
{
Props props1, props2;
Query op1 = ProcessNode(root.Operand1, Flags.None, out props1);
Query op2 = ProcessNode(root.Operand2, Flags.None, out props2);
props = props1 | props2;
switch (root.OperatorType)
{
case Operator.Op.PLUS:
case Operator.Op.MINUS:
case Operator.Op.MUL:
case Operator.Op.MOD:
case Operator.Op.DIV:
return new NumericExpr(root.OperatorType, op1, op2);
case Operator.Op.LT:
case Operator.Op.GT:
case Operator.Op.LE:
case Operator.Op.GE:
case Operator.Op.EQ:
case Operator.Op.NE:
return new LogicalExpr(root.OperatorType, op1, op2);
case Operator.Op.OR:
case Operator.Op.AND:
return new BooleanExpr(root.OperatorType, op1, op2);
case Operator.Op.UNION:
props |= Props.NonFlat;
return new UnionExpr(op1, op2);
default: return null;
}
}
private Query ProcessVariable(Variable root)
{
_needContext = true;
if (!_allowVar)
{
throw XPathException.Create(SR.Xp_InvalidKeyPattern, _query);
}
return new VariableQuery(root.Localname, root.Prefix);
}
private Query ProcessFunction(Function root, out Props props)
{
props = Props.None;
Query qy = null;
switch (root.TypeOfFunction)
{
case FT.FuncLast:
qy = new NodeFunctions(root.TypeOfFunction, null);
props |= Props.HasLast;
return qy;
case FT.FuncPosition:
qy = new NodeFunctions(root.TypeOfFunction, null);
props |= Props.HasPosition;
return qy;
case FT.FuncCount:
return new NodeFunctions(FT.FuncCount,
ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)
);
case FT.FuncID:
qy = new IDQuery(ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props));
props |= Props.NonFlat;
return qy;
case FT.FuncLocalName:
case FT.FuncNameSpaceUri:
case FT.FuncName:
if (root.ArgumentList != null && root.ArgumentList.Count > 0)
{
return new NodeFunctions(root.TypeOfFunction,
ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)
);
}
else
{
return new NodeFunctions(root.TypeOfFunction, null);
}
case FT.FuncString:
case FT.FuncConcat:
case FT.FuncStartsWith:
case FT.FuncContains:
case FT.FuncSubstringBefore:
case FT.FuncSubstringAfter:
case FT.FuncSubstring:
case FT.FuncStringLength:
case FT.FuncNormalize:
case FT.FuncTranslate:
return new StringFunctions(root.TypeOfFunction, ProcessArguments(root.ArgumentList, out props));
case FT.FuncNumber:
case FT.FuncSum:
case FT.FuncFloor:
case FT.FuncCeiling:
case FT.FuncRound:
if (root.ArgumentList != null && root.ArgumentList.Count > 0)
{
return new NumberFunctions(root.TypeOfFunction,
ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props)
);
}
else
{
return new NumberFunctions(Function.FunctionType.FuncNumber, null);
}
case FT.FuncTrue:
case FT.FuncFalse:
return new BooleanFunctions(root.TypeOfFunction, null);
case FT.FuncNot:
case FT.FuncLang:
case FT.FuncBoolean:
return new BooleanFunctions(root.TypeOfFunction,
ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props)
);
case FT.FuncUserDefined:
_needContext = true;
if (!_allowCurrent && root.Name == "current" && root.Prefix.Length == 0)
{
throw XPathException.Create(SR.Xp_CurrentNotAllowed);
}
if (!_allowKey && root.Name == "key" && root.Prefix.Length == 0)
{
throw XPathException.Create(SR.Xp_InvalidKeyPattern, _query);
}
qy = new FunctionQuery(root.Prefix, root.Name, ProcessArguments(root.ArgumentList, out props));
props |= Props.NonFlat;
return qy;
default:
throw XPathException.Create(SR.Xp_NotSupported, _query);
}
}
private List<Query> ProcessArguments(List<AstNode> args, out Props props)
{
int numArgs = args != null ? args.Count : 0;
List<Query> argList = new List<Query>(numArgs);
props = Props.None;
for (int count = 0; count < numArgs; count++)
{
Props argProps;
argList.Add(ProcessNode((AstNode)args[count], Flags.None, out argProps));
props |= argProps;
}
return argList;
}
private int _parseDepth = 0;
private const int MaxParseDepth = 1024;
private Query ProcessNode(AstNode root, Flags flags, out Props props)
{
if (++_parseDepth > MaxParseDepth)
{
throw XPathException.Create(SR.Xp_QueryTooComplex);
}
Debug.Assert(root != null, "root != null");
Query result = null;
props = Props.None;
switch (root.Type)
{
case AstNode.AstType.Axis:
result = ProcessAxis((Axis)root, flags, out props);
break;
case AstNode.AstType.Operator:
result = ProcessOperator((Operator)root, out props);
break;
case AstNode.AstType.Filter:
result = ProcessFilter((Filter)root, flags, out props);
break;
case AstNode.AstType.ConstantOperand:
result = new OperandQuery(((Operand)root).OperandValue);
break;
case AstNode.AstType.Variable:
result = ProcessVariable((Variable)root);
break;
case AstNode.AstType.Function:
result = ProcessFunction((Function)root, out props);
break;
case AstNode.AstType.Group:
result = new GroupQuery(ProcessNode(((Group)root).GroupNode, Flags.None, out props));
break;
case AstNode.AstType.Root:
result = new AbsoluteQuery();
break;
default:
Debug.Fail("Unknown QueryType encountered!!");
break;
}
--_parseDepth;
return result;
}
private Query Build(AstNode root, string query)
{
Reset();
Props props;
_query = query;
Query result = ProcessNode(root, Flags.None, out props);
return result;
}
internal Query Build(string query, bool allowVar, bool allowKey)
{
_allowVar = allowVar;
_allowKey = allowKey;
_allowCurrent = true;
return Build(XPathParser.ParseXPathExpression(query), query);
}
internal Query Build(string query, out bool needContext)
{
Query result = Build(query, true, true);
needContext = _needContext;
return result;
}
internal Query BuildPatternQuery(string query, bool allowVar, bool allowKey)
{
_allowVar = allowVar;
_allowKey = allowKey;
_allowCurrent = false;
return Build(XPathParser.ParseXPathPattern(query), query);
}
internal Query BuildPatternQuery(string query, out bool needContext)
{
Query result = BuildPatternQuery(query, true, true);
needContext = _needContext;
return result;
}
}
}
| |
using Lucene.Net.Codecs;
using Lucene.Net.Codecs.Asserting;
using Lucene.Net.Codecs.CheapBastard;
using Lucene.Net.Codecs.Compressing;
using Lucene.Net.Codecs.Lucene3x;
using Lucene.Net.Codecs.Lucene40;
using Lucene.Net.Codecs.Lucene41;
using Lucene.Net.Codecs.Lucene42;
using Lucene.Net.Codecs.Lucene45;
using Lucene.Net.Codecs.Lucene46;
using Lucene.Net.Codecs.MockRandom;
using Lucene.Net.Codecs.SimpleText;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Search.Similarities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using JCG = J2N.Collections.Generic;
using Console = Lucene.Net.Util.SystemConsole;
// LUCENENET NOTE: These are primarily here because they are referred to
// in the XML documentation. Be sure to add a new option if a new test framework
// is being supported.
#if TESTFRAMEWORK_MSTEST
using AssumptionViolatedException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException;
#elif TESTFRAMEWORK_NUNIT
using AssumptionViolatedException = NUnit.Framework.InconclusiveException;
#elif TESTFRAMEWORK_XUNIT
using AssumptionViolatedException = Lucene.Net.TestFramework.SkipTestException;
#endif
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Setup and restore suite-level environment (fine grained junk that
/// doesn't fit anywhere else).
/// </summary>
// LUCENENET specific: This class was refactored to be called directly from LuceneTestCase, since
// we didn't port over the entire test suite from Java.
internal sealed class TestRuleSetupAndRestoreClassEnv : AbstractBeforeAfterRule
{
/// <summary>
/// Restore these system property values.
/// </summary>
private Dictionary<string, string> restoreProperties = new Dictionary<string, string>();
private Codec savedCodec;
private CultureInfo savedLocale;
private InfoStream savedInfoStream;
private TimeZoneInfo savedTimeZone;
internal CultureInfo locale;
internal TimeZoneInfo timeZone;
internal Similarity similarity;
internal Codec codec;
/// <seealso cref="LuceneTestCase.SuppressCodecsAttribute"/>
internal ISet<string> avoidCodecs;
internal class ThreadNameFixingPrintStreamInfoStream : TextWriterInfoStream
{
public ThreadNameFixingPrintStreamInfoStream(TextWriter @out)
: base(@out)
{
}
public override void Message(string component, string message)
{
if ("TP".Equals(component, StringComparison.Ordinal))
{
return; // ignore test points!
}
string name;
if (Thread.CurrentThread.Name != null && Thread.CurrentThread.Name.StartsWith("TEST-", StringComparison.Ordinal))
{
// The name of the main thread is way too
// long when looking at IW verbose output...
name = "main";
}
else
{
name = Thread.CurrentThread.Name;
}
m_stream.WriteLine(component + " " + m_messageID + " [" + DateTime.Now + "; " + name + "]: " + message);
}
}
public override void Before(LuceneTestCase testInstance)
{
// LUCENENET specific - SOLR setup code removed
// if verbose: print some debugging stuff about which codecs are loaded.
if (LuceneTestCase.Verbose)
{
// LUCENENET: Only list the services if the underlying ICodecFactory
// implements IServiceListable
if (Codec.GetCodecFactory() is IServiceListable)
{
ICollection<string> codecs = Codec.AvailableCodecs;
foreach (string codec in codecs)
{
Console.WriteLine("Loaded codec: '" + codec + "': " + Codec.ForName(codec).GetType().Name);
}
}
// LUCENENET: Only list the services if the underlying IPostingsFormatFactory
// implements IServiceListable
if (PostingsFormat.GetPostingsFormatFactory() is IServiceListable)
{
ICollection<string> postingsFormats = PostingsFormat.AvailablePostingsFormats;
foreach (string postingsFormat in postingsFormats)
{
Console.WriteLine("Loaded postingsFormat: '" + postingsFormat + "': " + PostingsFormat.ForName(postingsFormat).GetType().Name);
}
}
}
savedInfoStream = InfoStream.Default;
Random random = LuceneTestCase.Random;
bool v = random.NextBoolean();
if (LuceneTestCase.UseInfoStream)
{
InfoStream.Default = new ThreadNameFixingPrintStreamInfoStream(Console.Out);
}
else if (v)
{
InfoStream.Default = new NullInfoStream();
}
Type targetClass = testInstance?.GetType() ?? LuceneTestCase.GetTestClass();
avoidCodecs = new JCG.HashSet<string>();
var suppressCodecsAttribute = targetClass.GetCustomAttribute<LuceneTestCase.SuppressCodecsAttribute>();
if (suppressCodecsAttribute != null)
{
avoidCodecs.UnionWith(suppressCodecsAttribute.Value);
}
// set back to default
LuceneTestCase.OldFormatImpersonationIsActive = false;
savedCodec = Codec.Default;
int randomVal = random.Next(10);
if ("Lucene3x".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestDocValuesFormat, StringComparison.Ordinal) &&
randomVal == 3 &&
!ShouldAvoidCodec("Lucene3x"))) // preflex-only setup
{
codec = Codec.ForName("Lucene3x");
if (Debugging.AssertsEnabled) Debugging.Assert((codec is PreFlexRWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
LuceneTestCase.OldFormatImpersonationIsActive = true;
}
else if ("Lucene40".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal) &&
randomVal == 0 &&
!ShouldAvoidCodec("Lucene40"))) // 4.0 setup
{
codec = Codec.ForName("Lucene40");
LuceneTestCase.OldFormatImpersonationIsActive = true;
if (Debugging.AssertsEnabled) Debugging.Assert((codec is Lucene40RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
if (Debugging.AssertsEnabled) Debugging.Assert((PostingsFormat.ForName("Lucene40") is Lucene40RWPostingsFormat), "fix your IPostingsFormatFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if ("Lucene41".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestDocValuesFormat, StringComparison.Ordinal) &&
randomVal == 1 &&
!ShouldAvoidCodec("Lucene41")))
{
codec = Codec.ForName("Lucene41");
LuceneTestCase.OldFormatImpersonationIsActive = true;
if (Debugging.AssertsEnabled) Debugging.Assert((codec is Lucene41RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if ("Lucene42".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestDocValuesFormat, StringComparison.Ordinal) &&
randomVal == 2 &&
!ShouldAvoidCodec("Lucene42")))
{
codec = Codec.ForName("Lucene42");
LuceneTestCase.OldFormatImpersonationIsActive = true;
if (Debugging.AssertsEnabled) Debugging.Assert((codec is Lucene42RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if ("Lucene45".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TestDocValuesFormat, StringComparison.Ordinal) &&
randomVal == 5 &&
!ShouldAvoidCodec("Lucene45")))
{
codec = Codec.ForName("Lucene45");
LuceneTestCase.OldFormatImpersonationIsActive = true;
if (Debugging.AssertsEnabled) Debugging.Assert((codec is Lucene45RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if (("random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal) == false)
|| ("random".Equals(LuceneTestCase.TestDocValuesFormat, StringComparison.Ordinal) == false))
{
// the user wired postings or DV: this is messy
// refactor into RandomCodec....
PostingsFormat format;
if ("random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal))
{
format = PostingsFormat.ForName("Lucene41");
}
else if ("MockRandom".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal))
{
format = new MockRandomPostingsFormat(new Random(random.Next()));
}
else
{
format = PostingsFormat.ForName(LuceneTestCase.TestPostingsFormat);
}
DocValuesFormat dvFormat;
if ("random".Equals(LuceneTestCase.TestDocValuesFormat, StringComparison.Ordinal))
{
dvFormat = DocValuesFormat.ForName("Lucene45");
}
else
{
dvFormat = DocValuesFormat.ForName(LuceneTestCase.TestDocValuesFormat);
}
codec = new Lucene46CodecAnonymousInnerClassHelper(this, format, dvFormat);
}
else if ("SimpleText".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) && randomVal == 9 && LuceneTestCase.Rarely(random) && !ShouldAvoidCodec("SimpleText")))
{
codec = new SimpleTextCodec();
}
else if ("CheapBastard".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) && randomVal == 8 && !ShouldAvoidCodec("CheapBastard") && !ShouldAvoidCodec("Lucene41")))
{
// we also avoid this codec if Lucene41 is avoided, since thats the postings format it uses.
codec = new CheapBastardCodec();
}
else if ("Asserting".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) && randomVal == 6 && !ShouldAvoidCodec("Asserting")))
{
codec = new AssertingCodec();
}
else if ("Compressing".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal) && randomVal == 5 && !ShouldAvoidCodec("Compressing")))
{
codec = CompressingCodec.RandomInstance(random);
}
else if (!"random".Equals(LuceneTestCase.TestCodec, StringComparison.Ordinal))
{
codec = Codec.ForName(LuceneTestCase.TestCodec);
}
else if ("random".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal))
{
codec = new RandomCodec(random, avoidCodecs);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(false);
}
Codec.Default = codec;
// Initialize locale/ timezone.
string testLocale = SystemProperties.GetProperty("tests:locale", "random"); // LUCENENET specific - reformatted with :
string testTimeZone = SystemProperties.GetProperty("tests:timezone", "random"); // LUCENENET specific - reformatted with :
// Always pick a random one for consistency (whether tests.locale was specified or not).
savedLocale = CultureInfo.CurrentCulture;
CultureInfo randomLocale = LuceneTestCase.RandomCulture(random);
locale = testLocale.Equals("random", StringComparison.Ordinal) ? randomLocale : LuceneTestCase.CultureForName(testLocale);
#if FEATURE_CULTUREINFO_CURRENTCULTURE_SETTER
CultureInfo.CurrentCulture = locale;
#else
Thread.CurrentThread.CurrentCulture = locale;
#endif
// TimeZone.getDefault will set user.timezone to the default timezone of the user's locale.
// So store the original property value and restore it at end.
// LUCENENET specific - commented
//restoreProperties["user:timezone"] = SystemProperties.GetProperty("user:timezone");
savedTimeZone = TimeZoneInfo.Local;
TimeZoneInfo randomTimeZone = LuceneTestCase.RandomTimeZone(random);
timeZone = testTimeZone.Equals("random", StringComparison.Ordinal) ? randomTimeZone : TimeZoneInfo.FindSystemTimeZoneById(testTimeZone);
//TimeZone.Default = TimeZone; // LUCENENET NOTE: There doesn't seem to be an equivalent to this, but I don't think we need it.
similarity = random.NextBoolean() ? (Similarity)new DefaultSimilarity() : new RandomSimilarityProvider(random);
// Check codec restrictions once at class level.
try
{
CheckCodecRestrictions(codec);
}
catch (Exception e)
{
Console.Error.WriteLine("NOTE: " + e.Message + " Suppressed codecs: " + avoidCodecs);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
private class Lucene46CodecAnonymousInnerClassHelper : Lucene46Codec
{
private readonly TestRuleSetupAndRestoreClassEnv outerInstance;
private PostingsFormat format;
private DocValuesFormat dvFormat;
public Lucene46CodecAnonymousInnerClassHelper(TestRuleSetupAndRestoreClassEnv outerInstance, PostingsFormat format, DocValuesFormat dvFormat)
{
this.outerInstance = outerInstance;
this.format = format;
this.dvFormat = dvFormat;
}
public override PostingsFormat GetPostingsFormatForField(string field)
{
return format;
}
public override DocValuesFormat GetDocValuesFormatForField(string field)
{
return dvFormat;
}
public override string ToString()
{
return base.ToString() + ": " + format.ToString() + ", " + dvFormat.ToString();
}
}
/// <summary>
/// Check codec restrictions.
/// </summary>
/// <exception cref="AssumptionViolatedException"> if the class does not work with a given codec. </exception>
private void CheckCodecRestrictions(Codec codec)
{
LuceneTestCase.AssumeFalse("Class not allowed to use codec: " + codec.Name + ".", ShouldAvoidCodec(codec.Name));
if (codec is RandomCodec && avoidCodecs.Count > 0)
{
foreach (string name in ((RandomCodec)codec).FormatNames)
{
LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + name + ".", ShouldAvoidCodec(name));
}
}
PostingsFormat pf = codec.PostingsFormat;
LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + pf.Name + ".", ShouldAvoidCodec(pf.Name));
LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + LuceneTestCase.TestPostingsFormat + ".", ShouldAvoidCodec(LuceneTestCase.TestPostingsFormat));
}
/// <summary>
/// After suite cleanup (always invoked).
/// </summary>
public override void After(LuceneTestCase testInstance)
{
// LUCENENT specific - Not used in .NET
//foreach (KeyValuePair<string, string> e in restoreProperties)
//{
// SystemProperties.SetProperty(e.Key, e.Value);
//}
//restoreProperties.Clear();
Codec.Default = savedCodec;
InfoStream.Default = savedInfoStream;
if (savedLocale != null)
{
locale = savedLocale;
#if FEATURE_CULTUREINFO_CURRENTCULTURE_SETTER
CultureInfo.CurrentCulture = savedLocale;
#else
Thread.CurrentThread.CurrentCulture = savedLocale;
#endif
}
if (savedTimeZone != null)
{
timeZone = savedTimeZone;
}
}
/// <summary>
/// Should a given codec be avoided for the currently executing suite?
/// </summary>
private bool ShouldAvoidCodec(string codec)
{
return avoidCodecs.Count > 0 && avoidCodecs.Contains(codec);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Management.Infrastructure;
using Microsoft.PowerShell.Commands;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
#if !UNIX
using System.DirectoryServices;
#endif
using System.Globalization;
using System.Linq;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Net;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Numerics;
using System.Reflection;
using System.Security;
using System.Security.AccessControl;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Xml;
namespace System.Management.Automation.Language
{
internal static class TypeResolver
{
// our interface
// internal static Type ConvertTypeNameToType(TypeName typeName, out Exception exception)
// Used by TypeName.GetReflectionType and in TypeResolver
// internal static bool TryResolveType(string typeName, out Type type)
// Used in a bunch of places
// internal static Type ConvertStringToType(string typeName, out Exception exception)
// Used primarily in LanguagePrimitives.ConvertTo
private static Type LookForTypeInSingleAssembly(Assembly assembly, string typename)
{
Type targetType = assembly.GetType(typename, false, true);
if (targetType != null && IsPublic(targetType))
{
return targetType;
}
return null;
}
/// <summary>
/// Inherited from InvalidCastException, because it happens in [string] -> [Type] conversion.
/// </summary>
internal class AmbiguousTypeException : InvalidCastException
{
public string[] Candidates { private set; get; }
public TypeName TypeName { private set; get; }
public AmbiguousTypeException(TypeName typeName, IEnumerable<string> candidates)
{
Candidates = candidates.ToArray();
TypeName = typeName;
Diagnostics.Assert(Candidates.Length > 1, "AmbiguousTypeException can be created only when there are more then 1 candidate.");
}
}
private static Type LookForTypeInAssemblies(TypeName typeName,
IEnumerable<Assembly> assemblies,
HashSet<Assembly> searchedAssemblies,
TypeResolutionState typeResolutionState,
bool reportAmbiguousException,
out Exception exception)
{
exception = null;
string alternateNameToFind = typeResolutionState.GetAlternateTypeName(typeName.Name);
Type foundType = null;
Type foundType2 = null;
foreach (Assembly assembly in assemblies)
{
// Skip the assemblies that we already searched and found no matching type.
if (searchedAssemblies.Contains(assembly)) { continue; }
try
{
Type targetType = LookForTypeInSingleAssembly(assembly, typeName.Name);
if (targetType == null && alternateNameToFind != null)
{
targetType = LookForTypeInSingleAssembly(assembly, alternateNameToFind);
}
if (targetType != null)
{
if (!reportAmbiguousException)
{
// accelerator for the common case, when we are not interested in ambiguity exception.
return targetType;
}
// .NET has forward notation for types, when they declared in one assembly and implemented in another one.
// We want to support both scenarios:
// 1) When we pass assembly with declared forwarded type (CoreCLR)
// 2) When we pass assembly with declared forwarded type and assembly with implemented forwarded type (FullCLR)
// In the case (2) we should not report duplicate, hence this check
if (foundType != targetType)
{
if (foundType != null)
{
foundType2 = targetType;
break;
}
else
{
foundType = targetType;
}
}
}
else
{
// We didn't find a match from the current assembly, so update the searchedAssemblies set.
searchedAssemblies.Add(assembly);
}
}
catch (Exception) // Assembly.GetType might throw unadvertised exceptions
{
}
}
if (foundType2 != null)
{
exception = new AmbiguousTypeException(typeName, new string[] { foundType.AssemblyQualifiedName, foundType2.AssemblyQualifiedName });
return null;
}
return foundType;
}
/// <summary>
/// A type IsPublic if IsPublic or (IsNestedPublic and is nested in public type(s))
/// </summary>
internal static bool IsPublic(Type type)
{
if (type.IsPublic)
{
return true;
}
if (!type.IsNestedPublic)
{
return false;
}
while ((type = type.DeclaringType) != null)
{
if (!(type.IsPublic || type.IsNestedPublic))
{
return false;
}
}
return true;
}
private static Type ResolveTypeNameWorker(TypeName typeName,
SessionStateScope currentScope,
IEnumerable<Assembly> loadedAssemblies,
HashSet<Assembly> searchedAssemblies,
TypeResolutionState typeResolutionState,
bool onlySearchInGivenAssemblies,
bool reportAmbiguousException,
out Exception exception)
{
Type result;
exception = null;
if (!onlySearchInGivenAssemblies)
{
while (currentScope != null)
{
result = currentScope.LookupType(typeName.Name);
if (result != null)
{
return result;
}
currentScope = currentScope.Parent;
}
if (TypeAccelerators.builtinTypeAccelerators.TryGetValue(typeName.Name, out result))
{
return result;
}
}
result = LookForTypeInAssemblies(typeName, loadedAssemblies, searchedAssemblies, typeResolutionState, reportAmbiguousException, out exception);
if (exception != null)
{
// skip the rest of lookups, if exception reported.
return result;
}
if (!onlySearchInGivenAssemblies && result == null)
{
lock (TypeAccelerators.userTypeAccelerators)
{
TypeAccelerators.userTypeAccelerators.TryGetValue(typeName.Name, out result);
}
}
return result;
}
/// <summary>
/// A set of assemblies that we have searched from but found no matching type. By checking this set, we can
/// avoid searching from some assemblies multiple times.
/// This set is made thread static, so that type resolution happens on the same thread can reuse the HashSet
/// without having to create a new HashSet instance every time. This will reduce GC given that type resolution
/// is a frequent operation in powershell script.
/// </summary>
/// <remarks>
/// This set should be used directly only in the method CallResolveTypeNameWorkerHelper.
/// </remarks>
[ThreadStatic]
private static HashSet<Assembly> s_searchedAssemblies = null;
/// <summary>
/// A helper method to call ResolveTypeNameWorker in steps.
/// </summary>
private static Type CallResolveTypeNameWorkerHelper(TypeName typeName,
ExecutionContext context,
IEnumerable<Assembly> assemblies,
bool isAssembliesExplicitlyPassedIn,
TypeResolutionState typeResolutionState,
out Exception exception)
{
if (s_searchedAssemblies == null)
{
s_searchedAssemblies = new HashSet<Assembly>();
}
else
{
// Clear the set before starting a full search to make sure we have a clean start.
s_searchedAssemblies.Clear();
}
try
{
exception = null;
var currentScope = context != null ? context.EngineSessionState.CurrentScope : null;
Type result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, s_searchedAssemblies, typeResolutionState,
/*onlySearchInGivenAssemblies*/ false, /* reportAmbiguousException */ true, out exception);
if (exception == null && result == null)
{
if (context != null && !isAssembliesExplicitlyPassedIn)
{
// If the assemblies to search from is not specified by the caller of 'ResolveTypeNameWithContext',
// then we search our assembly cache first, so as to give preference to resolving the type against
// assemblies explicitly loaded by powershell, for example, via importing module/snapin.
result = ResolveTypeNameWorker(typeName, currentScope, context.AssemblyCache.Values, s_searchedAssemblies, typeResolutionState,
/*onlySearchInGivenAssemblies*/ true, /* reportAmbiguousException */ false, out exception);
}
if (result == null)
{
// Search from the assembly list passed in.
result = ResolveTypeNameWorker(typeName, currentScope, assemblies, s_searchedAssemblies, typeResolutionState,
/*onlySearchInGivenAssemblies*/ true, /* reportAmbiguousException */ false, out exception);
}
}
return result;
}
finally
{
// Clear the set after a full search, so dynamic assemblies can get reclaimed as needed.
s_searchedAssemblies.Clear();
}
}
internal static Type ResolveAssemblyQualifiedTypeName(TypeName typeName, out Exception exception)
{
// If an assembly name was specified, we let Type.GetType deal with loading the assembly
// and resolving the type.
exception = null;
try
{
// We shouldn't really bother looking for the type in System namespace, but
// we've always done that. We explicitly are not supporting arbitrary
// 'using namespace' here because there is little value, if you need the assembly
// qualifier, it's best to just fully specify the type.
var result = Type.GetType(typeName.FullName, false, true) ??
Type.GetType("System." + typeName.FullName, false, true);
if (result != null && IsPublic(result))
{
return result;
}
}
catch (Exception e)
{
exception = e;
}
return null;
}
internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception exception, Assembly[] assemblies, TypeResolutionState typeResolutionState)
{
ExecutionContext context = null;
exception = null;
if (typeResolutionState == null)
{
// Usings from script scope (and if no script scope, fall back to default 'using namespace system')
context = LocalPipeline.GetExecutionContextFromTLS();
typeResolutionState = TypeResolutionState.GetDefaultUsingState(context);
}
// We can do the cache lookup only if we don't define type in the current scope (cache would be invalid in this case).
var result = typeResolutionState.ContainsTypeDefined(typeName.Name)
? null
: TypeCache.Lookup(typeName, typeResolutionState);
if (result != null)
{
return result;
}
if (typeName.AssemblyName != null)
{
result = ResolveAssemblyQualifiedTypeName(typeName, out exception);
TypeCache.Add(typeName, typeResolutionState, result);
return result;
}
// Simple typename (no generics, no arrays, no assembly name)
// We use the following search order, using the specified name (assumed to be fully namespace qualified):
//
// * Search scope table (includes 'using type x = ...' aliases)
// * Built in type accelerators (implicit 'using type x = ...' aliases that are effectively in global scope
// * typeResolutionState.assemblies, which contains:
// - Assemblies with PS types, added by 'using module'
// - Assemblies added by 'using assembly'.
// For this case, we REPORT ambiguity, since user explicitly specifies the set of assemblies.
// * All other loaded assemblies (excluding dynamic assemblies created for PS defined types).
// IGNORE ambiguity. It mimics PS v4. There are two reasons:
// 1) If we report ambiguity, we need to fix our caching logic accordingly.
// Consider this code
// Add-Type 'public class Q {}' # ok
// Add-Type 'public class Q { }' # get error about the same name
// [Q] # we would get error about ambiguous type, because we added assembly with duplicated type
// # before we can report TYPE_ALREADY_EXISTS error.
//
// Add-Type 'public class Q2 {}' # ok
// [Q2] # caching Q2 type
// Add-Type 'public class Q2 { }' # get error about the same name
// [Q2] # we don't get an error about ambiguous type, because it's cached already
// 2) NuGet (VS Package Management console) uses MEF extensibility model.
// Different assemblies includes same interface (i.e. NuGet.VisualStudio.IVsPackageInstallerServices),
// where they include only methods that they are interested in the interface declaration (result interfaces are different!).
// Then, at runtime VS provides an instance. Everything work as far as instance has compatible API.
// So [NuGet.VisualStudio.IVsPackageInstallerServices] can be resolved to several different assemblies and it's ok.
// * User defined type accelerators (rare - interface was never public)
//
// If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'.
// We must search all using aliases and REPORT an error if there is an ambiguity.
// If this is TypeDefinition we should not cache anything in TypeCache.
if (typeName._typeDefinitionAst != null)
{
return typeName._typeDefinitionAst.Type;
}
if (context == null)
{
context = LocalPipeline.GetExecutionContextFromTLS();
}
// Use the explicitly passed-in assembly list when it's specified by the caller.
// Otherwise, retrieve all currently loaded assemblies.
var assemList = assemblies ?? ClrFacade.GetAssemblies(typeResolutionState, typeName);
var isAssembliesExplicitlyPassedIn = assemblies != null;
result = CallResolveTypeNameWorkerHelper(typeName, context, assemList, isAssembliesExplicitlyPassedIn, typeResolutionState, out exception);
if (result != null)
{
TypeCache.Add(typeName, typeResolutionState, result);
return result;
}
if (exception == null)
{
foreach (var ns in typeResolutionState.namespaces)
{
var newTypeNameToSearch = ns + "." + typeName.Name;
newTypeNameToSearch = typeResolutionState.GetAlternateTypeName(newTypeNameToSearch) ??
newTypeNameToSearch;
var newTypeName = new TypeName(typeName.Extent, newTypeNameToSearch);
#if CORECLR
if (!isAssembliesExplicitlyPassedIn)
{
// We called 'ClrFacade.GetAssemblies' to get assemblies. That means the assemblies to search from
// are not pre-defined, and thus we have to refetch assembly again based on the new type name.
assemList = ClrFacade.GetAssemblies(typeResolutionState, newTypeName);
}
#endif
var newResult = CallResolveTypeNameWorkerHelper(newTypeName, context, assemList, isAssembliesExplicitlyPassedIn, typeResolutionState, out exception);
if (exception != null)
{
break;
}
if (newResult != null)
{
if (result == null)
{
result = newResult;
}
else
{
exception = new AmbiguousTypeException(typeName, new string[] { result.FullName, newResult.FullName });
result = null;
break;
}
}
}
}
if (exception != null)
{
// AmbiguousTypeException is for internal representation only.
var ambiguousException = exception as AmbiguousTypeException;
if (ambiguousException != null)
{
exception = new PSInvalidCastException("AmbiguousTypeReference", exception,
ParserStrings.AmbiguousTypeReference, ambiguousException.TypeName.Name,
ambiguousException.Candidates[0], ambiguousException.Candidates[1]);
}
}
if (result != null)
{
TypeCache.Add(typeName, typeResolutionState, result);
}
return result;
}
internal static Type ResolveTypeName(TypeName typeName, out Exception exception)
{
return ResolveTypeNameWithContext(typeName, out exception, null, null);
}
internal static bool TryResolveType(string typeName, out Type type)
{
Exception exception;
type = ResolveType(typeName, out exception);
return (type != null);
}
internal static Type ResolveITypeName(ITypeName iTypeName, out Exception exception)
{
exception = null;
var typeName = iTypeName as TypeName;
if (typeName == null)
{
// The type is something more complicated - generic or array.
try
{
return iTypeName.GetReflectionType();
}
catch (Exception e)
{
exception = e;
return null;
}
}
return ResolveTypeName(typeName, out exception);
}
/// <summary>
/// This routine converts a string into a Type object using the msh rules.
/// </summary>
/// <param name="strTypeName">A string representing the name of the type to convert.</param>
/// <param name="exception">The exception, if one happened, trying to find the type.</param>
/// <returns>A type if the conversion was successful, null otherwise.</returns>
internal static Type ResolveType(string strTypeName, out Exception exception)
{
exception = null;
if (string.IsNullOrWhiteSpace(strTypeName))
{
return null;
}
var iTypeName = Parser.ScanType(strTypeName, ignoreErrors: false);
if (iTypeName == null)
{
return null;
}
return ResolveITypeName(iTypeName, out exception);
}
}
/// <summary>
/// The idea behind this class is: I should be able to re-use expensive
/// type resolution operation result in the same context.
/// Hence, this class is a key for TypeCache dictionary.
///
/// Every SessionStateScope has TypeResolutionState.
/// typesDefined contains PowerShell types names defined in the current scope and all scopes above.
/// Same for namespaces.
///
/// If TypeResolutionState doesn't add anything new compare to it's parent, we represent it as null.
/// So, when we do lookup, we need to find first non-null TypeResolutionState.
/// </summary>
internal class TypeResolutionState
{
internal static readonly string[] systemNamespace = { "System" };
internal static readonly Assembly[] emptyAssemblies = Utils.EmptyArray<Assembly>();
internal static readonly TypeResolutionState UsingSystem = new TypeResolutionState();
internal readonly string[] namespaces;
internal readonly Assembly[] assemblies;
private readonly HashSet<string> _typesDefined;
internal readonly int genericArgumentCount;
internal readonly bool attribute;
private TypeResolutionState()
: this(systemNamespace, emptyAssemblies)
{
}
/// <summary>
/// TypeResolutionState can be shared and that's why it should be represented as an immutable object.
/// So, we use this API to alternate TypeResolutionState, but instead of mutating existing one, we clone it.
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
internal TypeResolutionState CloneWithAddTypesDefined(IEnumerable<string> types)
{
var newTypesDefined = new HashSet<string>(_typesDefined, StringComparer.OrdinalIgnoreCase);
foreach (var type in types)
{
newTypesDefined.Add(type);
}
return new TypeResolutionState(this, newTypesDefined);
}
internal bool ContainsTypeDefined(string type)
{
return _typesDefined.Contains(type);
}
internal TypeResolutionState(string[] namespaces, Assembly[] assemblies)
{
this.namespaces = namespaces ?? systemNamespace;
this.assemblies = assemblies ?? emptyAssemblies;
_typesDefined = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
internal TypeResolutionState(TypeResolutionState other, int genericArgumentCount, bool attribute)
{
this.namespaces = other.namespaces;
this.assemblies = other.assemblies;
_typesDefined = other._typesDefined;
this.genericArgumentCount = genericArgumentCount;
this.attribute = attribute;
}
private TypeResolutionState(TypeResolutionState other, HashSet<string> typesDefined)
{
this.namespaces = other.namespaces;
this.assemblies = other.assemblies;
_typesDefined = typesDefined;
this.genericArgumentCount = other.genericArgumentCount;
this.attribute = other.attribute;
}
internal static TypeResolutionState GetDefaultUsingState(ExecutionContext context)
{
if (context == null)
{
context = LocalPipeline.GetExecutionContextFromTLS();
}
if (context != null)
{
return context.EngineSessionState.CurrentScope.TypeResolutionState;
}
return TypeResolutionState.UsingSystem;
}
internal string GetAlternateTypeName(string typeName)
{
string alternateName = null;
if (genericArgumentCount > 0 && typeName.IndexOf('`') < 0)
{
alternateName = typeName + "`" + genericArgumentCount;
}
else if (attribute && !typeName.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase))
{
alternateName = typeName + "Attribute";
}
return alternateName;
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
var other = obj as TypeResolutionState;
if (other == null)
return false;
if (this.attribute != other.attribute)
return false;
if (this.genericArgumentCount != other.genericArgumentCount)
return false;
if (this.namespaces.Length != other.namespaces.Length)
return false;
if (this.assemblies.Length != other.assemblies.Length)
return false;
for (int i = 0; i < namespaces.Length; i++)
{
if (!this.namespaces[i].Equals(other.namespaces[i], StringComparison.OrdinalIgnoreCase))
return false;
}
for (int i = 0; i < assemblies.Length; i++)
{
if (!this.assemblies[i].Equals(other.assemblies[i]))
return false;
}
if (_typesDefined.Count != other._typesDefined.Count)
return false;
return _typesDefined.SetEquals(other._typesDefined);
}
public override int GetHashCode()
{
var stringComparer = StringComparer.OrdinalIgnoreCase;
int result = Utils.CombineHashCodes(genericArgumentCount.GetHashCode(), attribute.GetHashCode());
for (int i = 0; i < namespaces.Length; i++)
{
result = Utils.CombineHashCodes(result, stringComparer.GetHashCode(namespaces[i]));
}
for (int i = 0; i < assemblies.Length; i++)
{
result = Utils.CombineHashCodes(result, this.assemblies[i].GetHashCode());
}
foreach (var t in _typesDefined)
{
result = Utils.CombineHashCodes(result, t.GetHashCode());
}
return result;
}
}
internal class TypeCache
{
private class KeyComparer : IEqualityComparer<Tuple<ITypeName, TypeResolutionState>>
{
public bool Equals(Tuple<ITypeName, TypeResolutionState> x,
Tuple<ITypeName, TypeResolutionState> y)
{
return x.Item1.Equals(y.Item1) && x.Item2.Equals(y.Item2);
}
public int GetHashCode(Tuple<ITypeName, TypeResolutionState> obj)
{
return obj.GetHashCode();
}
}
private static readonly ConcurrentDictionary<Tuple<ITypeName, TypeResolutionState>, Type> s_cache = new ConcurrentDictionary<Tuple<ITypeName, TypeResolutionState>, Type>(new KeyComparer());
internal static Type Lookup(ITypeName typeName, TypeResolutionState typeResolutionState)
{
Type result;
s_cache.TryGetValue(Tuple.Create(typeName, typeResolutionState), out result);
return result;
}
internal static void Add(ITypeName typeName, TypeResolutionState typeResolutionState, Type type)
{
s_cache.GetOrAdd(Tuple.Create(typeName, typeResolutionState), type);
}
}
}
namespace System.Management.Automation
{
/// <summary>
/// A class to the core types in PowerShell.
/// </summary>
internal static class CoreTypes
{
// A list of the core PowerShell types, and their accelerator.
//
// These types are frequently used in scripting, and for parameter validation in scripts.
//
// When in ConstrainedLanguage mode, all operations on these types are fully supported unlike all other
// types that are assumed to have dangerous constructors or methods.
//
// Do not add types to this pool unless they can be safely exposed to an attacker and will not
// expose the ability to corrupt or escape PowerShell's environment. The following operations must
// be safe: type conversion, all constructors, all methods (instance and static), and
// and properties (instance and static).
internal static Lazy<Dictionary<Type, string[]>> Items = new Lazy<Dictionary<Type, string[]>>(
() =>
new Dictionary<Type, string[]>
{
{ typeof(AliasAttribute), new[] { "Alias" } },
{ typeof(AllowEmptyCollectionAttribute), new[] { "AllowEmptyCollection" } },
{ typeof(AllowEmptyStringAttribute), new[] { "AllowEmptyString" } },
{ typeof(AllowNullAttribute), new[] { "AllowNull" } },
{ typeof(ArgumentCompleterAttribute), new[] { "ArgumentCompleter" } },
{ typeof(ArgumentCompletionsAttribute), new[] { "ArgumentCompletions" } },
{ typeof(Array), new[] { "array" } },
{ typeof(bool), new[] { "bool" } },
{ typeof(byte), new[] { "byte" } },
{ typeof(char), new[] { "char" } },
{ typeof(CmdletBindingAttribute), new[] { "CmdletBinding" } },
{ typeof(DateTime), new[] { "datetime" } },
{ typeof(decimal), new[] { "decimal" } },
{ typeof(double), new[] { "double" } },
{ typeof(DscResourceAttribute), new[] { "DscResource" } },
{ typeof(ExperimentAction), new[] { "ExperimentAction" } },
{ typeof(ExperimentalAttribute), new[] { "Experimental" } },
{ typeof(ExperimentalFeature), new[] { "ExperimentalFeature" } },
{ typeof(float), new[] { "float", "single" } },
{ typeof(Guid), new[] { "guid" } },
{ typeof(Hashtable), new[] { "hashtable" } },
{ typeof(int), new[] { "int", "int32" } },
{ typeof(Int16), new[] { "short", "int16" } },
{ typeof(long), new[] { "long", "int64" } },
{ typeof(CimInstance), new[] { "ciminstance" } },
{ typeof(CimClass), new[] { "cimclass" } },
{ typeof(Microsoft.Management.Infrastructure.CimType), new[] { "cimtype" } },
{ typeof(CimConverter), new[] { "cimconverter" } },
{ typeof(ModuleSpecification), null },
{ typeof(IPEndPoint), new[] { "IPEndpoint" } },
{ typeof(NullString), new[] { "NullString" } },
{ typeof(OutputTypeAttribute), new[] { "OutputType" } },
{ typeof(Object[]), null },
{ typeof(ObjectSecurity), new[] { "ObjectSecurity" } },
{ typeof(ParameterAttribute), new[] { "Parameter" } },
{ typeof(PhysicalAddress), new[] { "PhysicalAddress" } },
{ typeof(PSCredential), new[] { "pscredential" } },
{ typeof(PSDefaultValueAttribute), new[] { "PSDefaultValue" } },
{ typeof(PSListModifier), new[] { "pslistmodifier" } },
{ typeof(PSObject), new[] { "psobject", "pscustomobject" } },
{ typeof(PSPrimitiveDictionary), new[] { "psprimitivedictionary" } },
{ typeof(PSReference), new[] { "ref" } },
{ typeof(PSTypeNameAttribute), new[] { "PSTypeNameAttribute" } },
{ typeof(Regex), new[] { "regex" } },
{ typeof(DscPropertyAttribute), new[] { "DscProperty" } },
{ typeof(SByte), new[] { "sbyte" } },
{ typeof(string), new[] { "string" } },
{ typeof(SupportsWildcardsAttribute), new[] { "SupportsWildcards" } },
{ typeof(SwitchParameter), new[] { "switch" } },
{ typeof(CultureInfo), new[] { "cultureinfo" } },
{ typeof(BigInteger), new[] { "bigint" } },
{ typeof(SecureString), new[] { "securestring" } },
{ typeof(TimeSpan), new[] { "timespan" } },
{ typeof(UInt16), new[] { "ushort", "uint16" } },
{ typeof(UInt32), new[] { "uint", "uint32" } },
{ typeof(UInt64), new[] { "ulong", "uint64" } },
{ typeof(Uri), new[] { "uri" } },
{ typeof(ValidateCountAttribute), new[] { "ValidateCount" } },
{ typeof(ValidateDriveAttribute), new[] { "ValidateDrive" } },
{ typeof(ValidateLengthAttribute), new[] { "ValidateLength" } },
{ typeof(ValidateNotNullAttribute), new[] { "ValidateNotNull" } },
{ typeof(ValidateNotNullOrEmptyAttribute), new[] { "ValidateNotNullOrEmpty" } },
{ typeof(ValidatePatternAttribute), new[] { "ValidatePattern" } },
{ typeof(ValidateRangeAttribute), new[] { "ValidateRange" } },
{ typeof(ValidateScriptAttribute), new[] { "ValidateScript" } },
{ typeof(ValidateSetAttribute), new[] { "ValidateSet" } },
{ typeof(ValidateTrustedDataAttribute), new[] { "ValidateTrustedData" } },
{ typeof(ValidateUserDriveAttribute), new[] { "ValidateUserDrive"} },
{ typeof(Version), new[] { "version" } },
{ typeof(void), new[] { "void" } },
{ typeof(IPAddress), new[] { "ipaddress" } },
{ typeof(DscLocalConfigurationManagerAttribute), new[] {"DscLocalConfigurationManager"}},
{ typeof(WildcardPattern), new[] { "WildcardPattern" } },
{ typeof(X509Certificate), new[] { "X509Certificate" } },
{ typeof(X500DistinguishedName), new[] { "X500DistinguishedName" } },
{ typeof(XmlDocument), new[] { "xml" } },
{ typeof(CimSession), new[] { "CimSession" } },
{ typeof(MailAddress), new[] { "mailaddress" } },
{ typeof(SemanticVersion), new[] { "semver" } },
#if !UNIX
{ typeof(DirectoryEntry), new[] { "adsi" } },
{ typeof(DirectorySearcher), new[] { "adsisearcher" } },
{ typeof(ManagementClass), new[] { "wmiclass" } },
{ typeof(ManagementObject), new[] { "wmi" } },
{ typeof(ManagementObjectSearcher), new[] { "wmisearcher" } }
#endif
}
);
internal static bool Contains(Type inputType)
{
if (Items.Value.ContainsKey(inputType))
{
return true;
}
if (inputType.IsEnum)
{
return true;
}
if (inputType.IsGenericType)
{
var genericTypeDefinition = inputType.GetGenericTypeDefinition();
return genericTypeDefinition == typeof(Nullable<>) || genericTypeDefinition == typeof(FlagsExpression<>);
}
return (inputType.IsArray && Contains(inputType.GetElementType()));
}
}
/// <summary>
/// A class to view and modify the type accelerators used by the PowerShell engine. Builtin
/// type accelerators are read only, but user defined type accelerators may be added.
/// </summary>
internal static class TypeAccelerators
{
// builtins are not exposed publicly in a direct manner so they can't be changed at all
internal static Dictionary<string, Type> builtinTypeAccelerators = new Dictionary<string, Type>(64, StringComparer.OrdinalIgnoreCase);
// users can add to user added accelerators (but not currently remove any.) Keeping a separate
// list allows us to add removing in the future w/o worrying about breaking the builtins.
internal static Dictionary<string, Type> userTypeAccelerators = new Dictionary<string, Type>(64, StringComparer.OrdinalIgnoreCase);
// We expose this one publicly for programmatic access to our type accelerator table, but it is
// otherwise unused (so changes to this dictionary don't affect internals.)
private static Dictionary<string, Type> s_allTypeAccelerators;
static TypeAccelerators()
{
// Add all the core types
foreach (KeyValuePair<Type, string[]> coreType in CoreTypes.Items.Value)
{
if (coreType.Value != null)
{
foreach (string accelerator in coreType.Value)
{
builtinTypeAccelerators.Add(accelerator, coreType.Key);
}
}
}
// Add additional utility types that are useful as type accelerators, but aren't
// fundamentally "core language", or may be unsafe to expose to untrusted input.
builtinTypeAccelerators.Add("scriptblock", typeof(ScriptBlock));
builtinTypeAccelerators.Add("pspropertyexpression", typeof(PSPropertyExpression));
builtinTypeAccelerators.Add("psvariable", typeof(PSVariable));
builtinTypeAccelerators.Add("type", typeof(Type));
builtinTypeAccelerators.Add("psmoduleinfo", typeof(PSModuleInfo));
builtinTypeAccelerators.Add("powershell", typeof(PowerShell));
builtinTypeAccelerators.Add("runspacefactory", typeof(RunspaceFactory));
builtinTypeAccelerators.Add("runspace", typeof(Runspace));
builtinTypeAccelerators.Add("initialsessionstate", typeof(InitialSessionState));
builtinTypeAccelerators.Add("psscriptmethod", typeof(PSScriptMethod));
builtinTypeAccelerators.Add("psscriptproperty", typeof(PSScriptProperty));
builtinTypeAccelerators.Add("psnoteproperty", typeof(PSNoteProperty));
builtinTypeAccelerators.Add("psaliasproperty", typeof(PSAliasProperty));
builtinTypeAccelerators.Add("psvariableproperty", typeof(PSVariableProperty));
}
internal static string FindBuiltinAccelerator(Type type, string expectedKey = null)
{
// Taking attributes as special case. In this case, we only want to return the
// accelerator.
if (expectedKey == null || typeof(Attribute).IsAssignableFrom(type))
{
foreach (KeyValuePair<string, Type> entry in builtinTypeAccelerators)
{
if (entry.Value == type)
{
return entry.Key;
}
}
}
else
{
Type resultType = null;
builtinTypeAccelerators.TryGetValue(expectedKey, out resultType);
if (resultType != null && resultType == type)
{
return expectedKey;
}
}
return null;
}
/// <summary>
/// Add a type accelerator.
/// </summary>
/// <param name="typeName">The type accelerator name.</param>
/// <param name="type">The type of the type accelerator.</param>
public static void Add(string typeName, Type type)
{
userTypeAccelerators[typeName] = type;
if (s_allTypeAccelerators != null)
{
s_allTypeAccelerators[typeName] = type;
}
}
/// <summary>
/// Remove a type accelerator.
/// </summary>
/// <returns>True if the accelerator was removed, false otherwise.</returns>
/// <param name="typeName">The accelerator to remove.</param>
public static bool Remove(string typeName)
{
userTypeAccelerators.Remove(typeName);
if (s_allTypeAccelerators != null)
{
s_allTypeAccelerators.Remove(typeName);
}
return true;
}
/// <summary>
/// This property is useful to tools that need to know what
/// type accelerators are available (e.g. to allow for autocompletion.)
/// </summary>
/// <remarks>
/// The returned dictionary should be treated as read only. Changes made
/// to the dictionary will not affect PowerShell scripts in any way. Use
/// <see cref="TypeAccelerators.Add"/> and
/// <see cref="TypeAccelerators.Remove"/> to
/// affect the type resolution in PowerShell scripts.
/// </remarks>
public static Dictionary<string, Type> Get
{
get
{
if (s_allTypeAccelerators == null)
{
s_allTypeAccelerators = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
FillCache(s_allTypeAccelerators);
}
return s_allTypeAccelerators;
}
}
internal static void FillCache(Dictionary<string, Type> cache)
{
foreach (KeyValuePair<string, Type> val in builtinTypeAccelerators)
{
cache.Add(val.Key, val.Value);
}
foreach (KeyValuePair<string, Type> val in userTypeAccelerators)
{
cache.Add(val.Key, val.Value);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <license file="QName.cs">
//
// The use and distribution terms for this software are contained in the file
// named 'LICENSE', which can be found in the resources directory of this
// distribution.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// </license>
//------------------------------------------------------------------------------
using System;
using EcmaScript.NET;
using EcmaScript.NET.Types;
namespace EcmaScript.NET.Types.E4X
{
/// <summary> Class QName
///
/// </summary>
[Serializable]
sealed class QName : IdScriptableObject
{
override public string ClassName
{
get
{
return "QName";
}
}
protected override internal int MaxInstanceId
{
get
{
return base.MaxInstanceId + MAX_INSTANCE_ID;
}
}
private static readonly object QNAME_TAG = new object ();
internal XMLLib lib;
private string prefix;
private string localName;
private string uri;
internal QName (XMLLib lib)
: base (lib.GlobalScope, lib.qnamePrototype)
{
this.lib = lib;
}
internal QName (XMLLib lib, QName qname)
:
this (lib, qname.Uri, qname.LocalName, qname.Prefix)
{
;
}
internal QName (XMLLib lib, string uri, string localName, string prefix)
: base (lib.GlobalScope, lib.qnamePrototype)
{
if (localName == null)
throw new System.ArgumentException ();
this.lib = lib;
this.uri = uri;
this.prefix = prefix;
this.localName = localName;
}
internal void ExportAsJSClass (bool zealed)
{
ExportAsJSClass (MAX_PROTOTYPE_ID, lib.GlobalScope, zealed);
}
/// <summary> </summary>
/// <returns>
/// </returns>
public override string ToString ()
{
string result;
if (uri == null) {
result = string.Concat ("*::", localName);
}
else if (uri.Length == 0) {
result = localName;
}
else {
result = uri + "::" + localName;
}
return result;
}
public string LocalName
{
get
{
return localName;
}
}
internal string Prefix
{
get
{
return (prefix == null) ? prefix : "";
}
}
internal string Uri
{
get
{
return uri;
}
}
public override int GetHashCode ()
{
return base.GetHashCode ();
}
public override bool Equals (object obj)
{
QName qName = (obj as QName);
if (qName == null)
return false;
return Equals (qName);
}
protected internal override object EquivalentValues (object value)
{
QName qName = (value as QName);
if (qName == null)
return UniqueTag.NotFound;
return Equals (qName);
}
private bool Equals (QName q)
{
return CliHelper.Equals (LocalName, q.LocalName)
&& CliHelper.Equals (Uri, q.Uri);
}
/// <summary> </summary>
/// <param name="">hint
/// </param>
/// <returns>
/// </returns>
public override object GetDefaultValue (System.Type hint)
{
return ToString ();
}
#region InstanceIds
private const int Id_localName = 1;
private const int Id_uri = 2;
private const int MAX_INSTANCE_ID = 2;
#endregion
protected internal override int FindInstanceIdInfo (string s)
{
int id;
#region Generated InstanceId Switch
L0: {
id = 0;
string X = null;
int s_length = s.Length;
if (s_length == 3) { X = "uri"; id = Id_uri; }
else if (s_length == 9) { X = "localName"; id = Id_localName; }
if (X != null && X != s && !X.Equals (s))
id = 0;
}
EL0:
#endregion
if (id == 0)
return base.FindInstanceIdInfo (s);
int attr;
switch (id) {
case Id_localName:
case Id_uri:
attr = PERMANENT | READONLY;
break;
default:
throw new System.SystemException ();
}
return InstanceIdInfo (attr, base.MaxInstanceId + id);
}
protected internal override string GetInstanceIdName (int id)
{
switch (id - base.MaxInstanceId) {
case Id_localName:
return "localName";
case Id_uri:
return "uri";
}
return base.GetInstanceIdName (id);
}
protected internal override object GetInstanceIdValue (int id)
{
switch (id - base.MaxInstanceId) {
case Id_localName:
return localName;
case Id_uri:
return uri;
}
return base.GetInstanceIdValue (id);
}
#region PrototypeIds
private const int Id_constructor = 1;
private const int Id_toString = 2;
private const int Id_toSource = 3;
private const int MAX_PROTOTYPE_ID = 3;
#endregion
protected internal override int FindPrototypeId (string s)
{
int id;
#region Generated PrototypeId Switch
L0: {
id = 0;
string X = null;
int c;
int s_length = s.Length;
if (s_length == 8) {
c = s [3];
if (c == 'o') { X = "toSource"; id = Id_toSource; }
else if (c == 't') { X = "toString"; id = Id_toString; }
}
else if (s_length == 11) { X = "constructor"; id = Id_constructor; }
if (X != null && X != s && !X.Equals (s))
id = 0;
}
EL0:
#endregion
return id;
}
protected internal override void InitPrototypeId (int id)
{
string s;
int arity;
switch (id) {
case Id_constructor:
arity = 2;
s = "constructor";
break;
case Id_toString:
arity = 0;
s = "toString";
break;
case Id_toSource:
arity = 0;
s = "toSource";
break;
default:
throw new ArgumentException (System.Convert.ToString (id));
}
InitPrototypeMethod (QNAME_TAG, id, s, arity);
}
public override object ExecIdCall (IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args)
{
if (!f.HasTag (QNAME_TAG)) {
return base.ExecIdCall (f, cx, scope, thisObj, args);
}
int id = f.MethodId;
switch (id) {
case Id_constructor:
return jsConstructor (cx, (thisObj == null), args);
case Id_toString:
return realThis (thisObj, f).ToString ();
case Id_toSource:
return realThis (thisObj, f).js_toSource ();
}
throw new ArgumentException (System.Convert.ToString (id));
}
private QName realThis (IScriptable thisObj, IdFunctionObject f)
{
if (!(thisObj is QName))
throw IncompatibleCallError (f);
return (QName)thisObj;
}
private object jsConstructor (Context cx, bool inNewExpr, object [] args)
{
if (!inNewExpr && args.Length == 1) {
return QName.Parse (lib, cx, args [0]);
}
if (args.Length == 0) {
return QName.Parse (lib, cx, Undefined.Value);
}
else if (args.Length == 1) {
return QName.Parse (lib, cx, args [0]);
}
else {
return QName.Parse (lib, cx, args [0], args [1]);
}
}
internal static QName Parse (XMLLib lib, Context cx, object value)
{
QName result;
if (value is QName) {
QName qname = (QName)value;
result = new QName (lib, qname.Uri, qname.LocalName,
qname.Prefix);
}
else {
result = Parse (lib, cx, ScriptConvert.ToString (value));
}
return result;
}
internal static QName Parse (XMLLib lib, Context cx, string localName)
{
if (localName == null)
throw new ArgumentNullException ("localName");
String uri;
String prefix;
if ("*".Equals (localName)) {
uri = null;
prefix = null;
}
else {
Namespace ns = lib.GetDefaultNamespace (cx);
uri = ns.Uri;
prefix = ns.Prefix;
}
return new QName (lib, uri, localName, prefix);
}
internal static QName Parse (XMLLib lib, Context cx, object namespaceValue, object nameValue)
{
String uri;
String localName;
String prefix;
if (nameValue is QName) {
QName qname = (QName)nameValue;
localName = qname.LocalName;
}
else {
localName = ScriptConvert.ToString (nameValue);
}
Namespace ns;
if (namespaceValue == Undefined.Value) {
if ("*".Equals (localName)) {
ns = null;
}
else {
ns = lib.GetDefaultNamespace (cx);
}
}
else if (namespaceValue == null) {
ns = null;
}
else if (namespaceValue is Namespace) {
ns = (Namespace)namespaceValue;
}
else {
ns = Namespace.Parse (lib, cx, namespaceValue);
}
if (ns == null) {
uri = null;
prefix = null;
}
else {
uri = ns.Uri;
prefix = ns.Prefix;
}
return new QName (lib, uri, localName, prefix);
}
private string js_toSource ()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
sb.Append ('(');
toSourceImpl (uri, localName, prefix, sb);
sb.Append (')');
return sb.ToString ();
}
private static void toSourceImpl (string uri, string localName, string prefix, System.Text.StringBuilder sb)
{
sb.Append ("new QName(");
if (uri == null && prefix == null) {
if (!"*".Equals (localName)) {
sb.Append ("null, ");
}
}
else {
Namespace.toSourceImpl (prefix, uri, sb);
sb.Append (", ");
}
sb.Append ('\'');
sb.Append (ScriptRuntime.escapeString (localName, '\''));
sb.Append ("')");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor
{
public class RazorPageCreateModelExpressionTest
{
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_IdentityExpressions_ForModelGivesM()
{
// m => m
// Arrange
var viewContext = CreateViewContext();
var modelExplorer = viewContext.ViewData.ModelExplorer.GetExplorerForProperty(
nameof(RazorPageCreateModelExpressionModel.Name));
var viewData = new ViewDataDictionary<string>(viewContext.ViewData)
{
ModelExplorer = modelExplorer,
};
viewContext.ViewData = viewData;
var page = CreateIdentityPage(viewContext);
// Act
var modelExpression = page.CreateModelExpression1();
// Assert
Assert.NotNull(modelExpression);
Assert.Empty(modelExpression.Name);
Assert.Same(modelExplorer, modelExpression.ModelExplorer);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_IdentityExpressions_ForModelGivesModel()
{
// m => m.Model
// Arrange
var viewContext = CreateViewContext();
var modelExplorer = viewContext.ViewData.ModelExplorer.GetExplorerForProperty(
nameof(RazorPageCreateModelExpressionModel.Name));
var viewData = new ViewDataDictionary<string>(viewContext.ViewData)
{
ModelExplorer = modelExplorer,
};
viewContext.ViewData = viewData;
var page = CreateIdentityPage(viewContext);
// Act
var modelExpression = page.CreateModelExpression2();
// Assert
Assert.NotNull(modelExpression);
Assert.Empty(modelExpression.Name);
Assert.Same(modelExplorer, modelExpression.ModelExplorer);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_NotQuiteIdentityExpressions_ForModelGivesMDotModel()
{
// m => m.Model
// Arrange
var expectedName = "Model";
var expectedType = typeof(RecursiveModel);
CreateModelExpression_NotQuiteIdentityExpressions(page => page.CreateModelExpression1(), expectedName, expectedType);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_NotQuiteIdentityExpressions_ForModelGivesViewDataDotModel()
{
// m => ViewData.Model
// Arrange
var expectedName = "ViewData.Model";
var expectedType = typeof(RecursiveModel);
CreateModelExpression_NotQuiteIdentityExpressions(page => page.CreateModelExpression2(), expectedName, expectedType);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_NotQuiteIdentityExpressions_ForModelGivesViewContextDotViewDataDotModel()
{
// m => ViewContext.ViewData.Model
// Arrange
var expectedName = "ViewContext.ViewData.Model";
// This property has type object because ViewData is not exposed as ViewDataDictionary<TModel>.
var expectedType = typeof(object);
CreateModelExpression_NotQuiteIdentityExpressions(page => page.CreateModelExpression3(), expectedName, expectedType);
}
private static void CreateModelExpression_NotQuiteIdentityExpressions(
Func<NotQuiteIdentityRazorPage, ModelExpression> createModelExpression,
string expectedName,
Type expectedType)
{
var viewContext = CreateViewContext();
var viewData = new ViewDataDictionary<RecursiveModel>(viewContext.ViewData);
viewContext.ViewData = viewData;
var modelExplorer = viewData.ModelExplorer;
var page = CreateNotQuiteIdentityPage(viewContext);
// Act
var modelExpression = createModelExpression(page);
// Assert
Assert.NotNull(modelExpression);
Assert.Equal(expectedName, modelExpression.Name);
Assert.NotNull(modelExpression.ModelExplorer);
Assert.NotSame(modelExplorer, modelExpression.ModelExplorer);
Assert.NotNull(modelExpression.Metadata);
Assert.Equal(ModelMetadataKind.Property, modelExpression.Metadata.MetadataKind);
Assert.Equal(expectedType, modelExpression.Metadata.ModelType);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_IntExpressions_ForModelGivesSomethingElse()
{
// Arrange
var expected = "somethingElse";
var somethingElse = 23;
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => somethingElse);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(int), result.Metadata.ModelType);
Assert.Equal(expected, result.Name);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_IntExpressions_ForModelGivesId()
{
// Arrange
var expected = "Id";
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => model.Id);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(int), result.Metadata.ModelType);
Assert.Equal(expected, result.Name);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_IntExpressions_ForModelGivesSubModelId()
{
// Arrange
var expected = "SubModel.Id";
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => model.SubModel.Id);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(int), result.Metadata.ModelType);
Assert.Equal(expected, result.Name);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_IntExpressions_ForModelGivesSubSubModelId()
{
// Arrange
var expected = "SubModel.SubSubModel.Id";
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => model.SubModel.SubSubModel.Id);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(int), result.Metadata.ModelType);
Assert.Equal(expected, result.Name);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_StringExpressions_ForModelGivesSomethingElse()
{
// Arrange
var somethingElse = "This is something else";
var expectedName = "somethingElse";
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => somethingElse);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(string), result.Metadata.ModelType);
Assert.Equal(expectedName, result.Name);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_StringExpressions_ForModelGivesName()
{
// Arrange
var expectedName = "Name";
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => model.Name);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(string), result.Metadata.ModelType);
Assert.Equal(expectedName, result.Name);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_StringExpressions_ForModelGivesSubmodelName()
{
// Arrange
var expectedName = "SubModel.SubSubModel.Name";
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => model.SubModel.SubSubModel.Name);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(string), result.Metadata.ModelType);
Assert.Equal(expectedName, result.Name);
}
[Fact]
public void CreateModelExpression_ReturnsExpectedMetadata_StringExpressions_ForModelGivesSubSubmodelName()
{
// Arrange
var expectedName = "SubModel.Name";
var viewContext = CreateViewContext();
var page = CreatePage(viewContext);
// Act
var result = page.ModelExpressionProvider.CreateModelExpression(page.ViewData, model => model.SubModel.Name);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Metadata);
Assert.Equal(typeof(string), result.Metadata.ModelType);
Assert.Equal(expectedName, result.Name);
}
private static IdentityRazorPage CreateIdentityPage(ViewContext viewContext)
{
return new IdentityRazorPage
{
ViewContext = viewContext,
ViewData = (ViewDataDictionary<string>)viewContext.ViewData,
ModelExpressionProvider = CreateModelExpressionProvider(),
};
}
public static NotQuiteIdentityRazorPage CreateNotQuiteIdentityPage(ViewContext viewContext)
{
return new NotQuiteIdentityRazorPage
{
ViewContext = viewContext,
ViewData = (ViewDataDictionary<RecursiveModel>)viewContext.ViewData,
ModelExpressionProvider = CreateModelExpressionProvider(),
};
}
private static TestRazorPage CreatePage(ViewContext viewContext)
{
return new TestRazorPage
{
ViewContext = viewContext,
ViewData = (ViewDataDictionary<RazorPageCreateModelExpressionModel>)viewContext.ViewData,
ModelExpressionProvider = CreateModelExpressionProvider(),
};
}
private static IModelExpressionProvider CreateModelExpressionProvider()
{
var provider = new EmptyModelMetadataProvider();
var modelExpressionProvider = new ModelExpressionProvider(provider);
return modelExpressionProvider;
}
private static ViewContext CreateViewContext()
{
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<RazorPageCreateModelExpressionModel>(provider, new ModelStateDictionary());
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IModelMetadataProvider>(provider);
var httpContext = new DefaultHttpContext
{
RequestServices = serviceCollection.BuildServiceProvider(),
};
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
return new ViewContext(
actionContext,
NullView.Instance,
viewData,
Mock.Of<ITempDataDictionary>(),
new StringWriter(),
new HtmlHelperOptions());
}
public class IdentityRazorPage : TestRazorPage<string>
{
public ModelExpression CreateModelExpression1()
{
return ModelExpressionProvider.CreateModelExpression(ViewData, m => m);
}
public ModelExpression CreateModelExpression2()
{
return ModelExpressionProvider.CreateModelExpression(ViewData, m => Model);
}
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
public class NotQuiteIdentityRazorPage : TestRazorPage<RecursiveModel>
{
public ModelExpression CreateModelExpression1()
{
return ModelExpressionProvider.CreateModelExpression(ViewData, m => m.Model);
}
public ModelExpression CreateModelExpression2()
{
return ModelExpressionProvider.CreateModelExpression(ViewData, m => ViewData.Model);
}
public ModelExpression CreateModelExpression3()
{
return ModelExpressionProvider.CreateModelExpression(ViewData, m => ViewContext.ViewData.Model);
}
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
private class TestRazorPage : TestRazorPage<RazorPageCreateModelExpressionModel>
{
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
public class TestRazorPage<TModel> : RazorPage<TModel>
{
public IModelExpressionProvider ModelExpressionProvider { get; set; }
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
public class RecursiveModel
{
public RecursiveModel Model { get; set; }
}
public class RazorPageCreateModelExpressionModel
{
public int Id { get; set; }
public string Name { get; set; }
public RazorPageCreateModelExpressionSubModel SubModel { get; set; }
}
public class RazorPageCreateModelExpressionSubModel
{
public int Id { get; set; }
public string Name { get; set; }
public RazorPageCreateModelExpressionSubSubModel SubSubModel { get; set; }
}
public class RazorPageCreateModelExpressionSubSubModel
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.