context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Security;
// POP3 Quoted Printable
// =====================
//
// copyright by Peter Huber, Singapore, 2006
// this code is provided as is, bugs are probable, free for any use, no responsiblity accepted :-)
//
// based on QuotedPrintable Class from ASP emporium, http://www.aspemporium.com/classes.aspx?cid=6
namespace SoftLogik.Mail
{
namespace Mail
{
namespace Pop3
{
/// <summary>
/// <para>
/// Robust and fast implementation of Quoted Printable
/// Multipart Internet Mail Encoding (MIME) which encodes every
/// character, not just "special characters" for transmission over SMTP.
/// </para>
/// <para>
/// More information on the quoted-printable encoding can be found
/// here: http://www.freesoft.org/CIE/RFC/1521/6.htm
/// </para>
/// </summary>
/// <remarks>
/// <para>
/// detailed in: RFC 1521
/// </para>
/// <para>
/// more info: http://www.freesoft.org/CIE/RFC/1521/6.htm
/// </para>
/// <para>
/// The QuotedPrintable class encodes and decodes strings and files
/// that either were encoded or need encoded in the Quoted-Printable
/// MIME encoding for Internet mail. The encoding methods of the class
/// use pointers wherever possible to guarantee the fastest possible
/// encoding times for any size file or string. The decoding methods
/// use only the .NET framework classes.
/// </para>
/// <para>
/// The Quoted-Printable implementation
/// is robust which means it encodes every character to ensure that the
/// information is decoded properly regardless of machine or underlying
/// operating system or protocol implementation. The decode can recognize
/// robust encodings as well as minimal encodings that only encode special
/// characters and any implementation in between. Internally, the
/// class uses a regular expression replace pattern to decode a quoted-
/// printable string or file.
/// </para>
/// </remarks>
/// <example>
/// This example shows how to quoted-printable encode an html file and then
/// decode it.
/// <code>
/// string encoded = QuotedPrintable.EncodeFile(
/// @"C:\WEBS\wwwroot\index.html"
/// );
///
/// string decoded = QuotedPrintable.Decode(encoded);
///
/// Console.WriteLine(decoded);
/// </code>
/// </example>
internal class QuotedPrintable
{
private QuotedPrintable()
{
}
/// <summary>
/// Gets the maximum number of characters per quoted-printable
/// line as defined in the RFC minus 1 to allow for the =
/// character (soft line break).
/// </summary>
/// <remarks>
/// (Soft Line Breaks): The Quoted-Printable encoding REQUIRES
/// that encoded lines be no more than 76 characters long. If
/// longer lines are to be encoded with the Quoted-Printable
/// encoding, 'soft' line breaks must be used. An equal sign
/// as the last character on a encoded line indicates such a
/// non-significant ('soft') line break in the encoded text.
/// </remarks>
public const int RFC_1521_MAX_CHARS_PER_LINE = 75;
private static string HexDecoderEvaluator(Match m)
{
string hex = m.Groups[2].Value;
int iHex = Convert.ToInt32(hex, 16);
char c = (char)iHex;
return c.ToString();
}
static public string HexDecoder(string line)
{
if (line == null)
{
throw (new ArgumentNullException());
}
//parse looking for =XX where XX is hexadecimal
Regex re = new Regex("(\\=([0-9A-F][0-9A-F]))", RegexOptions.IgnoreCase);
return re.Replace(line, new MatchEvaluator(HexDecoderEvaluator));
}
/// <summary>
/// decodes an entire file's contents into plain text that
/// was encoded with quoted-printable.
/// </summary>
/// <param name="filepath">
/// The path to the quoted-printable encoded file to decode.
/// </param>
/// <returns>The decoded string.</returns>
/// <exception cref="ObjectDisposedException">
/// A problem occurred while attempting to decode the
/// encoded string.
/// </exception>
/// <exception cref="OutOfMemoryException">
/// There is insufficient memory to allocate a buffer for the
/// returned string.
/// </exception>
/// <exception cref="ArgumentNullException">
/// A string is passed in as a null reference.
/// </exception>
/// <exception cref="IOException">
/// An I/O error occurs, such as the stream being closed.
/// </exception>
/// <exception cref="FileNotFoundException">
/// The file was not found.
/// </exception>
/// <exception cref="SecurityException">
/// The caller does not have the required permission to open
/// the file specified in filepath.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// filepath is read-only or a directory.
/// </exception>
/// <remarks>
/// Decodes a quoted-printable encoded file into a string
/// of unencoded text of any size.
/// </remarks>
public static string DecodeFile(string filepath)
{
if (filepath == null)
{
throw (new ArgumentNullException());
}
string decodedHtml = "";
string line;
FileInfo f = new FileInfo(filepath);
if (! f.Exists)
{
throw (new FileNotFoundException());
}
StreamReader sr = f.OpenText();
try
{
line = sr.ReadLine();
while (line != null)
{
decodedHtml += Decode(line);
line = sr.ReadLine();
}
return decodedHtml;
}
finally
{
sr.Close();
sr = null;
f = null;
}
}
/// <summary>
/// Decodes a Quoted-Printable string of any size into
/// it's original text.
/// </summary>
/// <param name="encoded">
/// The encoded string to decode.
/// </param>
/// <returns>The decoded string.</returns>
/// <exception cref="ArgumentNullException">
/// A string is passed in as a null reference.
/// </exception>
/// <remarks>
/// Decodes a quoted-printable encoded string into a string
/// of unencoded text of any size.
/// </remarks>
public static string Decode(string encoded)
{
if (encoded == null)
{
throw (new ArgumentNullException());
}
string line;
StringWriter sw = new StringWriter();
StringReader sr = new StringReader(encoded);
try
{
line = sr.ReadLine();
while (line != null)
{
if (line.EndsWith("="))
{
sw.Write(HexDecoder(line.Substring(0, line.Length - 1)));
}
else
{
sw.WriteLine(HexDecoder(line));
}
sw.Flush();
line = sr.ReadLine();
}
return sw.ToString();
}
finally
{
sw.Close();
sr.Close();
sw = null;
sr = null;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime.GrainDirectory
{
internal class AdaptiveDirectoryCacheMaintainer<TValue> : AsynchAgent
{
private static readonly TimeSpan SLEEP_TIME_BETWEEN_REFRESHES = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(1); // this should be something like minTTL/4
private readonly AdaptiveGrainDirectoryCache<TValue> cache;
private readonly LocalGrainDirectory router;
private readonly Func<List<ActivationAddress>, TValue> updateFunc;
private long lastNumAccesses; // for stats
private long lastNumHits; // for stats
internal AdaptiveDirectoryCacheMaintainer(
LocalGrainDirectory router,
AdaptiveGrainDirectoryCache<TValue> cache,
Func<List<ActivationAddress>, TValue> updateFunc)
{
this.updateFunc = updateFunc;
this.router = router;
this.cache = cache;
lastNumAccesses = 0;
lastNumHits = 0;
OnFault = FaultBehavior.RestartOnFault;
}
protected override void Run()
{
while (router.Running)
{
// Run through all cache entries and do the following:
// 1. If the entry is not expired, skip it
// 2. If the entry is expired and was not accessed in the last time interval -- throw it away
// 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list
// At the end of the process, fetch batch requests for entries that need to be refreshed
// Upon receiving refreshing answers, if the entry was not changed, double its expiration timer.
// If it was changed, update the cache and reset the expiration timer.
// this dictionary holds a map between a silo address and the list of grains that need to be refreshed
var fetchInBatchList = new Dictionary<SiloAddress, List<GrainId>>();
// get the list of cached grains
// for debug only
int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0;
// run through all cache entries
var enumerator = cache.GetStoredEntries();
while (enumerator.MoveNext())
{
var pair = enumerator.Current;
GrainId grain = pair.Key;
var entry = pair.Value;
SiloAddress owner = router.CalculateTargetSilo(grain);
if (owner == null) // Null means there's no other silo and we're shutting down, so skip this entry
{
continue;
}
if (owner.Equals(router.MyAddress))
{
// we found our owned entry in the cache -- it is not supposed to happen unless there were
// changes in the membership
Log.Warn(ErrorCode.Runtime_Error_100185, "Grain {0} owned by {1} was found in the cache of {1}", grain, owner, owner);
cache.Remove(grain);
cnt1++; // for debug
}
else
{
if (entry == null)
{
// 0. If the entry was deleted in parallel, presumably due to cleanup after silo death
cache.Remove(grain); // for debug
cnt3++;
}
else if (!entry.IsExpired())
{
// 1. If the entry is not expired, skip it
cnt2++; // for debug
}
else if (entry.NumAccesses == 0)
{
// 2. If the entry is expired and was not accessed in the last time interval -- throw it away
cache.Remove(grain); // for debug
cnt3++;
}
else
{
// 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list
if (!fetchInBatchList.ContainsKey(owner))
{
fetchInBatchList[owner] = new List<GrainId>();
}
fetchInBatchList[owner].Add(grain);
// And reset the entry's access count for next time
entry.NumAccesses = 0;
cnt4++; // for debug
}
}
}
if (Log.IsVerbose2) Log.Verbose2("Silo {0} self-owned (and removed) {1}, kept {2}, removed {3} and tries to refresh {4} grains", router.MyAddress, cnt1, cnt2, cnt3, cnt4);
// send batch requests
SendBatchCacheRefreshRequests(fetchInBatchList);
ProduceStats();
// recheck every X seconds (Consider making it a configurable parameter)
Thread.Sleep(SLEEP_TIME_BETWEEN_REFRESHES);
}
}
private void SendBatchCacheRefreshRequests(Dictionary<SiloAddress, List<GrainId>> refreshRequests)
{
foreach (SiloAddress silo in refreshRequests.Keys)
{
List<Tuple<GrainId, int>> cachedGrainAndETagList = BuildGrainAndETagList(refreshRequests[silo]);
SiloAddress capture = silo;
router.CacheValidationsSent.Increment();
// Send all of the items in one large request
var validator = InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryCacheValidatorId, capture);
router.Scheduler.QueueTask(async () =>
{
var response = await validator.LookUpMany(cachedGrainAndETagList);
ProcessCacheRefreshResponse(capture, response);
}, router.CacheValidator.SchedulingContext).Ignore();
if (Log.IsVerbose2) Log.Verbose2("Silo {0} is sending request to silo {1} with {2} entries", router.MyAddress, silo, cachedGrainAndETagList.Count);
}
}
private void ProcessCacheRefreshResponse(
SiloAddress silo,
IReadOnlyCollection<Tuple<GrainId, int, List<ActivationAddress>>> refreshResponse)
{
if (Log.IsVerbose2) Log.Verbose2("Silo {0} received ProcessCacheRefreshResponse. #Response entries {1}.", router.MyAddress, refreshResponse.Count);
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
// pass through returned results and update the cache if needed
foreach (Tuple<GrainId, int, List<ActivationAddress>> tuple in refreshResponse)
{
if (tuple.Item3 != null)
{
// the server returned an updated entry
var updated = updateFunc(tuple.Item3);
cache.AddOrUpdate(tuple.Item1, updated, tuple.Item2);
cnt1++;
}
else if (tuple.Item2 == -1)
{
// The server indicates that it does not own the grain anymore.
// It could be that by now, the cache has been already updated and contains an entry received from another server (i.e., current owner for the grain).
// For simplicity, we do not care about this corner case and simply remove the cache entry.
cache.Remove(tuple.Item1);
cnt2++;
}
else
{
// The server returned only a (not -1) generation number, indicating that we hold the most
// updated copy of the grain's activations list.
// Validate that the generation number in the request and the response are equal
// Contract.Assert(tuple.Item2 == refreshRequest.Find(o => o.Item1 == tuple.Item1).Item2);
// refresh the entry in the cache
cache.MarkAsFresh(tuple.Item1);
cnt3++;
}
}
if (Log.IsVerbose2) Log.Verbose2("Silo {0} processed refresh response from {1} with {2} updated, {3} removed, {4} unchanged grains", router.MyAddress, silo, cnt1, cnt2, cnt3);
}
/// <summary>
/// Gets the list of grains (all owned by the same silo) and produces a new list
/// of tuples, where each tuple holds the grain and its generation counter currently stored in the cache
/// </summary>
/// <param name="grains">List of grains owned by the same silo</param>
/// <returns>List of grains in input along with their generation counters stored in the cache </returns>
private List<Tuple<GrainId, int>> BuildGrainAndETagList(IEnumerable<GrainId> grains)
{
var grainAndETagList = new List<Tuple<GrainId, int>>();
foreach (GrainId grain in grains)
{
// NOTE: should this be done with TryGet? Won't Get invoke the LRU getter function?
AdaptiveGrainDirectoryCache<TValue>.GrainDirectoryCacheEntry entry = cache.Get(grain);
if (entry != null)
{
grainAndETagList.Add(new Tuple<GrainId, int>(grain, entry.ETag));
}
else
{
// this may happen only if the LRU cache is full and decided to drop this grain
// while we try to refresh it
Log.Warn(ErrorCode.Runtime_Error_100199, "Grain {0} disappeared from the cache during maintainance", grain);
}
}
return grainAndETagList;
}
private void ProduceStats()
{
// We do not want to synchronize the access on numAccess and numHits in cache to avoid performance issues.
// Thus we take the current reading of these fields and calculate the stats. We might miss an access or two,
// but it should not be matter.
long curNumAccesses = cache.NumAccesses;
long curNumHits = cache.NumHits;
long numAccesses = curNumAccesses - lastNumAccesses;
long numHits = curNumHits - lastNumHits;
if (Log.IsVerbose2) Log.Verbose2("#accesses: {0}, hit-ratio: {1}%", numAccesses, (numHits / Math.Max(numAccesses, 0.00001)) * 100);
lastNumAccesses = curNumAccesses;
lastNumHits = curNumHits;
}
}
}
| |
using BorderSkin.Settings;
namespace BorderSkin.Execlusion
{
partial class ExclusionDialogue : System.Windows.Forms.Form
{
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool disposing)
{
try {
if (disposing && components != null) {
components.Dispose();
}
} finally {
base.Dispose(disposing);
}
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExclusionDialogue));
this.WindowsIcons = new System.Windows.Forms.ImageList(this.components);
this.Panel1 = new System.Windows.Forms.Panel();
this.pnlButtonBright3d = new System.Windows.Forms.Panel();
this.pnlButtonDark3d = new System.Windows.Forms.Panel();
this.RefreshButton = new IconButton();
this.Cancel = new IconButton();
this.OkButton = new IconButton();
this.GroupBox1 = new System.Windows.Forms.GroupBox();
this.ProgramLbl = new System.Windows.Forms.Label();
this.ProcessLbl = new System.Windows.Forms.Label();
this.ClassesLbl = new System.Windows.Forms.Label();
this.ProgramTxt = new System.Windows.Forms.TextBox();
this.ProcessTxt = new System.Windows.Forms.TextBox();
this.ClassesTxt = new System.Windows.Forms.TextBox();
this.SkinGroup = new System.Windows.Forms.GroupBox();
this.SkinLbl = new System.Windows.Forms.Label();
this.ColorSchemeTxt = new System.Windows.Forms.ComboBox();
this.ColorSchemeLbl = new System.Windows.Forms.Label();
this.SkinTxt = new System.Windows.Forms.ComboBox();
this.SkinedCheckBox = new System.Windows.Forms.CheckBox();
this.GroupBox3 = new System.Windows.Forms.GroupBox();
this.WindowsList = new System.Windows.Forms.ListView();
this.WindowInfoLbl = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
this.Panel1.SuspendLayout();
this.GroupBox1.SuspendLayout();
this.SkinGroup.SuspendLayout();
this.GroupBox3.SuspendLayout();
this.SuspendLayout();
//
// WindowsIcons
//
this.WindowsIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("WindowsIcons.ImageStream")));
this.WindowsIcons.TransparentColor = System.Drawing.Color.Transparent;
this.WindowsIcons.Images.SetKeyName(0, "MaximizedTop.png");
//
// Panel1
//
this.Panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.Panel1.Controls.Add(this.pnlButtonBright3d);
this.Panel1.Controls.Add(this.pnlButtonDark3d);
this.Panel1.Controls.Add(this.RefreshButton);
this.Panel1.Controls.Add(this.Cancel);
this.Panel1.Controls.Add(this.OkButton);
this.Panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.Panel1.Location = new System.Drawing.Point(0, 302);
this.Panel1.Name = "Panel1";
this.Panel1.Size = new System.Drawing.Size(507, 58);
this.Panel1.TabIndex = 103;
//
// pnlButtonBright3d
//
this.pnlButtonBright3d.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.pnlButtonBright3d.Dock = System.Windows.Forms.DockStyle.Top;
this.pnlButtonBright3d.Location = new System.Drawing.Point(0, 1);
this.pnlButtonBright3d.Name = "pnlButtonBright3d";
this.pnlButtonBright3d.Size = new System.Drawing.Size(507, 1);
this.pnlButtonBright3d.TabIndex = 17;
//
// pnlButtonDark3d
//
this.pnlButtonDark3d.BackColor = System.Drawing.SystemColors.ControlDark;
this.pnlButtonDark3d.Dock = System.Windows.Forms.DockStyle.Top;
this.pnlButtonDark3d.Location = new System.Drawing.Point(0, 0);
this.pnlButtonDark3d.Name = "pnlButtonDark3d";
this.pnlButtonDark3d.Size = new System.Drawing.Size(507, 1);
this.pnlButtonDark3d.TabIndex = 18;
//
// RefreshButton
//
this.RefreshButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.RefreshButton.Image = global::BorderSkin.Properties.Resources.RefreshImage;
this.RefreshButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.RefreshButton.Location = new System.Drawing.Point(12, 20);
this.RefreshButton.Name = "RefreshButton";
this.RefreshButton.Size = new System.Drawing.Size(91, 25);
this.RefreshButton.TabIndex = 101;
this.RefreshButton.Tag = "Refresh List";
this.RefreshButton.Text = "Refresh List";
this.RefreshButton.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click);
//
// Cancel
//
this.Cancel.Cursor = System.Windows.Forms.Cursors.Hand;
this.Cancel.Image = global::BorderSkin.Properties.Resources.CancelImage;
this.Cancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.Cancel.Location = new System.Drawing.Point(414, 20);
this.Cancel.Name = "Cancel";
this.Cancel.Size = new System.Drawing.Size(66, 25);
this.Cancel.TabIndex = 101;
this.Cancel.Tag = "Cancel";
this.Cancel.Text = "Cancel";
this.Cancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.Cancel.Click += new System.EventHandler(this.Cancel_Click);
//
// OkButton
//
this.OkButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.OkButton.Image = global::BorderSkin.Properties.Resources.OKImage;
this.OkButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.OkButton.Location = new System.Drawing.Point(345, 20);
this.OkButton.Name = "OkButton";
this.OkButton.Size = new System.Drawing.Size(48, 25);
this.OkButton.TabIndex = 101;
this.OkButton.Tag = "OK";
this.OkButton.Text = "OK";
this.OkButton.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// GroupBox1
//
this.GroupBox1.Controls.Add(this.ProgramLbl);
this.GroupBox1.Controls.Add(this.ProcessLbl);
this.GroupBox1.Controls.Add(this.ClassesLbl);
this.GroupBox1.Controls.Add(this.ProgramTxt);
this.GroupBox1.Controls.Add(this.ProcessTxt);
this.GroupBox1.Controls.Add(this.ClassesTxt);
this.GroupBox1.Location = new System.Drawing.Point(240, 13);
this.GroupBox1.Name = "GroupBox1";
this.GroupBox1.Size = new System.Drawing.Size(247, 134);
this.GroupBox1.TabIndex = 104;
this.GroupBox1.TabStop = false;
//
// ProgramLbl
//
this.ProgramLbl.AutoSize = true;
this.ProgramLbl.ForeColor = System.Drawing.Color.Navy;
this.ProgramLbl.Location = new System.Drawing.Point(12, 32);
this.ProgramLbl.Name = "ProgramLbl";
this.ProgramLbl.Size = new System.Drawing.Size(77, 13);
this.ProgramLbl.TabIndex = 94;
this.ProgramLbl.Tag = "Program Name";
this.ProgramLbl.Text = "Program Name";
//
// ProcessLbl
//
this.ProcessLbl.AutoSize = true;
this.ProcessLbl.ForeColor = System.Drawing.Color.Navy;
this.ProcessLbl.Location = new System.Drawing.Point(12, 62);
this.ProcessLbl.Name = "ProcessLbl";
this.ProcessLbl.Size = new System.Drawing.Size(74, 13);
this.ProcessLbl.TabIndex = 93;
this.ProcessLbl.Tag = "Process Name";
this.ProcessLbl.Text = "Process Name";
//
// ClassesLbl
//
this.ClassesLbl.AutoSize = true;
this.ClassesLbl.ForeColor = System.Drawing.Color.Navy;
this.ClassesLbl.Location = new System.Drawing.Point(12, 93);
this.ClassesLbl.Name = "ClassesLbl";
this.ClassesLbl.Size = new System.Drawing.Size(43, 13);
this.ClassesLbl.TabIndex = 92;
this.ClassesLbl.Tag = "Classes";
this.ClassesLbl.Text = "Classes";
//
// ProgramTxt
//
this.ProgramTxt.Location = new System.Drawing.Point(102, 29);
this.ProgramTxt.Name = "ProgramTxt";
this.ProgramTxt.Size = new System.Drawing.Size(133, 20);
this.ProgramTxt.TabIndex = 97;
//
// ProcessTxt
//
this.ProcessTxt.Location = new System.Drawing.Point(102, 59);
this.ProcessTxt.Name = "ProcessTxt";
this.ProcessTxt.Size = new System.Drawing.Size(133, 20);
this.ProcessTxt.TabIndex = 96;
//
// ClassesTxt
//
this.ClassesTxt.Location = new System.Drawing.Point(102, 90);
this.ClassesTxt.Name = "ClassesTxt";
this.ClassesTxt.Size = new System.Drawing.Size(133, 20);
this.ClassesTxt.TabIndex = 95;
//
// SkinGroup
//
this.SkinGroup.Controls.Add(this.SkinLbl);
this.SkinGroup.Controls.Add(this.ColorSchemeTxt);
this.SkinGroup.Controls.Add(this.ColorSchemeLbl);
this.SkinGroup.Controls.Add(this.SkinTxt);
this.SkinGroup.Enabled = false;
this.SkinGroup.Location = new System.Drawing.Point(240, 167);
this.SkinGroup.Name = "SkinGroup";
this.SkinGroup.Size = new System.Drawing.Size(247, 115);
this.SkinGroup.TabIndex = 105;
this.SkinGroup.TabStop = false;
//
// SkinLbl
//
this.SkinLbl.AutoSize = true;
this.SkinLbl.ForeColor = System.Drawing.Color.Navy;
this.SkinLbl.Location = new System.Drawing.Point(20, 36);
this.SkinLbl.Name = "SkinLbl";
this.SkinLbl.Size = new System.Drawing.Size(26, 13);
this.SkinLbl.TabIndex = 95;
this.SkinLbl.Tag = "Skin";
this.SkinLbl.Text = "Skin";
//
// ColorSchemeTxt
//
this.ColorSchemeTxt.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ColorSchemeTxt.FormattingEnabled = true;
this.ColorSchemeTxt.Location = new System.Drawing.Point(100, 68);
this.ColorSchemeTxt.Name = "ColorSchemeTxt";
this.ColorSchemeTxt.Size = new System.Drawing.Size(131, 21);
this.ColorSchemeTxt.TabIndex = 99;
//
// ColorSchemeLbl
//
this.ColorSchemeLbl.AutoSize = true;
this.ColorSchemeLbl.ForeColor = System.Drawing.Color.Navy;
this.ColorSchemeLbl.Location = new System.Drawing.Point(20, 71);
this.ColorSchemeLbl.Name = "ColorSchemeLbl";
this.ColorSchemeLbl.Size = new System.Drawing.Size(72, 13);
this.ColorSchemeLbl.TabIndex = 98;
this.ColorSchemeLbl.Tag = "Color Scheme";
this.ColorSchemeLbl.Text = "Color Scheme";
//
// SkinTxt
//
this.SkinTxt.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.SkinTxt.FormattingEnabled = true;
this.SkinTxt.Location = new System.Drawing.Point(100, 31);
this.SkinTxt.Name = "SkinTxt";
this.SkinTxt.Size = new System.Drawing.Size(131, 21);
this.SkinTxt.TabIndex = 97;
this.SkinTxt.SelectedIndexChanged += new System.EventHandler(this.SkinTxt_SelectedIndexChanged);
//
// SkinedCheckBox
//
this.SkinedCheckBox.AutoSize = true;
this.SkinedCheckBox.ForeColor = System.Drawing.Color.Blue;
this.SkinedCheckBox.Location = new System.Drawing.Point(248, 164);
this.SkinedCheckBox.Name = "SkinedCheckBox";
this.SkinedCheckBox.Size = new System.Drawing.Size(92, 17);
this.SkinedCheckBox.TabIndex = 96;
this.SkinedCheckBox.Tag = "Specify a Skin";
this.SkinedCheckBox.Text = "Specify a Skin";
this.SkinedCheckBox.UseVisualStyleBackColor = true;
this.SkinedCheckBox.CheckedChanged += new System.EventHandler(this.SkinedCheckBox_CheckedChanged);
//
// GroupBox3
//
this.GroupBox3.Controls.Add(this.WindowsList);
this.GroupBox3.Location = new System.Drawing.Point(15, 13);
this.GroupBox3.Name = "GroupBox3";
this.GroupBox3.Padding = new System.Windows.Forms.Padding(3, 5, 3, 3);
this.GroupBox3.Size = new System.Drawing.Size(211, 269);
this.GroupBox3.TabIndex = 106;
this.GroupBox3.TabStop = false;
//
// WindowsList
//
this.WindowsList.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.WindowsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.WindowsList.FullRowSelect = true;
this.WindowsList.Location = new System.Drawing.Point(3, 18);
this.WindowsList.Name = "WindowsList";
this.WindowsList.Size = new System.Drawing.Size(205, 248);
this.WindowsList.SmallImageList = this.WindowsIcons;
this.WindowsList.TabIndex = 103;
this.WindowsList.UseCompatibleStateImageBehavior = false;
this.WindowsList.View = System.Windows.Forms.View.List;
this.WindowsList.SelectedIndexChanged += new System.EventHandler(this.WindowsList_SelectedIndexChanged);
//
// WindowInfoLbl
//
this.WindowInfoLbl.AutoSize = true;
this.WindowInfoLbl.BackColor = System.Drawing.Color.White;
this.WindowInfoLbl.ForeColor = System.Drawing.Color.Blue;
this.WindowInfoLbl.Location = new System.Drawing.Point(247, 12);
this.WindowInfoLbl.Name = "WindowInfoLbl";
this.WindowInfoLbl.Size = new System.Drawing.Size(68, 13);
this.WindowInfoLbl.TabIndex = 107;
this.WindowInfoLbl.Text = "Window Info";
//
// Label3
//
this.Label3.AutoSize = true;
this.Label3.BackColor = System.Drawing.Color.White;
this.Label3.ForeColor = System.Drawing.Color.Blue;
this.Label3.Location = new System.Drawing.Point(21, 13);
this.Label3.Name = "Label3";
this.Label3.Size = new System.Drawing.Size(84, 13);
this.Label3.TabIndex = 108;
this.Label3.Tag = "Select a window";
this.Label3.Text = "Select a window";
//
// ExclusionDialogue
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(507, 360);
this.Controls.Add(this.Label3);
this.Controls.Add(this.WindowInfoLbl);
this.Controls.Add(this.SkinedCheckBox);
this.Controls.Add(this.GroupBox3);
this.Controls.Add(this.SkinGroup);
this.Controls.Add(this.GroupBox1);
this.Controls.Add(this.Panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ExclusionDialogue";
this.Text = "Border Skin";
this.Panel1.ResumeLayout(false);
this.GroupBox1.ResumeLayout(false);
this.GroupBox1.PerformLayout();
this.SkinGroup.ResumeLayout(false);
this.SkinGroup.PerformLayout();
this.GroupBox3.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
internal System.Windows.Forms.ImageList WindowsIcons;
internal IconButton RefreshButton;
internal IconButton OkButton;
internal IconButton Cancel;
internal System.Windows.Forms.Panel Panel1;
private System.Windows.Forms.Panel pnlButtonBright3d;
private System.Windows.Forms.Panel pnlButtonDark3d;
internal System.Windows.Forms.GroupBox GroupBox1;
internal System.Windows.Forms.Label ProgramLbl;
internal System.Windows.Forms.Label ProcessLbl;
internal System.Windows.Forms.Label ClassesLbl;
internal System.Windows.Forms.TextBox ProgramTxt;
internal System.Windows.Forms.TextBox ProcessTxt;
internal System.Windows.Forms.TextBox ClassesTxt;
internal System.Windows.Forms.GroupBox SkinGroup;
internal System.Windows.Forms.Label SkinLbl;
internal System.Windows.Forms.ComboBox ColorSchemeTxt;
internal System.Windows.Forms.CheckBox SkinedCheckBox;
internal System.Windows.Forms.Label ColorSchemeLbl;
internal System.Windows.Forms.ComboBox SkinTxt;
internal System.Windows.Forms.GroupBox GroupBox3;
internal System.Windows.Forms.Label WindowInfoLbl;
internal System.Windows.Forms.Label Label3;
internal System.Windows.Forms.ListView WindowsList;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Logging;
namespace Orleans.CodeGenerator.MSBuild
{
public class CodeGeneratorCommand
{
private const string OrleansSerializationAssemblyShortName = "Orleans.Serialization";
private static readonly int[] SuppressCompilerWarnings =
{
162, // CS0162 - Unreachable code detected.
219, // CS0219 - The variable 'V' is assigned but its value is never used.
414, // CS0414 - The private field 'F' is assigned but its value is never used.
618, // CS0616 - Member is obsolete.
649, // CS0649 - Field 'F' is never assigned to, and will always have its default value.
693, // CS0693 - Type parameter 'type parameter' has the same name as the type parameter from outer type 'T'
1591, // CS1591 - Missing XML comment for publicly visible type or member 'Type_or_Member'
1998 // CS1998 - This async method lacks 'await' operators and will run synchronously
};
public ILogger Log { get; set; }
/// <summary>
/// The MS Build project path.
/// </summary>
public string ProjectPath { get; set; }
/// <summary>
/// The optional ProjectGuid.
/// </summary>
public string ProjectGuid { get; set; }
/// <summary>
/// The output type, such as Exe, or Library.
/// </summary>
public string OutputType { get; set; }
/// <summary>
/// The target path of the compilation.
/// </summary>
public string TargetPath { get; set; }
/// <summary>
/// The source files.
/// </summary>
public List<string> Compile { get; } = new();
/// <summary>
/// The libraries referenced by the project.
/// </summary>
public List<string> Reference { get; } = new();
/// <summary>
/// The file which holds the generated code.
/// </summary>
public string CodeGenOutputFile { get; set; }
/// <summary>
/// The metadata name of the attribute used to specify ids.
/// </summary>
public List<string> IdAttributes { get; set; } = new();
public List<string> AliasAttributes { get; private set; } = new();
public List<string> ImmutableAttributes { get; private set; } = new();
public List<string> GenerateSerializerAttributes { get; private set; } = new();
public async Task<bool> Execute(CancellationToken cancellationToken)
{
try
{
var projectName = Path.GetFileNameWithoutExtension(ProjectPath);
var projectId = !string.IsNullOrEmpty(ProjectGuid) && Guid.TryParse(ProjectGuid, out var projectIdGuid)
? ProjectId.CreateFromSerialized(projectIdGuid)
: ProjectId.CreateNewId();
Log.LogDebug($"ProjectGuid: {ProjectGuid}");
Log.LogDebug($"ProjectID: {projectId}");
var languageName = GetLanguageName(ProjectPath);
var documents = GetDocuments(Compile, projectId).ToList();
var metadataReferences = GetMetadataReferences(Reference).ToList();
foreach (var doc in documents)
{
Log.LogDebug($"Document: {doc.FilePath}");
}
foreach (var reference in metadataReferences)
{
Log.LogDebug($"Reference: {reference.Display}");
}
var projectInfo = ProjectInfo.Create(
projectId,
VersionStamp.Create(),
projectName,
projectName,
languageName,
ProjectPath,
TargetPath,
CreateCompilationOptions(OutputType, languageName),
documents: documents,
metadataReferences: metadataReferences
);
Log.LogDebug($"Project: {projectInfo}");
var workspace = new AdhocWorkspace();
_ = workspace.AddProject(projectInfo);
var project = workspace.CurrentSolution.Projects.Single();
var stopwatch = Stopwatch.StartNew();
var compilation = await project.GetCompilationAsync(cancellationToken);
Log.LogInformation($"GetCompilation completed in {stopwatch.ElapsedMilliseconds}ms.");
if (compilation.ReferencedAssemblyNames.All(name => name.Name != OrleansSerializationAssemblyShortName))
{
return false;
}
var codeGeneratorOptions = new CodeGeneratorOptions();
codeGeneratorOptions.IdAttributes.AddRange(IdAttributes);
codeGeneratorOptions.AliasAttributes.AddRange(AliasAttributes);
codeGeneratorOptions.ImmutableAttributes.AddRange(ImmutableAttributes);
codeGeneratorOptions.GenerateSerializerAttributes.AddRange(GenerateSerializerAttributes);
var generator = new CodeGenerator(compilation, codeGeneratorOptions);
stopwatch.Restart();
var syntax = generator.GenerateCode(cancellationToken);
Log.LogInformation($"GenerateCode completed in {stopwatch.ElapsedMilliseconds}ms.");
stopwatch.Restart();
var normalized = syntax.NormalizeWhitespace();
Log.LogInformation($"NormalizeWhitespace completed in {stopwatch.ElapsedMilliseconds}ms.");
stopwatch.Restart();
var source = normalized.ToFullString();
Log.LogInformation($"Generate source from syntax completed in {stopwatch.ElapsedMilliseconds}ms.");
stopwatch.Restart();
using (var sourceWriter = new StreamWriter(CodeGenOutputFile))
{
sourceWriter.WriteLine("#if !EXCLUDE_GENERATED_CODE");
foreach (var warningNum in SuppressCompilerWarnings)
{
await sourceWriter.WriteLineAsync($"#pragma warning disable {warningNum}");
}
if (!string.IsNullOrWhiteSpace(source))
{
await sourceWriter.WriteLineAsync(source);
}
foreach (var warningNum in SuppressCompilerWarnings)
{
await sourceWriter.WriteLineAsync($"#pragma warning restore {warningNum}");
}
sourceWriter.WriteLine("#endif");
}
Log.LogInformation($"Write source to disk completed in {stopwatch.ElapsedMilliseconds}ms.");
return true;
}
catch (ReflectionTypeLoadException rtle)
{
foreach (var ex in rtle.LoaderExceptions)
{
Log.LogDebug($"Exception: {ex}");
}
throw;
}
}
private static IEnumerable<DocumentInfo> GetDocuments(List<string> sources, ProjectId projectId) =>
sources
?.Where(File.Exists)
.Select(x => DocumentInfo.Create(
DocumentId.CreateNewId(projectId),
Path.GetFileName(x),
loader: TextLoader.From(
TextAndVersion.Create(
SourceText.From(File.ReadAllText(x)), VersionStamp.Create())),
filePath: x))
?? Array.Empty<DocumentInfo>();
private static IEnumerable<MetadataReference> GetMetadataReferences(List<string> references) =>
references
?.Where(File.Exists)
.Select(x => MetadataReference.CreateFromFile(x))
?? (IEnumerable<MetadataReference>)Array.Empty<MetadataReference>();
private static string GetLanguageName(string projectPath) => (Path.GetExtension(projectPath)) switch
{
".csproj" => LanguageNames.CSharp,
string ext when !string.IsNullOrWhiteSpace(ext) => throw new NotSupportedException($"Projects of type {ext} are not supported."),
_ => throw new InvalidOperationException("Could not determine supported language from project path"),
};
private static CompilationOptions CreateCompilationOptions(string outputType, string languageName)
{
OutputKind? kind = null;
switch (outputType)
{
case "Library":
kind = OutputKind.DynamicallyLinkedLibrary;
break;
case "Exe":
kind = OutputKind.ConsoleApplication;
break;
case "Module":
kind = OutputKind.NetModule;
break;
case "Winexe":
kind = OutputKind.WindowsApplication;
break;
}
if (kind.HasValue)
{
if (languageName == LanguageNames.CSharp)
{
return new CSharpCompilationOptions(kind.Value);
}
}
return null;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Brokerages;
using QuantConnect.Brokerages.GDAX;
namespace QuantConnect.Tests.Brokerages
{
public abstract class BrokerageTests
{
// ideally this class would be abstract, but I wanted to keep the order test cases here which use the
// various parameters required from derived types
private IBrokerage _brokerage;
private OrderProvider _orderProvider;
private SecurityProvider _securityProvider;
/// <summary>
/// Provides the data required to test each order type in various cases
/// </summary>
public virtual TestCaseData[] OrderParameters
{
get
{
return new[]
{
new TestCaseData(new MarketOrderTestParameters(Symbol)).SetName("MarketOrder"),
new TestCaseData(new LimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("LimitOrder"),
new TestCaseData(new StopMarketOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopMarketOrder"),
new TestCaseData(new StopLimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopLimitOrder")
};
}
}
#region Test initialization and cleanup
[SetUp]
public void Setup()
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- SETUP ---");
Log.Trace("");
Log.Trace("");
// we want to regenerate these for each test
_brokerage = null;
_orderProvider = null;
_securityProvider = null;
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
[TearDown]
public void Teardown()
{
try
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- TEARDOWN ---");
Log.Trace("");
Log.Trace("");
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
finally
{
if (_brokerage != null)
{
DisposeBrokerage(_brokerage);
}
}
}
public IBrokerage Brokerage
{
get
{
if (_brokerage == null)
{
_brokerage = InitializeBrokerage();
}
return _brokerage;
}
}
private IBrokerage InitializeBrokerage()
{
Log.Trace("");
Log.Trace("- INITIALIZING BROKERAGE -");
Log.Trace("");
var brokerage = CreateBrokerage(OrderProvider, SecurityProvider);
brokerage.Connect();
if (!brokerage.IsConnected)
{
Assert.Fail("Failed to connect to brokerage");
}
//gdax does not have a user data stream. Instead, we need to symbol subscribe and monitor for our orders.
if (brokerage.Name == "GDAX")
{
((QuantConnect.Brokerages.GDAX.GDAXBrokerage)brokerage).Subscribe(null, new[] { Symbol });
}
Log.Trace("");
Log.Trace("GET OPEN ORDERS");
Log.Trace("");
foreach (var openOrder in brokerage.GetOpenOrders())
{
OrderProvider.Add(openOrder);
}
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
foreach (var accountHolding in brokerage.GetAccountHoldings())
{
// these securities don't need to be real, just used for the ISecurityProvider impl, required
// by brokerages to track holdings
SecurityProvider[accountHolding.Symbol] = CreateSecurity(accountHolding.Symbol);
}
brokerage.OrderStatusChanged += (sender, args) =>
{
Log.Trace("");
Log.Trace("ORDER STATUS CHANGED: " + args);
Log.Trace("");
// we need to keep this maintained properly
if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled)
{
Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol.ToString());
Security security;
if (_securityProvider.TryGetValue(args.Symbol, out security))
{
var holding = _securityProvider[args.Symbol].Holdings;
holding.SetHoldings(args.FillPrice, holding.Quantity + args.FillQuantity);
}
else
{
_securityProvider[args.Symbol] = CreateSecurity(args.Symbol);
_securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity);
}
Log.Trace("--HOLDINGS: " + _securityProvider[args.Symbol]);
// update order mapping
var order = _orderProvider.GetOrderById(args.OrderId);
order.Status = args.Status;
}
};
return brokerage;
}
internal static Security CreateSecurity(Symbol symbol)
{
return new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false),
new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
}
public OrderProvider OrderProvider
{
get { return _orderProvider ?? (_orderProvider = new OrderProvider()); }
}
public SecurityProvider SecurityProvider
{
get { return _securityProvider ?? (_securityProvider = new SecurityProvider()); }
}
/// <summary>
/// Creates the brokerage under test and connects it
/// </summary>
/// <returns>A connected brokerage instance</returns>
protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider);
/// <summary>
/// Disposes of the brokerage and any external resources started in order to create it
/// </summary>
/// <param name="brokerage">The brokerage instance to be disposed of</param>
protected virtual void DisposeBrokerage(IBrokerage brokerage)
{
}
/// <summary>
/// This is used to ensure each test starts with a clean, known state.
/// </summary>
protected void LiquidateHoldings()
{
Log.Trace("");
Log.Trace("LIQUIDATE HOLDINGS");
Log.Trace("");
var holdings = Brokerage.GetAccountHoldings();
foreach (var holding in holdings)
{
if (holding.Quantity == 0) continue;
Log.Trace("Liquidating: " + holding);
var order = new MarketOrder(holding.Symbol, (int)-holding.Quantity, DateTime.Now);
_orderProvider.Add(order);
PlaceOrderWaitForStatus(order, OrderStatus.Filled);
}
}
protected void CancelOpenOrders()
{
Log.Trace("");
Log.Trace("CANCEL OPEN ORDERS");
Log.Trace("");
var openOrders = Brokerage.GetOpenOrders();
foreach (var openOrder in openOrders)
{
Log.Trace("Canceling: " + openOrder);
Brokerage.CancelOrder(openOrder);
}
}
#endregion
/// <summary>
/// Gets the symbol to be traded, must be shortable
/// </summary>
protected abstract Symbol Symbol { get; }
/// <summary>
/// Gets the security type associated with the <see cref="Symbol"/>
/// </summary>
protected abstract SecurityType SecurityType { get; }
/// <summary>
/// Gets a high price for the specified symbol so a limit sell won't fill
/// </summary>
protected abstract decimal HighPrice { get; }
/// <summary>
/// Gets a low price for the specified symbol so a limit buy won't fill
/// </summary>
protected abstract decimal LowPrice { get; }
/// <summary>
/// Gets the current market price of the specified security
/// </summary>
protected abstract decimal GetAskPrice(Symbol symbol);
/// <summary>
/// Gets the default order quantity
/// </summary>
protected virtual decimal GetDefaultQuantity()
{
return 1;
}
[Test]
public void IsConnected()
{
Assert.IsTrue(Brokerage.IsConnected);
}
[Test, TestCaseSource("OrderParameters")]
public void LongFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void CloseFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void ShortFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void CloseFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM SHORT");
Log.Trace("");
// first go short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void ShortFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()));
// now go net short
var order = PlaceOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test, TestCaseSource("OrderParameters")]
public void LongFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM SHORT");
Log.Trace("");
// first fo short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled);
// now go long
var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test]
public void GetCashBalanceContainsUSD()
{
Log.Trace("");
Log.Trace("GET CASH BALANCE");
Log.Trace("");
var balance = Brokerage.GetCashBalance();
Assert.AreEqual(1, balance.Count(x => x.Symbol == "USD"));
}
[Test]
public void GetAccountHoldings()
{
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
var before = Brokerage.GetAccountHoldings();
PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.Now));
var after = Brokerage.GetAccountHoldings();
var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol);
var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol);
var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity;
var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity;
Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity);
}
[Test, Ignore("This test requires reading the output and selection of a low volume security for the Brokerage")]
public void PartialFills()
{
var manualResetEvent = new ManualResetEvent(false);
var qty = 1000000m;
var remaining = qty;
var sync = new object();
Brokerage.OrderStatusChanged += (sender, orderEvent) =>
{
lock (sync)
{
remaining -= orderEvent.FillQuantity;
Console.WriteLine("Remaining: " + remaining + " FillQuantity: " + orderEvent.FillQuantity);
if (orderEvent.Status == OrderStatus.Filled)
{
manualResetEvent.Set();
}
}
};
// pick a security with low, but some, volume
var symbol = Symbols.EURUSD;
var order = new MarketOrder(symbol, qty, DateTime.UtcNow) { Id = 1 };
Brokerage.PlaceOrder(order);
// pause for a while to wait for fills to come in
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
Console.WriteLine("Remaining: " + remaining);
Assert.AreEqual(0, remaining);
}
/// <summary>
/// Updates the specified order in the brokerage until it fills or reaches a timeout
/// </summary>
/// <param name="order">The order to be modified</param>
/// <param name="parameters">The order test parameters that define how to modify the order</param>
/// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param>
protected virtual void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90)
{
if (order.Status == OrderStatus.Filled)
{
return;
}
var filledResetEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
if (args.Status == OrderStatus.Filled)
{
filledResetEvent.Set();
}
if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid)
{
Log.Trace("ModifyOrderUntilFilled(): " + order);
Assert.Fail("Unexpected order status: " + args.Status);
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
Log.Trace("");
Log.Trace("MODIFY UNTIL FILLED: " + order);
Log.Trace("");
var stopwatch = Stopwatch.StartNew();
while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout)
{
filledResetEvent.Reset();
if (order.Status == OrderStatus.PartiallyFilled) continue;
var marketPrice = GetAskPrice(order.Symbol);
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice);
var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice);
if (updateOrder)
{
if (order.Status == OrderStatus.Filled) break;
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order);
if (!Brokerage.UpdateOrder(order))
{
Assert.Fail("Brokerage failed to update the order");
}
}
}
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
}
/// <summary>
/// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event.
/// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID.
/// </summary>
/// <param name="order">The order to be submitted</param>
/// <param name="expectedStatus">The status to wait for</param>
/// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param>
/// <returns>The same order that was submitted.</returns>
protected Order PlaceOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled, double secondsTimeout = 10.0, bool allowFailedSubmission = false)
{
var requiredStatusEvent = new ManualResetEvent(false);
var desiredStatusEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
// no matter what, every order should fire at least one of these
if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid)
{
Log.Trace("");
Log.Trace("SUBMITTED: " + args);
Log.Trace("");
requiredStatusEvent.Set();
}
// make sure we fire the status we're expecting
if (args.Status == expectedStatus)
{
Log.Trace("");
Log.Trace("EXPECTED: " + args);
Log.Trace("");
desiredStatusEvent.Set();
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
OrderProvider.Add(order);
if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission)
{
Assert.Fail("Brokerage failed to place the order: " + order);
}
requiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "Expected every order to fire a submitted or invalid status event");
desiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout. Order Id:" + order.Id);
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
return order;
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text.Internal;
using System.Text.Unicode;
#if NETCOREAPP
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
namespace System.Text.Encodings.Web
{
internal sealed class DefaultJavaScriptEncoder : JavaScriptEncoder
{
private readonly AllowedCharactersBitmap _allowedCharacters;
private readonly int[] _asciiNeedsEscaping = new int[0x80];
public DefaultJavaScriptEncoder(TextEncoderSettings filter)
{
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
_allowedCharacters = filter.GetAllowedCharacters();
// Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed
// (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp)
_allowedCharacters.ForbidUndefinedCharacters();
// Forbid characters that are special in HTML.
// Even though this is a not HTML encoder,
// it's unfortunately common for developers to
// forget to HTML-encode a string once it has been JS-encoded,
// so this offers extra protection.
DefaultHtmlEncoder.ForbidHtmlCharacters(_allowedCharacters);
// '\' (U+005C REVERSE SOLIDUS) must always be escaped in Javascript / ECMAScript / JSON.
// '/' (U+002F SOLIDUS) is not Javascript / ECMAScript / JSON-sensitive so doesn't need to be escaped.
_allowedCharacters.ForbidCharacter('\\');
// '`' (U+0060 GRAVE ACCENT) is ECMAScript-sensitive (see ECMA-262).
_allowedCharacters.ForbidCharacter('`');
for (int i = 0; i < _asciiNeedsEscaping.Length; i++)
{
_asciiNeedsEscaping[i] = WillEncode(i) ? 1 : -1;
}
}
public DefaultJavaScriptEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges))
{ }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool WillEncode(int unicodeScalar)
{
if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar))
{
return true;
}
Debug.Assert(unicodeScalar >= char.MinValue && unicodeScalar <= char.MaxValue);
return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override unsafe int FindFirstCharacterToEncode(char* text, int textLength)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
return _allowedCharacters.FindFirstCharacterToEncode(text, textLength);
}
public override unsafe int FindFirstCharacterToEncodeUtf8(ReadOnlySpan<byte> utf8Text)
{
fixed (byte* ptr = utf8Text)
{
int idx = 0;
#if NETCOREAPP
if (Sse2.IsSupported)
{
sbyte* startingAddress = (sbyte*)ptr;
while (utf8Text.Length - 16 >= idx)
{
Debug.Assert(startingAddress >= ptr && startingAddress <= (ptr + utf8Text.Length - 16));
// Load the next 16 bytes.
Vector128<sbyte> sourceValue = Sse2.LoadVector128(startingAddress);
Vector128<sbyte> mask = Sse2Helper.CreateAsciiMask(sourceValue);
int index = Sse2.MoveMask(mask);
if (index != 0)
{
// At least one of the following 16 bytes is non-ASCII.
int processNextSixteen = idx + 16;
Debug.Assert(processNextSixteen <= utf8Text.Length);
while (idx < processNextSixteen)
{
Debug.Assert((ptr + idx) <= (ptr + utf8Text.Length));
if (UnicodeUtility.IsAsciiCodePoint(ptr[idx]))
{
if (DoesAsciiNeedEncoding(ptr[idx]) == 1)
{
goto Return;
}
idx++;
}
else
{
OperationStatus opStatus = UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Text.Slice(idx), out uint nextScalarValue, out int utf8BytesConsumedForScalar);
Debug.Assert(nextScalarValue <= int.MaxValue);
if (opStatus != OperationStatus.Done || WillEncode((int)nextScalarValue))
{
goto Return;
}
Debug.Assert(opStatus == OperationStatus.Done);
idx += utf8BytesConsumedForScalar;
}
}
}
else
{
if (DoesAsciiNeedEncoding(ptr[idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1
|| DoesAsciiNeedEncoding(ptr[++idx]) == 1)
{
goto Return;
}
idx++;
}
startingAddress = (sbyte*)ptr + idx;
}
// Process the remaining bytes.
Debug.Assert(utf8Text.Length - idx < 16);
}
#endif
while (idx < utf8Text.Length)
{
Debug.Assert((ptr + idx) <= (ptr + utf8Text.Length));
if (UnicodeUtility.IsAsciiCodePoint(ptr[idx]))
{
if (DoesAsciiNeedEncoding(ptr[idx]) == 1)
{
goto Return;
}
idx++;
}
else
{
OperationStatus opStatus = UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Text.Slice(idx), out uint nextScalarValue, out int utf8BytesConsumedForScalar);
Debug.Assert(nextScalarValue <= int.MaxValue);
if (opStatus != OperationStatus.Done || WillEncode((int)nextScalarValue))
{
goto Return;
}
Debug.Assert(opStatus == OperationStatus.Done);
idx += utf8BytesConsumedForScalar;
}
}
idx = -1; // All bytes are allowed.
Return:
return idx;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int DoesAsciiNeedEncoding(byte value)
{
Debug.Assert(value <= 0x7F);
int needsEscaping = _asciiNeedsEscaping[value];
Debug.Assert(needsEscaping == 1 || needsEscaping == -1);
return needsEscaping;
}
// The worst case encoding is 6 output chars per input char: [input] U+FFFF -> [output] "\uFFFF"
// We don't need to worry about astral code points since they're represented as encoded
// surrogate pairs in the output.
public override int MaxOutputCharactersPerInputCharacter => 12; // "\uFFFF\uFFFF" is the longest encoded form
private static readonly char[] s_b = new char[] { '\\', 'b' };
private static readonly char[] s_t = new char[] { '\\', 't' };
private static readonly char[] s_n = new char[] { '\\', 'n' };
private static readonly char[] s_f = new char[] { '\\', 'f' };
private static readonly char[] s_r = new char[] { '\\', 'r' };
private static readonly char[] s_back = new char[] { '\\', '\\' };
// Writes a scalar value as a JavaScript-escaped character (or sequence of characters).
// See ECMA-262, Sec. 7.8.4, and ECMA-404, Sec. 9
// http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
// http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
public override unsafe bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
// ECMA-262 allows encoding U+000B as "\v", but ECMA-404 does not.
// Both ECMA-262 and ECMA-404 allow encoding U+002F SOLIDUS as "\/"
// (in ECMA-262 this character is a NonEscape character); however, we
// don't encode SOLIDUS by default unless the caller has provided an
// explicit bitmap which does not contain it. In this case we'll assume
// that the caller didn't want a SOLIDUS written to the output at all,
// so it should be written using "\u002F" encoding.
// HTML-specific characters (including apostrophe and quotes) will
// be written out as numeric entities for defense-in-depth.
// See UnicodeEncoderBase ctor comments for more info.
if (!WillEncode(unicodeScalar))
{
return TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten);
}
char[] toCopy;
switch (unicodeScalar)
{
case '\b': toCopy = s_b; break;
case '\t': toCopy = s_t; break;
case '\n': toCopy = s_n; break;
case '\f': toCopy = s_f; break;
case '\r': toCopy = s_r; break;
case '\\': toCopy = s_back; break;
default: return JavaScriptEncoderHelper.TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten);
}
return TryCopyCharacters(toCopy, buffer, bufferLength, out numberOfCharactersWritten);
}
}
}
| |
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using NUnit.Framework;
using Projac.SqlClient;
namespace Projac.Sql.Tests.SqlClient
{
public class SqlClientSyntaxTestCases
{
private static readonly SqlClientSyntax Sql = new SqlClientSyntax();
public static IEnumerable<TestCaseData> QueryProcedureCases()
{
yield return new TestCaseData(
Sql.QueryProcedure("text"),
new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedure("text", parameters: null),
new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedure("text", new { }),
new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedure("text", new { Parameter = new SqlParameterValueStub() }),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedure("text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure));
}
public static IEnumerable<TestCaseData> QueryProcedureIfCases()
{
yield return new TestCaseData(
Sql.QueryProcedureIf(true, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureIf(true, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureIf(true, "text", new { }),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureIf(true, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureIf(true, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureIf(false, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureIf(false, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureIf(false, "text", new { }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureIf(false, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureIf(false, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
}
public static IEnumerable<TestCaseData> QueryProcedureUnlessCases()
{
yield return new TestCaseData(
Sql.QueryProcedureUnless(false, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureUnless(false, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureUnless(false, "text", new { }),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureUnless(false, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureUnless(false, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureUnless(true, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureUnless(true, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureUnless(true, "text", new { }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureUnless(true, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureUnless(true, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
}
public static IEnumerable<TestCaseData> QueryProcedureFormatCases()
{
yield return new TestCaseData(
Sql.QueryProcedureFormat("text"),
new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedureFormat("text", parameters: null),
new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedureFormat("text", new IDbParameterValue[0]),
new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedureFormat("text", new SqlParameterValueStub()),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedureFormat("text {0}", new SqlParameterValueStub()),
new SqlQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedureFormat("text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.QueryProcedureFormat("text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure));
}
public static IEnumerable<TestCaseData> QueryProcedureFormatIfCases()
{
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(true, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(true, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(true, "text", new IDbParameterValue[0]),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(true, "text", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(true, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(false, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(false, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(false, "text", new IDbParameterValue[0]),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(false, "text", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(false, "text {0}", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatIf(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
}
public static IEnumerable<TestCaseData> QueryProcedureFormatUnlessCases()
{
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(false, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(false, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(false, "text", new IDbParameterValue[0]),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(false, "text", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(false, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(true, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(true, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(true, "text", new IDbParameterValue[0]),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(true, "text", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(true, "text {0}", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryProcedureFormatUnless(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryProcedureCases()
{
yield return new TestCaseData(
Sql.NonQueryProcedure("text"),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedure("text", parameters: null),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedure("text", new { }),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedure("text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedure("text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure));
}
public static IEnumerable<TestCaseData> NonQueryProcedureIfCases()
{
yield return new TestCaseData(
Sql.NonQueryProcedureIf(true, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureIf(true, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureIf(true, "text", new { }),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureIf(true, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureIf(true, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureIf(false, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureIf(false, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureIf(false, "text", new { }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureIf(false, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureIf(false, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryProcedureUnlessCases()
{
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(false, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(false, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(false, "text", new { }),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(false, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(false, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(true, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(true, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(true, "text", new { }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(true, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureUnless(true, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryProcedureFormatCases()
{
yield return new TestCaseData(
Sql.NonQueryProcedureFormat("text"),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedureFormat("text", parameters: null),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedureFormat("text", new IDbParameterValue[0]),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedureFormat("text", new SqlParameterValueStub()),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedureFormat("text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedureFormat("text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
Sql.NonQueryProcedureFormat("text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure));
}
public static IEnumerable<TestCaseData> NonQueryProcedureFormatIfCases()
{
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(true, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(true, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(true, "text", new IDbParameterValue[0]),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(true, "text", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(true, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(false, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(false, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(false, "text", new IDbParameterValue[0]),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(false, "text", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(false, "text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatIf(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryProcedureFormatUnlessCases()
{
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(false, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(false, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(false, "text", new IDbParameterValue[0]),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(false, "text", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(false, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(true, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(true, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(true, "text", new IDbParameterValue[0]),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(true, "text", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(true, "text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryProcedureFormatUnless(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryStatementCases()
{
yield return new TestCaseData(
Sql.NonQueryStatement("text"),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatement("text", parameters: null),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatement("text", new { }),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatement("text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatement("text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.Text));
}
public static IEnumerable<TestCaseData> NonQueryStatementIfCases()
{
yield return new TestCaseData(
Sql.NonQueryStatementIf(true, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementIf(true, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementIf(true, "text", new { }),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementIf(true, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementIf(true, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementIf(false, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementIf(false, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementIf(false, "text", new { }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementIf(false, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementIf(false, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryStatementUnlessCases()
{
yield return new TestCaseData(
Sql.NonQueryStatementUnless(false, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementUnless(false, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementUnless(false, "text", new { }),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementUnless(false, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementUnless(false, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementUnless(true, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementUnless(true, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementUnless(true, "text", new { }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementUnless(true, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementUnless(true, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryStatementFormatCases()
{
yield return new TestCaseData(
Sql.NonQueryStatementFormat("text"),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatementFormat("text", parameters: null),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatementFormat("text", new IDbParameterValue[0]),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatementFormat("text", new SqlParameterValueStub()),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatementFormat("text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatementFormat("text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text));
yield return new TestCaseData(
Sql.NonQueryStatementFormat("text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text));
}
public static IEnumerable<TestCaseData> NonQueryStatementFormatIfCases()
{
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(true, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(true, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(true, "text", new IDbParameterValue[0]),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(true, "text", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(true, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(false, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(false, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(false, "text", new IDbParameterValue[0]),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(false, "text", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(false, "text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatIf(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> NonQueryStatementFormatUnlessCases()
{
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(false, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(false, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(false, "text", new IDbParameterValue[0]),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(false, "text", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(false, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(true, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(true, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(true, "text", new IDbParameterValue[0]),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(true, "text", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(true, "text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
Sql.NonQueryStatementFormatUnless(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
}
public static IEnumerable<TestCaseData> QueryStatementCases()
{
yield return new TestCaseData(
Sql.QueryStatement("text"),
new SqlQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatement("text", parameters: null),
new SqlQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatement("text", new { }),
new SqlQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatement("text", new { Parameter = new SqlParameterValueStub() }),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatement("text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.Text));
}
public static IEnumerable<TestCaseData> QueryStatementIfCases()
{
yield return new TestCaseData(
Sql.QueryStatementIf(true, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementIf(true, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementIf(true, "text", new { }),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementIf(true, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementIf(true, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementIf(false, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementIf(false, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementIf(false, "text", new { }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementIf(false, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementIf(false, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
}
public static IEnumerable<TestCaseData> QueryStatementUnlessCases()
{
yield return new TestCaseData(
Sql.QueryStatementUnless(false, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementUnless(false, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementUnless(false, "text", new { }),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementUnless(false, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementUnless(false, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementUnless(true, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementUnless(true, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementUnless(true, "text", new { }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementUnless(true, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementUnless(true, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlQueryCommand[0]);
}
public static IEnumerable<TestCaseData> QueryStatementFormatCases()
{
yield return new TestCaseData(
Sql.QueryStatementFormat("text"),
new SqlQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatementFormat("text", parameters: null),
new SqlQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatementFormat("text", new IDbParameterValue[0]),
new SqlQueryCommand("text", new DbParameter[0], CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatementFormat("text", new SqlParameterValueStub()),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatementFormat("text {0}", new SqlParameterValueStub()),
new SqlQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatementFormat("text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text));
yield return new TestCaseData(
Sql.QueryStatementFormat("text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text));
}
public static IEnumerable<TestCaseData> QueryStatementFormatIfCases()
{
yield return new TestCaseData(
Sql.QueryStatementFormatIf(true, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementFormatIf(true, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementFormatIf(true, "text", new IDbParameterValue[0]),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementFormatIf(true, "text", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatIf(true, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatIf(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatIf(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatIf(false, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatIf(false, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatIf(false, "text", new IDbParameterValue[0]),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatIf(false, "text", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatIf(false, "text {0}", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatIf(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatIf(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
}
public static IEnumerable<TestCaseData> QueryStatementFormatUnlessCases()
{
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(false, "text"),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(false, "text", parameters: null),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(false, "text", new IDbParameterValue[0]),
new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) });
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(false, "text", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(false, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.Text)
});
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(true, "text"),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(true, "text", parameters: null),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(true, "text", new IDbParameterValue[0]),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(true, "text", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(true, "text {0}", new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
yield return new TestCaseData(
Sql.QueryStatementFormatUnless(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlQueryCommand[0]);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using Dbg = System.Management.Automation;
namespace System.Management.Automation
{
/// <summary>
/// Exposes the APIs to manipulate variables in the Runspace.
/// </summary>
public sealed class PSVariableIntrinsics
{
#region Constructors
/// <summary>
/// Hide the default constructor since we always require an instance of SessionState
/// </summary>
private PSVariableIntrinsics()
{
Dbg.Diagnostics.Assert(
false,
"This constructor should never be called. Only the constructor that takes an instance of SessionState should be called.");
} // PSVariableInterfaces private
/// <summary>
/// Constructs a facade for the specified session.
/// </summary>
///
/// <param name="sessionState">
/// The session for which the facade wraps.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="sessionState"/> is null.
/// </exception>
///
internal PSVariableIntrinsics(SessionStateInternal sessionState)
{
if (sessionState == null)
{
throw PSTraceSource.NewArgumentException("sessionState");
}
_sessionState = sessionState;
} // PSVariableInterfaces internal
#endregion Constructors
#region Public methods
/// <summary>
/// Gets the specified variable from session state.
/// </summary>
///
/// <param name="name">
/// The name of the variable to get. The name can contain drive and/or
/// scope specifiers like "ENV:path" or "global:myvar".
/// </param>
///
/// <returns>
/// The specified variable.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
public PSVariable Get(string name)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
// Null is returned whenever the requested variable is String.Empty.
// As per Powershell V1 implementation:
// 1. If the requested variable exists in the session scope, the variable value is returned.
// 2. If the requested variable is not null and does not exist in the session scope, then a null value is returned to the pipeline.
// 3. If the requested variable is null then an NewArgumentNullException is thrown.
// PowerShell V3 has the similar experience.
if (name != null && name.Equals(string.Empty))
{
return null;
}
return _sessionState.GetVariable(name);
} // Get
/// <summary>
/// Gets the specified variable from session state in the specified scope.
/// If the variable doesn't exist in the specified scope no additional lookup
/// will be done.
/// </summary>
///
/// <param name="name">
/// The name of the variable to get. The name can contain drive and/or
/// scope specifiers like "ENV:path" or "global:myvar".
/// </param>
///
/// <param name="scope">
/// The ID of the scope to do the lookup in.
/// </param>
///
/// <returns>
/// The specified variable.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
/// <exception cref="ArgumentException">
/// If <paramref name="scope"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
///
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal PSVariable GetAtScope(string name, string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.GetVariableAtScope(name, scope);
} // GetAtScope
/// <summary>
/// Gets the specified variable value from session state.
/// </summary>
///
/// <param name="name">
/// The name of the variable to get. The name can contain drive and/or
/// scope specifiers like "ENV:path" or "global:myvar".
/// </param>
///
/// <returns>
/// The value of the specified variable.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="name"/> refers to a provider that could not be found.
/// </exception>
///
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="name"/> refers to a drive that could not be found.
/// </exception>
///
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="name"/> refers to does
/// not support this operation.
/// </exception>
///
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
public object GetValue(string name)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.GetVariableValue(name);
} // GetValue
/// <summary>
/// Gets the specified variable from session state. If the variable
/// is not found the default value is returned.
/// </summary>
///
/// <param name="name">
/// The name of the variable to get. The name can contain drive and/or
/// scope specifiers like "ENV:path" or "global:myvar".
/// </param>
///
/// <param name="defaultValue">
/// The default value returned if the variable could not be found.
/// </param>
///
/// <returns>
/// The value of the specified variable or the default value if the variable
/// is not found.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="name"/> refers to a provider that could not be found.
/// </exception>
///
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="name"/> refers to a drive that could not be found.
/// </exception>
///
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="name"/> refers to does
/// not support this operation.
/// </exception>
///
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
public object GetValue(string name, object defaultValue)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.GetVariableValue(name) ?? defaultValue;
} // GetValue
/// <summary>
/// Gets the specified variable from session state in the specified scope.
/// If the variable doesn't exist in the specified scope no additional lookup
/// will be done.
/// </summary>
///
/// <param name="name">
/// The name of the variable to get. The name can contain drive and/or
/// scope specifiers like "ENV:path" or "global:myvar".
/// </param>
///
/// <param name="scope">
/// The ID of the scope to do the lookup in.
/// </param>
///
/// <returns>
/// The value of the specified variable.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
/// <exception cref="ArgumentException">
/// If <paramref name="scope"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
///
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
///
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="name"/> refers to a provider that could not be found.
/// </exception>
///
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="name"/> refers to a drive that could not be found.
/// </exception>
///
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="name"/> refers to does
/// not support this operation.
/// </exception>
///
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal object GetValueAtScope(string name, string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.GetVariableValueAtScope(name, scope);
} // GetValueAtScope
/// <summary>
/// Sets the variable to the specified value.
/// </summary>
///
/// <param name="name">
/// The name of the variable to be set. The name can contain drive and/or
/// scope specifiers like "ENV:path" or "global:myvar".
/// </param>
///
/// <param name="value">
/// The value to set the variable to.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the variable is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of variables has been reached for this scope.
/// </exception>
///
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="name"/> refers to a provider that could not be found.
/// </exception>
///
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="name"/> refers to a drive that could not be found.
/// </exception>
///
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="name"/> refers to does
/// not support this operation.
/// </exception>
///
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
public void Set(string name, object value)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.SetVariableValue(name, value, CommandOrigin.Internal);
} // SetVariable
/// <summary>
/// Sets the variable.
/// </summary>
///
/// <param name="variable">
///
/// The variable to set
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="variable"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the variable is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of variables has been reached for this scope.
/// </exception>
public void Set(PSVariable variable)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.SetVariable(variable, false, CommandOrigin.Internal);
} // SetVariable
/// <summary>
/// Removes the specified variable from session state.
/// </summary>
///
/// <param name="name">
/// The name of the variable to be removed. The name can contain drive and/or
/// scope specifiers like "ENV:path" or "global:myvar".
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// if the variable is constant.
/// </exception>
///
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="name"/> refers to a provider that could not be found.
/// </exception>
///
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="name"/> refers to a drive that could not be found.
/// </exception>
///
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="name"/> refers to does
/// not support this operation.
/// </exception>
///
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
public void Remove(string name)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.RemoveVariable(name);
} // RemoveVariable
/// <summary>
/// Removes the specified variable from session state.
/// </summary>
///
/// <param name="variable">
/// The variable to be removed. It is removed based on the name of the variable.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="variable"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// if the variable is constant.
/// </exception>
public void Remove(PSVariable variable)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.RemoveVariable(variable);
} // RemoveVariable
/// <summary>
/// Removes the specified variable from the specified scope
/// </summary>
///
/// <param name="name">
/// The name of the variable to remove.
/// </param>
///
/// <param name="scope">
/// The ID of the scope to do the lookup in. The ID is a zero based index
/// of the scope tree with the current scope being zero, its parent scope
/// being 1 and so on.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
///
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
///
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// if the variable is constant.
/// </exception>
///
/// <exception cref="ProviderInvocationException">
/// If <paramref name="name"/> refers to an MSH path (not a variable)
/// and the provider throws an exception.
/// </exception>
internal void RemoveAtScope(string name, string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.RemoveVariableAtScope(name, scope);
}
/// <summary>
/// Removes the specified variable from the specified scope
/// </summary>
///
/// <param name="variable">
/// The variable to be removed. It is removed based on the name of the variable.
/// </param>
///
/// <param name="scope">
/// The ID of the scope to do the lookup in. The ID is a zero based index
/// of the scope tree with the current scope being zero, its parent scope
/// being 1 and so on.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="variable"/> is null.
/// </exception>
///
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
///
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// if the variable is constant.
/// </exception>
internal void RemoveAtScope(PSVariable variable, string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.RemoveVariableAtScope(variable, scope);
}
#endregion Public methods
#region private data
private SessionStateInternal _sessionState;
#endregion private data
} // PSVariableIntrinsics
}
| |
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using FileHelpers;
using FileHelpers.Events;
using FileHelpersSamples.Properties;
namespace FileHelpersSamples
{
/// <summary>
/// This example show how progress bars work
/// </summary>
public class frmProgressSample : frmFather
{
private Button cmdRun;
private Framework.Controls.XpProgressBar prog1;
private Framework.Controls.XpProgressBar prog4;
private Framework.Controls.XpProgressBar prog3;
private Framework.Controls.XpProgressBar prog2;
private System.Windows.Forms.TextBox txtClass;
private System.Windows.Forms.Label label2;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public frmProgressSample()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdRun = new System.Windows.Forms.Button();
this.prog1 = new Framework.Controls.XpProgressBar();
this.prog3 = new Framework.Controls.XpProgressBar();
this.prog2 = new Framework.Controls.XpProgressBar();
this.prog4 = new Framework.Controls.XpProgressBar();
this.txtClass = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// cmdRun
//
this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdRun.Font = new System.Drawing.Font("Tahoma",
9.75F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdRun.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdRun.Location = new System.Drawing.Point(336, 8);
this.cmdRun.Name = "cmdRun";
this.cmdRun.Size = new System.Drawing.Size(152, 32);
this.cmdRun.TabIndex = 0;
this.cmdRun.Text = "RUN >>";
this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
//
// prog1
//
this.prog1.Color1 = System.Drawing.Color.Blue;
this.prog1.Color2 = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (64)));
this.prog1.ColorText = System.Drawing.Color.WhiteSmoke;
this.prog1.ColorTextShadow = System.Drawing.Color.DimGray;
this.prog1.Font = new System.Drawing.Font("Tahoma",
14.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog1.GradientStyle = Framework.Controls.GradientMode.Horizontal;
this.prog1.Location = new System.Drawing.Point(8, 64);
this.prog1.Name = "prog1";
this.prog1.Position = 0;
this.prog1.PositionMax = 100;
this.prog1.PositionMin = 0;
this.prog1.Size = new System.Drawing.Size(654, 32);
this.prog1.StepDistance = ((System.Byte) (0));
this.prog1.StepWidth = ((System.Byte) (3));
this.prog1.Text = "CodeProject XpProgressBar";
this.prog1.TextShadowAlpha = ((System.Byte) (200));
this.prog1.WatermarkAlpha = 255;
this.prog1.WatermarkImage = null;
//
// prog3
//
this.prog3.Color1 = System.Drawing.Color.FromArgb(((System.Byte) (255)),
((System.Byte) (224)),
((System.Byte) (192)));
this.prog3.Color2 = System.Drawing.Color.FromArgb(((System.Byte) (192)),
((System.Byte) (64)),
((System.Byte) (0)));
this.prog3.ColorText = System.Drawing.Color.FromArgb(((System.Byte) (115)),
((System.Byte) (50)),
((System.Byte) (0)));
this.prog3.ColorTextShadow = System.Drawing.Color.DimGray;
this.prog3.Font = new System.Drawing.Font("Tahoma",
12F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog3.GradientStyle = Framework.Controls.GradientMode.Vertical;
this.prog3.Location = new System.Drawing.Point(8, 144);
this.prog3.Name = "prog3";
this.prog3.Position = 0;
this.prog3.PositionMax = 100;
this.prog3.PositionMin = 0;
this.prog3.Size = new System.Drawing.Size(654, 32);
this.prog3.StepDistance = ((System.Byte) (0));
this.prog3.StepWidth = ((System.Byte) (3));
this.prog3.WatermarkAlpha = 255;
this.prog3.WatermarkImage = null;
//
// prog2
//
this.prog2.Color1 = System.Drawing.Color.AliceBlue;
this.prog2.Color2 = System.Drawing.Color.SteelBlue;
this.prog2.ColorText = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (64)));
this.prog2.Font = new System.Drawing.Font("Tahoma",
12F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog2.GradientStyle = Framework.Controls.GradientMode.Diagonal;
this.prog2.Location = new System.Drawing.Point(8, 104);
this.prog2.Name = "prog2";
this.prog2.Position = 0;
this.prog2.PositionMax = 100;
this.prog2.PositionMin = 0;
this.prog2.Size = new System.Drawing.Size(654, 32);
this.prog2.Text = "Full Customizable";
this.prog2.TextShadow = false;
this.prog2.WatermarkAlpha = 255;
this.prog2.WatermarkImage = null;
//
// prog4
//
this.prog4.Color1 = System.Drawing.Color.RoyalBlue;
this.prog4.Color2 = System.Drawing.Color.AliceBlue;
this.prog4.ColorText = System.Drawing.Color.Navy;
this.prog4.ColorTextShadow = System.Drawing.Color.DimGray;
this.prog4.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog4.GradientStyle = Framework.Controls.GradientMode.HorizontalCenter;
this.prog4.Location = new System.Drawing.Point(8, 184);
this.prog4.Name = "prog4";
this.prog4.Position = 0;
this.prog4.PositionMax = 100;
this.prog4.PositionMin = 0;
this.prog4.Size = new System.Drawing.Size(654, 32);
this.prog4.StepDistance = ((System.Byte) (0));
this.prog4.StepWidth = ((System.Byte) (3));
this.prog4.WatermarkAlpha = 255;
this.prog4.WatermarkImage = null;
//
// txtClass
//
this.txtClass.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.txtClass.Location = new System.Drawing.Point(8, 240);
this.txtClass.Multiline = true;
this.txtClass.Name = "txtClass";
this.txtClass.ReadOnly = true;
this.txtClass.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtClass.Size = new System.Drawing.Size(656, 224);
this.txtClass.TabIndex = 12;
this.txtClass.Text = @"private void Run()
{
FileHelperEngine engine = new FileHelperEngine(typeof (CustomersVerticalBar));
engine.SetProgressHandler(new ProgressChangeHandler(ProgressChange));
engine.WriteFile(""test.txt"", records);
}
private void ProgressChange(ProgressEventArgs e)
{
prog1.PositionMax = e.ProgressTotal;
prog1.Position = e.ProgressCurrent;
prog1.Text = ""Record "" + e.ProgressCurrent.ToString();
Application.DoEvents();
}";
this.txtClass.WordWrap = false;
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(8, 224);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(272, 16);
this.label2.TabIndex = 13;
this.label2.Text = "Sample code of using the ProgressChange";
//
// frmProgressSample
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(674, 496);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtClass);
this.Controls.Add(this.prog4);
this.Controls.Add(this.prog2);
this.Controls.Add(this.prog3);
this.Controls.Add(this.prog1);
this.Controls.Add(this.cmdRun);
this.Name = "frmProgressSample";
this.Text = "FileHelpers - Progress Example";
this.Controls.SetChildIndex(this.cmdRun, 0);
this.Controls.SetChildIndex(this.prog1, 0);
this.Controls.SetChildIndex(this.prog3, 0);
this.Controls.SetChildIndex(this.prog2, 0);
this.Controls.SetChildIndex(this.prog4, 0);
this.Controls.SetChildIndex(this.txtClass, 0);
this.Controls.SetChildIndex(this.label2, 0);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Run the engine with a progress bar
/// hooked into it to give the user a visual
/// cue on how things are progressing.
/// </summary>
private void cmdRun_Click(object sender, EventArgs e)
{
// Disable the button, don't want it clicked twice
cmdRun.Enabled = false;
FileHelperEngine engine = new FileHelperEngine(typeof (CustomersVerticalBar));
object[] records = engine.ReadString(Resources.Customers);
Application.DoEvents();
engine.Progress += ProgressChange;
engine.WriteString(records);
// enable the button again we have finished.
cmdRun.Enabled = true;
}
/// <summary>
/// Set the progress bars data, how it is used is
/// up to the progress bars themselves.
/// </summary>
private void ProgressChange(object sender, ProgressEventArgs e)
{
prog1.PositionMax = e.TotalRecords;
prog2.PositionMax = e.TotalRecords;
prog3.PositionMax = e.TotalRecords;
prog4.PositionMax = e.TotalRecords;
prog1.Position = e.CurrentRecord;
prog2.Position = e.CurrentRecord;
prog3.Position = e.CurrentRecord;
prog4.Position = e.CurrentRecord;
prog3.Text = "Record " + e.CurrentRecord.ToString();
prog4.Text = e.CurrentRecord.ToString() + " Of " + e.TotalRecords.ToString();
Application.DoEvents();
Thread.Sleep(10);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TestPublisher.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Akka.Actor;
using Akka.Event;
using Akka.Streams.Implementation;
using Akka.TestKit;
using Reactive.Streams;
namespace Akka.Streams.TestKit
{
/// <summary>
/// Provides factory methods for various Publishers.
/// </summary>
public static class TestPublisher
{
#region messages
public interface IPublisherEvent : INoSerializationVerificationNeeded, IDeadLetterSuppression { }
public struct Subscribe : IPublisherEvent
{
public readonly ISubscription Subscription;
public Subscribe(ISubscription subscription)
{
Subscription = subscription;
}
}
public struct CancelSubscription : IPublisherEvent
{
public readonly ISubscription Subscription;
public CancelSubscription(ISubscription subscription)
{
Subscription = subscription;
}
}
public struct RequestMore : IPublisherEvent
{
public readonly ISubscription Subscription;
public readonly long NrOfElements;
public RequestMore(ISubscription subscription, long nrOfElements)
{
Subscription = subscription;
NrOfElements = nrOfElements;
}
}
#endregion
/// <summary>
/// Implementation of <see cref="IPublisher{T}"/> that allows various assertions.
/// This probe does not track demand.Therefore you need to expect demand before sending
/// elements downstream.
/// </summary>
public class ManualProbe<T> : IPublisher<T>
{
private readonly TestProbe _probe;
internal ManualProbe(TestKitBase system, bool autoOnSubscribe = true)
{
_probe = system.CreateTestProbe();
AutoOnSubscribe = autoOnSubscribe;
}
public bool AutoOnSubscribe { get; private set; }
public IPublisher<T> Publisher { get { return this; } }
/// <summary>
/// Subscribes a given <paramref name="subscriber"/> to this probe.
/// </summary>
public void Subscribe(ISubscriber<T> subscriber)
{
var subscription = new StreamTestKit.PublisherProbeSubscription<T>(subscriber, _probe);
_probe.Ref.Tell(new TestPublisher.Subscribe(subscription));
if (AutoOnSubscribe) subscriber.OnSubscribe(subscription);
}
/// <summary>
/// Expect a subscription.
/// </summary>
public StreamTestKit.PublisherProbeSubscription<T> ExpectSubscription()
{
return
(StreamTestKit.PublisherProbeSubscription<T>) _probe.ExpectMsg<Subscribe>().Subscription;
}
/// <summary>
/// Expect demand from the given subscription.
/// </summary>
public ManualProbe<T> ExpectRequest(ISubscription subscription, int n)
{
_probe.ExpectMsg<TestPublisher.RequestMore>(x => x.NrOfElements == n && x.Subscription == subscription);
return this;
}
/// <summary>
/// Expect no messages.
/// </summary>
public ManualProbe<T> ExpectNoMsg()
{
_probe.ExpectNoMsg();
return this;
}
/// <summary>
/// Expect no messages for given duration.
/// </summary>
public ManualProbe<T> ExpectNoMsg(TimeSpan duration)
{
_probe.ExpectNoMsg(duration);
return this;
}
/// <summary>
/// Receive messages for a given duration or until one does not match a given partial function.
/// </summary>
public IEnumerable<TOther> ReceiveWhile<TOther>(TimeSpan? max = null, TimeSpan? idle = null, Func<object, TOther> filter = null, int msgs = int.MaxValue) where TOther : class
{
return _probe.ReceiveWhile(max, idle, filter, msgs);
}
public IPublisherEvent ExpectEvent()
{
return _probe.ExpectMsg<IPublisherEvent>();
}
}
/// <summary>
/// Single subscription and demand tracking for <see cref="ManualProbe{T}"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Probe<T> : ManualProbe<T>
{
private readonly long _initialPendingRequests;
private readonly Lazy<StreamTestKit.PublisherProbeSubscription<T>> _subscription;
internal Probe(TestKitBase system, long initialPendingRequests) : base(system)
{
_initialPendingRequests = Pending = initialPendingRequests;
_subscription = new Lazy<StreamTestKit.PublisherProbeSubscription<T>>(ExpectSubscription);
}
/// <summary>
/// Current pending requests.
/// </summary>
public long Pending { get; private set; }
/// <summary>
/// Asserts that a subscription has been received or will be received
/// </summary>
public void EnsureSubscription()
{
var _ = _subscription.Value;
}
public Probe<T> SendNext(T element)
{
var sub = _subscription.Value;
if (Pending == 0) Pending = sub.ExpectRequest();
Pending--;
sub.SendNext(element);
return this;
}
public Probe<T> UnsafeSendNext(T element)
{
_subscription.Value.SendNext(element);
return this;
}
public Probe<T> SendComplete()
{
_subscription.Value.SendComplete();
return this;
}
public Probe<T> SendError(Exception e)
{
_subscription.Value.SendError(e);
return this;
}
public long ExpectRequest()
{
var requests = _subscription.Value.ExpectRequest();
Pending += requests;
return requests;
}
public Probe<T> ExpectCancellation()
{
_subscription.Value.ExpectCancellation();
return this;
}
}
internal sealed class LazyEmptyPublisher<T> : IPublisher<T>
{
public static readonly IPublisher<T> Instance = new LazyEmptyPublisher<T>();
private LazyEmptyPublisher() { }
public void Subscribe(ISubscriber<T> subscriber)
{
subscriber.OnSubscribe(new StreamTestKit.CompletedSubscription<T>(subscriber));
}
public override string ToString()
{
return "soon-to-complete-publisher";
}
}
internal sealed class LazyErrorPublisher<T> : IPublisher<T>
{
public readonly string Name;
public readonly Exception Cause;
public LazyErrorPublisher(Exception cause, string name)
{
Name = name;
Cause = cause;
}
public void Subscribe(ISubscriber<T> subscriber)
{
subscriber.OnSubscribe(new StreamTestKit.FailedSubscription<T>(subscriber, Cause));
}
public override string ToString()
{
return Name;
}
}
/// <summary>
/// Publisher that signals complete to subscribers, after handing a void subscription.
/// </summary>
public static IPublisher<T> Empty<T>()
{
return EmptyPublisher<T>.Instance;
}
/// <summary>
/// Publisher that subscribes the subscriber and completes after the first request.
/// </summary>
public static IPublisher<T> LazyEmpty<T>()
{
return LazyEmptyPublisher<T>.Instance;
}
/// <summary>
/// Publisher that signals error to subscribers immediately after handing out subscription.
/// </summary>
public static IPublisher<T> Error<T>(Exception exception)
{
return new ErrorPublisher<T>(exception, "error");
}
/// <summary>
/// Publisher subscribes the subscriber and signals error after the first request.
/// </summary>
public static IPublisher<T> LazyError<T>(Exception exception)
{
return new LazyErrorPublisher<T>(exception, "error");
}
/// <summary>
/// Probe that implements <see cref="IPublisher{T}"/> interface.
/// </summary>
public static ManualProbe<T> CreateManualPublisherProbe<T>(this TestKitBase testKit, bool autoOnSubscribe = true)
{
return new ManualProbe<T>(testKit, autoOnSubscribe);
}
public static Probe<T> CreatePublisherProbe<T>(this TestKitBase testKit, long initialPendingRequests = 0L)
{
return new Probe<T>(testKit, initialPendingRequests);
}
}
}
| |
// leveldb-sharp
//
// Copyright (c) 2012-2013, Mirco Bauer <meebey@meebey.net>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.IO;
using System.Collections.Generic;
using NUnit.Framework;
namespace LevelDB
{
[TestFixture]
public class NativeTests
{
IntPtr Database { get; set; }
string DatabasePath { get; set; }
[SetUp]
public void SetUp()
{
var tempPath = Path.GetTempPath();
var randName = Path.GetRandomFileName();
DatabasePath = Path.Combine(tempPath, randName);
var options = Native.leveldb_options_create();
Native.leveldb_options_set_create_if_missing(options, true);
Database = Native.leveldb_open(options, DatabasePath);
}
[TearDown]
public void TearDown()
{
if (Database != IntPtr.Zero) {
Native.leveldb_close(Database);
Database = IntPtr.Zero;
}
if (Directory.Exists(DatabasePath)) {
Directory.Delete(DatabasePath, true);
}
}
[Test]
public void Open()
{
// NOOP, SetUp calls open for us
}
[Test]
public void Reopen()
{
Native.leveldb_close(Database);
Database = IntPtr.Zero;
var options = Native.leveldb_options_create();
Database = Native.leveldb_open(options, DatabasePath);
var readOptions = Native.leveldb_readoptions_create();
Native.leveldb_get(Database, readOptions, "key1");
Native.leveldb_readoptions_destroy(readOptions);
}
[Test]
public void Put()
{
var options = Native.leveldb_writeoptions_create();
Native.leveldb_put(Database, options, "key1", "value1");
Native.leveldb_put(Database, options, "key2", "value2");
Native.leveldb_put(Database, options, "key3", "value3");
// sync
Native.leveldb_writeoptions_set_sync(options, true);
Native.leveldb_put(Database, options, "key4", "value4");
}
[Test]
public void Get()
{
var options = Native.leveldb_readoptions_create();
Native.leveldb_put(Database, options, "key1", "value1");
var value1 = Native.leveldb_get(Database, options, "key1");
Assert.AreEqual("value1", value1);
Native.leveldb_put(Database, options, "key2", "value2");
var value2 = Native.leveldb_get(Database, options, "key2");
Assert.AreEqual("value2", value2);
Native.leveldb_put(Database, options, "key3", "value3");
var value3 = Native.leveldb_get(Database, options, "key3");
Assert.AreEqual("value3", value3);
// verify checksums
Native.leveldb_readoptions_set_verify_checksums(options, true);
value1 = Native.leveldb_get(Database, options, "key1");
Assert.AreEqual("value1", value1);
// no fill cache
Native.leveldb_readoptions_set_fill_cache(options, false);
value2 = Native.leveldb_get(Database, options, "key2");
Assert.AreEqual("value2", value2);
Native.leveldb_readoptions_destroy(options);
}
[Test]
public void Delete()
{
var writeOptions = Native.leveldb_writeoptions_create();
Native.leveldb_put(Database, writeOptions, "key1", "value1");
var readOptions = Native.leveldb_readoptions_create();
var value1 = Native.leveldb_get(Database, readOptions, "key1");
Assert.AreEqual("value1", value1);
Native.leveldb_delete(Database, writeOptions, "key1");
value1 = Native.leveldb_get(Database, readOptions, "key1");
Assert.IsNull(value1);
Native.leveldb_writeoptions_destroy(writeOptions);
Native.leveldb_readoptions_destroy(readOptions);
}
[Test]
public void WriteBatch()
{
var writeOptions = Native.leveldb_writeoptions_create();
Native.leveldb_put(Database, writeOptions, "key1", "value1");
var writeBatch = Native.leveldb_writebatch_create();
Native.leveldb_writebatch_delete(writeBatch, "key1");
Native.leveldb_writebatch_put(writeBatch, "key2", "value2");
Native.leveldb_write(Database, writeOptions, writeBatch);
var readOptions = Native.leveldb_readoptions_create();
var value1 = Native.leveldb_get(Database, readOptions, "key1");
Assert.IsNull(value1);
var value2 = Native.leveldb_get(Database, readOptions, "key2");
Assert.AreEqual("value2", value2);
Native.leveldb_writebatch_delete(writeBatch, "key2");
Native.leveldb_writebatch_clear(writeBatch);
Native.leveldb_write(Database, writeOptions, writeBatch);
value2 = Native.leveldb_get(Database, readOptions, "key2");
Assert.AreEqual("value2", value2);
Native.leveldb_writebatch_destroy(writeBatch);
Native.leveldb_writeoptions_destroy(writeOptions);
Native.leveldb_writeoptions_destroy(readOptions);
}
[Test]
public void Enumerator()
{
var writeOptions = Native.leveldb_writeoptions_create();
Native.leveldb_put(Database, writeOptions, "key1", "value1");
Native.leveldb_put(Database, writeOptions, "key2", "value2");
Native.leveldb_put(Database, writeOptions, "key3", "value3");
var entries = new List<KeyValuePair<string, string>>();
var readOptions = Native.leveldb_readoptions_create();
IntPtr iter = Native.leveldb_create_iterator(Database, readOptions);
for (Native.leveldb_iter_seek_to_first(iter);
(int)Native.leveldb_iter_valid(iter) != 0;
Native.leveldb_iter_next(iter)) {
string key = Native.leveldb_iter_key(iter);
string value = Native.leveldb_iter_value(iter);
var entry = new KeyValuePair<string, string>(key, value);
entries.Add(entry);
}
Native.leveldb_iter_destroy(iter);
Native.leveldb_readoptions_destroy(readOptions);
Assert.AreEqual(3, entries.Count);
Assert.AreEqual("key1", entries[0].Key);
Assert.AreEqual("value1", entries[0].Value);
Assert.AreEqual("key2", entries[1].Key);
Assert.AreEqual("value2", entries[1].Value);
Assert.AreEqual("key3", entries[2].Key);
Assert.AreEqual("value3", entries[2].Value);
Native.leveldb_writeoptions_destroy(writeOptions);
}
[Test]
public void Cache()
{
Native.leveldb_close(Database);
Database = IntPtr.Zero;
// open the DB with a cache that is not owned by LevelDB, then
// close DB and then free the cache
var options = Native.leveldb_options_create();
var cache = Native.leveldb_cache_create_lru((UIntPtr) 64);
Native.leveldb_options_set_cache(options, cache);
Database = Native.leveldb_open(options, DatabasePath);
Native.leveldb_close(Database);
Database = IntPtr.Zero;
Native.leveldb_cache_destroy(cache);
Native.leveldb_options_destroy(options);
}
[Test]
public void Snapshot()
{
// modify db
var writeOptions = Native.leveldb_writeoptions_create();
Native.leveldb_put(Database, writeOptions, "key1", "value1");
Native.leveldb_writeoptions_destroy(writeOptions);
// create snapshot
var snapshot = Native.leveldb_create_snapshot(Database);
// modify db again
writeOptions = Native.leveldb_writeoptions_create();
Native.leveldb_put(Database, writeOptions, "key2", "value2");
Native.leveldb_writeoptions_destroy(writeOptions);
// read from snapshot
var readOptions = Native.leveldb_readoptions_create();
Native.leveldb_readoptions_set_snapshot(readOptions, snapshot);
var val1 = Native.leveldb_get(Database, readOptions, "key1");
Assert.AreEqual("value1", val1);
var val2 = Native.leveldb_get(Database, readOptions, "key2");
Assert.IsNull(val2);
Native.leveldb_readoptions_destroy(readOptions);
// release snapshot
Native.leveldb_release_snapshot(Database, snapshot);
snapshot = IntPtr.Zero;
}
[Test]
public void Version()
{
var major = Native.leveldb_major_version();
Assert.Greater(major, 0);
var minor = Native.leveldb_minor_version();
Assert.Greater(minor, 0);
Console.WriteLine("LevelDB version: {0}.{1}", major, minor);
}
[Test]
public void CompactRange()
{
Native.leveldb_compact_range(Database, null, null);
}
[Test]
public void Destroy()
{
Native.leveldb_close(Database);
Database = IntPtr.Zero;
var options = Native.leveldb_options_create();
Native.leveldb_destroy_db(options, DatabasePath);
Native.leveldb_options_destroy(options);
}
[Test]
public void Repair()
{
Native.leveldb_close(Database);
Database = IntPtr.Zero;
var options = Native.leveldb_options_create();
Native.leveldb_repair_db(options, DatabasePath);
Native.leveldb_options_destroy(options);
}
[Test]
public void Property()
{
var property = Native.leveldb_property_value(Database, "leveldb.stats");
Assert.IsNotNull(property);
Console.WriteLine("LevelDB stats: {0}", property);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// An event registration token table stores mappings from delegates to event tokens, in order to support
// sourcing WinRT style events from managed code.
public sealed class EventRegistrationTokenTable<T> where T : class
{
// Note this dictionary is also used as the synchronization object for this table
private Dictionary<EventRegistrationToken, T> m_tokens = new Dictionary<EventRegistrationToken, T>();
// Cached multicast delegate which will invoke all of the currently registered delegates. This
// will be accessed frequently in common coding paterns, so we don't want to calculate it repeatedly.
private volatile T m_invokeList;
public EventRegistrationTokenTable()
{
// T must be a delegate type, but we cannot constrain on being a delegate. Therefore, we'll do a
// static check at construction time
/*
if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EventTokenTableRequiresDelegate", typeof(T)));
}
*/
}
// The InvocationList property provides access to a delegate which will invoke every registered event handler
// in this table. If the property is set, the new value will replace any existing token registrations.
public T InvocationList
{
get
{
return m_invokeList;
}
set
{
lock (m_tokens)
{
// The value being set replaces any of the existing values
m_tokens.Clear();
m_invokeList = null;
if (value != null)
{
AddEventHandlerNoLock(value);
}
}
}
}
public EventRegistrationToken AddEventHandler(T handler)
{
// Windows Runtime allows null handlers. Assign those a token value of 0 for easy identity
if (handler == null)
{
return new EventRegistrationToken(0);
}
lock (m_tokens)
{
return AddEventHandlerNoLock(handler);
}
}
private EventRegistrationToken AddEventHandlerNoLock(T handler)
{
Contract.Requires(handler != null);
// Get a registration token, making sure that we haven't already used the value. This should be quite
// rare, but in the case it does happen, just keep trying until we find one that's unused.
EventRegistrationToken token = GetPreferredToken(handler);
while (m_tokens.ContainsKey(token))
{
token = new EventRegistrationToken(token.Value + 1);
}
m_tokens[token] = handler;
// Update the current invocation list to include the newly added delegate
Delegate invokeList = (Delegate)(object)m_invokeList;
invokeList = MulticastDelegate.Combine(invokeList, (Delegate)(object)handler);
m_invokeList = (T)(object)invokeList;
return token;
}
// Get the delegate associated with an event registration token if it exists. Additionally,
// remove the registration from the table at the same time. If the token is not registered,
// Extract returns null and does not modify the table.
// [System.Runtime.CompilerServices.FriendAccessAllowed]
internal T ExtractHandler(EventRegistrationToken token)
{
T handler = null;
lock (m_tokens)
{
if (m_tokens.TryGetValue(token, out handler))
{
RemoveEventHandlerNoLock(token);
}
}
return handler;
}
// Generate a token that may be used for a particular event handler. We will frequently be called
// upon to look up a token value given only a delegate to start from. Therefore, we want to make
// an initial token value that is easily determined using only the delegate instance itself. Although
// in the common case this token value will be used to uniquely identify the handler, it is not
// the only possible token that can represent the handler.
//
// This means that both:
// * if there is a handler assigned to the generated initial token value, it is not necessarily
// this handler.
// * if there is no handler assigned to the generated initial token value, the handler may still
// be registered under a different token
//
// Effectively the only reasonable thing to do with this value is either to:
// 1. Use it as a good starting point for generating a token for handler
// 2. Use it as a guess to quickly see if the handler was really assigned this token value
private static EventRegistrationToken GetPreferredToken(T handler)
{
Contract.Requires(handler != null);
// We want to generate a token value that has the following properties:
// 1. is quickly obtained from the handler instance
// 2. uses bits in the upper 32 bits of the 64 bit value, in order to avoid bugs where code
// may assume the value is realy just 32 bits
// 3. uses bits in the bottom 32 bits of the 64 bit value, in order to ensure that code doesn't
// take a dependency on them always being 0.
//
// The simple algorithm chosen here is to simply assign the upper 32 bits the metadata token of the
// event handler type, and the lower 32 bits the hash code of the handler instance itself. Using the
// metadata token for the upper 32 bits gives us at least a small chance of being able to identify a
// totally corrupted token if we ever come across one in a minidump or other scenario.
//
// The hash code of a unicast delegate is not tied to the method being invoked, so in the case
// of a unicast delegate, the hash code of the target method is used instead of the full delegate
// hash code.
//
// While calculating this initial value will be somewhat more expensive than just using a counter
// for events that have few registrations, it will also gives us a shot at preventing unregistration
// from becoming an O(N) operation.
//
// We should feel free to change this algorithm as other requirements / optimizations become
// available. This implementation is sufficiently random that code cannot simply guess the value to
// take a dependency upon it. (Simply applying the hash-value algorithm directly won't work in the
// case of collisions, where we'll use a different token value).
uint handlerHashCode = 0;
/*
Delegate[] invocationList = ((Delegate)(object)handler).GetInvocationList();
if (invocationList.Length == 1)
{
handlerHashCode = (uint)invocationList[0].Method.GetHashCode();
}
else
{
*/
handlerHashCode = (uint)handler.GetHashCode();
// }
ulong tokenValue = /* ((ulong)(uint)typeof(T).MetadataToken << 32) | */ handlerHashCode;
return new EventRegistrationToken(unchecked((long)tokenValue));
}
public void RemoveEventHandler(EventRegistrationToken token)
{
// The 0 token is assigned to null handlers, so there's nothing to do
if (token.Value == 0)
{
return;
}
lock (m_tokens)
{
RemoveEventHandlerNoLock(token);
}
}
public void RemoveEventHandler(T handler)
{
// To match the Windows Runtime behaivor when adding a null handler, removing one is a no-op
if (handler == null)
{
return;
}
lock (m_tokens)
{
// Fast path - if the delegate is stored with its preferred token, then there's no need to do
// a full search of the table for it. Note that even if we find something stored using the
// preferred token value, it's possible we have a collision and another delegate was using that
// value. Therefore we need to make sure we really have the handler we want before taking the
// fast path.
EventRegistrationToken preferredToken = GetPreferredToken(handler);
T registeredHandler;
if (m_tokens.TryGetValue(preferredToken, out registeredHandler))
{
if (registeredHandler == handler)
{
RemoveEventHandlerNoLock(preferredToken);
return;
}
}
// Slow path - we didn't find the delegate with its preferred token, so we need to fall
// back to a search of the table
foreach (KeyValuePair<EventRegistrationToken, T> registration in m_tokens)
{
if (registration.Value == (T)(object)handler)
{
RemoveEventHandlerNoLock(registration.Key);
// If a delegate has been added multiple times to handle an event, then it
// needs to be removed the same number of times to stop handling the event.
// Stop after the first one we find.
return;
}
}
// Note that falling off the end of the loop is not an error, as removing a registration
// for a handler that is not currently registered is simply a no-op
}
}
private void RemoveEventHandlerNoLock(EventRegistrationToken token)
{
T handler;
if (m_tokens.TryGetValue(token, out handler))
{
m_tokens.Remove(token);
// Update the current invocation list to remove the delegate
Delegate invokeList = (Delegate)(object)m_invokeList;
invokeList = MulticastDelegate.Remove(invokeList, (Delegate)(object)handler);
m_invokeList = (T)(object)invokeList;
}
}
public static EventRegistrationTokenTable<T> GetOrCreateEventRegistrationTokenTable(ref EventRegistrationTokenTable<T> refEventTable)
{
if (refEventTable == null)
{
Interlocked.CompareExchange(ref refEventTable, new EventRegistrationTokenTable<T>(), null);
}
return refEventTable;
}
}
public static partial class EventRegistrationHelpers
{
/// <summary>
/// A helper method that exposed in our System.Private.MCG
/// contract assembly to access the internal ExtractHandler method
/// There are other options such as
/// 1) define another EventRegistrationTokenTable.Extracthandler in
/// System.Private.MCG assembly. Unfortunately this doesn't work because
/// compiler sees two EventRegistrationTokenTable classes in two contracts
/// 2) make a Extracthandler an extention method. This requires having a "using" statement for the
/// extension methods and doesn't make things easier to understand
/// </summary>
public static T ExtractHandler<T>(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<T> table, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken token) where T : class
{
return table.ExtractHandler(token);
}
/// <summary>
/// Given a key, locate the corresponding value in the ConditionalWeakTable according to value
/// equality. Will create a new value if the key is not found.
/// <summary>
public static TValue GetValueFromEquivalentKey<TKey, TValue>(ConditionalWeakTable<TKey, TValue> table, TKey key, ConditionalWeakTable<TKey, TValue>.CreateValueCallback callback)
where TKey : class
where TValue : class
{
TValue value;
TKey foundKey = table.FindEquivalentKeyUnsafe(key, out value);
if (foundKey == default(TKey))
{
value = callback(key);
table.Add(key, value);
}
return value;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Cli.CommandParsing;
using Microsoft.TemplateEngine.Cli.PostActionProcessors;
using Microsoft.TemplateEngine.Edge.Template;
namespace Microsoft.TemplateEngine.Cli.HelpAndUsage
{
public static class TemplateUsageHelp
{
public static void ShowInvocationExamples(TemplateListResolutionResult templateResolutionResult, IHostSpecificDataLoader hostDataLoader, string commandName)
{
const int ExamplesToShow = 2;
IReadOnlyList<string> preferredNameList = new List<string>() { "mvc" };
int numShown = 0;
IReadOnlyList<ITemplateMatchInfo> bestMatchedTemplates = templateResolutionResult.GetBestTemplateMatchList()
.Where(x => !x.HasNameMismatch()).ToList();
if (bestMatchedTemplates.Count == 0)
{
return;
}
IList<ITemplateInfo> templateList = bestMatchedTemplates.Select(x => x.Info).ToList();
Reporter.Output.WriteLine("Examples:");
HashSet<string> usedGroupIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string preferredName in preferredNameList)
{
ITemplateInfo template = templateList.FirstOrDefault(x => string.Equals(x.ShortName, preferredName, StringComparison.OrdinalIgnoreCase));
if (template != null)
{
string identity = string.IsNullOrWhiteSpace(template.GroupIdentity) ? string.IsNullOrWhiteSpace(template.Identity) ? string.Empty : template.Identity : template.GroupIdentity;
if (usedGroupIds.Add(identity))
{
GenerateUsageForTemplate(template, hostDataLoader, commandName);
numShown++;
}
}
templateList.Remove(template); // remove it so it won't get chosen again
}
// show up to 2 examples (total, including the above)
Random rnd = new Random();
for (int i = numShown; i < ExamplesToShow && templateList.Count > 0; i++)
{
int index = rnd.Next(0, templateList.Count - 1);
ITemplateInfo template = templateList[index];
string identity = string.IsNullOrWhiteSpace(template.GroupIdentity) ? string.IsNullOrWhiteSpace(template.Identity) ? string.Empty : template.Identity : template.GroupIdentity;
if (usedGroupIds.Add(identity) && !GenerateUsageForTemplate(template, hostDataLoader, commandName))
{
--i;
}
templateList.Remove(template); // remove it so it won't get chosen again
}
// show a help example
Reporter.Output.WriteLine($" dotnet {commandName} --help");
}
private static bool GenerateUsageForTemplate(ITemplateInfo templateInfo, IHostSpecificDataLoader hostDataLoader, string commandName)
{
HostSpecificTemplateData hostTemplateData = hostDataLoader.ReadHostSpecificTemplateData(templateInfo);
if (hostTemplateData.UsageExamples != null)
{
if (hostTemplateData.UsageExamples.Count == 0)
{
return false;
}
Reporter.Output.WriteLine($" dotnet {commandName} {templateInfo.ShortName} {hostTemplateData.UsageExamples[0]}");
return true;
}
Reporter.Output.Write($" dotnet {commandName} {templateInfo.ShortName}");
IReadOnlyList<ITemplateParameter> allParameterDefinitions = templateInfo.Parameters;
IEnumerable<ITemplateParameter> filteredParams = TemplateParameterHelpBase.FilterParamsForHelp(allParameterDefinitions, hostTemplateData.HiddenParameterNames, parametersToAlwaysShow: hostTemplateData.ParametersToAlwaysShow);
foreach (ITemplateParameter parameter in filteredParams)
{
if (string.Equals(parameter.DataType, "bool", StringComparison.OrdinalIgnoreCase)
&& string.Equals(parameter.DefaultValue, "false", StringComparison.OrdinalIgnoreCase))
{
continue;
}
else if (string.Equals(parameter.DataType, "string", StringComparison.OrdinalIgnoreCase))
{
continue;
}
else if (string.Equals(parameter.DataType, "choice", StringComparison.OrdinalIgnoreCase) && parameter.Choices.Count == 1)
{
continue;
}
string displayParameter = hostTemplateData.DisplayNameForParameter(parameter.Name);
Reporter.Output.Write($" --{displayParameter}");
if (!string.IsNullOrEmpty(parameter.DefaultValue) && !string.Equals(parameter.DataType, "bool", StringComparison.OrdinalIgnoreCase))
{
Reporter.Output.Write($" {parameter.DefaultValue}");
}
}
Reporter.Output.WriteLine();
return true;
}
// TODO: rework this method... it's a bit of a god-method, for very specific purposes.
// Number of times I've deferred on reworking this method: 4
internal static TemplateUsageInformation? GetTemplateUsageInformation(ITemplateInfo templateInfo, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IHostSpecificDataLoader hostDataLoader, TemplateCreator templateCreator)
{
IParameterSet allParams;
IReadOnlyList<string> userParamsWithInvalidValues;
HashSet<string> userParamsWithDefaultValues;
bool hasPostActionScriptRunner;
ITemplate template = environmentSettings.SettingsLoader.LoadTemplate(templateInfo, commandInput.BaselineName);
if (template == null)
{
return null;
}
TemplateListResolver.ParseTemplateArgs(templateInfo, hostDataLoader, commandInput);
allParams = templateCreator.SetupDefaultParamValuesFromTemplateAndHost(template, template.DefaultName ?? "testName", out IReadOnlyList<string> defaultParamsWithInvalidValues);
templateCreator.ResolveUserParameters(template, allParams, commandInput.InputTemplateParams, out userParamsWithInvalidValues);
hasPostActionScriptRunner = CheckIfTemplateHasScriptRunningPostActions(template, environmentSettings, commandInput, templateCreator);
templateCreator.ReleaseMountPoints(template);
List<InvalidParameterInfo> invalidParameters = new List<InvalidParameterInfo>();
if (userParamsWithInvalidValues.Any())
{
// Lookup the input param formats - userParamsWithInvalidValues has canonical.
foreach (string canonical in userParamsWithInvalidValues)
{
commandInput.InputTemplateParams.TryGetValue(canonical, out string specifiedValue);
string inputFormat = commandInput.TemplateParamInputFormat(canonical);
InvalidParameterInfo invalidParam = new InvalidParameterInfo(inputFormat, specifiedValue, canonical);
invalidParameters.Add(invalidParam);
}
}
if (templateCreator.AnyParametersWithInvalidDefaultsUnresolved(defaultParamsWithInvalidValues, userParamsWithInvalidValues, commandInput.InputTemplateParams, out IReadOnlyList<string> defaultsWithUnresolvedInvalidValues))
{
IParameterSet templateParams = template.Generator.GetParametersForTemplate(environmentSettings, template);
foreach (string defaultParamName in defaultsWithUnresolvedInvalidValues)
{
ITemplateParameter param = templateParams.ParameterDefinitions.FirstOrDefault(x => string.Equals(x.Name, defaultParamName, StringComparison.Ordinal));
if (param != null)
{
// Get the best input format available.
IReadOnlyList<string> inputVariants = commandInput.VariantsForCanonical(param.Name);
string displayName = inputVariants.FirstOrDefault(x => x.Contains(param.Name))
?? inputVariants.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur)
?? param.Name;
InvalidParameterInfo invalidParam = new InvalidParameterInfo(displayName, param.DefaultValue, displayName, true);
invalidParameters.Add(invalidParam);
}
}
}
// get all the flags
// get all the user input params that have the default value
Dictionary<string, IReadOnlyList<string>> inputFlagVariants = new Dictionary<string, IReadOnlyList<string>>();
userParamsWithDefaultValues = new HashSet<string>();
foreach (string paramName in allParams.ParameterDefinitions.Select(x => x.Name))
{
inputFlagVariants[paramName] = commandInput.VariantsForCanonical(paramName);
if (commandInput.TemplateParamHasValue(paramName) && string.IsNullOrEmpty(commandInput.TemplateParamValue(paramName)))
{
userParamsWithDefaultValues.Add(paramName);
}
}
IReadOnlyDictionary<string, IReadOnlyList<string>> variantsForCanonicals = inputFlagVariants;
return new TemplateUsageInformation
{
InvalidParameters = invalidParameters,
AllParameters = allParams,
UserParametersWithInvalidValues = userParamsWithInvalidValues,
UserParametersWithDefaultValues = userParamsWithDefaultValues,
VariantsForCanonicals = variantsForCanonicals,
HasPostActionScriptRunner = hasPostActionScriptRunner
};
}
private static bool CheckIfTemplateHasScriptRunningPostActions(ITemplate template, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, TemplateCreator templateCreator)
{
// use a throwaway set of params for getting the creation effects - it makes changes to them.
string targetDir = commandInput.OutputPath ?? environmentSettings.Host.FileSystem.GetCurrentDirectory();
IParameterSet paramsForCreationEffects = templateCreator.SetupDefaultParamValuesFromTemplateAndHost(template, template.DefaultName ?? "testName", out IReadOnlyList<string> throwaway);
templateCreator.ResolveUserParameters(template, paramsForCreationEffects, commandInput.InputTemplateParams, out IReadOnlyList<string> userParamsWithInvalidValues);
ICreationEffects creationEffects = template.Generator.GetCreationEffects(environmentSettings, template, paramsForCreationEffects, environmentSettings.SettingsLoader.Components, targetDir);
return creationEffects.CreationResult.PostActions.Any(x => x.ActionId == ProcessStartPostActionProcessor.ActionProcessorId);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text;
using Microsoft.PowerShell.Commands;
namespace System.Management.Automation
{
/// <summary>
/// Defines the types of commands that MSH can execute.
/// </summary>
[Flags]
public enum CommandTypes
{
/// <summary>
/// Aliases create a name that refers to other command types.
/// </summary>
/// <remarks>
/// Aliases are only persisted within the execution of a single engine.
/// </remarks>
Alias = 0x0001,
/// <summary>
/// Script functions that are defined by a script block.
/// </summary>
/// <remarks>
/// Functions are only persisted within the execution of a single engine.
/// </remarks>
Function = 0x0002,
/// <summary>
/// Script filters that are defined by a script block.
/// </summary>
/// <remarks>
/// Filters are only persisted within the execution of a single engine.
/// </remarks>
Filter = 0x0004,
/// <summary>
/// A cmdlet.
/// </summary>
Cmdlet = 0x0008,
/// <summary>
/// An MSH script (*.ps1 file)
/// </summary>
ExternalScript = 0x0010,
/// <summary>
/// Any existing application (can be console or GUI).
/// </summary>
/// <remarks>
/// An application can have any extension that can be executed either directly through CreateProcess
/// or indirectly through ShellExecute.
/// </remarks>
Application = 0x0020,
/// <summary>
/// A script that is built into the runspace configuration.
/// </summary>
Script = 0x0040,
/// <summary>
/// A workflow.
/// </summary>
Workflow = 0x0080,
/// <summary>
/// A Configuration.
/// </summary>
Configuration = 0x0100,
/// <summary>
/// All possible command types.
/// </summary>
/// <remarks>
/// Note, a CommandInfo instance will never specify
/// All as its CommandType but All can be used when filtering the CommandTypes.
/// </remarks>
All = Alias | Function | Filter | Cmdlet | Script | ExternalScript | Application | Workflow | Configuration,
}
/// <summary>
/// The base class for the information about commands. Contains the basic information about
/// the command, like name and type.
/// </summary>
public abstract class CommandInfo : IHasSessionStateEntryVisibility
{
#region ctor
/// <summary>
/// Creates an instance of the CommandInfo class with the specified name and type.
/// </summary>
/// <param name="name">
/// The name of the command.
/// </param>
/// <param name="type">
/// The type of the command.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
internal CommandInfo(string name, CommandTypes type)
{
// The name can be empty for functions and filters but it
// can't be null
if (name == null)
{
throw new ArgumentNullException("name");
}
Name = name;
CommandType = type;
}
/// <summary>
/// Creates an instance of the CommandInfo class with the specified name and type.
/// </summary>
/// <param name="name">
/// The name of the command.
/// </param>
/// <param name="type">
/// The type of the command.
/// </param>
/// <param name="context">
/// The execution context for the command.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
internal CommandInfo(string name, CommandTypes type, ExecutionContext context)
: this(name, type)
{
this.Context = context;
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal CommandInfo(CommandInfo other)
{
// Computed fields not copied:
// this._externalCommandMetadata = other._externalCommandMetadata;
// this._moduleName = other._moduleName;
// this.parameterSets = other.parameterSets;
this.Module = other.Module;
_visibility = other._visibility;
Arguments = other.Arguments;
this.Context = other.Context;
Name = other.Name;
CommandType = other.CommandType;
CopiedCommand = other;
this.DefiningLanguageMode = other.DefiningLanguageMode;
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal CommandInfo(string name, CommandInfo other)
: this(other)
{
Name = name;
}
#endregion ctor
/// <summary>
/// Gets the name of the command.
/// </summary>
public string Name { get; private set; } = string.Empty;
// Name
/// <summary>
/// Gets the type of the command.
/// </summary>
public CommandTypes CommandType { get; private set; } = CommandTypes.Application;
// CommandType
/// <summary>
/// Gets the source of the command (shown by default in Get-Command)
/// </summary>
public virtual string Source { get { return this.ModuleName; } }
/// <summary>
/// Gets the source version (shown by default in Get-Command)
/// </summary>
public virtual Version Version
{
get
{
if (_version == null)
{
if (Module != null)
{
if (Module.Version.Equals(new Version(0, 0)))
{
if (Module.Path.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
// Manifest module (.psd1)
Module.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(Module.Path));
}
else if (Module.Path.EndsWith(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
Module.Path.EndsWith(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))
{
// Binary module (.dll or .exe)
Module.SetVersion(AssemblyName.GetAssemblyName(Module.Path).Version);
}
}
_version = Module.Version;
}
}
return _version;
}
}
private Version _version;
/// <summary>
/// The execution context this command will run in.
/// </summary>
internal ExecutionContext Context
{
get { return _context; }
set
{
_context = value;
if ((value != null) && !this.DefiningLanguageMode.HasValue)
{
this.DefiningLanguageMode = value.LanguageMode;
}
}
}
private ExecutionContext _context;
/// <summary>
/// The language mode that was in effect when this alias was defined.
/// </summary>
internal PSLanguageMode? DefiningLanguageMode { get; set; }
internal virtual HelpCategory HelpCategory
{
get { return HelpCategory.None; }
}
internal CommandInfo CopiedCommand { get; set; }
/// <summary>
/// Internal interface to change the type of a CommandInfo object.
/// </summary>
/// <param name="newType"></param>
internal void SetCommandType(CommandTypes newType)
{
CommandType = newType;
}
/// <summary>
/// A string representing the definition of the command.
/// </summary>
/// <remarks>
/// This is overridden by derived classes to return specific
/// information for the command type.
/// </remarks>
public abstract string Definition { get; }
/// <summary>
/// This is required for renaming aliases, functions, and filters.
/// </summary>
/// <param name="newName">
/// The new name for the command.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="newName"/> is null or empty.
/// </exception>
internal void Rename(string newName)
{
if (string.IsNullOrEmpty(newName))
{
throw new ArgumentNullException("newName");
}
Name = newName;
}
/// <summary>
/// For diagnostic purposes.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return ModuleCmdletBase.AddPrefixToCommandName(Name, Prefix);
}
/// <summary>
/// Indicates if the command is to be allowed to be executed by a request
/// external to the runspace.
/// </summary>
public virtual SessionStateEntryVisibility Visibility
{
get
{
return CopiedCommand == null ? _visibility : CopiedCommand.Visibility;
}
set
{
if (CopiedCommand == null)
{
_visibility = value;
}
else
{
CopiedCommand.Visibility = value;
}
if (value == SessionStateEntryVisibility.Private && Module != null)
{
Module.ModuleHasPrivateMembers = true;
}
}
}
private SessionStateEntryVisibility _visibility = SessionStateEntryVisibility.Public;
/// <summary>
/// Return a CommandMetadata instance that is never exposed publicly.
/// </summary>
internal virtual CommandMetadata CommandMetadata
{
get
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Returns the syntax of a command.
/// </summary>
internal virtual string Syntax
{
get { return Definition; }
}
/// <summary>
/// The module name of this command. It will be empty for commands
/// not imported from either a module or snapin.
/// </summary>
public string ModuleName
{
get
{
string moduleName = null;
if (Module != null && !string.IsNullOrEmpty(Module.Name))
{
moduleName = Module.Name;
}
else
{
CmdletInfo cmdlet = this as CmdletInfo;
if (cmdlet != null && cmdlet.PSSnapIn != null)
{
moduleName = cmdlet.PSSnapInName;
}
}
if (moduleName == null)
return string.Empty;
return moduleName;
}
}
/// <summary>
/// The module that defines this cmdlet. This will be null for commands
/// that are not defined in the context of a module.
/// </summary>
public PSModuleInfo Module { get; internal set; }
/// <summary>
/// The remoting capabilities of this cmdlet, when exposed in a context
/// with ambient remoting.
/// </summary>
public RemotingCapability RemotingCapability
{
get
{
try
{
return ExternalCommandMetadata.RemotingCapability;
}
catch (PSNotSupportedException)
{
// Thrown on an alias that hasn't been resolved yet (i.e.: in a module that
// hasn't been loaded.) Assume the default.
return RemotingCapability.PowerShell;
}
}
}
/// <summary>
/// True if the command has dynamic parameters, false otherwise.
/// </summary>
internal virtual bool ImplementsDynamicParameters
{
get { return false; }
}
/// <summary>
/// Constructs the MergedCommandParameterMetadata, using any arguments that
/// may have been specified so that dynamic parameters can be determined, if any.
/// </summary>
/// <returns></returns>
private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely()
{
if (_context == null)
return null;
MergedCommandParameterMetadata result;
if (_context != LocalPipeline.GetExecutionContextFromTLS())
{
// In the normal case, _context is from the thread we're on, and we won't get here.
// But, if it's not, we can't safely get the parameter metadata without running on
// on the correct thread, because that thread may be busy doing something else.
// One of the things we do here is change the current scope in execution context,
// that can mess up the runspace our CommandInfo object came from.
var runspace = (RunspaceBase)_context.CurrentRunspace;
if (!runspace.RunActionIfNoRunningPipelinesWithThreadCheck(
() => GetMergedCommandParameterMetadata(out result)))
{
_context.Events.SubscribeEvent(
source: null,
eventName: PSEngineEvent.GetCommandInfoParameterMetadata,
sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
data: null,
handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler),
supportEvent: true,
forwardEvent: false,
shouldQueueAndProcessInExecutionThread: true,
maxTriggerCount: 1);
var eventArgs = new GetMergedCommandParameterMetadataSafelyEventArgs();
_context.Events.GenerateEvent(
sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
sender: null,
args: new[] { eventArgs },
extraData: null,
processInCurrentThread: true,
waitForCompletionInCurrentThread: true);
if (eventArgs.Exception != null)
{
// An exception happened on a different thread, rethrow it here on the correct thread.
eventArgs.Exception.Throw();
}
return eventArgs.Result;
}
}
GetMergedCommandParameterMetadata(out result);
return result;
}
private class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs
{
public MergedCommandParameterMetadata Result;
public ExceptionDispatchInfo Exception;
}
private void OnGetMergedCommandParameterMetadataSafelyEventHandler(object sender, PSEventArgs args)
{
var eventArgs = args.SourceEventArgs as GetMergedCommandParameterMetadataSafelyEventArgs;
if (eventArgs != null)
{
try
{
// Save the result in our event args as the return value.
GetMergedCommandParameterMetadata(out eventArgs.Result);
}
catch (Exception e)
{
// Save the exception so we can throw it on the correct thread.
eventArgs.Exception = ExceptionDispatchInfo.Capture(e);
}
}
}
private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadata result)
{
// MSFT:652277 - When invoking cmdlets or advanced functions, MyInvocation.MyCommand.Parameters do not contain the dynamic parameters
// When trying to get parameter metadata for a CommandInfo that has dynamic parameters, a new CommandProcessor will be
// created out of this CommandInfo and the parameter binding algorithm will be invoked. However, when this happens via
// 'MyInvocation.MyCommand.Parameter', it's actually retrieving the parameter metadata of the same cmdlet that is currently
// running. In this case, information about the specified parameters are not kept around in 'MyInvocation.MyCommand', so
// going through the binding algorithm again won't give us the metadata about the dynamic parameters that should have been
// discovered already.
// The fix is to check if the CommandInfo is actually representing the currently running cmdlet. If so, the retrieval of parameter
// metadata actually stems from the running of the same cmdlet. In this case, we can just use the current CommandProcessor to
// retrieve all bindable parameters, which should include the dynamic parameters that have been discovered already.
CommandProcessor processor;
if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this)
{
// Accessing the parameters within the invocation of the same cmdlet/advanced function.
processor = (CommandProcessor)Context.CurrentCommandProcessor;
}
else
{
IScriptCommandInfo scriptCommand = this as IScriptCommandInfo;
processor = scriptCommand != null
? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false,
sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState)
: new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true };
ParameterBinderController.AddArgumentsToCommandProcessor(processor, Arguments);
CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor;
try
{
Context.CurrentCommandProcessor = processor;
processor.SetCurrentScopeToExecutionScope();
processor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(processor.arguments);
}
catch (ParameterBindingException)
{
// Ignore the binding exception if no argument is specified
if (processor.arguments.Count > 0)
{
throw;
}
}
finally
{
Context.CurrentCommandProcessor = oldCurrentCommandProcessor;
processor.RestorePreviousScope();
}
}
result = processor.CmdletParameterBinderController.BindableParameters;
}
/// <summary>
/// Return the parameters for this command.
/// </summary>
public virtual Dictionary<string, ParameterMetadata> Parameters
{
get
{
Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase);
if (ImplementsDynamicParameters && Context != null)
{
MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair in merged.BindableParameters)
{
result.Add(pair.Key, new ParameterMetadata(pair.Value.Parameter));
}
// Don't cache this data...
return result;
}
return ExternalCommandMetadata.Parameters;
}
}
internal CommandMetadata ExternalCommandMetadata
{
get { return _externalCommandMetadata ?? (_externalCommandMetadata = new CommandMetadata(this, true)); }
set { _externalCommandMetadata = value; }
}
private CommandMetadata _externalCommandMetadata;
/// <summary>
/// Resolves a full, shortened, or aliased parameter name to the actual
/// cmdlet parameter name, using PowerShell's standard parameter resolution
/// algorithm.
/// </summary>
/// <param name="name">The name of the parameter to resolve.</param>
/// <returns>The parameter that matches this name.</returns>
public ParameterMetadata ResolveParameter(string name)
{
MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely();
MergedCompiledCommandParameter result = merged.GetMatchingParameter(name, true, true, null);
return this.Parameters[result.Parameter.Name];
}
/// <summary>
/// Gets the information about the parameters and parameter sets for
/// this command.
/// </summary>
public ReadOnlyCollection<CommandParameterSetInfo> ParameterSets
{
get
{
if (_parameterSets == null)
{
Collection<CommandParameterSetInfo> parameterSetInfo =
GenerateCommandParameterSetInfo();
_parameterSets = new ReadOnlyCollection<CommandParameterSetInfo>(parameterSetInfo);
}
return _parameterSets;
}
}
internal ReadOnlyCollection<CommandParameterSetInfo> _parameterSets;
/// <summary>
/// A possibly incomplete or even incorrect list of types the command could return.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public abstract ReadOnlyCollection<PSTypeName> OutputType { get; }
/// <summary>
/// Specifies whether this command was imported from a module or not.
/// This is used in Get-Command to figure out which of the commands in module session state were imported.
/// </summary>
internal bool IsImported { get; set; } = false;
/// <summary>
/// The prefix that was used when importing this command.
/// </summary>
internal string Prefix { get; set; } = string.Empty;
/// <summary>
/// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
/// sets based on an argument list (so we can get the dynamic parameters.)
/// </summary>
internal virtual CommandInfo CreateGetCommandCopy(object[] argumentList)
{
throw new InvalidOperationException();
}
/// <summary>
/// Generates the parameter and parameter set info from the cmdlet metadata.
/// </summary>
/// <returns>
/// A collection of CommandParameterSetInfo representing the cmdlet metadata.
/// </returns>
/// <exception cref="ArgumentException">
/// The type name is invalid or the length of the type name
/// exceeds 1024 characters.
/// </exception>
/// <exception cref="System.Security.SecurityException">
/// The caller does not have the required permission to load the assembly
/// or create the type.
/// </exception>
/// <exception cref="ParsingMetadataException">
/// If more than int.MaxValue parameter-sets are defined for the command.
/// </exception>
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
internal Collection<CommandParameterSetInfo> GenerateCommandParameterSetInfo()
{
Collection<CommandParameterSetInfo> result;
if (IsGetCommandCopy && ImplementsDynamicParameters)
{
result = GetParameterMetadata(CommandMetadata, GetMergedCommandParameterMetadataSafely());
}
else
{
result = GetCacheableMetadata(CommandMetadata);
}
return result;
}
/// <summary>
/// Gets or sets whether this CmdletInfo instance is a copy used for get-command.
/// If true, and the cmdlet supports dynamic parameters, it means that the dynamic
/// parameter metadata will be merged into the parameter set information.
/// </summary>
internal bool IsGetCommandCopy { get; set; }
/// <summary>
/// Gets or sets the command line arguments/parameters that were specified
/// which will allow for the dynamic parameters to be retrieved and their
/// metadata merged into the parameter set information.
/// </summary>
internal object[] Arguments { get; set; }
internal static Collection<CommandParameterSetInfo> GetCacheableMetadata(CommandMetadata metadata)
{
return GetParameterMetadata(metadata, metadata.StaticCommandParameterMetadata);
}
internal static Collection<CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata)
{
Collection<CommandParameterSetInfo> result = new Collection<CommandParameterSetInfo>();
if (parameterMetadata != null)
{
if (parameterMetadata.ParameterSetCount == 0)
{
const string parameterSetName = ParameterAttribute.AllParameterSets;
result.Add(
new CommandParameterSetInfo(
parameterSetName,
false,
uint.MaxValue,
parameterMetadata));
}
else
{
int parameterSetCount = parameterMetadata.ParameterSetCount;
for (int index = 0; index < parameterSetCount; ++index)
{
uint currentFlagPosition = (uint)0x1 << index;
// Get the parameter set name
string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition);
// Is the parameter set the default?
bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0;
result.Add(
new CommandParameterSetInfo(
parameterSetName,
isDefaultParameterSet,
currentFlagPosition,
parameterMetadata));
}
}
}
return result;
}
}
/// <summary>
/// Represents <see cref="System.Type"/>, but can be used where a real type
/// might not be available, in which case the name of the type can be used.
/// </summary>
public class PSTypeName
{
/// <summary>
/// This constructor is used when the type exists and is currently loaded.
/// </summary>
/// <param name="type">The type.</param>
public PSTypeName(Type type)
{
_type = type;
if (_type != null)
{
Name = _type.FullName;
}
}
/// <summary>
/// This constructor is used when the type may not exist, or is not loaded.
/// </summary>
/// <param name="name">The name of the type.</param>
public PSTypeName(string name)
{
Name = name;
_type = null;
}
/// <summary>
/// This constructor is used when the creating a PSObject with a custom typename.
/// </summary>
/// <param name="name">The name of the type.</param>
/// <param name="type">The real type.</param>
public PSTypeName(string name, Type type)
{
Name = name;
_type = type;
}
/// <summary>
/// This constructor is used when the type is defined in PowerShell.
/// </summary>
/// <param name="typeDefinitionAst">The type definition from the ast.</param>
public PSTypeName(TypeDefinitionAst typeDefinitionAst)
{
if (typeDefinitionAst == null)
{
throw PSTraceSource.NewArgumentNullException("typeDefinitionAst");
}
TypeDefinitionAst = typeDefinitionAst;
Name = typeDefinitionAst.Name;
}
/// <summary>
/// This constructor creates a type from a ITypeName.
/// </summary>
public PSTypeName(ITypeName typeName)
{
if (typeName == null)
{
throw PSTraceSource.NewArgumentNullException("typeName");
}
_type = typeName.GetReflectionType();
if (_type != null)
{
Name = _type.FullName;
}
else
{
var t = typeName as TypeName;
if (t != null && t._typeDefinitionAst != null)
{
TypeDefinitionAst = t._typeDefinitionAst;
Name = TypeDefinitionAst.Name;
}
else
{
_type = null;
Name = typeName.FullName;
}
}
}
/// <summary>
/// Return the name of the type.
/// </summary>
public string Name { get; }
/// <summary>
/// Return the type with metadata, or null if the type is not loaded.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public Type Type
{
get
{
if (!_typeWasCalculated)
{
if (_type == null)
{
if (TypeDefinitionAst != null)
{
_type = TypeDefinitionAst.Type;
}
else
{
TypeResolver.TryResolveType(Name, out _type);
}
}
if (_type == null)
{
// We ignore the exception.
if (Name != null &&
Name.StartsWith("[", StringComparison.OrdinalIgnoreCase) &&
Name.EndsWith("]", StringComparison.OrdinalIgnoreCase))
{
string tmp = Name.Substring(1, Name.Length - 2);
TypeResolver.TryResolveType(tmp, out _type);
}
}
_typeWasCalculated = true;
}
return _type;
}
}
private Type _type;
/// <summary>
/// When a type is defined by PowerShell, the ast for that type.
/// </summary>
public TypeDefinitionAst TypeDefinitionAst { get; private set; }
private bool _typeWasCalculated;
/// <summary>
/// Returns a String that represents the current PSTypeName.
/// </summary>
/// <returns>String that represents the current PSTypeName.</returns>
public override string ToString()
{
return Name ?? string.Empty;
}
}
[DebuggerDisplay("{PSTypeName} {Name}")]
internal struct PSMemberNameAndType
{
public readonly string Name;
public readonly PSTypeName PSTypeName;
public readonly object Value;
public PSMemberNameAndType(string name, PSTypeName typeName, object value = null)
{
Name = name;
PSTypeName = typeName;
Value = value;
}
}
/// <summary>
/// Represents dynamic types such as <see cref="System.Management.Automation.PSObject"/>,
/// but can be used where a real type might not be available, in which case the name of the type can be used.
/// The type encodes the members of dynamic objects in the type name.
/// </summary>
internal class PSSyntheticTypeName : PSTypeName
{
internal static PSSyntheticTypeName Create(string typename, IList<PSMemberNameAndType> membersTypes) => Create(new PSTypeName(typename), membersTypes);
internal static PSSyntheticTypeName Create(Type type, IList<PSMemberNameAndType> membersTypes) => Create(new PSTypeName(type), membersTypes);
internal static PSSyntheticTypeName Create(PSTypeName typename, IList<PSMemberNameAndType> membersTypes)
{
var typeName = GetMemberTypeProjection(typename.Name, membersTypes);
var members = new List<PSMemberNameAndType>();
members.AddRange(membersTypes);
members.Sort((c1,c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase));
return new PSSyntheticTypeName(typeName, typename.Type, members);
}
private PSSyntheticTypeName(string typeName, Type type, IList<PSMemberNameAndType> membersTypes)
: base(typeName, type)
{
Members = membersTypes;
if (type != typeof(PSObject))
{
return;
}
for (int i = 0; i < Members.Count; i++)
{
var psMemberNameAndType = Members[i];
if (IsPSTypeName(psMemberNameAndType))
{
Members.RemoveAt(i);
break;
}
}
}
private static bool IsPSTypeName(PSMemberNameAndType member) => member.Name.Equals(nameof(PSTypeName), StringComparison.OrdinalIgnoreCase);
private static string GetMemberTypeProjection(string typename, IList<PSMemberNameAndType> members)
{
if (typename == typeof(PSObject).FullName)
{
foreach (var mem in members)
{
if (IsPSTypeName(mem))
{
typename = mem.Value.ToString();
}
}
}
var builder = new StringBuilder(typename, members.Count * 7);
builder.Append('#');
foreach (var m in members.OrderBy(m => m.Name))
{
if (!IsPSTypeName(m))
{
builder.Append(m.Name).Append(":");
}
}
builder.Length--;
return builder.ToString();
}
public IList<PSMemberNameAndType> Members { get; }
}
internal interface IScriptCommandInfo
{
ScriptBlock ScriptBlock { get; }
}
}
| |
// 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.Tests;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentQueueTests : IEnumerable_Generic_Tests<int>
{
protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>();
protected override IEnumerable<int> GenericIEnumerableFactory(int count) => new ConcurrentQueue<int>(Enumerable.Range(0, count));
protected override int CreateT(int seed) => new Random(seed).Next();
protected override EnumerableOrder Order => EnumerableOrder.Unspecified;
protected override bool ResetImplemented => false;
protected override bool IEnumerable_Generic_Enumerator_Current_EnumerationNotStarted_ThrowsInvalidOperationException => false;
[Fact]
public void Ctor_NoArg_ItemsAndCountMatch()
{
var q = new ConcurrentQueue<int>();
Assert.True(q.IsEmpty);
Assert.Equal(0, q.Count);
Assert.Equal(Enumerable.Empty<int>(), q);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void Ctor_Collection_ItemsAndCountMatch(int count)
{
var q = new ConcurrentQueue<int>(Enumerable.Range(1, count));
Assert.Equal(count == 0, q.IsEmpty);
Assert.Equal(count, q.Count);
Assert.Equal(Enumerable.Range(1, count), q);
}
[Fact]
public void Ctor_NullEnumerable_Throws()
{
Assert.Throws<ArgumentNullException>("collection", () => new ConcurrentQueue<int>(null));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public static void ToArray_ItemsAndCountMatch(int count)
{
ConcurrentQueue<int> q = new ConcurrentQueue<int>(Enumerable.Range(42, count));
Assert.Equal(Enumerable.Range(42, count), q.ToArray());
if (count > 0)
{
int item;
Assert.True(q.TryDequeue(out item));
Assert.Equal(42, item);
Assert.Equal(Enumerable.Range(43, count - 1), q.ToArray());
}
}
[Fact]
public void DebuggerAttributes_Success()
{
var q = new ConcurrentQueue<int>(Enumerable.Range(0, 10));
DebuggerAttributes.ValidateDebuggerDisplayReferences(q);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(q);
}
[Fact]
public void Enqueue_TryDequeue_MatchesQueue()
{
var q = new Queue<int>();
var cq = new ConcurrentQueue<int>();
Action dequeue = () =>
{
int item1 = q.Dequeue();
int item2;
Assert.True(cq.TryDequeue(out item2));
Assert.Equal(item1, item2);
Assert.Equal(q.Count, cq.Count);
Assert.Equal(q, cq);
};
for (int i = 0; i < 100; i++)
{
cq.Enqueue(i);
q.Enqueue(i);
Assert.Equal(q.Count, cq.Count);
Assert.Equal(q, cq);
// Start dequeueing some after we've added some
if (i > 50)
{
dequeue();
}
}
// Dequeue the rest
while (q.Count > 0)
{
dequeue();
}
}
[Fact]
public void TryPeek_Idempotent()
{
var cq = new ConcurrentQueue<int>();
int item;
Assert.False(cq.TryPeek(out item));
Assert.Equal(0, item);
Assert.False(cq.TryPeek(out item));
Assert.Equal(0, item);
cq.Enqueue(42);
Assert.True(cq.TryPeek(out item));
Assert.Equal(42, item);
Assert.True(cq.TryPeek(out item));
Assert.Equal(42, item);
Assert.True(cq.TryDequeue(out item));
Assert.Equal(42, item);
Assert.False(cq.TryPeek(out item));
Assert.Equal(0, item);
}
[Fact]
public void Concurrent_Enqueue_TryDequeue_AllItemsReceived()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
// Consumer dequeues items until it gets as many as it expects
Task consumer = Task.Run(() =>
{
int lastReceived = 0;
int item;
while (true)
{
if (q.TryDequeue(out item))
{
Assert.Equal(lastReceived + 1, item);
lastReceived = item;
if (item == items) break;
}
else
{
Assert.Equal(0, item);
}
}
});
// Producer queues the expected number of items
Task producer = Task.Run(() =>
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void Concurrent_Enqueue_TryPeek_TryDequeue_AllItemsSeen()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
// Consumer peeks and then dequeues the expected number of items
Task consumer = Task.Run(() =>
{
int lastReceived = 0;
int item;
while (true)
{
if (q.TryPeek(out item))
{
Assert.Equal(lastReceived + 1, item);
Assert.True(q.TryDequeue(out item));
Assert.Equal(lastReceived + 1, item);
lastReceived = item;
if (item == items) break;
}
}
});
// Producer queues the expected number of items
Task producer = Task.Run(() =>
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void Concurrent_EnqueueDequeue_IsEmpty_AlwaysFalse()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
q.Enqueue(0); // make sure it's never empty
var cts = new CancellationTokenSource();
// Consumer repeatedly calls IsEmpty until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested) Assert.False(q.IsEmpty);
});
// Producer enqueues/dequeues a bunch of items, then tells the consumer to stop
Task producer = Task.Run(() =>
{
int ignored;
for (int i = 1; i <= items; i++)
{
q.Enqueue(i);
Assert.True(q.TryDequeue(out ignored));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void Concurrent_EnqueueObjects_Enumerate_NeverEmptyOrNull()
{
int items = 1000;
object obj = new object();
var q = new ConcurrentQueue<object>();
q.Enqueue(obj); // ensure always at least one item
var cts = new CancellationTokenSource();
// Consumer repeatedly iterates the collection until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
bool gotOne = false;
foreach (object o in q)
{
gotOne = true;
Assert.NotNull(o);
}
Assert.True(gotOne);
}
});
// Producer enqueues and dequeues a bunch of items, then tells consumer to stop
Task producer = Task.Run(() =>
{
for (int iters = 0; iters < 3; iters++)
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
object item;
for (int i = 1; i <= items; i++) Assert.True(q.TryDequeue(out item));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Theory]
[InlineData(1, 4, 1024)]
[InlineData(4, 1, 1024)]
[InlineData(3, 3, 1024)]
public void MultipleProducerConsumer_AllItemsTransferred(int producers, int consumers, int itemsPerProducer)
{
var cq = new ConcurrentQueue<int>();
var tasks = new List<Task>();
int totalItems = producers * itemsPerProducer;
int remainingItems = totalItems;
int sum = 0;
for (int i = 0; i < consumers; i++)
{
tasks.Add(Task.Run(() =>
{
while (Volatile.Read(ref remainingItems) > 0)
{
int item;
if (cq.TryDequeue(out item))
{
Interlocked.Add(ref sum, item);
Interlocked.Decrement(ref remainingItems);
}
}
}));
}
for (int i = 0; i < producers; i++)
{
tasks.Add(Task.Run(() =>
{
for (int item = 1; item <= itemsPerProducer; item++)
{
cq.Enqueue(item);
}
}));
}
Task.WaitAll(tasks.ToArray());
Assert.Equal(producers * (itemsPerProducer * (itemsPerProducer + 1) / 2), sum);
}
[Fact]
public void CopyTo_InvalidArgs_Throws()
{
Assert.Throws<ArgumentNullException>("array", () => new ConcurrentQueue<int>().CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentQueue<int>().CopyTo(new int[1], -1));
Assert.Throws<ArgumentException>(() => new ConcurrentQueue<int>().CopyTo(new int[1], 2));
}
[Fact]
public void CopyTo_Empty_Success()
{
var q = new ConcurrentQueue<int>();
q.CopyTo(Array.Empty<int>(), 0);
}
[Theory]
[InlineData(1, false)]
[InlineData(100, false)]
[InlineData(512, false)]
[InlineData(1, true)]
[InlineData(100, true)]
[InlineData(512, true)]
public void CopyTo_AllItemsCopiedAtCorrectLocation(int count, bool viaInterface)
{
var q = new ConcurrentQueue<int>(Enumerable.Range(0, count));
var c = (ICollection)q;
int[] arr = new int[count];
if (viaInterface)
{
c.CopyTo(arr, 0);
}
else
{
q.CopyTo(arr, 0);
}
Assert.Equal(q, arr);
if (count > 1)
{
int toRemove = count / 2;
int remaining = count - toRemove;
for (int i = 0; i < toRemove; i++)
{
int item;
Assert.True(q.TryDequeue(out item));
Assert.Equal(i, item);
}
if (viaInterface)
{
c.CopyTo(arr, 1);
}
else
{
q.CopyTo(arr, 1);
}
Assert.Equal(0, arr[0]);
for (int i = 0; i < remaining; i++)
{
Assert.Equal(arr[1 + i], i + toRemove);
}
}
}
[Fact]
public void ICollection_Count_Success()
{
ICollection c = new ConcurrentQueue<int>(Enumerable.Range(0, 5));
Assert.Equal(5, c.Count);
}
[Fact]
public void ICollection_IsSynchronized_AlwaysFalse()
{
ICollection c = new ConcurrentQueue<int>(Enumerable.Range(0, 5));
Assert.False(c.IsSynchronized);
}
[Fact]
public void ICollection_SyncRoot_AlwaysNull()
{
ICollection c = new ConcurrentQueue<int>(Enumerable.Range(0, 5));
Assert.Throws<NotSupportedException>(() => c.SyncRoot);
}
[Fact]
public void ICollection_CopyTo_InvalidArg_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => ((ICollection)new ConcurrentQueue<int>()).CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)new ConcurrentQueue<int>()).CopyTo(new int[0], -1));
Assert.Throws<ArgumentException>(() => ((ICollection)new ConcurrentQueue<int>()).CopyTo(new int[0], 1));
}
[Fact]
public void IProducerConsumerCollection_TryAddTryTake_Success()
{
IProducerConsumerCollection<int> pcc = new ConcurrentQueue<int>();
Assert.True(pcc.TryAdd(1));
Assert.True(pcc.TryAdd(2));
int item;
Assert.True(pcc.TryTake(out item));
Assert.Equal(1, item);
Assert.True(pcc.TryTake(out item));
Assert.Equal(2, item);
}
[Fact]
public void IEnumerable_GetAllExpectedItems()
{
IEnumerable<int> enumerable1 = new ConcurrentQueue<int>(Enumerable.Range(1, 5));
IEnumerable enumerable2 = enumerable1;
int expectedNext = 1;
using (IEnumerator<int> enumerator1 = enumerable1.GetEnumerator())
{
IEnumerator enumerator2 = enumerable2.GetEnumerator();
while (enumerator1.MoveNext())
{
Assert.True(enumerator2.MoveNext());
Assert.Equal(expectedNext, enumerator1.Current);
Assert.Equal(expectedNext, enumerator2.Current);
expectedNext++;
}
Assert.False(enumerator2.MoveNext());
Assert.Equal(expectedNext, 6);
}
}
[Fact]
public void ReferenceTypes_NulledAfterDequeue()
{
int iterations = 10; // any number <32 will do
var mres = new ManualResetEventSlim[iterations];
// Separated out into another method to ensure that even in debug
// the JIT doesn't force anything to be kept alive for longer than we need.
var queue = ((Func<ConcurrentQueue<Finalizable>>)(() =>
{
var q = new ConcurrentQueue<Finalizable>();
for (int i = 0; i < iterations; i++)
{
mres[i] = new ManualResetEventSlim();
q.Enqueue(new Finalizable(mres[i]));
}
for (int i = 0; i < iterations; i++)
{
Finalizable temp;
Assert.True(q.TryDequeue(out temp));
}
return q;
}))();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(Array.TrueForAll(mres, e => e.IsSet));
GC.KeepAlive(queue);
}
/// <summary>Sets an event when finalized.</summary>
private sealed class Finalizable
{
private ManualResetEventSlim _mres;
public Finalizable(ManualResetEventSlim mres) { _mres = mres; }
~Finalizable() { _mres.Set(); }
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Linq;
using Encog.ML.Data.Basic;
using Encog.Neural.Data.Basic;
using Encog.Util.Time;
namespace Encog.ML.Data.Temporal
{
/// <summary>
/// This class implements a temporal neural data set. A temporal neural dataset
/// is designed to use a neural network to predict.
///
/// A temporal dataset is a stream of data over a time range. This time range is
/// broken up into "points". Each point can contain one or more values. These
/// values are either the values that you would like to predict, or use to
/// predict. It is possible for a value to be both predicted and used to predict.
/// For example, if you were trying to predict a trend in a stock's price
/// fluctuations you might very well use the security price for both.
///
/// Each point that we have data for is stored in the TemporalPoint class. Each
/// TemporalPoint will contain one more data values. These data values are
/// described by the TemporalDataDescription class. For example, if you had five
/// TemporalDataDescription objects added to this class, each Temporal point
/// object would contain five values.
///
/// Points are arranged by sequence number. No two points can have the same
/// sequence numbers. Methods are provided to allow you to add points using the
/// Date class. These dates are resolved to sequence number using the level
/// of granularity specified for this class. No two points can occupy the same
/// granularity increment.
/// </summary>
public class TemporalMLDataSet : BasicMLDataSet
{
/// <summary>
/// Error message: adds are not supported.
/// </summary>
public const String AddNotSupported = "Direct adds to the temporal dataset are not supported. "
+ "Add TemporalPoint objects and call generate.";
/// <summary>
/// Descriptions of the data needed.
/// </summary>
private readonly IList<TemporalDataDescription> _descriptions =
new List<TemporalDataDescription>();
/// <summary>
/// The temporal points at which we have data.
/// </summary>
private readonly List<TemporalPoint> _points = new List<TemporalPoint>();
/// <summary>
/// How big would we like the input size to be.
/// </summary>
private int _desiredSetSize;
/// <summary>
/// The highest sequence.
/// </summary>
private int _highSequence;
/// <summary>
/// How many input neurons will be used.
/// </summary>
private int _inputNeuronCount;
/// <summary>
/// The size of the input window, this is the data being used to predict.
/// </summary>
private int _inputWindowSize;
/// <summary>
/// The lowest sequence.
/// </summary>
private int _lowSequence;
/// <summary>
/// How many output neurons will there be.
/// </summary>
private int _outputNeuronCount;
/// <summary>
/// The size of the prediction window.
/// </summary>
private int _predictWindowSize;
/// <summary>
/// What is the granularity of the temporal points? Days, months, years,
/// etc?
/// </summary>
private TimeUnit _sequenceGrandularity;
/// <summary>
/// What is the date for the first temporal point.
/// </summary>
private DateTime _startingPoint = DateTime.MinValue;
/// <summary>
/// Construct a dataset.
/// </summary>
/// <param name="inputWindowSize">What is the input window size.</param>
/// <param name="predictWindowSize">What is the prediction window size.</param>
public TemporalMLDataSet(int inputWindowSize,
int predictWindowSize)
{
_inputWindowSize = inputWindowSize;
_predictWindowSize = predictWindowSize;
_lowSequence = int.MinValue;
_highSequence = int.MaxValue;
_desiredSetSize = int.MaxValue;
_startingPoint = DateTime.MinValue;
_sequenceGrandularity = TimeUnit.Days;
}
/// <summary>
/// The data descriptions.
/// </summary>
public virtual IList<TemporalDataDescription> Descriptions
{
get { return _descriptions; }
}
/// <summary>
/// The points, or time slices to take data from.
/// </summary>
public virtual IList<TemporalPoint> Points
{
get { return _points; }
}
/// <summary>
/// Get the size of the input window.
/// </summary>
public virtual int InputWindowSize
{
get { return _inputWindowSize; }
set { _inputWindowSize = value; }
}
/// <summary>
/// The prediction window size.
/// </summary>
public virtual int PredictWindowSize
{
get { return _predictWindowSize; }
set { _predictWindowSize = value; }
}
/// <summary>
/// The low value for the sequence.
/// </summary>
public virtual int LowSequence
{
get { return _lowSequence; }
set { _lowSequence = value; }
}
/// <summary>
/// The high value for the sequence.
/// </summary>
public virtual int HighSequence
{
get { return _highSequence; }
set { _highSequence = value; }
}
/// <summary>
/// The desired dataset size.
/// </summary>
public virtual int DesiredSetSize
{
get { return _desiredSetSize; }
set { _desiredSetSize = value; }
}
/// <summary>
/// The number of input neurons.
/// </summary>
public virtual int InputNeuronCount
{
get { return _inputNeuronCount; }
set { _inputNeuronCount = value; }
}
/// <summary>
/// The number of output neurons.
/// </summary>
public virtual int OutputNeuronCount
{
get { return _outputNeuronCount; }
set { _outputNeuronCount = value; }
}
/// <summary>
/// The starting point.
/// </summary>
public virtual DateTime StartingPoint
{
get { return _startingPoint; }
set { _startingPoint = value; }
}
/// <summary>
/// The size of the timeslices.
/// </summary>
public virtual TimeUnit SequenceGrandularity
{
get { return _sequenceGrandularity; }
set { _sequenceGrandularity = value; }
}
/// <summary>
/// Add a data description.
/// </summary>
/// <param name="desc">The data description to add.</param>
public virtual void AddDescription(TemporalDataDescription desc)
{
if (_points.Count > 0)
{
throw new TemporalError(
"Can't add anymore descriptions, there are "
+ "already temporal points defined.");
}
int index = _descriptions.Count;
desc.Index = index;
_descriptions.Add(desc);
CalculateNeuronCounts();
}
/// <summary>
/// Clear the entire dataset.
/// </summary>
public virtual void Clear()
{
_descriptions.Clear();
_points.Clear();
Data.Clear();
}
/// <summary>
/// Adding directly is not supported. Rather, add temporal points and
/// generate the training data.
/// </summary>
/// <param name="inputData">Not used</param>
/// <param name="idealData">Not used</param>
public sealed override void Add(IMLData inputData, IMLData idealData)
{
throw new TemporalError(AddNotSupported);
}
/// <summary>
/// Adding directly is not supported. Rather, add temporal points and
/// generate the training data.
/// </summary>
/// <param name="inputData">Not used.</param>
public sealed override void Add(IMLDataPair inputData)
{
throw new TemporalError(AddNotSupported);
}
/// <summary>
/// Adding directly is not supported. Rather, add temporal points and
/// generate the training data.
/// </summary>
/// <param name="data">Not used.</param>
public sealed override void Add(IMLData data)
{
throw new TemporalError(AddNotSupported);
}
/// <summary>
/// Create a temporal data point using a sequence number. They can also be
/// created using time. No two points should have the same sequence number.
/// </summary>
/// <param name="sequence">The sequence number.</param>
/// <returns>A new TemporalPoint object.</returns>
public virtual TemporalPoint CreatePoint(int sequence)
{
var point = new TemporalPoint(_descriptions.Count) {Sequence = sequence};
_points.Add(point);
return point;
}
/// <summary>
/// Create a sequence number from a time. The first date will be zero, and
/// subsequent dates will be increased according to the grandularity
/// specified.
/// </summary>
/// <param name="when">The date to generate the sequence number for.</param>
/// <returns>A sequence number.</returns>
public virtual int GetSequenceFromDate(DateTime when)
{
int sequence;
if (_startingPoint != DateTime.MinValue)
{
var span = new TimeSpanUtil(_startingPoint, when);
sequence = (int) span.GetSpan(_sequenceGrandularity);
}
else
{
_startingPoint = when;
sequence = 0;
}
return sequence;
}
/// <summary>
/// Create a temporal point from a time. Using the grandularity each date is
/// given a unique sequence number. No two dates that fall in the same
/// grandularity should be specified.
/// </summary>
/// <param name="when">The time that this point should be created at.</param>
/// <returns>The point TemporalPoint created.</returns>
public virtual TemporalPoint CreatePoint(DateTime when)
{
int sequence = GetSequenceFromDate(when);
var point = new TemporalPoint(_descriptions.Count) {Sequence = sequence};
_points.Add(point);
return point;
}
/// <summary>
/// Calculate how many points are in the high and low range. These are the
/// points that the training set will be generated on.
/// </summary>
/// <returns>The number of points.</returns>
public virtual int CalculatePointsInRange()
{
return _points.Count(IsPointInRange);
}
/// <summary>
/// Calculate the actual set size, this is the number of training set entries
/// that will be generated.
/// </summary>
/// <returns>The size of the training set.</returns>
public virtual int CalculateActualSetSize()
{
int result = CalculatePointsInRange();
result = Math.Min(_desiredSetSize, result);
return result;
}
/// <summary>
/// Calculate how many input and output neurons will be needed for the
/// current data.
/// </summary>
public virtual void CalculateNeuronCounts()
{
_inputNeuronCount = 0;
_outputNeuronCount = 0;
foreach (TemporalDataDescription desc in _descriptions)
{
if (desc.IsInput)
{
_inputNeuronCount += _inputWindowSize;
}
if (desc.IsPredict)
{
_outputNeuronCount += _predictWindowSize;
}
}
}
/// <summary>
/// Is the specified point within the range. If a point is in the selection
/// range, then the point will be used to generate the training sets.
/// </summary>
/// <param name="point">The point to consider.</param>
/// <returns>True if the point is within the range.</returns>
public virtual bool IsPointInRange(TemporalPoint point)
{
return ((point.Sequence >= LowSequence) && (point.Sequence <= HighSequence));
}
/// <summary>
/// Generate input neural data for the specified index.
/// </summary>
/// <param name="index">The index to generate neural data for.</param>
/// <returns>The input neural data generated.</returns>
public virtual BasicNeuralData GenerateInputNeuralData(int index)
{
if (index + _inputWindowSize > _points.Count)
{
throw new TemporalError("Can't generate input temporal data "
+ "beyond the end of provided data.");
}
var result = new BasicNeuralData(_inputNeuronCount);
int resultIndex = 0;
for (int i = 0; i < _inputWindowSize; i++)
{
foreach (TemporalDataDescription desc in _descriptions)
{
if (desc.IsInput)
{
result[resultIndex++] = FormatData(desc, index
+ i);
}
}
}
return result;
}
/// <summary>
/// Get data between two points in raw form.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to get data from.</param>
/// <returns>The requested data.</returns>
private double GetDataRaw(TemporalDataDescription desc,
int index)
{
// Note: The reason that we subtract 1 from the index is because we are always one ahead.
// This allows the DELTA change formatter to work. DELTA change requires two timeslices,
// so we have to be one ahead. RAW only requires one, so we shift backwards.
TemporalPoint point = _points[index-1];
return point[desc.Index];
}
/// <summary>
/// Get data between two points in delta form.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to get data from.</param>
/// <returns>The requested data.</returns>
private double GetDataDeltaChange(TemporalDataDescription desc,
int index)
{
if (index == 0)
{
return 0.0;
}
TemporalPoint point = _points[index];
TemporalPoint previousPoint = _points[index - 1];
return point[desc.Index]
- previousPoint[desc.Index];
}
/// <summary>
/// Get data between two points in percent form.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to get data from.</param>
/// <returns>The requested data.</returns>
private double GetDataPercentChange(TemporalDataDescription desc,
int index)
{
if (index == 0)
{
return 0.0;
}
TemporalPoint point = _points[index];
TemporalPoint previousPoint = _points[index - 1];
double currentValue = point[desc.Index];
double previousValue = previousPoint[desc.Index];
return (currentValue - previousValue)/previousValue;
}
/// <summary>
/// Format data according to the type specified in the description.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to format the data at.</param>
/// <returns>The formatted data.</returns>
private double FormatData(TemporalDataDescription desc,
int index)
{
var result = new double[1];
switch (desc.DescriptionType)
{
case TemporalDataDescription.Type.DeltaChange:
result[0] = GetDataDeltaChange(desc, index);
break;
case TemporalDataDescription.Type.PercentChange:
result[0] = GetDataPercentChange(desc, index);
break;
case TemporalDataDescription.Type.Raw:
result[0] = GetDataRaw(desc, index);
break;
default:
throw new TemporalError("Unsupported data type.");
}
if (desc.ActivationFunction != null)
{
desc.ActivationFunction.ActivationFunction(result, 0, 1);
}
return result[0];
}
/// <summary>
/// Generate neural ideal data for the specified index.
/// </summary>
/// <param name="index">The index to generate for.</param>
/// <returns>The neural data generated.</returns>
public virtual BasicNeuralData GenerateOutputNeuralData(int index)
{
if (index + _predictWindowSize > _points.Count)
{
throw new TemporalError("Can't generate prediction temporal data "
+ "beyond the end of provided data.");
}
var result = new BasicNeuralData(_outputNeuronCount);
int resultIndex = 0;
for (int i = 0; i < _predictWindowSize; i++)
{
foreach (TemporalDataDescription desc in _descriptions)
{
if (desc.IsPredict)
{
result[resultIndex++] = FormatData(desc, index
+ i);
}
}
}
return result;
}
/// <summary>
/// Calculate the index to start at.
/// </summary>
/// <returns>The starting point.</returns>
public virtual int CalculateStartIndex()
{
for (int i = 0; i < _points.Count; i++)
{
TemporalPoint point = _points[i];
if (IsPointInRange(point))
{
return i;
}
}
return -1;
}
/// <summary>
/// Sort the points.
/// </summary>
public virtual void SortPoints()
{
_points.Sort();
}
/// <summary>
/// Generate the training sets.
/// </summary>
public virtual void Generate()
{
SortPoints();
int start = CalculateStartIndex() + 1;
int setSize = CalculateActualSetSize();
int range = start
+ (setSize - _predictWindowSize - _inputWindowSize);
for (int i = start; i < range; i++)
{
BasicNeuralData input = GenerateInputNeuralData(i);
BasicNeuralData ideal = GenerateOutputNeuralData(i
+ _inputWindowSize);
var pair = new BasicNeuralDataPair(input, ideal);
base.Add(pair);
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Batch
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ApplicationOperations.
/// </summary>
public static partial class ApplicationOperationsExtensions
{
/// <summary>
/// Activates the specified application package.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='id'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application to activate.
/// </param>
/// <param name='parameters'>
/// The parameters for the request.
/// </param>
public static void ActivateApplicationPackage(this IApplicationOperations operations, string resourceGroupName, string accountName, string id, string version, ActivateApplicationPackageParameters parameters)
{
Task.Factory.StartNew(s => ((IApplicationOperations)s).ActivateApplicationPackageAsync(resourceGroupName, accountName, id, version, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Activates the specified application package.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='id'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application to activate.
/// </param>
/// <param name='parameters'>
/// The parameters for the request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ActivateApplicationPackageAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string id, string version, ActivateApplicationPackageParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ActivateApplicationPackageWithHttpMessagesAsync(resourceGroupName, accountName, id, version, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds an application to the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='parameters'>
/// The parameters for the request.
/// </param>
public static Application AddApplication(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, AddApplicationParameters parameters = default(AddApplicationParameters))
{
return Task.Factory.StartNew(s => ((IApplicationOperations)s).AddApplicationAsync(resourceGroupName, accountName, applicationId, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Adds an application to the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='parameters'>
/// The parameters for the request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Application> AddApplicationAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, AddApplicationParameters parameters = default(AddApplicationParameters), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddApplicationWithHttpMessagesAsync(resourceGroupName, accountName, applicationId, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
public static void DeleteApplication(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId)
{
Task.Factory.StartNew(s => ((IApplicationOperations)s).DeleteApplicationAsync(resourceGroupName, accountName, applicationId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteApplicationAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteApplicationWithHttpMessagesAsync(resourceGroupName, accountName, applicationId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets information about the specified application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
public static Application GetApplication(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId)
{
return Task.Factory.StartNew(s => ((IApplicationOperations)s).GetApplicationAsync(resourceGroupName, accountName, applicationId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Application> GetApplicationAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetApplicationWithHttpMessagesAsync(resourceGroupName, accountName, applicationId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates settings for the specified application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='parameters'>
/// The parameters for the request.
/// </param>
public static void UpdateApplication(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, UpdateApplicationParameters parameters)
{
Task.Factory.StartNew(s => ((IApplicationOperations)s).UpdateApplicationAsync(resourceGroupName, accountName, applicationId, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates settings for the specified application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='parameters'>
/// The parameters for the request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateApplicationAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, UpdateApplicationParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpdateApplicationWithHttpMessagesAsync(resourceGroupName, accountName, applicationId, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates an application package record.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </param>
public static AddApplicationPackageResult AddApplicationPackage(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, string version)
{
return Task.Factory.StartNew(s => ((IApplicationOperations)s).AddApplicationPackageAsync(resourceGroupName, accountName, applicationId, version), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates an application package record.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AddApplicationPackageResult> AddApplicationPackageAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, string version, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddApplicationPackageWithHttpMessagesAsync(resourceGroupName, accountName, applicationId, version, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an application package record and its associated binary file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application to delete.
/// </param>
public static void DeleteApplicationPackage(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, string version)
{
Task.Factory.StartNew(s => ((IApplicationOperations)s).DeleteApplicationPackageAsync(resourceGroupName, accountName, applicationId, version), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an application package record and its associated binary file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteApplicationPackageAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, string version, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteApplicationPackageWithHttpMessagesAsync(resourceGroupName, accountName, applicationId, version, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets information about the specified application package.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </param>
public static GetApplicationPackageResult GetApplicationPackage(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, string version)
{
return Task.Factory.StartNew(s => ((IApplicationOperations)s).GetApplicationPackageAsync(resourceGroupName, accountName, applicationId, version), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified application package.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GetApplicationPackageResult> GetApplicationPackageAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, string applicationId, string version, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetApplicationPackageWithHttpMessagesAsync(resourceGroupName, accountName, applicationId, version, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the applications in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='maxresults'>
/// The maximum number of items to return in the response.
/// </param>
public static IPage<Application> List(this IApplicationOperations operations, string resourceGroupName, string accountName, int? maxresults = default(int?))
{
return Task.Factory.StartNew(s => ((IApplicationOperations)s).ListAsync(resourceGroupName, accountName, maxresults), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the applications in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='maxresults'>
/// The maximum number of items to return in the response.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Application>> ListAsync(this IApplicationOperations operations, string resourceGroupName, string accountName, int? maxresults = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, accountName, maxresults, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the applications in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Application> ListNext(this IApplicationOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IApplicationOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the applications in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Application>> ListNextAsync(this IApplicationOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class Comparer<T> : IComparer, IComparer<T>
{
// To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small
// as possible and define most of the creation logic in a non-generic class.
public static Comparer<T> Default { get; } = (Comparer<T>)ComparerHelpers.CreateDefaultComparer(typeof(T));
public static Comparer<T> Create(Comparison<T> comparison)
{
if (comparison == null)
throw new ArgumentNullException(nameof(comparison));
return new ComparisonComparer<T>(comparison);
}
public abstract int Compare(T x, T y);
int IComparer.Compare(object x, object y)
{
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
if (x is T && y is T) return Compare((T)x, (T)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return 0;
}
}
// Note: although there is a lot of shared code in the following
// comparers, we do not incorporate it into a base class for perf
// reasons. Adding another base class (even one with no fields)
// means another generic instantiation, which can be costly esp.
// for value types.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
{
public override int Compare(T x, T y)
{
if (x != null)
{
if (y != null) return x.CompareTo(y);
return 1;
}
if (y != null) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class NullableComparer<T> : Comparer<T?> where T : struct, IComparable<T>
{
public override int Compare(T? x, T? y)
{
if (x.HasValue)
{
if (y.HasValue) return x.value.CompareTo(y.value);
return 1;
}
if (y.HasValue) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class ObjectComparer<T> : Comparer<T>
{
public override int Compare(T x, T y)
{
return System.Collections.Comparer.Default.Compare(x, y);
}
// Equals method for the comparer itself.
public override bool Equals(object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
internal sealed class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
public override int Compare(T x, T y)
{
return _comparison(x, y);
}
}
// Enum comparers (specialized to avoid boxing)
// NOTE: Each of these needs to implement ISerializable
// and have a SerializationInfo/StreamingContext ctor,
// since we want to serialize as ObjectComparer for
// back-compat reasons (see below).
[Serializable]
internal sealed class Int32EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public Int32EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
// Used by the serialization engine.
private Int32EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
int ix = JitHelpers.UnsafeEnumCast(x);
int iy = JitHelpers.UnsafeEnumCast(y);
return ix.CompareTo(iy);
}
// Equals method for the comparer itself.
public override bool Equals(object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Previously Comparer<T> was not specialized for enums,
// and instead fell back to ObjectComparer which uses boxing.
// Set the type as ObjectComparer here so code that serializes
// Comparer for enums will not break.
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
internal sealed class UInt32EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public UInt32EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
// Used by the serialization engine.
private UInt32EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
uint ix = (uint)JitHelpers.UnsafeEnumCast(x);
uint iy = (uint)JitHelpers.UnsafeEnumCast(y);
return ix.CompareTo(iy);
}
// Equals method for the comparer itself.
public override bool Equals(object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
internal sealed class Int64EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public Int64EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
public override int Compare(T x, T y)
{
long lx = JitHelpers.UnsafeEnumCastLong(x);
long ly = JitHelpers.UnsafeEnumCastLong(y);
return lx.CompareTo(ly);
}
// Equals method for the comparer itself.
public override bool Equals(object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
internal sealed class UInt64EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public UInt64EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
// Used by the serialization engine.
private UInt64EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
ulong lx = (ulong)JitHelpers.UnsafeEnumCastLong(x);
ulong ly = (ulong)JitHelpers.UnsafeEnumCastLong(y);
return lx.CompareTo(ly);
}
// Equals method for the comparer itself.
public override bool Equals(object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Statistics;
using OpenSim.Region.ClientStack;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
using OpenSim.Region.Interfaces;
namespace OpenSim
{
/// <summary>
/// Common OpenSim simulator code
/// </summary>
public class OpenSimBase : RegionApplicationBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// These are the names of the plugin-points extended by this
// class during system startup.
private const string PLUGIN_ASSET_CACHE = "/OpenSim/AssetCache";
private const string PLUGIN_ASSET_SERVER_CLIENT = "/OpenSim/AssetClient";
protected string proxyUrl;
protected int proxyOffset = 0;
public string userStatsURI = String.Empty;
protected bool m_autoCreateClientStack = true;
/// <summary>
/// The file used to load and save prim backup xml if no filename has been specified
/// </summary>
protected const string DEFAULT_PRIM_BACKUP_FILENAME = "prim-backup.xml";
/// <summary>
/// The file used to load and save an opensim archive if no filename has been specified
/// </summary>
protected const string DEFAULT_OAR_BACKUP_FILENAME = "region.oar";
public ConfigSettings ConfigurationSettings
{
get { return m_configSettings; }
set { m_configSettings = value; }
}
protected ConfigSettings m_configSettings;
protected ConfigurationLoader m_configLoader;
protected GridInfoService m_gridInfoService;
public ConsoleCommand CreateAccount = null;
protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>();
/// <value>
/// The config information passed into the OpenSim region server.
/// </value>
public OpenSimConfigSource ConfigSource
{
get { return m_config; }
set { m_config = value; }
}
protected OpenSimConfigSource m_config;
public List<IClientNetworkServer> ClientServers
{
get { return m_clientServers; }
}
protected List<IClientNetworkServer> m_clientServers = new List<IClientNetworkServer>();
/*
public uint HttpServerPort
{
get { return m_httpServerPort; }
}
*/
public ModuleLoader ModuleLoader
{
get { return m_moduleLoader; }
set { m_moduleLoader = value; }
}
protected ModuleLoader m_moduleLoader;
protected IRegistryCore m_applicationRegistry = new RegistryCore();
public IRegistryCore ApplicationRegistry
{
get { return m_applicationRegistry; }
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="configSource"></param>
public OpenSimBase(IConfigSource configSource) : base()
{
LoadConfigSettings(configSource);
}
protected virtual void LoadConfigSettings(IConfigSource configSource)
{
m_configLoader = new ConfigurationLoader();
m_config = m_configLoader.LoadConfigSettings(configSource, out m_configSettings, out m_networkServersInfo);
ReadExtraConfigSettings();
}
protected virtual void ReadExtraConfigSettings()
{
IConfig networkConfig = m_config.Source.Configs["Network"];
if (networkConfig != null)
{
proxyUrl = networkConfig.GetString("proxy_url", String.Empty);
proxyOffset = Int32.Parse(networkConfig.GetString("proxy_offset", "0"));
}
}
protected virtual void LoadPlugins()
{
PluginLoader<IApplicationPlugin> loader =
new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitializer(this));
loader.Load("/OpenSim/Startup");
m_plugins = loader.Plugins;
}
protected override List<string> GetHelpTopics()
{
List<string> topics = base.GetHelpTopics();
Scene s = SceneManager.CurrentOrFirstScene;
if (s != null && s.GetCommanders() != null)
topics.AddRange(s.GetCommanders().Keys);
return topics;
}
/// <summary>
/// Performs startup specific to the region server, including initialization of the scene
/// such as loading configuration from disk.
/// </summary>
protected override void StartupSpecific()
{
IConfig startupConfig = m_config.Source.Configs["Startup"];
if (startupConfig != null)
{
string pidFile = startupConfig.GetString("PIDFile", String.Empty);
if (!String.IsNullOrEmpty(pidFile))
CreatePIDFile(pidFile);
userStatsURI = startupConfig.GetString("Stats_URI", String.Empty);
}
base.StartupSpecific();
m_stats = StatsManager.StartCollectingSimExtraStats();
// Create a ModuleLoader instance
m_moduleLoader = new ModuleLoader(m_config.Source);
LoadPlugins();
foreach (IApplicationPlugin plugin in m_plugins)
{
plugin.PostInitialize();
}
// Only enable logins to the regions once we have completely finished starting up (apart from scripts)
if ((m_commsManager != null) && (m_commsManager.GridService != null))
{
m_commsManager.GridService.RegionLoginsEnabled = true;
}
AddPluginCommands();
}
protected virtual void AddPluginCommands()
{
// If console exists add plugin commands.
if (m_console != null)
{
List<string> topics = GetHelpTopics();
foreach (string topic in topics)
{
m_console.Commands.AddCommand("plugin", false, "help " + topic,
"help " + topic,
"Get help on plugin command '" + topic + "'",
HandleCommanderHelp);
m_console.Commands.AddCommand("plugin", false, topic,
topic,
"Execute subcommand for plugin '" + topic + "'",
null);
ICommander commander = null;
Scene s = SceneManager.CurrentOrFirstScene;
if (s != null && s.GetCommanders() != null)
{
if (s.GetCommanders().ContainsKey(topic))
commander = s.GetCommanders()[topic];
}
if (commander == null)
continue;
foreach (string command in commander.Commands.Keys)
{
m_console.Commands.AddCommand(topic, false,
topic + " " + command,
topic + " " + commander.Commands[command].ShortHelp(),
String.Empty, HandleCommanderCommand);
}
}
}
}
private void HandleCommanderCommand(string module, string[] cmd)
{
m_sceneManager.SendCommandToPluginModules(cmd);
}
private void HandleCommanderHelp(string module, string[] cmd)
{
// Only safe for the interactive console, since it won't
// let us come here unless both scene and commander exist
//
ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1]);
if (moduleCommander != null)
m_console.Notice(moduleCommander.Help);
}
protected override void Initialize()
{
// Called from base.StartUp()
m_httpServerPort = m_networkServersInfo.HttpListenerPort;
InitializeAssetCache();
}
/// <summary>
/// Initializes the asset cache. This supports legacy configuration values
/// to ensure consistent operation, but values outside of that namespace
/// are handled by the more generic resolution mechanism provided by
/// the ResolveAssetServer virtual method. If extended resolution fails,
/// then the normal default action is taken.
/// Creation of the AssetCache is handled by ResolveAssetCache. This
/// function accepts a reference to the instantiated AssetServer and
/// returns an IAssetCache implementation, if possible. This is a virtual
/// method.
/// </summary>
protected virtual void InitializeAssetCache()
{
IAssetServer assetServer = null;
string mode = m_configSettings.AssetStorage;
if (String.IsNullOrEmpty(mode))
{
throw new Exception("No asset server specified");
}
AssetClientPluginInitializer linit = new AssetClientPluginInitializer(m_configSettings);
//todo: hack to handle transition from whip
if (mode.ToUpper() == "WHIP") mode = mode.ToUpper();
assetServer = loadAssetServer(mode, linit);
if (assetServer == null)
{
throw new Exception(String.Format("Asset server {0} could not be loaded", mode));
}
// Initialize the asset cache, passing a reference to the selected
// asset server interface.
m_assetCache = ResolveAssetCache(assetServer);
assetServer.Start();
}
// This method loads the identified asset server, passing an approrpiately
// initialized Initialize wrapper. There should to be exactly one match,
// if not, then the first match is used.
private IAssetServer loadAssetServer(string id, PluginInitializerBase pi)
{
if (!String.IsNullOrEmpty(id))
{
m_log.DebugFormat("[HALCYONBASE] Attempting to load asset server id={0}", id);
try
{
PluginLoader<IAssetServer> loader = new PluginLoader<IAssetServer>(pi);
loader.AddFilter(PLUGIN_ASSET_SERVER_CLIENT, new PluginProviderFilter(id));
loader.Load(PLUGIN_ASSET_SERVER_CLIENT);
if (loader.Plugins.Count > 0)
{
m_log.DebugFormat("[HALCYONBASE] Asset server {0} loaded", id);
return (IAssetServer) loader.Plugins[0];
}
}
catch (Exception e)
{
m_log.DebugFormat("[HALCYONBASE] Asset server {0} not loaded ({1})", id, e.Message);
}
}
return null;
}
/// <summary>
/// Attempt to instantiate an IAssetCache implementation, using the
/// provided IAssetServer reference.
/// An asset cache implementation must provide a constructor that
/// accepts two parameters;
/// [1] A ConfigSettings reference.
/// [2] An IAssetServer reference.
/// The AssetCache value is obtained from the
/// [StartUp]/AssetCache value in the configuration file.
/// </summary>
protected virtual IAssetCache ResolveAssetCache(IAssetServer assetServer)
{
return new Framework.Communications.Cache.AssetCache(assetServer);
}
public void ProcessLogin(bool LoginEnabled)
{
if (LoginEnabled)
{
m_log.Info("[LOGIN]: Login is now enabled.");
m_commsManager.GridService.RegionLoginsEnabled = true;
}
else
{
m_log.Info("[LOGIN]: Login is now disabled.");
m_commsManager.GridService.RegionLoginsEnabled = false;
}
}
/// <summary>
/// Execute the region creation process. This includes setting up scene infrastructure.
/// </summary>
/// <param name="regionInfo"></param>
/// <param name="portadd_flag"></param>
/// <returns></returns>
public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene)
{
return CreateRegion(regionInfo, portadd_flag, false, out scene);
}
/// <summary>
/// Execute the region creation process. This includes setting up scene infrastructure.
/// </summary>
/// <param name="regionInfo"></param>
/// <param name="portadd_flag"></param>
/// <param name="do_post_init"></param>
/// <returns></returns>
private IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene)
{
int port = regionInfo.InternalEndPoint.Port;
// set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims)
// Commented this out because otherwise regions can't register with
// the grid as there is already another region with the same UUID
// at those coordinates. This is required for the load balancer to work.
// --Mike, 2009.02.25
//regionInfo.originRegionID = regionInfo.RegionID;
// set initial ServerURI
regionInfo.HttpPort = m_httpServerPort;
regionInfo.osSecret = m_osSecret;
if (!String.IsNullOrEmpty(proxyUrl) && (portadd_flag))
{
// set proxy url to RegionInfo
regionInfo.proxyUrl = proxyUrl;
regionInfo.ProxyOffset = proxyOffset;
Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName);
}
IClientNetworkServer clientServer;
Scene scene = SetupScene(regionInfo, proxyOffset, m_config.Source, out clientServer);
m_log.Info("[MODULES]: Loading Region's modules (old style)");
List<IRegionModule> modules = m_moduleLoader.PickupModules(scene, ".");
// This needs to be ahead of the script engine load, so the
// script module can pick up events exposed by a module
m_moduleLoader.InitializeSharedModules(scene);
// Use this in the future, the line above will be deprecated soon
m_log.Info("[MODULES]: Loading Region's modules (new style)");
IRegionModulesController controller;
if (ApplicationRegistry.TryGet(out controller))
{
controller.AddRegionToModules(scene);
}
else m_log.Error("[MODULES]: The new RegionModulesController is missing...");
// Check if a (any) permission module has been loaded.
// This can be any permissions module, including the default PermissionsModule with m_bypassPermissions==true.
// To disable permissions, specify [Startup] permissionmodules=DefaultPermissionsModule in the .ini file, and
// serverside_object_permissions=false, optionally propagate_permissions=false.
if (!scene.Permissions.IsAvailable())
{
m_log.Error("[MODULES]: Permissions module is not set, or set incorrectly.");
Environment.Exit(1);
// Note that an Exit here can trigger a PhysX exception but if that happens it is the result of this
// permissions problem and hopefully the lot will show this error and intentional exit.
}
scene.SetModuleInterfaces();
// this must be done before prims try to rez or they'll rez over no land
scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
//we need to fire up the scene here. physics may depend ont he heartbeat running
scene.Start();
// Prims have to be loaded after module configuration since some modules may be invoked during the load
scene.LoadPrimsFromStorage(regionInfo.originRegionID);
// moved these here as the terrain texture has to be created after the modules are initialized
// and has to happen before the region is registered with the grid.
scene.CreateTerrainTexture(false);
try
{
scene.RegisterRegionWithGrid();
}
catch (Exception e)
{
m_log.ErrorFormat("[STARTUP]: Registration of region with grid failed, aborting startup - {0}", e);
// Carrying on now causes a lot of confusion down the
// line - we need to get the user's attention
Environment.Exit(1);
}
// We need to do this after we've initialized the
// scripting engines.
scene.CreateScriptInstances();
scene.EventManager.TriggerParcelPrimCountUpdate();
m_sceneManager.Add(scene);
if (m_autoCreateClientStack)
{
m_clientServers.Add(clientServer);
clientServer.Start();
}
if (do_post_init)
{
foreach (IRegionModule module in modules)
{
module.PostInitialize();
}
}
scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); };
mscene = scene;
return clientServer;
}
private void ShutdownRegion(Scene scene)
{
m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName);
IRegionModulesController controller;
if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller))
{
controller.RemoveRegionFromModules(scene);
}
}
public void RemoveRegion(Scene scene, bool cleanup)
{
// only need to check this if we are not at the
// root level
if ((m_sceneManager.CurrentScene != null) &&
(m_sceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
{
m_sceneManager.TrySetCurrentScene("..");
}
scene.DeleteAllSceneObjects();
m_sceneManager.CloseScene(scene);
if (!cleanup)
return;
if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile))
{
File.Delete(scene.RegionInfo.RegionFile);
m_log.InfoFormat("[HALCYON]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile);
}
}
public void RemoveRegion(string name, bool cleanUp)
{
Scene target;
if (m_sceneManager.TryGetScene(name, out target))
RemoveRegion(target, cleanUp);
}
/// <summary>
/// Create a scene and its initial base structures.
/// </summary>
/// <param name="regionInfo"></param>
/// <param name="clientServer"> </param>
/// <returns></returns>
protected Scene SetupScene(RegionInfo regionInfo, out IClientNetworkServer clientServer)
{
return SetupScene(regionInfo, 0, null, out clientServer);
}
/// <summary>
/// Create a scene and its initial base structures.
/// </summary>
/// <param name="regionInfo"></param>
/// <param name="proxyOffset"></param>
/// <param name="configSource"></param>
/// <param name="clientServer"> </param>
/// <returns></returns>
protected Scene SetupScene(
RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out IClientNetworkServer clientServer)
{
IPAddress listenIP = regionInfo.InternalEndPoint.Address;
//if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP))
// listenIP = IPAddress.Parse("0.0.0.0");
uint port = (uint) regionInfo.InternalEndPoint.Port;
if (m_autoCreateClientStack)
{
clientServer
= m_clientStackManager.CreateServer(
listenIP, ref port, proxyOffset, regionInfo.m_allow_alternate_ports, configSource,
m_assetCache);
}
else
{
clientServer = null;
}
regionInfo.InternalEndPoint.Port = (int) port;
// TODO: Remove this cruft once MasterAvatar is fully deprecated
//Master Avatar Setup
UserProfileData masterAvatar;
if (regionInfo.MasterAvatarAssignedUUID == UUID.Zero)
{
masterAvatar =
m_commsManager.UserService.SetupMasterUser(regionInfo.MasterAvatarFirstName,
regionInfo.MasterAvatarLastName,
regionInfo.MasterAvatarSandboxPassword);
}
else
{
masterAvatar = m_commsManager.UserService.SetupMasterUser(regionInfo.MasterAvatarAssignedUUID);
}
if (masterAvatar == null)
{
regionInfo.MasterAvatarAssignedUUID = UUID.Zero;
m_log.Error("[PARCEL]: No master avatar found, using null UUID for master avatar.");
// Should be a fatal error?
}
else
{
regionInfo.MasterAvatarAssignedUUID = masterAvatar.ID;
regionInfo.MasterAvatarFirstName = masterAvatar.FirstName;
regionInfo.MasterAvatarLastName = masterAvatar.SurName;
m_log.InfoFormat("[PARCEL]: Found master avatar {0} {1} [{2}]",
regionInfo.MasterAvatarFirstName,
regionInfo.MasterAvatarLastName,
regionInfo.MasterAvatarAssignedUUID.ToString()
);
}
Scene scene = CreateScene(regionInfo, m_storageManager);
if (m_autoCreateClientStack)
{
clientServer.AddScene(scene);
}
scene.LoadWorldMap();
scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName, scene.RegionInfo.RegionID);
scene.PhysicsScene.TerrainChannel = scene.Heightmap;
scene.PhysicsScene.RegionSettings = scene.RegionInfo.RegionSettings;
scene.PhysicsScene.SetStartupTerrain(scene.Heightmap.GetFloatsSerialized(), scene.Heightmap.RevisionNumber);
scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight);
return scene;
}
protected override StorageManager CreateStorageManager()
{
return
CreateStorageManager(m_configSettings.StorageConnectionString, m_configSettings.EstateConnectionString);
}
protected StorageManager CreateStorageManager(string connectionstring, string estateconnectionstring)
{
return new StorageManager(m_configSettings.StorageDll, connectionstring, estateconnectionstring);
}
protected override ClientStackManager CreateClientStackManager()
{
return new ClientStackManager(m_configSettings.ClientstackDll);
}
protected override Scene CreateScene(RegionInfo regionInfo, StorageManager storageManager)
{
SceneCommunicationService sceneGridService = new SceneCommunicationService(m_commsManager);
return new Scene(
regionInfo, m_commsManager, sceneGridService,
storageManager, m_moduleLoader, m_configSettings.PhysicalPrim,
m_configSettings.See_into_region_from_neighbor, m_config.Source);
}
# region Setup methods
protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier, UUID regionId)
{
return GetPhysicsScene(
m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, m_config.Source, osSceneIdentifier,
regionId);
}
/// <summary>
/// Handler to supply the current status of this sim
/// </summary>
/// Currently this is always OK if the simulator is still listening for connections on its HTTP service
public class SimStatusHandler : IStreamedRequestHandler
{
public string Name { get { return "SimStatusHandler"; } }
public string Description { get { return String.Empty; } }
public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return Encoding.UTF8.GetBytes("OK");
}
public string ContentType
{
get { return "text/plain"; }
}
public string HttpMethod
{
get { return "GET"; }
}
public string Path
{
get { return "/simstatus/"; }
}
}
/// <summary>
/// Handler to supply the current extended status of this sim
/// Sends the statistical data in a json serialization
/// </summary>
public class XSimStatusHandler : IStreamedRequestHandler
{
public string Name { get { return "XSimStatusHandler"; } }
public string Description { get { return String.Empty; } }
OpenSimBase m_opensim;
string osXStatsURI = String.Empty;
public XSimStatusHandler(OpenSimBase sim)
{
m_opensim = sim;
osXStatsURI = Util.SHA1Hash(sim.osSecret);
}
public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
}
public string ContentType
{
get { return "text/plain"; }
}
public string HttpMethod
{
get { return "GET"; }
}
public string Path
{
// This is for the OpenSim instance and is the osSecret hashed
get { return "/" + osXStatsURI + "/"; }
}
}
/// <summary>
/// Handler to supply the current extended status of this sim to a user configured URI
/// Sends the statistical data in a json serialization
/// If the request contains a key, "callback" the response will be wrappend in the
/// associated value for jsonp used with ajax/javascript
/// </summary>
public class UXSimStatusHandler : IStreamedRequestHandler
{
public string Name { get { return "UXSimStatusHandler"; } }
public string Description { get { return String.Empty; } }
OpenSimBase m_opensim;
string osUXStatsURI = String.Empty;
public UXSimStatusHandler(OpenSimBase sim)
{
m_opensim = sim;
osUXStatsURI = sim.userStatsURI;
}
public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
}
public string ContentType
{
get { return "text/plain"; }
}
public string HttpMethod
{
get { return "GET"; }
}
public string Path
{
// This is for the OpenSim instance and is the user provided URI
get { return "/" + osUXStatsURI + "/"; }
}
}
#endregion
/// <summary>
/// Performs any last-minute sanity checking and shuts down the region server
/// </summary>
public override void ShutdownSpecific()
{
if (!String.IsNullOrEmpty(proxyUrl))
{
Util.XmlRpcCommand(proxyUrl, "Stop");
}
try
{
m_log.Info("[SHUTDOWN]: Closing scene manager");
m_sceneManager.Close();
}
catch (Exception e)
{
m_log.ErrorFormat("[SHUTDOWN]: Ignoring failure during shutdown - {0}", e);
}
try
{
m_log.Info("[SHUTDOWN]: Disposing asset cache and services");
m_assetCache.Dispose();
}
catch (Exception e)
{
m_log.ErrorFormat("[SHUTDOWN]: Ignoring failure during shutdown - {0}", e);
}
}
/// <summary>
/// Get the start time and up time of Region server
/// </summary>
/// <param name="starttime">The first out parameter describing when the Region server started</param>
/// <param name="uptime">The second out parameter describing how long the Region server has run</param>
public void GetRunTime(out string starttime, out string uptime)
{
starttime = m_startuptime.ToString();
uptime = (DateTime.Now - m_startuptime).ToString();
}
/// <summary>
/// Get the number of the avatars in the Region server
/// </summary>
/// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
public void GetAvatarNumber(out int usernum)
{
usernum = m_sceneManager.GetCurrentSceneAvatars().Count;
}
/// <summary>
/// Get the number of regions
/// </summary>
/// <param name="regionnum">The first out parameter describing the number of regions</param>
public void GetRegionNumber(out int regionnum)
{
regionnum = m_sceneManager.Scenes.Count;
}
}
public class OpenSimConfigSource
{
public IConfigSource Source;
public void Save(string path)
{
if (Source is IniConfigSource)
{
IniConfigSource iniCon = (IniConfigSource) Source;
iniCon.Save(path);
}
else if (Source is XmlConfigSource)
{
XmlConfigSource xmlCon = (XmlConfigSource) Source;
xmlCon.Save(path);
}
}
}
}
| |
// 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.
namespace System.Drawing
{
/// <summary>
/// Represents an ordered pair of x and y coordinates that
/// define a point in a two-dimensional plane.
/// </summary>
public struct PointF
{
/// <summary>
/// <para>
/// Creates a new instance of the <see cref='System.Drawing.PointF'/> class
/// with member data left uninitialized.
/// </para>
/// </summary>
public static readonly PointF Empty = new PointF();
private float _x;
private float _y;
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.PointF'/> class
/// with the specified coordinates.
/// </para>
/// </summary>
public PointF(float x, float y)
{
_x = x;
_y = y;
}
/// <summary>
/// <para>
/// Gets a value indicating whether this <see cref='System.Drawing.PointF'/> is empty.
/// </para>
/// </summary>
public bool IsEmpty
{
get
{
return _x == 0f && _y == 0f;
}
}
/// <summary>
/// <para>
/// Gets the x-coordinate of this <see cref='System.Drawing.PointF'/>.
/// </para>
/// </summary>
public float X
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// <para>
/// Gets the y-coordinate of this <see cref='System.Drawing.PointF'/>.
/// </para>
/// </summary>
public float Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static PointF operator +(PointF pt, Size sz)
{
return Add(pt, sz);
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static PointF operator -(PointF pt, Size sz)
{
return Subtract(pt, sz);
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </summary>
public static PointF operator +(PointF pt, SizeF sz)
{
return Add(pt, sz);
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </summary>
public static PointF operator -(PointF pt, SizeF sz)
{
return Subtract(pt, sz);
}
/// <summary>
/// <para>
/// Compares two <see cref='System.Drawing.PointF'/> objects. The result specifies
/// whether the values of the <see cref='System.Drawing.PointF.X'/> and <see cref='System.Drawing.PointF.Y'/> properties of the two <see cref='System.Drawing.PointF'/>
/// objects are equal.
/// </para>
/// </summary>
public static bool operator ==(PointF left, PointF right)
{
return left.X == right.X && left.Y == right.Y;
}
/// <summary>
/// <para>
/// Compares two <see cref='System.Drawing.PointF'/> objects. The result specifies whether the values
/// of the <see cref='System.Drawing.PointF.X'/> or <see cref='System.Drawing.PointF.Y'/> properties of the two
/// <see cref='System.Drawing.PointF'/>
/// objects are unequal.
/// </para>
/// </summary>
public static bool operator !=(PointF left, PointF right)
{
return !(left == right);
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static PointF Add(PointF pt, Size sz)
{
return new PointF(pt.X + sz.Width, pt.Y + sz.Height);
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static PointF Subtract(PointF pt, Size sz)
{
return new PointF(pt.X - sz.Width, pt.Y - sz.Height);
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </summary>
public static PointF Add(PointF pt, SizeF sz)
{
return new PointF(pt.X + sz.Width, pt.Y + sz.Height);
}
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </summary>
public static PointF Subtract(PointF pt, SizeF sz)
{
return new PointF(pt.X - sz.Width, pt.Y - sz.Height);
}
public override bool Equals(object obj)
{
if (!(obj is PointF))
return false;
PointF comp = (PointF)obj;
return comp.X == X && comp.Y == Y;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return "{X=" + _x.ToString() + ", Y=" + _y.ToString() + "}";
}
}
}
| |
using JetBrains.Annotations;
using System;
using System.Linq;
using WireMock.Types;
using WireMock.Util;
using Stef.Validation;
namespace WireMock.Matchers.Request
{
/// <summary>
/// The request body matcher.
/// </summary>
public class RequestMessageBodyMatcher : IRequestMatcher
{
/// <summary>
/// The body function
/// </summary>
public Func<string, bool> Func { get; }
/// <summary>
/// The body data function for byte[]
/// </summary>
public Func<byte[], bool> DataFunc { get; }
/// <summary>
/// The body data function for json
/// </summary>
public Func<object, bool> JsonFunc { get; }
/// <summary>
/// The body data function for BodyData
/// </summary>
public Func<IBodyData, bool> BodyDataFunc { get; }
/// <summary>
/// The matchers.
/// </summary>
public IMatcher[] Matchers { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="body">The body.</param>
public RequestMessageBodyMatcher(MatchBehaviour matchBehaviour, [NotNull] string body) : this(new[] { new WildcardMatcher(matchBehaviour, body) }.Cast<IMatcher>().ToArray())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="body">The body.</param>
public RequestMessageBodyMatcher(MatchBehaviour matchBehaviour, [NotNull] byte[] body) : this(new[] { new ExactObjectMatcher(matchBehaviour, body) }.Cast<IMatcher>().ToArray())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="body">The body.</param>
public RequestMessageBodyMatcher(MatchBehaviour matchBehaviour, [NotNull] object body) : this(new[] { new ExactObjectMatcher(matchBehaviour, body) }.Cast<IMatcher>().ToArray())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<string, bool> func)
{
Guard.NotNull(func, nameof(func));
Func = func;
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<byte[], bool> func)
{
Guard.NotNull(func, nameof(func));
DataFunc = func;
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<object, bool> func)
{
Guard.NotNull(func, nameof(func));
JsonFunc = func;
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<IBodyData, bool> func)
{
Guard.NotNull(func, nameof(func));
BodyDataFunc = func;
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="matchers">The matchers.</param>
public RequestMessageBodyMatcher([NotNull] params IMatcher[] matchers)
{
Guard.NotNull(matchers, nameof(matchers));
Matchers = matchers;
}
/// <see cref="IRequestMatcher.GetMatchingScore"/>
public double GetMatchingScore(IRequestMessage requestMessage, RequestMatchResult requestMatchResult)
{
double score = CalculateMatchScore(requestMessage);
return requestMatchResult.AddScore(GetType(), score);
}
private double CalculateMatchScore(IRequestMessage requestMessage, IMatcher matcher)
{
if (matcher is NotNullOrEmptyMatcher notNullOrEmptyMatcher)
{
switch (requestMessage?.BodyData?.DetectedBodyType)
{
case BodyType.Json:
case BodyType.String:
return notNullOrEmptyMatcher.IsMatch(requestMessage.BodyData.BodyAsString);
case BodyType.Bytes:
return notNullOrEmptyMatcher.IsMatch(requestMessage.BodyData.BodyAsBytes);
default:
return MatchScores.Mismatch;
}
}
if (matcher is ExactObjectMatcher exactObjectMatcher)
{
// If the body is a byte array, try to match.
var detectedBodyType = requestMessage?.BodyData?.DetectedBodyType;
if (detectedBodyType == BodyType.Bytes || detectedBodyType == BodyType.String)
{
return exactObjectMatcher.IsMatch(requestMessage.BodyData.BodyAsBytes);
}
}
// Check if the matcher is a IObjectMatcher
if (matcher is IObjectMatcher objectMatcher)
{
// If the body is a JSON object, try to match.
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
{
return objectMatcher.IsMatch(requestMessage.BodyData.BodyAsJson);
}
// If the body is a byte array, try to match.
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Bytes)
{
return objectMatcher.IsMatch(requestMessage.BodyData.BodyAsBytes);
}
}
// Check if the matcher is a IStringMatcher
if (matcher is IStringMatcher stringMatcher)
{
// If the body is a Json or a String, use the BodyAsString to match on.
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json || requestMessage?.BodyData?.DetectedBodyType == BodyType.String)
{
return stringMatcher.IsMatch(requestMessage.BodyData.BodyAsString);
}
}
return MatchScores.Mismatch;
}
private double CalculateMatchScore(IRequestMessage requestMessage)
{
if (Matchers != null && Matchers.Any())
{
return Matchers.Max(matcher => CalculateMatchScore(requestMessage, matcher));
}
if (Func != null)
{
return MatchScores.ToScore(Func(requestMessage?.BodyData?.BodyAsString));
}
if (JsonFunc != null)
{
return MatchScores.ToScore(JsonFunc(requestMessage?.BodyData?.BodyAsJson));
}
if (DataFunc != null)
{
return MatchScores.ToScore(DataFunc(requestMessage?.BodyData?.BodyAsBytes));
}
if (BodyDataFunc != null)
{
return MatchScores.ToScore(BodyDataFunc(requestMessage?.BodyData));
}
return MatchScores.Mismatch;
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Sensus.WinPhone.Resources;
namespace Sensus.WinPhone
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public static PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += CheckForResetNavigation;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
// If the app has received a 'reset' navigation, then we need to check
// on the next navigation to see if the page stack should be reset
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
// Unregister the event so it doesn't get called again
RootFrame.Navigated -= ClearBackStackAfterReset;
// Only clear the stack for 'new' (forward) and 'refresh' navigations
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// For UI consistency, clear the entire page stack
while (RootFrame.RemoveBackEntry() != null)
{
; // do nothing
}
}
#endregion
// Initialize the app's font and flow direction as defined in its localized resource strings.
//
// To ensure that the font of your application is aligned with its supported languages and that the
// FlowDirection for each of those languages follows its traditional direction, ResourceLanguage
// and ResourceFlowDirection should be initialized in each resx file to match these values with that
// file's culture. For example:
//
// AppResources.es-ES.resx
// ResourceLanguage's value should be "es-ES"
// ResourceFlowDirection's value should be "LeftToRight"
//
// AppResources.ar-SA.resx
// ResourceLanguage's value should be "ar-SA"
// ResourceFlowDirection's value should be "RightToLeft"
//
// For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072.
//
private void InitializeLanguage()
{
try
{
// Set the font to match the display language defined by the
// ResourceLanguage resource string for each supported language.
//
// Fall back to the font of the neutral language if the Display
// language of the phone is not supported.
//
// If a compiler error is hit then ResourceLanguage is missing from
// the resource file.
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// Set the FlowDirection of all elements under the root frame based
// on the ResourceFlowDirection resource string for each
// supported language.
//
// If a compiler error is hit then ResourceFlowDirection is missing from
// the resource file.
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// If an exception is caught here it is most likely due to either
// ResourceLangauge not being correctly set to a supported language
// code or ResourceFlowDirection is set to a value other than LeftToRight
// or RightToLeft.
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2018 Helix Toolkit contributors
*/
using System;
using SharpDX.DXGI;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// An unmanaged buffer of pixels.
/// </summary>
public sealed class PixelBuffer
{
private int width;
private int height;
private DXGI.Format format;
private int rowStride;
private int bufferStride;
private readonly IntPtr dataPointer;
private int pixelSize;
/// <summary>
/// True when RowStride == sizeof(pixelformat) * width
/// </summary>
private bool isStrictRowStride;
/// <summary>
/// Initializes a new instance of the <see cref="PixelBuffer" /> struct.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">The format.</param>
/// <param name="rowStride">The row pitch.</param>
/// <param name="bufferStride">The slice pitch.</param>
/// <param name="dataPointer">The pixels.</param>
public PixelBuffer(int width, int height, Format format, int rowStride, int bufferStride, IntPtr dataPointer)
{
if (dataPointer == IntPtr.Zero)
throw new ArgumentException("Pointer cannot be equal to IntPtr.Zero", "dataPointer");
this.width = width;
this.height = height;
this.format = format;
this.rowStride = rowStride;
this.bufferStride = bufferStride;
this.dataPointer = dataPointer;
this.pixelSize = FormatHelper.SizeOfInBytes(this.format);
this.isStrictRowStride = (pixelSize * width) == rowStride;
}
/// <summary>
/// Gets the width.
/// </summary>
/// <value>The width.</value>
public int Width { get { return width; } }
/// <summary>
/// Gets the height.
/// </summary>
/// <value>The height.</value>
public int Height { get { return height; } }
/// <summary>
/// Gets the format (this value can be changed)
/// </summary>
/// <value>The format.</value>
public Format Format
{
get
{
return format;
}
set
{
if (PixelSize != (int)FormatHelper.SizeOfInBytes(value))
{
throw new ArgumentException(string.Format("Format [{0}] doesn't have same pixel size in bytes than current format [{1}]", value, format));
}
format = value;
}
}
/// <summary>
/// Gets the pixel size in bytes.
/// </summary>
/// <value>The pixel size in bytes.</value>
public int PixelSize { get { return this.pixelSize; } }
/// <summary>
/// Gets the row stride in number of bytes.
/// </summary>
/// <value>The row stride in number of bytes.</value>
public int RowStride { get { return this.rowStride; } }
/// <summary>
/// Gets the total size in bytes of this pixel buffer.
/// </summary>
/// <value>The size in bytes of the pixel buffer.</value>
public int BufferStride { get { return this.bufferStride; } }
/// <summary>
/// Gets the pointer to the pixel buffer.
/// </summary>
/// <value>The pointer to the pixel buffer.</value>
public IntPtr DataPointer { get { return this.dataPointer; } }
/// <summary>
/// Copies this pixel buffer to a destination pixel buffer.
/// </summary>
/// <param name="pixelBuffer">The destination pixel buffer.</param>
/// <remarks>
/// The destination pixel buffer must have exactly the same dimensions (width, height) and format than this instance.
/// Destination buffer can have different row stride.
/// </remarks>
public unsafe void CopyTo(PixelBuffer pixelBuffer)
{
// Check that buffers are identical
if (this.Width != pixelBuffer.Width
|| this.Height != pixelBuffer.Height
|| PixelSize != FormatHelper.SizeOfInBytes(pixelBuffer.Format))
{
throw new ArgumentException("Invalid destination pixelBufferArray. Mush have same Width, Height and Format", "pixelBuffer");
}
// If buffers have same size, than we can copy it directly
if (this.BufferStride == pixelBuffer.BufferStride)
{
Utilities.CopyMemory(pixelBuffer.DataPointer, this.DataPointer, this.BufferStride);
}
else
{
var srcPointer = (byte*)this.DataPointer;
var dstPointer = (byte*)pixelBuffer.DataPointer;
var rowStride = Math.Min(RowStride, pixelBuffer.RowStride);
// Copy per scanline
for(int i = 0; i < Height; i++)
{
Utilities.CopyMemory(new IntPtr(dstPointer), new IntPtr(srcPointer), rowStride);
srcPointer += this.RowStride;
dstPointer += pixelBuffer.RowStride;
}
}
}
/// <summary>
/// Gets the pixel value at a specified position.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="x">The x-coordinate.</param>
/// <param name="y">The y-coordinate.</param>
/// <returns>The pixel value.</returns>
/// <remarks>
/// Caution, this method doesn't check bounding.
/// </remarks>
public unsafe T GetPixel<T>(int x, int y) where T : struct
{
return Utilities.Read<T>(new IntPtr(((byte*)this.DataPointer + RowStride * y + x * PixelSize)));
}
/// <summary>
/// Gets the pixel value at a specified position.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="x">The x-coordinate.</param>
/// <param name="y">The y-coordinate.</param>
/// <param name="value">The pixel value.</param>
/// <remarks>
/// Caution, this method doesn't check bounding.
/// </remarks>
public unsafe void SetPixel<T>(int x, int y, T value) where T : struct
{
Utilities.Write(new IntPtr((byte*)this.DataPointer + RowStride * y + x * PixelSize), ref value);
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="yOffset">The y line offset.</param>
/// <returns>Scanline pixels from the buffer</returns>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <paramref name="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public T[] GetPixels<T>(int yOffset = 0) where T : struct
{
var sizeOfOutputPixel = Utilities.SizeOf<T>();
var totalSize = Width * Height * pixelSize;
if ((totalSize % sizeOfOutputPixel) != 0)
throw new ArgumentException(string.Format("Invalid sizeof(T), not a multiple of current size [{0}]in bytes ", totalSize));
var buffer = new T[totalSize / sizeOfOutputPixel];
GetPixels(buffer, yOffset);
return buffer;
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="pixels">An allocated scanline pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <returns>Scanline pixels from the buffer</returns>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <paramref name="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public void GetPixels<T>(T[] pixels, int yOffset = 0) where T : struct
{
GetPixels(pixels, yOffset, 0, pixels.Length);
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="pixels">An allocated scanline pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <param name="pixelIndex">Offset into the destination <paramref name="pixels"/> buffer.</param>
/// <param name="pixelCount">Number of pixels to write into the destination <paramref name="pixels"/> buffer.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <paramref name="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public unsafe void GetPixels<T>(T[] pixels, int yOffset, int pixelIndex, int pixelCount) where T : struct
{
var pixelPointer = (byte*)this.DataPointer + yOffset * rowStride;
if (isStrictRowStride)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, 0, pixelCount);
}
else
{
var sizeOfOutputPixel = Utilities.SizeOf<T>() * pixelCount;
var sizePerWidth = sizeOfOutputPixel / Width;
var remainingPixels = sizeOfOutputPixel % Width;
for(int i = 0; i < sizePerWidth; i++)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, pixelIndex, Width);
pixelPointer += rowStride;
pixelIndex += Width;
}
if (remainingPixels > 0)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, pixelIndex, remainingPixels);
}
}
}
/// <summary>
/// Sets scanline pixels to the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="sourcePixels">Source pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <paramref name="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public void SetPixels<T>(T[] sourcePixels, int yOffset = 0) where T : struct
{
SetPixels(sourcePixels, yOffset, 0, sourcePixels.Length);
}
/// <summary>
/// Sets scanline pixels to the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="sourcePixels">Source pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <param name="pixelIndex">Offset into the source <paramref name="sourcePixels"/> buffer.</param>
/// <param name="pixelCount">Number of pixels to write into the source <paramref name="sourcePixels"/> buffer.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <paramref name="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public unsafe void SetPixels<T>(T[] sourcePixels, int yOffset, int pixelIndex, int pixelCount) where T : struct
{
var pixelPointer = (byte*)this.DataPointer + yOffset * rowStride;
if (isStrictRowStride)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, 0, pixelCount);
}
else
{
var sizeOfOutputPixel = Utilities.SizeOf<T>() * pixelCount;
var sizePerWidth = sizeOfOutputPixel / Width;
var remainingPixels = sizeOfOutputPixel % Width;
for (int i = 0; i < sizePerWidth; i++)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, pixelIndex, Width);
pixelPointer += rowStride;
pixelIndex += Width;
}
if (remainingPixels > 0)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, pixelIndex, remainingPixels);
}
}
}
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.Threading;
using System.Xml;
// This class tracks the lifetime of the InnerChannelListener (ICL). The ICL must be kept open
// as long as some communication object uses it. ReliableChannelListener (RCL) and all the
// channels it produces use it. The RCL + the channel count forms a ref count. If the ref
// count is 1, the object that wishes to close (since it is the last object to release the
// reference) must also close the ICL. If the ref count is 0 any object may abort the ICL. This
// means the last closing object may not release its reference until after the ICL's close.
abstract class ReliableChannelListenerBase<TChannel>
: DelegatingChannelListener<TChannel>, IReliableFactorySettings
where TChannel : class, IChannel
{
TimeSpan acknowledgementInterval;
bool closed = false;
FaultHelper faultHelper;
bool flowControlEnabled;
TimeSpan inactivityTimeout;
IMessageFilterTable<EndpointAddress> localAddresses;
int maxPendingChannels;
int maxRetryCount;
int maxTransferWindowSize;
MessageVersion messageVersion;
bool ordered;
ReliableMessagingVersion reliableMessagingVersion;
protected ReliableChannelListenerBase(ReliableSessionBindingElement settings, Binding binding)
: base(true, binding)
{
this.acknowledgementInterval = settings.AcknowledgementInterval;
this.flowControlEnabled = settings.FlowControlEnabled;
this.inactivityTimeout = settings.InactivityTimeout;
this.maxPendingChannels = settings.MaxPendingChannels;
this.maxRetryCount = settings.MaxRetryCount;
this.maxTransferWindowSize = settings.MaxTransferWindowSize;
this.messageVersion = binding.MessageVersion;
this.ordered = settings.Ordered;
this.reliableMessagingVersion = settings.ReliableMessagingVersion;
}
public TimeSpan AcknowledgementInterval
{
get { return this.acknowledgementInterval; }
}
protected FaultHelper FaultHelper
{
get { return this.faultHelper; }
set { this.faultHelper = value; }
}
public bool FlowControlEnabled
{
get { return this.flowControlEnabled; }
}
public TimeSpan InactivityTimeout
{
get { return this.inactivityTimeout; }
}
// Must call under lock.
protected bool IsAccepting
{
get { return this.State == CommunicationState.Opened; }
}
public IMessageFilterTable<EndpointAddress> LocalAddresses
{
get { return this.localAddresses; }
set { this.localAddresses = value; }
}
public int MaxPendingChannels
{
get { return this.maxPendingChannels; }
}
public int MaxRetryCount
{
get { return this.maxRetryCount; }
}
public int MaxTransferWindowSize
{
get { return this.maxTransferWindowSize; }
}
public MessageVersion MessageVersion
{
get { return this.messageVersion; }
}
public bool Ordered
{
get { return this.ordered; }
}
public ReliableMessagingVersion ReliableMessagingVersion
{
get { return this.reliableMessagingVersion; }
}
public TimeSpan SendTimeout
{
get { return this.InternalSendTimeout; }
}
protected abstract bool Duplex
{
get;
}
// Must call under lock.
protected abstract bool HasChannels();
// Must call under lock. Must call after the ReliableChannelListener has been opened.
protected abstract bool IsLastChannel(UniqueId inputId);
protected override void OnAbort()
{
bool abortInnerChannelListener;
lock (this.ThisLock)
{
this.closed = true;
abortInnerChannelListener = !this.HasChannels();
}
if (abortInnerChannelListener)
{
this.AbortInnerListener();
}
base.OnAbort();
}
protected virtual void AbortInnerListener()
{
this.faultHelper.Abort();
this.InnerChannelListener.Abort();
}
protected virtual void CloseInnerListener(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.faultHelper.Close(timeoutHelper.RemainingTime());
this.InnerChannelListener.Close(timeoutHelper.RemainingTime());
}
protected virtual IAsyncResult BeginCloseInnerListener(TimeSpan timeout, AsyncCallback callback, object state)
{
OperationWithTimeoutBeginCallback[] beginOperations = new OperationWithTimeoutBeginCallback[] {
new OperationWithTimeoutBeginCallback(this.faultHelper.BeginClose),
new OperationWithTimeoutBeginCallback(this.InnerChannelListener.BeginClose) };
OperationEndCallback[] endOperations = new OperationEndCallback[] {
new OperationEndCallback(this.faultHelper.EndClose),
new OperationEndCallback(this.InnerChannelListener.EndClose) };
return OperationWithTimeoutComposer.BeginComposeAsyncOperations(timeout, beginOperations, endOperations,
callback, state);
}
protected virtual void EndCloseInnerListener(IAsyncResult result)
{
OperationWithTimeoutComposer.EndComposeAsyncOperations(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.ShouldCloseOnChannelListenerClose())
{
this.CloseInnerListener(timeoutHelper.RemainingTime());
this.closed = true;
}
base.OnClose(timeoutHelper.RemainingTime());
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback,
object state)
{
return new CloseAsyncResult(this, base.OnBeginClose, base.OnEndClose, timeout,
callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseAsyncResult.End(result);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnOpen(timeoutHelper.RemainingTime());
this.InnerChannelListener.Open(timeoutHelper.RemainingTime());
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback,
object state)
{
return OperationWithTimeoutComposer.BeginComposeAsyncOperations(
timeout,
new OperationWithTimeoutBeginCallback[]
{
new OperationWithTimeoutBeginCallback(base.OnBeginOpen),
new OperationWithTimeoutBeginCallback(this.InnerChannelListener.BeginOpen)
},
new OperationEndCallback[]
{
new OperationEndCallback(base.OnEndOpen),
new OperationEndCallback(this.InnerChannelListener.EndOpen)
},
callback,
state);
}
protected override void OnEndOpen(IAsyncResult result)
{
OperationWithTimeoutComposer.EndComposeAsyncOperations(result);
}
public void OnReliableChannelAbort(UniqueId inputId, UniqueId outputId)
{
lock (this.ThisLock)
{
this.RemoveChannel(inputId, outputId);
if (!this.closed || this.HasChannels())
{
return;
}
}
this.AbortInnerListener();
}
public void OnReliableChannelClose(UniqueId inputId, UniqueId outputId,
TimeSpan timeout)
{
if (this.ShouldCloseOnReliableChannelClose(inputId, outputId))
{
this.CloseInnerListener(timeout);
lock (this.ThisLock)
{
this.RemoveChannel(inputId, outputId);
}
}
}
public IAsyncResult OnReliableChannelBeginClose(UniqueId inputId,
UniqueId outputId, TimeSpan timeout, AsyncCallback callback, object state)
{
return new OnReliableChannelCloseAsyncResult(this, inputId, outputId, timeout,
callback, state);
}
public void OnReliableChannelEndClose(IAsyncResult result)
{
OnReliableChannelCloseAsyncResult.End(result);
}
// Must call under lock.
protected abstract void RemoveChannel(UniqueId inputId, UniqueId outputId);
bool ShouldCloseOnChannelListenerClose()
{
lock (this.ThisLock)
{
if (!this.HasChannels())
{
return true;
}
else
{
this.closed = true;
return false;
}
}
}
bool ShouldCloseOnReliableChannelClose(UniqueId inputId, UniqueId outputId)
{
lock (this.ThisLock)
{
if (this.closed && this.IsLastChannel(inputId))
{
return true;
}
else
{
this.RemoveChannel(inputId, outputId);
return false;
}
}
}
class CloseAsyncResult : AsyncResult
{
OperationWithTimeoutBeginCallback baseBeginClose;
OperationEndCallback baseEndClose;
ReliableChannelListenerBase<TChannel> parent;
TimeoutHelper timeoutHelper;
static AsyncCallback onBaseChannelListenerCloseComplete =
Fx.ThunkCallback(OnBaseChannelListenerCloseCompleteStatic);
static AsyncCallback onInnerChannelListenerCloseComplete =
Fx.ThunkCallback(OnInnerChannelListenerCloseCompleteStatic);
public CloseAsyncResult(ReliableChannelListenerBase<TChannel> parent,
OperationWithTimeoutBeginCallback baseBeginClose,
OperationEndCallback baseEndClose, TimeSpan timeout, AsyncCallback callback,
object state)
: base(callback, state)
{
this.parent = parent;
this.baseBeginClose = baseBeginClose;
this.baseEndClose = baseEndClose;
bool complete = false;
if (this.parent.ShouldCloseOnChannelListenerClose())
{
this.timeoutHelper = new TimeoutHelper(timeout);
IAsyncResult result = this.parent.BeginCloseInnerListener(
timeoutHelper.RemainingTime(), onInnerChannelListenerCloseComplete, this);
if (result.CompletedSynchronously)
{
complete = this.CompleteInnerChannelListenerClose(result);
}
}
else
{
complete = this.CloseBaseChannelListener(timeout);
}
if (complete)
{
this.Complete(true);
}
}
bool CloseBaseChannelListener(TimeSpan timeout)
{
IAsyncResult result = this.baseBeginClose(timeout,
onBaseChannelListenerCloseComplete, this);
if (result.CompletedSynchronously)
{
this.baseEndClose(result);
return true;
}
else
{
return false;
}
}
bool CompleteInnerChannelListenerClose(IAsyncResult result)
{
this.parent.EndCloseInnerListener(result);
this.parent.closed = true;
this.parent.faultHelper.Abort();
return this.CloseBaseChannelListener(this.timeoutHelper.RemainingTime());
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseAsyncResult>(result);
}
void OnBaseChannelListenerCloseComplete(IAsyncResult result)
{
Exception completeException = null;
try
{
this.baseEndClose(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeException = e;
}
this.Complete(false, completeException);
}
static void OnBaseChannelListenerCloseCompleteStatic(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
CloseAsyncResult closeResult = (CloseAsyncResult)result.AsyncState;
closeResult.OnBaseChannelListenerCloseComplete(result);
}
}
void OnInnerChannelListenerCloseComplete(IAsyncResult result)
{
bool complete;
Exception completeException = null;
try
{
complete = this.CompleteInnerChannelListenerClose(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
complete = true;
completeException = e;
}
if (complete)
{
this.Complete(false, completeException);
}
}
static void OnInnerChannelListenerCloseCompleteStatic(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
CloseAsyncResult closeResult = (CloseAsyncResult)result.AsyncState;
closeResult.OnInnerChannelListenerCloseComplete(result);
}
}
}
class OnReliableChannelCloseAsyncResult : AsyncResult
{
ReliableChannelListenerBase<TChannel> channelListener;
UniqueId inputId;
UniqueId outputId;
static AsyncCallback onInnerChannelListenerCloseComplete =
Fx.ThunkCallback(new AsyncCallback(OnInnerChannelListenerCloseCompleteStatic));
public OnReliableChannelCloseAsyncResult(
ReliableChannelListenerBase<TChannel> channelListener, UniqueId inputId,
UniqueId outputId, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
if (!channelListener.ShouldCloseOnReliableChannelClose(inputId, outputId))
{
this.Complete(true);
return;
}
this.channelListener = channelListener;
this.inputId = inputId;
this.outputId = outputId;
IAsyncResult result = this.channelListener.BeginCloseInnerListener(timeout,
onInnerChannelListenerCloseComplete, this);
if (result.CompletedSynchronously)
{
this.CompleteInnerChannelListenerClose(result);
this.Complete(true);
}
}
void CompleteInnerChannelListenerClose(IAsyncResult result)
{
this.channelListener.EndCloseInnerListener(result);
lock (this.channelListener.ThisLock)
{
this.channelListener.RemoveChannel(this.inputId, this.outputId);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<OnReliableChannelCloseAsyncResult>(result);
}
void OnInnerChannelListenerCloseComplete(IAsyncResult result)
{
Exception completeException = null;
try
{
this.CompleteInnerChannelListenerClose(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeException = e;
}
this.Complete(false, completeException);
}
static void OnInnerChannelListenerCloseCompleteStatic(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
OnReliableChannelCloseAsyncResult closeResult =
(OnReliableChannelCloseAsyncResult)result.AsyncState;
closeResult.OnInnerChannelListenerCloseComplete(result);
}
}
}
}
abstract class ReliableChannelListener<TChannel, TReliableChannel, TInnerChannel>
: ReliableChannelListenerBase<TChannel>
where TChannel : class, IChannel
where TReliableChannel : class, IChannel
where TInnerChannel : class, IChannel
{
Dictionary<UniqueId, TReliableChannel> channelsByInput;
Dictionary<UniqueId, TReliableChannel> channelsByOutput;
InputQueueChannelAcceptor<TChannel> inputQueueChannelAcceptor;
static AsyncCallback onAcceptCompleted = Fx.ThunkCallback(new AsyncCallback(OnAcceptCompletedStatic));
IChannelListener<TInnerChannel> typedListener;
protected ReliableChannelListener(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context.Binding)
{
this.typedListener = context.BuildInnerChannelListener<TInnerChannel>();
this.inputQueueChannelAcceptor = new InputQueueChannelAcceptor<TChannel>(this);
this.Acceptor = this.inputQueueChannelAcceptor;
}
internal override IChannelListener InnerChannelListener
{
get
{
return this.typedListener;
}
set
{
// until the public setter is removed, throw
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
IServerReliableChannelBinder CreateBinder(TInnerChannel channel, EndpointAddress localAddress, EndpointAddress remoteAddress)
{
return ServerReliableChannelBinder<TInnerChannel>.CreateBinder(channel, localAddress,
remoteAddress, TolerateFaultsMode.IfNotSecuritySession, this.DefaultCloseTimeout,
this.DefaultSendTimeout);
}
protected abstract TReliableChannel CreateChannel(UniqueId id, CreateSequenceInfo createSequenceInfo, IServerReliableChannelBinder binder);
protected void Dispatch()
{
this.inputQueueChannelAcceptor.Dispatch();
}
// override to hook up events, etc pre-Open
protected virtual void OnInnerChannelAccepted(TInnerChannel channel)
{
}
protected bool EnqueueWithoutDispatch(TChannel channel)
{
return this.inputQueueChannelAcceptor.EnqueueWithoutDispatch(channel, null);
}
protected TReliableChannel GetChannel(WsrmMessageInfo info, out UniqueId id)
{
id = WsrmUtilities.GetInputId(info);
lock (this.ThisLock)
{
TReliableChannel channel = null;
if ((id == null) || !this.channelsByInput.TryGetValue(id, out channel))
{
if (this.Duplex)
{
UniqueId outputId = WsrmUtilities.GetOutputId(this.ReliableMessagingVersion, info);
if (outputId != null)
{
id = outputId;
this.channelsByOutput.TryGetValue(id, out channel);
}
}
}
return channel;
}
}
void HandleAcceptComplete(TInnerChannel channel)
{
if (channel == null)
{
return;
}
try
{
OnInnerChannelAccepted(channel);
channel.Open();
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
channel.Abort();
return;
}
this.ProcessChannel(channel);
}
protected bool HandleException(Exception e, ICommunicationObject o)
{
if ((e is CommunicationException || e is TimeoutException) &&
(o.State == CommunicationState.Opened))
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
return true;
}
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
return false;
}
// Must call under lock.
protected override bool HasChannels()
{
return (this.channelsByInput == null) ? false : (this.channelsByInput.Count > 0);
}
bool IsExpectedException(Exception e)
{
if (e is ProtocolException)
{
return false;
}
else
{
return e is CommunicationException;
}
}
// Must call under lock. Must call after the ReliableChannelListener has been opened.
protected override bool IsLastChannel(UniqueId inputId)
{
return (this.channelsByInput.Count == 1) ? channelsByInput.ContainsKey(inputId) : false;
}
void OnAcceptCompleted(IAsyncResult result)
{
TInnerChannel channel = null;
Exception expectedException = null;
Exception unexpectedException = null;
try
{
channel = this.typedListener.EndAcceptChannel(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (this.IsExpectedException(e))
{
expectedException = e;
}
else
{
unexpectedException = e;
}
}
if (channel != null)
{
this.HandleAcceptComplete(channel);
this.StartAccepting();
}
else if (unexpectedException != null)
{
this.Fault(unexpectedException);
}
else if ((expectedException != null)
&& (this.typedListener.State == CommunicationState.Opened))
{
DiagnosticUtility.TraceHandledException(expectedException, TraceEventType.Warning);
this.StartAccepting();
}
else if (this.typedListener.State == CommunicationState.Faulted)
{
this.Fault(expectedException);
}
}
static void OnAcceptCompletedStatic(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ReliableChannelListener<TChannel, TReliableChannel, TInnerChannel> listener =
(ReliableChannelListener<TChannel, TReliableChannel, TInnerChannel>)result.AsyncState;
try
{
listener.OnAcceptCompleted(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
listener.Fault(e);
}
}
}
protected override void OnFaulted()
{
this.typedListener.Abort();
this.inputQueueChannelAcceptor.FaultQueue();
base.OnFaulted();
}
protected override void OnOpened()
{
base.OnOpened();
this.channelsByInput = new Dictionary<UniqueId, TReliableChannel>();
if (this.Duplex)
this.channelsByOutput = new Dictionary<UniqueId, TReliableChannel>();
if (Thread.CurrentThread.IsThreadPoolThread)
{
try
{
StartAccepting();
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
this.Fault(e);
}
}
else
{
ActionItem.Schedule(new Action<object>(StartAccepting), this);
}
}
protected TReliableChannel ProcessCreateSequence(WsrmMessageInfo info, TInnerChannel channel, out bool dispatch, out bool newChannel)
{
dispatch = false;
newChannel = false;
CreateSequenceInfo createSequenceInfo = info.CreateSequenceInfo;
EndpointAddress acksTo;
if (!WsrmUtilities.ValidateCreateSequence<TChannel>(info, this, channel, out acksTo))
return null;
lock (this.ThisLock)
{
UniqueId id;
TReliableChannel reliableChannel = null;
if ((createSequenceInfo.OfferIdentifier != null)
&& this.Duplex
&& this.channelsByOutput.TryGetValue(createSequenceInfo.OfferIdentifier, out reliableChannel))
{
return reliableChannel;
}
if (!this.IsAccepting)
{
info.FaultReply = WsrmUtilities.CreateEndpointNotFoundFault(this.MessageVersion, SR.GetString(SR.RMEndpointNotFoundReason, this.Uri));
return null;
}
if (this.inputQueueChannelAcceptor.PendingCount >= this.MaxPendingChannels)
{
info.FaultReply = WsrmUtilities.CreateCSRefusedServerTooBusyFault(this.MessageVersion, this.ReliableMessagingVersion, SR.GetString(SR.ServerTooBusy, this.Uri));
return null;
}
id = WsrmUtilities.NextSequenceId();
reliableChannel = this.CreateChannel(id, createSequenceInfo,
this.CreateBinder(channel, acksTo, createSequenceInfo.ReplyTo));
this.channelsByInput.Add(id, reliableChannel);
if (this.Duplex)
this.channelsByOutput.Add(createSequenceInfo.OfferIdentifier, reliableChannel);
dispatch = this.EnqueueWithoutDispatch((TChannel)(object)reliableChannel);
newChannel = true;
return reliableChannel;
}
}
protected abstract void ProcessChannel(TInnerChannel channel);
// Must call under lock.
protected override void RemoveChannel(UniqueId inputId, UniqueId outputId)
{
this.channelsByInput.Remove(inputId);
if (this.Duplex)
this.channelsByOutput.Remove(outputId);
}
void StartAccepting()
{
Exception expectedException = null;
Exception unexpectedException = null;
while (this.typedListener.State == CommunicationState.Opened)
{
TInnerChannel channel = null;
expectedException = null;
unexpectedException = null;
try
{
IAsyncResult result = this.typedListener.BeginAcceptChannel(TimeSpan.MaxValue, onAcceptCompleted, this);
if (!result.CompletedSynchronously)
return;
channel = this.typedListener.EndAcceptChannel(result);
if (channel == null)
break;
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (this.IsExpectedException(e))
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
expectedException = e;
continue;
}
else
{
unexpectedException = e;
break;
}
}
this.HandleAcceptComplete(channel);
}
if (unexpectedException != null)
{
this.Fault(unexpectedException);
}
else if (this.typedListener.State == CommunicationState.Faulted)
{
this.Fault(expectedException);
}
}
static void StartAccepting(object state)
{
ReliableChannelListener<TChannel, TReliableChannel, TInnerChannel> channelListener =
(ReliableChannelListener<TChannel, TReliableChannel, TInnerChannel>)state;
try
{
channelListener.StartAccepting();
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
channelListener.Fault(e);
}
}
}
abstract class ReliableListenerOverDatagram<TChannel, TReliableChannel, TInnerChannel, TItem>
: ReliableChannelListener<TChannel, TReliableChannel, TInnerChannel>
where TChannel : class, IChannel
where TReliableChannel : class, IChannel
where TInnerChannel : class, IChannel
where TItem : class, IDisposable
{
Action<object> asyncHandleReceiveComplete;
AsyncCallback onTryReceiveComplete;
ChannelTracker<TInnerChannel, object> channelTracker;
protected ReliableListenerOverDatagram(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
this.asyncHandleReceiveComplete = new Action<object>(this.AsyncHandleReceiveComplete);
this.onTryReceiveComplete = Fx.ThunkCallback(new AsyncCallback(this.OnTryReceiveComplete));
this.channelTracker = new ChannelTracker<TInnerChannel, object>();
}
void AsyncHandleReceiveComplete(object state)
{
try
{
IAsyncResult result = (IAsyncResult)state;
TInnerChannel channel = (TInnerChannel)result.AsyncState;
TItem item = null;
try
{
this.EndTryReceiveItem(channel, result, out item);
if (item == null)
return;
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, channel))
{
channel.Abort();
return;
}
}
if (item != null && this.HandleReceiveComplete(item, channel))
StartReceiving(channel, true);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
this.Fault(e);
}
}
bool BeginProcessItem(TItem item, WsrmMessageInfo info, TInnerChannel channel, out TReliableChannel reliableChannel, out bool newChannel, out bool dispatch)
{
dispatch = false;
reliableChannel = null;
newChannel = false;
Message faultReply;
if (info.FaultReply != null)
{
faultReply = info.FaultReply;
}
else if (info.CreateSequenceInfo == null)
{
UniqueId id;
reliableChannel = this.GetChannel(info, out id);
if (reliableChannel != null)
return true;
if (id == null)
{
this.DisposeItem(item);
return true;
}
faultReply = new UnknownSequenceFault(id).CreateMessage(this.MessageVersion,
this.ReliableMessagingVersion);
}
else
{
reliableChannel = this.ProcessCreateSequence(info, channel, out dispatch, out newChannel);
if (reliableChannel != null)
return true;
faultReply = info.FaultReply;
}
try
{
this.SendReply(faultReply, channel, item);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, channel))
{
channel.Abort();
return false;
}
}
finally
{
faultReply.Close();
this.DisposeItem(item);
}
return true;
}
protected abstract IAsyncResult BeginTryReceiveItem(TInnerChannel channel, AsyncCallback callback, object state);
protected abstract void DisposeItem(TItem item);
protected abstract void EndTryReceiveItem(TInnerChannel channel, IAsyncResult result, out TItem item);
void EndProcessItem(TItem item, WsrmMessageInfo info, TReliableChannel channel, bool dispatch)
{
this.ProcessSequencedItem(channel, item, info);
if (dispatch)
this.Dispatch();
}
protected abstract Message GetMessage(TItem item);
bool HandleReceiveComplete(TItem item, TInnerChannel channel)
{
Message message = null;
// Minimalist fix for MB60747: GetMessage can call RequestContext.RequestMessage which can throw.
// If we can handle the exception then keep the receive loop going.
try
{
message = this.GetMessage(item);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, this))
throw;
item.Dispose();
return true;
}
WsrmMessageInfo info = WsrmMessageInfo.Get(this.MessageVersion, this.ReliableMessagingVersion, channel,
null, message);
if (info.ParsingException != null)
{
this.DisposeItem(item);
return true;
}
TReliableChannel reliableChannel;
bool newChannel;
bool dispatch;
if (!this.BeginProcessItem(item, info, channel, out reliableChannel, out newChannel, out dispatch))
return false;
if (reliableChannel == null)
{
this.DisposeItem(item);
return true;
}
// On the one hand the contract of HandleReceiveComplete is that it won't stop the receive loop;
// it can block, but it will ensure the loop doesn't stall.
// On the other hand we don't want to take on the cost of blindly jumping threads.
// So, if we know EndProcessItem might block (dispatch || !newChannel) then we
// try another receive. If that completes async then we know it is safe for us to block,
// if not then we force the receive to complete async and *make* it safe for us to block.
if (dispatch || !newChannel)
{
this.StartReceiving(channel, false);
this.EndProcessItem(item, info, reliableChannel, dispatch);
return false;
}
else
{
this.EndProcessItem(item, info, reliableChannel, dispatch);
return true;
}
}
void OnTryReceiveComplete(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
try
{
TInnerChannel channel = (TInnerChannel)result.AsyncState;
TItem item = null;
try
{
this.EndTryReceiveItem(channel, result, out item);
if (item == null)
return;
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, channel))
{
channel.Abort();
return;
}
}
if (item != null && this.HandleReceiveComplete(item, channel))
StartReceiving(channel, true);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
this.Fault(e);
}
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, this.channelTracker.BeginOpen, this.channelTracker.EndOpen,
base.OnBeginOpen, base.OnEndOpen);
}
protected override void OnEndOpen(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.channelTracker.Open(timeoutHelper.RemainingTime());
base.OnOpen(timeoutHelper.RemainingTime());
}
protected override void OnInnerChannelAccepted(TInnerChannel channel)
{
base.OnInnerChannelAccepted(channel);
this.channelTracker.PrepareChannel(channel);
}
protected override void ProcessChannel(TInnerChannel channel)
{
try
{
this.channelTracker.Add(channel, null);
this.StartReceiving(channel, false);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
this.Fault(e);
}
}
protected override void AbortInnerListener()
{
base.AbortInnerListener();
this.channelTracker.Abort();
}
protected override void CloseInnerListener(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.CloseInnerListener(timeoutHelper.RemainingTime());
this.channelTracker.Close(timeoutHelper.RemainingTime());
}
protected override IAsyncResult BeginCloseInnerListener(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, base.BeginCloseInnerListener, base.EndCloseInnerListener,
channelTracker.BeginClose, channelTracker.EndClose);
}
protected override void EndCloseInnerListener(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
protected abstract void ProcessSequencedItem(TReliableChannel reliableChannel, TItem item, WsrmMessageInfo info);
protected abstract void SendReply(Message reply, TInnerChannel channel, TItem item);
void StartReceiving(TInnerChannel channel, bool canBlock)
{
while (true)
{
TItem item = null;
try
{
IAsyncResult result = this.BeginTryReceiveItem(channel, this.onTryReceiveComplete, channel);
if (!result.CompletedSynchronously)
break;
if (!canBlock)
{
ActionItem.Schedule(this.asyncHandleReceiveComplete, result);
break;
}
this.EndTryReceiveItem(channel, result, out item);
if (item == null)
break;
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, channel))
{
channel.Abort();
break;
}
}
if (item != null && !this.HandleReceiveComplete(item, channel))
break;
}
}
}
abstract class ReliableListenerOverDuplex<TChannel, TReliableChannel> :
ReliableListenerOverDatagram<TChannel, TReliableChannel, IDuplexChannel, Message>
where TChannel : class, IChannel
where TReliableChannel : class, IChannel
{
protected ReliableListenerOverDuplex(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
this.FaultHelper = new SendFaultHelper(context.Binding.SendTimeout, context.Binding.CloseTimeout);
}
protected override IAsyncResult BeginTryReceiveItem(IDuplexChannel channel, AsyncCallback callback, object state)
{
return channel.BeginTryReceive(TimeSpan.MaxValue, callback, state);
}
protected override void DisposeItem(Message item)
{
((IDisposable)item).Dispose();
}
protected override void EndTryReceiveItem(IDuplexChannel channel, IAsyncResult result, out Message item)
{
channel.EndTryReceive(result, out item);
}
protected override Message GetMessage(Message item)
{
return item;
}
protected override void SendReply(Message reply, IDuplexChannel channel, Message item)
{
if (FaultHelper.AddressReply(item, reply))
channel.Send(reply);
}
}
abstract class ReliableListenerOverReply<TChannel, TReliableChannel>
: ReliableListenerOverDatagram<TChannel, TReliableChannel, IReplyChannel, RequestContext>
where TChannel : class, IChannel
where TReliableChannel : class, IChannel
{
protected ReliableListenerOverReply(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
this.FaultHelper = new ReplyFaultHelper(context.Binding.SendTimeout, context.Binding.CloseTimeout);
}
protected override IAsyncResult BeginTryReceiveItem(IReplyChannel channel, AsyncCallback callback, object state)
{
return channel.BeginTryReceiveRequest(TimeSpan.MaxValue, callback, state);
}
protected override void DisposeItem(RequestContext item)
{
((IDisposable)item.RequestMessage).Dispose();
((IDisposable)item).Dispose();
}
protected override void EndTryReceiveItem(IReplyChannel channel, IAsyncResult result, out RequestContext item)
{
channel.EndTryReceiveRequest(result, out item);
}
protected override Message GetMessage(RequestContext item)
{
return item.RequestMessage;
}
protected override void SendReply(Message reply, IReplyChannel channel, RequestContext item)
{
if (FaultHelper.AddressReply(item.RequestMessage, reply))
item.Reply(reply);
}
}
abstract class ReliableListenerOverSession<TChannel, TReliableChannel, TInnerChannel, TInnerSession, TItem>
: ReliableChannelListener<TChannel, TReliableChannel, TInnerChannel>
where TChannel : class, IChannel
where TReliableChannel : class, IChannel
where TInnerChannel : class, IChannel, ISessionChannel<TInnerSession>
where TInnerSession : ISession
where TItem : IDisposable
{
Action<object> asyncHandleReceiveComplete;
AsyncCallback onReceiveComplete;
protected ReliableListenerOverSession(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
this.asyncHandleReceiveComplete = new Action<object>(this.AsyncHandleReceiveComplete);
this.onReceiveComplete = Fx.ThunkCallback(new AsyncCallback(this.OnReceiveComplete));
}
void AsyncHandleReceiveComplete(object state)
{
try
{
IAsyncResult result = (IAsyncResult)state;
TInnerChannel channel = (TInnerChannel)result.AsyncState;
TItem item = default(TItem);
try
{
this.EndTryReceiveItem(channel, result, out item);
if (item == null)
{
channel.Close();
return;
}
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, channel))
{
channel.Abort();
return;
}
}
if (item != null)
this.HandleReceiveComplete(item, channel);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
this.Fault(e);
}
}
protected abstract IAsyncResult BeginTryReceiveItem(TInnerChannel channel, AsyncCallback callback, object state);
protected abstract void DisposeItem(TItem item);
protected abstract void EndTryReceiveItem(TInnerChannel channel, IAsyncResult result, out TItem item);
protected abstract Message GetMessage(TItem item);
void HandleReceiveComplete(TItem item, TInnerChannel channel)
{
WsrmMessageInfo info = WsrmMessageInfo.Get(this.MessageVersion, this.ReliableMessagingVersion, channel,
channel.Session as ISecureConversationSession, this.GetMessage(item));
if (info.ParsingException != null)
{
this.DisposeItem(item);
channel.Abort();
return;
}
TReliableChannel reliableChannel = null;
bool dispatch = false;
bool newChannel = false;
Message faultReply = null;
if (info.FaultReply != null)
{
faultReply = info.FaultReply;
}
else if (info.CreateSequenceInfo == null)
{
UniqueId id;
reliableChannel = this.GetChannel(info, out id);
if ((reliableChannel == null) && (id == null))
{
this.DisposeItem(item);
channel.Abort();
return;
}
if (reliableChannel == null)
faultReply = new UnknownSequenceFault(id).CreateMessage(this.MessageVersion,
this.ReliableMessagingVersion);
}
else
{
reliableChannel = this.ProcessCreateSequence(info, channel, out dispatch, out newChannel);
if (reliableChannel == null)
faultReply = info.FaultReply;
}
if (reliableChannel != null)
{
this.ProcessSequencedItem(channel, item, reliableChannel, info, newChannel);
if (dispatch)
this.Dispatch();
}
else
{
try
{
this.SendReply(faultReply, channel, item);
channel.Close();
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
channel.Abort();
}
finally
{
faultReply.Close();
this.DisposeItem(item);
}
}
}
void OnReceiveComplete(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
try
{
TInnerChannel channel = (TInnerChannel)result.AsyncState;
TItem item = default(TItem);
try
{
this.EndTryReceiveItem(channel, result, out item);
if (item == null)
{
channel.Close();
return;
}
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, channel))
{
channel.Abort();
return;
}
}
if (item != null)
this.HandleReceiveComplete(item, channel);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
this.Fault(e);
}
}
}
protected override void ProcessChannel(TInnerChannel channel)
{
try
{
IAsyncResult result = this.BeginTryReceiveItem(channel, this.onReceiveComplete, channel);
if (result.CompletedSynchronously)
{
ActionItem.Schedule(this.asyncHandleReceiveComplete, result);
}
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
channel.Abort();
return;
}
}
protected abstract void ProcessSequencedItem(TInnerChannel channel, TItem item, TReliableChannel reliableChannel, WsrmMessageInfo info, bool newChannel);
protected abstract void SendReply(Message reply, TInnerChannel channel, TItem item);
}
abstract class ReliableListenerOverDuplexSession<TChannel, TReliableChannel>
: ReliableListenerOverSession<TChannel, TReliableChannel, IDuplexSessionChannel, IDuplexSession, Message>
where TChannel : class, IChannel
where TReliableChannel : class, IChannel
{
protected ReliableListenerOverDuplexSession(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
this.FaultHelper = new SendFaultHelper(context.Binding.SendTimeout, context.Binding.CloseTimeout);
}
protected override IAsyncResult BeginTryReceiveItem(IDuplexSessionChannel channel, AsyncCallback callback, object state)
{
return channel.BeginTryReceive(TimeSpan.MaxValue, callback, channel);
}
protected override void DisposeItem(Message item)
{
((IDisposable)item).Dispose();
}
protected override void EndTryReceiveItem(IDuplexSessionChannel channel, IAsyncResult result, out Message item)
{
channel.EndTryReceive(result, out item);
}
protected override Message GetMessage(Message item)
{
return item;
}
protected override void SendReply(Message reply, IDuplexSessionChannel channel, Message item)
{
if (FaultHelper.AddressReply(item, reply))
channel.Send(reply);
}
}
abstract class ReliableListenerOverReplySession<TChannel, TReliableChannel>
: ReliableListenerOverSession<TChannel, TReliableChannel, IReplySessionChannel, IInputSession, RequestContext>
where TChannel : class, IChannel
where TReliableChannel : class, IChannel
{
protected ReliableListenerOverReplySession(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
this.FaultHelper = new ReplyFaultHelper(context.Binding.SendTimeout, context.Binding.CloseTimeout);
}
protected override IAsyncResult BeginTryReceiveItem(IReplySessionChannel channel, AsyncCallback callback, object state)
{
return channel.BeginTryReceiveRequest(TimeSpan.MaxValue, callback, channel);
}
protected override void DisposeItem(RequestContext item)
{
((IDisposable)item.RequestMessage).Dispose();
((IDisposable)item).Dispose();
}
protected override void EndTryReceiveItem(IReplySessionChannel channel, IAsyncResult result, out RequestContext item)
{
channel.EndTryReceiveRequest(result, out item);
}
protected override Message GetMessage(RequestContext item)
{
return item.RequestMessage;
}
protected override void SendReply(Message reply, IReplySessionChannel channel, RequestContext item)
{
if (FaultHelper.AddressReply(item.RequestMessage, reply))
item.Reply(reply);
}
}
class ReliableDuplexListenerOverDuplex : ReliableListenerOverDuplex<IDuplexSessionChannel, ServerReliableDuplexSessionChannel>
{
public ReliableDuplexListenerOverDuplex(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return true; }
}
protected override ServerReliableDuplexSessionChannel CreateChannel(
UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ServerReliableDuplexSessionChannel(this, binder, this.FaultHelper, id, createSequenceInfo.OfferIdentifier);
}
protected override void ProcessSequencedItem(ServerReliableDuplexSessionChannel channel, Message message, WsrmMessageInfo info)
{
channel.ProcessDemuxedMessage(info);
}
}
class ReliableInputListenerOverDuplex : ReliableListenerOverDuplex<IInputSessionChannel, ReliableInputSessionChannelOverDuplex>
{
public ReliableInputListenerOverDuplex(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return false; }
}
protected override ReliableInputSessionChannelOverDuplex CreateChannel(UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ReliableInputSessionChannelOverDuplex(this, binder, this.FaultHelper, id);
}
protected override void ProcessSequencedItem(ReliableInputSessionChannelOverDuplex channel, Message message, WsrmMessageInfo info)
{
channel.ProcessDemuxedMessage(info);
}
}
class ReliableDuplexListenerOverDuplexSession : ReliableListenerOverDuplexSession<IDuplexSessionChannel, ServerReliableDuplexSessionChannel>
{
public ReliableDuplexListenerOverDuplexSession(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return true; }
}
protected override ServerReliableDuplexSessionChannel CreateChannel(UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ServerReliableDuplexSessionChannel(this, binder, this.FaultHelper, id, createSequenceInfo.OfferIdentifier);
}
protected override void ProcessSequencedItem(IDuplexSessionChannel channel, Message message, ServerReliableDuplexSessionChannel reliableChannel, WsrmMessageInfo info, bool newChannel)
{
if (!newChannel)
{
IServerReliableChannelBinder binder = (IServerReliableChannelBinder)reliableChannel.Binder;
if (!binder.UseNewChannel(channel))
{
message.Close();
channel.Abort();
return;
}
}
reliableChannel.ProcessDemuxedMessage(info);
}
}
class ReliableInputListenerOverDuplexSession
: ReliableListenerOverDuplexSession<IInputSessionChannel, ReliableInputSessionChannelOverDuplex>
{
public ReliableInputListenerOverDuplexSession(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return false; }
}
protected override ReliableInputSessionChannelOverDuplex CreateChannel(UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ReliableInputSessionChannelOverDuplex(this, binder, this.FaultHelper, id);
}
protected override void ProcessSequencedItem(IDuplexSessionChannel channel, Message message, ReliableInputSessionChannelOverDuplex reliableChannel, WsrmMessageInfo info, bool newChannel)
{
if (!newChannel)
{
IServerReliableChannelBinder binder = reliableChannel.Binder;
if (!binder.UseNewChannel(channel))
{
message.Close();
channel.Abort();
return;
}
}
reliableChannel.ProcessDemuxedMessage(info);
}
}
class ReliableInputListenerOverReply : ReliableListenerOverReply<IInputSessionChannel, ReliableInputSessionChannelOverReply>
{
public ReliableInputListenerOverReply(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return false; }
}
protected override ReliableInputSessionChannelOverReply CreateChannel(UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ReliableInputSessionChannelOverReply(this, binder, this.FaultHelper, id);
}
protected override void ProcessSequencedItem(ReliableInputSessionChannelOverReply reliableChannel, RequestContext context, WsrmMessageInfo info)
{
reliableChannel.ProcessDemuxedRequest(reliableChannel.Binder.WrapRequestContext(context), info);
}
}
class ReliableReplyListenerOverReply : ReliableListenerOverReply<IReplySessionChannel, ReliableReplySessionChannel>
{
public ReliableReplyListenerOverReply(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return true; }
}
protected override ReliableReplySessionChannel CreateChannel(UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ReliableReplySessionChannel(this, binder, this.FaultHelper, id, createSequenceInfo.OfferIdentifier);
}
protected override void ProcessSequencedItem(ReliableReplySessionChannel reliableChannel, RequestContext context, WsrmMessageInfo info)
{
reliableChannel.ProcessDemuxedRequest(reliableChannel.Binder.WrapRequestContext(context), info);
}
}
class ReliableInputListenerOverReplySession : ReliableListenerOverReplySession<IInputSessionChannel, ReliableInputSessionChannelOverReply>
{
public ReliableInputListenerOverReplySession(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return false; }
}
protected override ReliableInputSessionChannelOverReply CreateChannel(
UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ReliableInputSessionChannelOverReply(this, binder, this.FaultHelper, id);
}
protected override void ProcessSequencedItem(IReplySessionChannel channel, RequestContext context, ReliableInputSessionChannelOverReply reliableChannel, WsrmMessageInfo info, bool newChannel)
{
if (!newChannel)
{
IServerReliableChannelBinder binder = reliableChannel.Binder;
if (!binder.UseNewChannel(channel))
{
context.RequestMessage.Close();
context.Abort();
channel.Abort();
return;
}
}
reliableChannel.ProcessDemuxedRequest(reliableChannel.Binder.WrapRequestContext(context), info);
}
}
class ReliableReplyListenerOverReplySession : ReliableListenerOverReplySession<IReplySessionChannel, ReliableReplySessionChannel>
{
public ReliableReplyListenerOverReplySession(ReliableSessionBindingElement binding, BindingContext context)
: base(binding, context)
{
}
protected override bool Duplex
{
get { return true; }
}
protected override ReliableReplySessionChannel CreateChannel(UniqueId id,
CreateSequenceInfo createSequenceInfo,
IServerReliableChannelBinder binder)
{
binder.Open(this.InternalOpenTimeout);
return new ReliableReplySessionChannel(this, binder, this.FaultHelper, id, createSequenceInfo.OfferIdentifier);
}
protected override void ProcessSequencedItem(IReplySessionChannel channel, RequestContext context, ReliableReplySessionChannel reliableChannel, WsrmMessageInfo info, bool newChannel)
{
if (!newChannel)
{
IServerReliableChannelBinder binder = reliableChannel.Binder;
if (!binder.UseNewChannel(channel))
{
context.RequestMessage.Close();
context.Abort();
channel.Abort();
return;
}
}
reliableChannel.ProcessDemuxedRequest(reliableChannel.Binder.WrapRequestContext(context), info);
}
}
}
| |
// <copyright file="CommonHistogram.cs" company="Public Domain">
// Released into the public domain
// </copyright>
// This file is part of the C# Packet Capture Analyser application. It is
// free and unencumbered software released into the public domain as detailed
// in the UNLICENSE file in the top level directory of this distribution
namespace PacketCaptureAnalyzer.Analysis
{
/// <summary>
/// This class provides common functionality associated with creating, maintaining and outputting histograms
/// </summary>
public class CommonHistogram
{
//// Private entities
/// <summary>
/// The object that provides for the logging of debug information
/// </summary>
private Analysis.DebugInformation theDebugInformation;
/// <summary>
/// The set of boundaries for the bins in the histogram
/// </summary>
private double[] theValueBinBoundaries;
/// <summary>
/// The number of values in each bin of the histogram
/// </summary>
private uint[] theValueBinCounts;
/// <summary>
/// The total number of values across all bins in the histogram
/// </summary>
private uint theNumberOfValuesAcrossAllBins = 0;
/// <summary>
/// The number of values added to the histogram that had a value lower than the minimum bin boundary
/// </summary>
private uint theNumberOfValuesLowerThanBins = 0;
/// <summary>
/// The number of values added to the histogram that had a value higher than the maximum bin boundary
/// </summary>
private uint theNumberOfValuesHigherThanBins = 0;
/// <summary>
/// The minimum value encountered during adding values to the histogram
/// </summary>
private double theMinValueEncountered = double.MaxValue;
/// <summary>
/// The maximum value encountered during adding values to the histogram
/// </summary>
private double theMaxValueEncountered = double.MinValue;
/// <summary>
/// Initializes a new instance of the CommonHistogram class
/// </summary>
/// <param name="theDebugInformation">The object that provides for the logging of debug information</param>
/// <param name="theNumOfValueBins">The number of bins to use for the histogram</param>
/// <param name="theMinAllowedValue">The minimum value allowed to be added to the bins for the histogram</param>
/// <param name="theMaxAllowedValue">The maximum value allowed to be added to the bins for the histogram</param>
public CommonHistogram(Analysis.DebugInformation theDebugInformation, uint theNumOfValueBins, double theMinAllowedValue, double theMaxAllowedValue)
{
if (theDebugInformation == null)
{
throw new System.ArgumentNullException("theDebugInformation");
}
this.theDebugInformation = theDebugInformation;
if (theMinAllowedValue == theMaxAllowedValue)
{
this.theDebugInformation.WriteErrorEvent(
"The minimum and maximum allowed values for the histogram are equal!!!");
throw new System.ArgumentException(
"Error: The minimum and maximum allowed values for the histogram are equal!!!");
}
this.theValueBinCounts = new uint[theNumOfValueBins];
if (theMaxAllowedValue > theMinAllowedValue)
{
this.CalculateValueBinBoundaries(
theNumOfValueBins,
theMinAllowedValue,
theMaxAllowedValue);
}
else
{
this.theDebugInformation.WriteErrorEvent(
"The minimum value is greater than the maximum value!");
this.CalculateValueBinBoundaries(
theNumOfValueBins,
theMaxAllowedValue,
theMinAllowedValue);
}
}
//// Public accessor methods
/// <summary>
/// Gets the minimum value allowed to be added to the bins for the histogram
/// </summary>
/// <returns>The minimum value allowed to be added to the bins for the histogram</returns>
public double MinAllowedValue
{
get
{
return this.theValueBinBoundaries[0];
}
}
/// <summary>
/// Gets the maximum value allowed to be added to the bins for the histogram
/// </summary>
/// <returns>The maximum value allowed to be added to the bins for the histogram</returns>
public double MaxAllowedValue
{
get
{
return this.theValueBinBoundaries[this.theValueBinBoundaries.Length - 1];
}
}
/// <summary>
/// Adds the supplied value to appropriate bin in the histogram and updates associated data
/// </summary>
/// <param name="theValue">The value to be added to the appropriate bin in the histogram</param>
/// <returns>Boolean flag that indicates whether the values was allowed to be added to the bins for the histogram</returns>
public bool AddValue(double theValue)
{
bool theResult = true;
// Check if the value is the lowest valid value encountered since the creation or reset of the histogram
if (this.theMinValueEncountered > theValue &&
theValue >= this.MinAllowedValue)
{
this.theMinValueEncountered = theValue;
}
// Check if the value is the highest valid value encountered since the creation or reset of the histogram
if (this.theMaxValueEncountered < theValue &&
theValue <= this.MaxAllowedValue)
{
this.theMaxValueEncountered = theValue;
}
if (theValue < this.MinAllowedValue)
{
++this.theNumberOfValuesLowerThanBins;
theResult = false;
}
else if (theValue > this.MaxAllowedValue)
{
++this.theNumberOfValuesHigherThanBins;
theResult = false;
}
else
{
// Loop while the supplied value is smaller than the next bin boundary
// Once the supplied value is no longer smaller than the next bin boundary then we've found our bin
// This ordering is more efficient when most supplied values are towards the lower end of the range
for (int i = 0; i < this.theValueBinBoundaries.Length; ++i)
{
if (theValue < this.theValueBinBoundaries[i + 1])
{
++this.theValueBinCounts[i];
break;
}
}
// Increment the counter of the number of valid values encountered
++this.theNumberOfValuesAcrossAllBins;
}
return theResult;
}
/// <summary>
/// Resets all data and values for the histogram
/// </summary>
public void ResetValues()
{
this.theNumberOfValuesAcrossAllBins = 0;
this.theNumberOfValuesLowerThanBins = 0;
this.theNumberOfValuesHigherThanBins = 0;
this.theMinValueEncountered = double.MaxValue;
this.theMaxValueEncountered = double.MinValue;
for (int i = 0; i < this.theValueBinCounts.Length; ++i)
{
this.theValueBinCounts[i] = 0;
}
}
/// <summary>
/// Formats the contents of the histogram and outputs it to the debug console
/// </summary>
public void OutputValues()
{
uint theNumberOfValuesProcessed = 0;
bool theFirstPercentileFound = false;
bool theNinetyNinthPercentileFound = false;
for (int i = 0; i < this.theValueBinCounts.Length; ++i)
{
// Do not start processing bins for the histogram until we've reached the minimum value encountered
if (this.theValueBinBoundaries[i + 1] < this.theMinValueEncountered)
{
continue;
}
// Update the running total of entries found so far
theNumberOfValuesProcessed += this.theValueBinCounts[i];
// Output an indication if the first percentile of all entries encountered has been reached
if (!theFirstPercentileFound)
{
if (theNumberOfValuesProcessed >= (this.theNumberOfValuesAcrossAllBins * 0.01))
{
theFirstPercentileFound = true;
this.theDebugInformation.WriteTextLine(
new string('+', 144) + " 1%");
}
}
//// Correct the formatting for negative values
if (this.theValueBinBoundaries[i] >= 0.0)
{
this.theDebugInformation.WriteTextElement(
string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0,11: ###0.00000}", this.theValueBinBoundaries[i]));
}
else
{
this.theDebugInformation.WriteTextElement(
string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0,11:###0.00000}", this.theValueBinBoundaries[i]));
}
this.theDebugInformation.WriteTextElement(" to ");
if (this.theValueBinBoundaries[i + 1] >= 0.0)
{
this.theDebugInformation.WriteTextElement(
string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0,11: ###0.00000}", this.theValueBinBoundaries[i + 1]));
}
else
{
this.theDebugInformation.WriteTextElement(
string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0,11:###0.00000}", this.theValueBinBoundaries[i + 1]));
}
this.theDebugInformation.WriteTextElement(" |");
// Except if there are no entries, leave a space before the first ) character
// for this bin for clarity
if (this.theValueBinCounts[i] > 0)
{
this.theDebugInformation.WriteTextElement(" ");
}
// Calculated a scaled count for this bin based on the percentage of the total number of values across all bins that is in this bin
// The scaling of the count will the ensure that the output does not exceed 115 columns to ensure it fits on screen
// Perform the calculations using floating point values to prevent rounding to zero due to integer division
int theScaledBinCount =
(int)(((float)this.theValueBinCounts[i] /
(float)this.theNumberOfValuesAcrossAllBins) * 115.0);
// Make sure that at least a single ) character is always output for a bin with a non-zero count
if (this.theValueBinCounts[i] > 0 &&
theScaledBinCount == 0)
{
theScaledBinCount = 1;
}
// Output a number of ) characters for this bin based on the scaled count
this.theDebugInformation.WriteTextElement(
new string(')', theScaledBinCount));
// Except if there are no entries, leave a space after the last ) character
// for this bin for clarity and then write out the number of entries in this
// bin (the real value, not the scaled value)
if (this.theValueBinCounts[i] > 0)
{
this.theDebugInformation.WriteTextElement(
" " + this.theValueBinCounts[i]);
}
// Complete the line for this bin
this.theDebugInformation.WriteBlankLine();
// Output an indication if the ninety ninth percentile of all entries encountered has been reached
if (!theNinetyNinthPercentileFound)
{
if (theNumberOfValuesProcessed >= (this.theNumberOfValuesAcrossAllBins * 0.99))
{
theNinetyNinthPercentileFound = true;
this.theDebugInformation.WriteTextLine(
new string('+', 144) + " 99%");
}
}
// Do not continue processing further bins for the histogram if we've reached the maximum value encountered
if (this.theValueBinBoundaries[i + 1] > this.theMaxValueEncountered)
{
break;
}
}
if (this.theNumberOfValuesLowerThanBins > 0)
{
this.theDebugInformation.WriteBlankLine();
this.theDebugInformation.WriteTextLine(
"Number of values lower than bins: " +
this.theNumberOfValuesLowerThanBins.ToString(System.Globalization.CultureInfo.CurrentCulture));
}
if (this.theNumberOfValuesHigherThanBins > 0)
{
this.theDebugInformation.WriteBlankLine();
this.theDebugInformation.WriteTextLine(
"Number of values higher than bins: " +
this.theNumberOfValuesHigherThanBins.ToString(System.Globalization.CultureInfo.CurrentCulture));
}
}
//// Private methods
/// <summary>
/// Calculates the bin boundaries to be used for the histogram based on the supplied number of bins, minimum allowed value, and maximum allowed value
/// </summary>
/// <param name="theNumOfValueBins">The number of bins to use for the histogram</param>
/// <param name="theMinAllowedValue">The minimum value allowed to be added to the bins for the histogram</param>
/// <param name="theMaxAllowedValue">The maximum value allowed to be added to the bins for the histogram</param>
private void CalculateValueBinBoundaries(uint theNumOfValueBins, double theMinAllowedValue, double theMaxAllowedValue)
{
this.theValueBinBoundaries =
new double[theNumOfValueBins + 1];
this.theValueBinBoundaries[0] =
theMinAllowedValue;
this.theValueBinBoundaries[this.theValueBinBoundaries.Length - 1] =
theMaxAllowedValue;
double theSizeOfValueBins =
(theMaxAllowedValue - theMinAllowedValue) / theNumOfValueBins;
for (int i = 1; i < this.theValueBinBoundaries.Length - 1; ++i)
{
this.theValueBinBoundaries[i] =
this.theValueBinBoundaries[0] +
(i * theSizeOfValueBins);
}
// Check that the calculated bin boundaries are a strictly monotonically increasing sequence of values
this.CheckBinBoundaries(this.theValueBinBoundaries);
}
/// <summary>
/// Checks that the supplied bin boundaries are a strictly monotonically increasing sequence of values
/// </summary>
/// <param name="theBinBoundaries">The bin boundaries to be checked</param>
private void CheckBinBoundaries(double[] theBinBoundaries)
{
for (int i = 0; i < theBinBoundaries.Length - 1; ++i)
{
if (theBinBoundaries[i] >= theBinBoundaries[i + 1])
{
string theExceptionMessage =
"Bin boundary " +
theBinBoundaries[i].ToString(System.Globalization.CultureInfo.CurrentCulture) +
" is >= Bin boundary " +
theBinBoundaries[i + 1].ToString(System.Globalization.CultureInfo.CurrentCulture) +
"!!!";
this.theDebugInformation.WriteErrorEvent(
theExceptionMessage);
throw new System.ArgumentException(
theExceptionMessage);
}
}
}
}
}
| |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace VkApi.Wrapper.Objects
{
public class VideoVideo
{
///<summary>
/// Video access key
///</summary>
[JsonProperty("access_key")]
public String AccessKey { get; set; }
///<summary>
/// Date when the video has been added in Unixtime
///</summary>
[JsonProperty("adding_date")]
public int AddingDate { get; set; }
///<summary>
/// Information whether current user can comment the video
///</summary>
[JsonProperty("can_comment")]
public int CanComment { get; set; }
///<summary>
/// Information whether current user can edit the video
///</summary>
[JsonProperty("can_edit")]
public int CanEdit { get; set; }
///<summary>
/// Information whether current user can like the video
///</summary>
[JsonProperty("can_like")]
public int CanLike { get; set; }
///<summary>
/// Information whether current user can repost the video
///</summary>
[JsonProperty("can_repost")]
public int CanRepost { get; set; }
///<summary>
/// Information whether current user can subscribe to author of the video
///</summary>
[JsonProperty("can_subscribe")]
public int CanSubscribe { get; set; }
///<summary>
/// Information whether current user can add the video to favourites
///</summary>
[JsonProperty("can_add_to_faves")]
public int CanAddToFaves { get; set; }
///<summary>
/// Information whether current user can add the video
///</summary>
[JsonProperty("can_add")]
public int CanAdd { get; set; }
///<summary>
/// Information whether current user can attach action button to the video
///</summary>
[JsonProperty("can_attach_link")]
public int CanAttachLink { get; set; }
///<summary>
/// 1 if video is private
///</summary>
[JsonProperty("is_private")]
public int IsPrivate { get; set; }
///<summary>
/// Number of comments
///</summary>
[JsonProperty("comments")]
public int Comments { get; set; }
///<summary>
/// Date when video has been uploaded in Unixtime
///</summary>
[JsonProperty("date")]
public int Date { get; set; }
///<summary>
/// Video description
///</summary>
[JsonProperty("description")]
public String Description { get; set; }
///<summary>
/// Video duration in seconds
///</summary>
[JsonProperty("duration")]
public int Duration { get; set; }
[JsonProperty("image")]
public VideoVideoImage[] Image { get; set; }
[JsonProperty("first_frame")]
public VideoVideoImage[] FirstFrame { get; set; }
///<summary>
/// Video width
///</summary>
[JsonProperty("width")]
public int Width { get; set; }
///<summary>
/// Video height
///</summary>
[JsonProperty("height")]
public int Height { get; set; }
///<summary>
/// Video ID
///</summary>
[JsonProperty("id")]
public int Id { get; set; }
///<summary>
/// Video owner ID
///</summary>
[JsonProperty("owner_id")]
public int OwnerId { get; set; }
///<summary>
/// Id of the user who uploaded the video if it was uploaded to a group by member
///</summary>
[JsonProperty("user_id")]
public int UserId { get; set; }
///<summary>
/// Video title
///</summary>
[JsonProperty("title")]
public String Title { get; set; }
///<summary>
/// Whether video is added to bookmarks
///</summary>
[JsonProperty("is_favorite")]
public Boolean IsFavorite { get; set; }
///<summary>
/// Video embed URL
///</summary>
[JsonProperty("player")]
public String Player { get; set; }
///<summary>
/// Returns if the video is processing
///</summary>
[JsonProperty("processing")]
public BasePropertyExists Processing { get; set; }
///<summary>
/// 1 if video is being converted
///</summary>
[JsonProperty("converting")]
public int Converting { get; set; }
[JsonProperty("restriction")]
public MediaRestriction Restriction { get; set; }
///<summary>
/// 1 if video is added to user's albums
///</summary>
[JsonProperty("added")]
public int Added { get; set; }
///<summary>
/// 1 if user is subscribed to author of the video
///</summary>
[JsonProperty("is_subscribed")]
public int IsSubscribed { get; set; }
[JsonProperty("track_code")]
public String TrackCode { get; set; }
///<summary>
/// Information whether the video is repeated
///</summary>
[JsonProperty("repeat")]
public BasePropertyExists Repeat { get; set; }
[JsonProperty("type")]
public String Type { get; set; }
///<summary>
/// Number of views
///</summary>
[JsonProperty("views")]
public int Views { get; set; }
///<summary>
/// If video is external, number of views on vk
///</summary>
[JsonProperty("local_views")]
public int LocalViews { get; set; }
///<summary>
/// Restriction code
///</summary>
[JsonProperty("content_restricted")]
public int ContentRestricted { get; set; }
///<summary>
/// Restriction text
///</summary>
[JsonProperty("content_restricted_message")]
public String ContentRestrictedMessage { get; set; }
///<summary>
/// Live donations balance
///</summary>
[JsonProperty("balance")]
public int Balance { get; set; }
///<summary>
/// Live stream status
///</summary>
[JsonProperty("live_status")]
public String LiveStatus { get; set; }
///<summary>
/// 1 if the video is a live stream
///</summary>
[JsonProperty("live")]
public BasePropertyExists Live { get; set; }
///<summary>
/// 1 if the video is an upcoming stream
///</summary>
[JsonProperty("upcoming")]
public BasePropertyExists Upcoming { get; set; }
///<summary>
/// Number of spectators of the stream
///</summary>
[JsonProperty("spectators")]
public int Spectators { get; set; }
///<summary>
/// External platform
///</summary>
[JsonProperty("platform")]
public String Platform { get; set; }
[JsonProperty("likes")]
public BaseLikes Likes { get; set; }
[JsonProperty("reposts")]
public BaseRepostsInfo Reposts { get; set; }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class GenericConstraintConversionTests : CSharpTestBase
{
/// <summary>
/// 6.1.10, bullet 1
/// </summary>
[Fact]
public void ImplicitInterfaceAndBaseTypeConversions01()
{
var source =
@"interface I { }
interface IA : I { }
interface IB : I { }
class A : IA { }
class B : A, IB { }
class C<T>
where T : B
{
static I i;
static IA ia;
static IB ib;
static A a;
static B b;
static void M<U, V>(T t, U u, V v)
where U : struct, IA
where V : class, IA
{
i = t;
i = u;
i = v;
ia = t;
ia = u;
ia = v;
ib = t;
ib = u;
ib = v;
a = t;
a = u;
b = t;
b = u;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (25,14): error CS0266: Cannot implicitly convert type 'U' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "IB").WithLocation(25, 14),
// (26,14): error CS0266: Cannot implicitly convert type 'V' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "IB").WithLocation(26, 14),
// (28,13): error CS0029: Cannot implicitly convert type 'U' to 'A'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "A").WithLocation(28, 13),
// (30,13): error CS0029: Cannot implicitly convert type 'U' to 'B'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "B").WithLocation(30, 13));
}
[Fact]
public void ImplicitInterfaceAndBaseTypeConversions02()
{
var source =
@"interface IA { }
interface IB { }
class A : IA { }
class B : A, IB { }
class C<T, U>
where T : A
where U : B, T
{
static IA ia;
static IB ib;
static void M<V>(T t, U u, V v)
where V : B, T
{
ia = t;
ia = u;
ia = v;
ib = t;
ib = u;
ib = v;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (17,14): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(17, 14));
}
/// <summary>
/// 6.1.10, bullet 2
/// </summary>
[Fact]
public void ImplicitConversionEffectiveInterfaceSet()
{
var source =
@"interface IA { }
interface IB { }
class A : IA { }
class B : IB { }
class C<T, U, V>
where T : A
where U : IB
where V : B, IA
{
static IA a;
static IB b;
static void M(T t, U u, V v)
{
a = t;
a = u;
b = t;
b = u;
}
static void M1<X>(X x) where X : T
{
a = x;
b = x;
}
static void M2<X>(X x) where X : U
{
a = x;
b = x;
}
static void M3<X>(X x) where X : T, U
{
a = x;
b = x;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (15,13): error CS0266: Cannot implicitly convert type 'U' to 'IA'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "IA").WithLocation(15, 13),
// (16,13): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(16, 13),
// (22,13): error CS0266: Cannot implicitly convert type 'X' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IB").WithLocation(22, 13),
// (26,13): error CS0266: Cannot implicitly convert type 'X' to 'IA'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IA").WithLocation(26, 13));
}
/// <summary>
/// 6.1.10, bullet 3
/// </summary>
[Fact]
public void ImplicitConversionToTypeParameter()
{
var source =
@"class C<T, U, V, W>
where T : U, V
where U : W
{
static T t;
static U u;
static V v;
static W w;
static void M()
{
t = u;
t = v;
t = w;
u = t;
u = v;
u = w;
v = t;
v = u;
v = w;
w = t;
w = u;
w = v;
}
static void M1<X>(X x) where X : T
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
static void M2<X>(X x) where X : U
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
static void M3<X>(X x) where X : U, V, W
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (11,13): error CS0266: Cannot implicitly convert type 'U' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "T").WithLocation(11, 13),
// (12,13): error CS0266: Cannot implicitly convert type 'V' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "T").WithLocation(12, 13),
// (13,13): error CS0266: Cannot implicitly convert type 'W' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "T").WithLocation(13, 13),
// (15,13): error CS0029: Cannot implicitly convert type 'V' to 'U'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "U").WithLocation(15, 13),
// (16,13): error CS0266: Cannot implicitly convert type 'W' to 'U'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "U").WithLocation(16, 13),
// (18,13): error CS0029: Cannot implicitly convert type 'U' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "V").WithLocation(18, 13),
// (19,13): error CS0029: Cannot implicitly convert type 'W' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "w").WithArguments("W", "V").WithLocation(19, 13),
// (22,13): error CS0029: Cannot implicitly convert type 'V' to 'W'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "W").WithLocation(22, 13),
// (30,13): error CS0266: Cannot implicitly convert type 'T' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "X").WithLocation(30, 13),
// (31,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(31, 13),
// (32,13): error CS0266: Cannot implicitly convert type 'V' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "X").WithLocation(32, 13),
// (33,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(33, 13),
// (37,13): error CS0029: Cannot implicitly convert type 'X' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "T").WithLocation(37, 13),
// (39,13): error CS0029: Cannot implicitly convert type 'X' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "V").WithLocation(39, 13),
// (41,13): error CS0029: Cannot implicitly convert type 'T' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "X").WithLocation(41, 13),
// (42,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(42, 13),
// (43,13): error CS0029: Cannot implicitly convert type 'V' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "X").WithLocation(43, 13),
// (44,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(44, 13),
// (48,13): error CS0029: Cannot implicitly convert type 'X' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "T").WithLocation(48, 13),
// (52,13): error CS0029: Cannot implicitly convert type 'T' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "X").WithLocation(52, 13),
// (53,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(53, 13),
// (54,13): error CS0266: Cannot implicitly convert type 'V' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "X").WithLocation(54, 13),
// (55,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(55, 13));
}
/// <summary>
/// 6.1.10, bullet 4
/// </summary>
[Fact]
public void ImplicitConversionFromNull()
{
var source =
@"interface I { }
class A { }
class B<T1, T2, T3, T4, T5, T6>
where T2 : class
where T3 : struct
where T4 : new()
where T5: I
where T6: A
{
static T1 F1 = null;
static T2 F2 = null;
static T3 F3 = null;
static T4 F4 = null;
static T5 F5 = null;
static T6 F6 = null;
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (10,20): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead.
// static T1 F1 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"),
// (12,20): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead.
// static T3 F3 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"),
// (13,20): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead.
// static T4 F4 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"),
// (14,20): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead.
// static T5 F5 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"),
// (11,15): warning CS0414: The field 'B<T1, T2, T3, T4, T5, T6>.F2' is assigned but its value is never used
// static T2 F2 = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F2").WithArguments("B<T1, T2, T3, T4, T5, T6>.F2"),
// (15,15): warning CS0414: The field 'B<T1, T2, T3, T4, T5, T6>.F6' is assigned but its value is never used
// static T6 F6 = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F6").WithArguments("B<T1, T2, T3, T4, T5, T6>.F6")
);
}
/// <summary>
/// 6.1.10, bullet 5
/// </summary>
[Fact]
public void ImplicitReferenceConversionToInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
class A : IA { }
class B : A, IB { }
class C<T, U>
where T : A
where U : B
{
static void M(T t, U u)
{
IA a;
IB b;
a = t;
a = u;
b = t;
b = u;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (15,13): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(15, 13));
}
/// <summary>
/// 6.1.10, bullet 6
/// </summary>
[Fact]
public void ImplicitInterfaceVarianceConversions01()
{
var source =
@"interface IIn<in T> { }
interface IOut<out T> { }
interface IInDerived<T> : IIn<T> { }
interface IOutDerived<T> : IOut<T> { }
class CIn<T> : IIn<T> { }
class COut<T> : IOut<T> { }
class C<T, U>
where T : class
where U : class, T
{
static IIn<T> it;
static IOut<T> ot;
static IIn<U> iu;
static IOut<U> ou;
static void M1<X, Y>(X x, Y y)
where X : IIn<T>
where Y : IIn<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M2<X, Y>(X x, Y y)
where X : IOut<T>
where Y : IOut<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
static void M3<X, Y>(X x, Y y)
where X : IInDerived<T>
where Y : IInDerived<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M4<X, Y>(X x, Y y)
where X : IOutDerived<T>
where Y : IOutDerived<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
static void M5<X, Y>(X x, Y y)
where X : CIn<T>
where Y : CIn<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M6<X, Y>(X x, Y y)
where X : COut<T>
where Y : COut<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (20,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(20, 14),
// (30,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(30, 14),
// (38,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(38, 14),
// (48,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(48, 14),
// (56,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(56, 14),
// (66,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(66, 14));
}
[Fact]
public void ImplicitInterfaceVarianceConversions02()
{
var source =
@"interface I<T> { }
interface IIn<in T> { }
interface IOut<out T> { }
class A<T, U>
where U : T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class B<T, U>
where T : class
where U : T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class C<T, U>
where T : class
where U : class, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it; // valid
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu; // valid
iu = it;
}
}
class D<T, U>
where U : struct, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class E<T, U>
where T : class
where U : struct, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (9,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(9, 14),
// (10,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(10, 14),
// (14,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(14, 14),
// (15,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(15, 14),
// (19,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(19, 14),
// (20,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(20, 14),
// (29,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(29, 14),
// (30,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(30, 14),
// (34,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(34, 14),
// (35,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(35, 14),
// (39,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(39, 14),
// (40,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(40, 14),
// (49,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(49, 14),
// (50,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(50, 14),
// (54,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(54, 14),
// (60,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(60, 14),
// (68,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(68, 14),
// (69,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(69, 14),
// (73,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(73, 14),
// (74,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(74, 14),
// (78,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(78, 14),
// (79,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(79, 14),
// (88,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(88, 14),
// (89,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(89, 14),
// (93,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(93, 14),
// (94,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(94, 14),
// (98,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(98, 14),
// (99,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(99, 14));
}
[Fact]
public void ImplicitReferenceConversions()
{
var source =
@"class C<T, U>
where T : U
where U : class
{
static void M<X>(X x, U u) where X : class, T
{
u = x;
x = u;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (8,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(8, 13));
}
[Fact]
public void ImplicitBoxingConversions()
{
var source =
@"class C<T, U>
where T : class
where U : T
{
static void M<X, Y>(Y y, T t)
where X : U
where Y : struct, X
{
t = y;
y = t;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (10,13): error CS0266: Cannot implicitly convert type 'T' to 'Y'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "Y").WithLocation(10, 13));
}
[Fact]
public void ImplicitInterfaceConversionsCircularConstraint()
{
var source =
@"interface I { }
class C<T, U>
where T : T
where U : U, I
{
static void M<V>(T t, U u, V v)
where V : U
{
I i;
i = t;
i = u;
i = v;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (2,9): error CS0454: Circular constraint dependency involving 'T' and 'T'
Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(2, 9),
// (2,12): error CS0454: Circular constraint dependency involving 'U' and 'U'
Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(2, 12),
// (10,13): error CS0266: Cannot implicitly convert type 'T' to 'I'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "I").WithLocation(10, 13));
}
/// <summary>
/// 6.2.7, bullet 1
/// </summary>
[Fact]
public void ExplicitBaseClassConversions()
{
var source =
@"class A { }
class B1<T> : A { }
class C<T> : B1<T> { }
class B2 : A { }
class D<T>
where T : C<object>
{
static void M<U>(object o, A a, B1<T> b1t, B1<object> b1o, B2 b2)
where U : C<T>
{
T t;
t = (T)o;
t = (T)a;
t = (T)b1t;
t = (T)b1o;
t = (T)b2;
U u;
u = (U)o;
u = (U)a;
u = (U)b1t;
u = (U)b1o;
u = (U)b2;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (14,13): error CS0030: Cannot convert type 'B1<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)b1t").WithArguments("B1<T>", "T").WithLocation(14, 13),
// (16,13): error CS0030: Cannot convert type 'B2' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)b2").WithArguments("B2", "T").WithLocation(16, 13),
// (21,13): error CS0030: Cannot convert type 'B1<object>' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)b1o").WithArguments("B1<object>", "U").WithLocation(21, 13),
// (22,13): error CS0030: Cannot convert type 'B2' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)b2").WithArguments("B2", "U").WithLocation(22, 13));
}
/// <summary>
/// 6.2.7, bullet 2
/// </summary>
[Fact]
public void ExplicitConversionFromInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
interface IC<T> { }
class A<T>
where T : IA
{
static void M<U>(IA a, IB b, IC<object> co, IC<T> ct)
where U : IC<T>
{
T t;
t = (T)a;
t = (T)b;
t = (T)co;
t = (T)ct;
U u;
u = (U)a;
u = (U)b;
u = (U)co;
u = (U)ct;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// 6.2.7, bullet 3
/// </summary>
[Fact]
public void ExplicitConversionToInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
interface IC<T> { }
class A<T>
where T : IA
{
static void M<U>(T t, U u)
where U : IC<T>
{
IA a;
IB b;
IC<object> co;
IC<T> ct;
b = (IB)t;
co = (IC<object>)t;
ct = (IC<T>)t;
a = (IA)u;
b = (IB)u;
co = (IC<object>)u;
ct = (IC<T>)u;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// 6.2.7, bullet 4
/// </summary>
[Fact]
public void ExplicitConversionToTypeParameter()
{
var source =
@"class C<T, U, V, W>
where T : U, V, W
where U : V, W
{
static T t;
static U u;
static V v;
static W w;
static void M()
{
t = (T)u;
t = (T)v;
t = (T)w;
u = (U)v;
u = (U)w;
v = (V)w;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (16,13): error CS0030: Cannot convert type 'W' to 'V'
// v = (V)w;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(V)w").WithArguments("W", "V"),
// (8,14): warning CS0649: Field 'C<T, U, V, W>.w' is never assigned to, and will always have its default value
// static W w;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "w").WithArguments("C<T, U, V, W>.w", "")
);
}
[Fact]
public void NoConversionsToValueType()
{
var source =
@"abstract class A<T>
{
internal abstract void M<U>(T t, U u) where U : T;
}
class B : A<int>
{
internal override void M<U>(int t, U u)
{
u = t;
u = (U)t;
t = u;
t = (int)u;
}
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (9,13): error CS0029: Cannot implicitly convert type 'int' to 'U'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("int", "U").WithLocation(9, 13),
// (10,13): error CS0030: Cannot convert type 'int' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)t").WithArguments("int", "U").WithLocation(10, 13),
// (11,13): error CS0029: Cannot implicitly convert type 'U' to 'int'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "int").WithLocation(11, 13),
// (12,13): error CS0030: Cannot convert type 'U' to 'int'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)u").WithArguments("U", "int").WithLocation(12, 13));
}
/// <summary>
/// 6.1.10
/// </summary>
[ClrOnlyFact]
public void EmitImplicitConversions()
{
var source =
@"interface I { }
interface I<in T> { }
class A { }
class B : A { }
class C<T1, T2, T3, T4, T5, T6>
where T2 : I
where T3 : T4
where T5 : B
where T6 : I<A>
{
static void F1(object o) { }
static void F2(I i) { }
static void F3(T4 t) { }
static void F5(A a) { }
static void F6(I<B> b) { }
static void M(T1 a, T2 b, T3 c, T5 d, T6 e)
{
// 6.1.10 bullet 1: conversion to base type.
F1(a);
// 6.1.10 bullet 2: conversion to interface.
F2(b);
// 6.1.10 bullet 3: conversion to type parameter.
F3(c);
// 6.1.10 bullet 4: conversion from null to reference type.
// ... no test
// 6.1.10 bullet 5: conversion to reference type.
F5(d);
// 6.1.10 bullet 6: conversion to variance-convertible interface.
F6(e);
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C<T1, T2, T3, T4, T5, T6>.M(T1, T2, T3, T5, T6)",
@"{
// Code size 62 (0x3e)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T1""
IL_0006: call ""void C<T1, T2, T3, T4, T5, T6>.F1(object)""
IL_000b: ldarg.1
IL_000c: box ""T2""
IL_0011: call ""void C<T1, T2, T3, T4, T5, T6>.F2(I)""
IL_0016: ldarg.2
IL_0017: box ""T3""
IL_001c: unbox.any ""T4""
IL_0021: call ""void C<T1, T2, T3, T4, T5, T6>.F3(T4)""
IL_0026: ldarg.3
IL_0027: box ""T5""
IL_002c: call ""void C<T1, T2, T3, T4, T5, T6>.F5(A)""
IL_0031: ldarg.s V_4
IL_0033: box ""T6""
IL_0038: call ""void C<T1, T2, T3, T4, T5, T6>.F6(I<B>)""
IL_003d: ret
}");
}
/// <summary>
/// 6.2.7
/// </summary>
[ClrOnlyFact]
public void EmitExplicitConversions()
{
var source =
@"interface I { }
class C<T1, T2, T3, T4, T5>
where T2 : I
where T5 : T4
{
static void F1(T1 t) { }
static void F2(T2 t) { }
static void F3(I i) { }
static void F5(T5 t) { }
static void M(object a, I b, T3 c, T4 d)
{
// 6.2.7 bullet 1: conversion from base class to type parameter.
F1((T1)a);
// 6.2.7 bullet 2: conversion from interface to type parameter.
F2((T2)b);
// 6.2.7 bullet 3: conversion from type parameter to interface
// not in interface set.
F3((I)c);
// 6.2.7 bullet 4: conversion from type parameter to type parameter.
F5((T5)d);
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C<T1, T2, T3, T4, T5>.M(object, I, T3, T4)",
@"{
// Code size 55 (0x37)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""T1""
IL_0006: call ""void C<T1, T2, T3, T4, T5>.F1(T1)""
IL_000b: ldarg.1
IL_000c: unbox.any ""T2""
IL_0011: call ""void C<T1, T2, T3, T4, T5>.F2(T2)""
IL_0016: ldarg.2
IL_0017: box ""T3""
IL_001c: castclass ""I""
IL_0021: call ""void C<T1, T2, T3, T4, T5>.F3(I)""
IL_0026: ldarg.3
IL_0027: box ""T4""
IL_002c: unbox.any ""T5""
IL_0031: call ""void C<T1, T2, T3, T4, T5>.F5(T5)""
IL_0036: ret
}");
}
[Fact]
public void ImplicitUserDefinedConversion()
{
var source =
@"class C0 { }
class C1
{
public static implicit operator C0(C1 o) { return null; }
}
class C2 { }
class C3<T>
{
public static implicit operator T(C3<T> t) { return default(T); }
}
class C4<T> { }
class C
{
// Implicit conversion from type parameter (success).
static C0 F1<T>(T t) where T : C1 { return t; }
// Implicit conversion from type parameter (error).
static C0 F2<T>(T t) where T : C2 { return t; }
// Implicit conversion to type parameter (success).
static T F3<T>(C3<T> c) { return c; }
// Implicit conversion to type parameter (error).
static T F4<T>(C4<T> c) { return c; }
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (17,48): error CS0029: Cannot implicitly convert type 'T' to 'C0'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "C0").WithLocation(17, 48),
// (21,38): error CS0029: Cannot implicitly convert type 'C4<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c").WithArguments("C4<T>", "T").WithLocation(21, 38));
}
[Fact]
public void ExplicitUserDefinedConversion()
{
var source =
@"class C0 { }
class C1
{
public static explicit operator C0(C1 o) { return null; }
}
class C2 { }
class C3<T>
{
public static explicit operator T(C3<T> t) { return default(T); }
}
class C4<T> { }
class C
{
// Explicit conversion from type parameter (success).
static C0 F1<T>(T t) where T : C1 { return (C0)t; }
// Explicit conversion from type parameter (error).
static C0 F2<T>(T t) where T : C2 { return (C0)t; }
// Explicit conversion to type parameter (success).
static T F3<T>(C3<T> c) { return (T)c; }
// Explicit conversion to type parameter (error).
static T F4<T>(C4<T> c) { return (T)c; }
}";
// Note: Dev10 also reports "CS0030: Cannot convert type 'T' to 'C0'" in F1<T>(T),
// although there is an explicit conversion from C1 to C0.
CreateStandardCompilation(source).VerifyDiagnostics(
// (17,48): error CS0030: Cannot convert type 'T' to 'C0'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C0)t").WithArguments("T", "C0").WithLocation(17, 48),
// (21,38): error CS0030: Cannot convert type 'C4<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)c").WithArguments("C4<T>", "T").WithLocation(21, 38));
}
/// <summary>
/// Dev10 does not report errors for implicit or explicit conversions between
/// base and derived types if one of those types is a type parameter.
/// </summary>
[Fact]
public void UserDefinedConversionsBaseToFromDerived()
{
var source =
@"class A { }
class B1 : A
{
public static implicit operator A(B1 b) { return null; }
}
class B2 : A
{
public static explicit operator A(B2 b) { return null; }
}
class B3 : A
{
public static implicit operator B3(A a) { return null; }
}
class B4 : A
{
public static explicit operator B4(A a) { return null; }
}
class C1<T> where T : C1<T>
{
public static implicit operator C1<T>(T t) { return null; }
}
class C2<T> where T : C2<T>
{
public static explicit operator C2<T>(T t) { return null; }
}
class C3<T> where T : C3<T>
{
public static implicit operator T(C3<T> c) { return null; }
}
class C4<T> where T : C4<T>
{
public static explicit operator T(C4<T> c) { return null; }
}";
CreateStandardCompilation(source).VerifyDiagnostics(
// (4,37): error CS0553: 'B1.implicit operator A(B1)': user-defined conversions to or from a base class are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "A").WithArguments("B1.implicit operator A(B1)").WithLocation(4, 37),
// (8,37): error CS0553: 'B2.explicit operator A(B2)': user-defined conversions to or from a base class are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "A").WithArguments("B2.explicit operator A(B2)").WithLocation(8, 37),
// (12,37): error CS0553: 'B3.implicit operator B3(A)': user-defined conversions to or from a base class are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "B3").WithArguments("B3.implicit operator B3(A)").WithLocation(12, 37),
// (16,37): error CS0553: 'B4.explicit operator B4(A)': user-defined conversions to or from a base class are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "B4").WithArguments("B4.explicit operator B4(A)").WithLocation(16, 37));
}
}
}
| |
//
// System.Net.ChunkStream
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace Reactor.Net
{
class ChunkStream
{
enum State
{
None,
Body,
BodyFinished,
Trailer
}
class Chunk
{
public byte[] Bytes;
public int Offset;
public Chunk(byte[] chunk)
{
this.Bytes = chunk;
}
public int Read(byte[] buffer, int offset, int size)
{
int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
System.Buffer.BlockCopy(Bytes, Offset, buffer, offset, nread);
Offset += nread;
return nread;
}
}
internal WebHeaderCollection headers;
int chunkSize;
int chunkRead;
int totalWritten;
State state;
//byte [] waitBuffer;
StringBuilder saved;
bool sawCR;
bool gotit;
int trailerState;
ArrayList chunks;
public ChunkStream(byte[] buffer, int offset, int size, WebHeaderCollection headers) : this(headers)
{
Write(buffer, offset, size);
}
public ChunkStream(WebHeaderCollection headers)
{
this.headers = headers;
saved = new StringBuilder();
chunks = new ArrayList();
chunkSize = -1;
totalWritten = 0;
}
public void ResetBuffer()
{
chunkSize = -1;
chunkRead = 0;
totalWritten = 0;
chunks.Clear();
}
public void WriteAndReadBack(byte[] buffer, int offset, int size, ref int read)
{
if (offset + read > 0)
{
Write(buffer, offset, offset + read);
}
read = Read(buffer, offset, size);
}
public int Read(byte[] buffer, int offset, int size)
{
return ReadFromChunks(buffer, offset, size);
}
int ReadFromChunks(byte[] buffer, int offset, int size)
{
int count = chunks.Count;
int nread = 0;
for (int i = 0; i < count; i++)
{
Chunk chunk = (Chunk)chunks[i];
if (chunk == null)
{
continue;
}
if (chunk.Offset == chunk.Bytes.Length)
{
chunks[i] = null;
continue;
}
nread += chunk.Read(buffer, offset + nread, size - nread);
if (nread == size)
{
break;
}
}
return nread;
}
public void Write(byte[] buffer, int offset, int size)
{
if (offset < size)
{
InternalWrite(buffer, ref offset, size);
}
}
void InternalWrite(byte[] buffer, ref int offset, int size)
{
if (state == State.None)
{
state = GetChunkSize(buffer, ref offset, size);
if (state == State.None)
{
return;
}
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (state == State.Body && offset < size)
{
state = ReadBody(buffer, ref offset, size);
if (state == State.Body)
{
return;
}
}
if (state == State.BodyFinished && offset < size)
{
state = ReadCRLF(buffer, ref offset, size);
if (state == State.BodyFinished)
{
return;
}
sawCR = false;
}
if (state == State.Trailer && offset < size)
{
state = ReadTrailer(buffer, ref offset, size);
if (state == State.Trailer)
{
return;
}
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (offset < size)
{
InternalWrite(buffer, ref offset, size);
}
}
public bool WantMore
{
get
{
return (chunkRead != chunkSize || chunkSize != 0 || state != State.None);
}
}
public bool DataAvailable
{
get
{
int count = chunks.Count;
for (int i = 0; i < count; i++)
{
Chunk ch = (Chunk)chunks[i];
if (ch == null || ch.Bytes == null)
{
continue;
}
if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
{
return (state != State.Body);
}
}
return false;
}
}
public int TotalDataSize
{
get
{
return totalWritten;
}
}
public int ChunkLeft
{
get
{
return chunkSize - chunkRead;
}
}
State ReadBody(byte[] buffer, ref int offset, int size)
{
if (chunkSize == 0)
{
return State.BodyFinished;
}
int diff = size - offset;
if (diff + chunkRead > chunkSize)
{
diff = chunkSize - chunkRead;
}
byte[] chunk = new byte[diff];
System.Buffer.BlockCopy(buffer, offset, chunk, 0, diff);
chunks.Add(new Chunk(chunk));
offset += diff;
chunkRead += diff;
totalWritten += diff;
return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
}
State GetChunkSize(byte[] buffer, ref int offset, int size)
{
chunkRead = 0;
chunkSize = 0;
char c = '\0';
while (offset < size)
{
c = (char)buffer[offset++];
if (c == '\r')
{
if (sawCR)
{
ThrowProtocolViolation("2 CR found");
}
sawCR = true;
continue;
}
if (sawCR && c == '\n')
{
break;
}
if (c == ' ')
{
gotit = true;
}
if (!gotit)
{
saved.Append(c);
}
if (saved.Length > 20)
{
ThrowProtocolViolation("chunk size too long.");
}
}
if (!sawCR || c != '\n')
{
if (offset < size)
{
ThrowProtocolViolation("Missing \\n");
}
try
{
if (saved.Length > 0)
{
chunkSize = Int32.Parse(RemoveChunkExtension(saved.ToString()), NumberStyles.HexNumber);
}
}
catch (Exception)
{
ThrowProtocolViolation("Cannot parse chunk size.");
}
return State.None;
}
chunkRead = 0;
try
{
chunkSize = Int32.Parse(RemoveChunkExtension(saved.ToString()), NumberStyles.HexNumber);
}
catch (Exception)
{
ThrowProtocolViolation("Cannot parse chunk size.");
}
if (chunkSize == 0)
{
trailerState = 2;
return State.Trailer;
}
return State.Body;
}
static string RemoveChunkExtension(string input)
{
int idx = input.IndexOf(';');
if (idx == -1)
{
return input;
}
return input.Substring(0, idx);
}
State ReadCRLF(byte[] buffer, ref int offset, int size)
{
if (!sawCR)
{
if ((char)buffer[offset++] != '\r')
{
ThrowProtocolViolation("Expecting \\r");
}
sawCR = true;
if (offset == size)
{
return State.BodyFinished;
}
}
if (sawCR && (char)buffer[offset++] != '\n')
{
ThrowProtocolViolation("Expecting \\n");
}
return State.None;
}
State ReadTrailer(byte[] buffer, ref int offset, int size)
{
char c = '\0';
// short path
if (trailerState == 2 && (char)buffer[offset] == '\r' && saved.Length == 0)
{
offset++;
if (offset < size && (char)buffer[offset] == '\n')
{
offset++;
return State.None;
}
offset--;
}
int st = trailerState;
string stString = "\r\n\r";
while (offset < size && st < 4)
{
c = (char)buffer[offset++];
if ((st == 0 || st == 2) && c == '\r')
{
st++;
continue;
}
if ((st == 1 || st == 3) && c == '\n')
{
st++;
continue;
}
if (st > 0)
{
saved.Append(stString.Substring(0, saved.Length == 0 ? st - 2 : st));
st = 0;
if (saved.Length > 4196)
{
ThrowProtocolViolation("Error reading trailer (too long).");
}
}
}
if (st < 4)
{
trailerState = st;
if (offset < size)
{
ThrowProtocolViolation("Error reading trailer.");
}
return State.Trailer;
}
StringReader reader = new StringReader(saved.ToString());
string line;
while ((line = reader.ReadLine()) != null && line != "")
{
headers.Add(line);
}
return State.None;
}
static void ThrowProtocolViolation(string message)
{
WebException we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null);
throw we;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphAssembly.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Pattern;
using Akka.Streams.Stage;
using static Akka.Streams.Implementation.Fusing.GraphInterpreter;
namespace Akka.Streams.Implementation.Fusing
{
/// <summary>
/// INTERNAL API
///
/// A GraphAssembly represents a small stream processing graph to be executed by the interpreter. Instances of this
/// class **must not** be mutated after construction.
///
/// The array <see cref="OriginalAttributes"/> may contain the attribute information of the original atomic module, otherwise
/// it must contain a none (otherwise the enclosing module could not overwrite attributes defined in this array).
///
/// The arrays <see cref="Inlets"/> and <see cref="Outlets"/> correspond to the notion of a *connection* in the <see cref="GraphInterpreter"/>. Each slot
/// *i* contains the input and output port corresponding to connection *i*. Slots where the graph is not closed (i.e.
/// ports are exposed to the external world) are marked with null values. For example if an input port p is
/// exposed, then Outlets[p] will contain a null.
///
/// The arrays <see cref="InletOwners"/> and <see cref="OutletOwners"/> are lookup tables from a connection id(the index of the slot)
/// to a slot in the <see cref="Stages"/> array, indicating which stage is the owner of the given input or output port.
///
/// Slots which would correspond to non-existent stages(where the corresponding port is null since it represents
/// the currently unknown external context) contain the value <see cref="GraphInterpreter.Boundary"/>.
///
///The current assumption by the infrastructure is that the layout of these arrays looks like this:
///
/// +---------------------------------------+-----------------+
/// inOwners: | index to stages array | Boundary(-1) |
/// +----------------+----------------------+-----------------+
/// ins: | exposed inputs | internal connections | nulls |
/// +----------------+----------------------+-----------------+
/// outs: | nulls | internal connections | exposed outputs |
/// +----------------+----------------------+-----------------+
/// outOwners: | Boundary(-1) | index to stages array |
/// +----------------+----------------------------------------+
///
/// In addition, it is also assumed by the infrastructure that the order of exposed inputs and outputs in the
/// corresponding segments of these arrays matches the exact same order of the ports in the <see cref="Shape"/>.
/// </summary>
public sealed class GraphAssembly
{
public static GraphAssembly Create(IList<Inlet> inlets, IList<Outlet> outlets, IList<IGraphStageWithMaterializedValue<Shape, object>> stages)
{
// add the contents of an iterator to an array starting at idx
var inletsCount = inlets.Count;
var outletsCount = outlets.Count;
var connectionsCount = inletsCount + outletsCount;
if (connectionsCount <= 0) throw new ArgumentException($"Sum of inlets ({inletsCount}) and outlets ({outletsCount}) must be > 0");
return new GraphAssembly(
stages: stages.ToArray(),
originalAttributes: SingleNoAttribute,
inlets: Add(inlets, new Inlet[connectionsCount], 0),
inletOwners: MarkBoundary(new int[connectionsCount], inletsCount, connectionsCount),
outlets: Add(outlets, new Outlet[connectionsCount], inletsCount),
outletOwners: MarkBoundary(new int[connectionsCount], 0, inletsCount));
}
private static int[] MarkBoundary(int[] owners, int from, int to)
{
for (var i = from; i < to; i++)
owners[i] = Boundary;
return owners;
}
private static T[] Add<T>(IList<T> seq, T[] array, int idx)
{
foreach (var t in seq)
array[idx++] = t;
return array;
}
public readonly IGraphStageWithMaterializedValue<Shape, object>[] Stages;
public readonly Attributes[] OriginalAttributes;
public readonly Inlet[] Inlets;
public readonly int[] InletOwners;
public readonly Outlet[] Outlets;
public readonly int[] OutletOwners;
public GraphAssembly(IGraphStageWithMaterializedValue<Shape, object>[] stages, Attributes[] originalAttributes, Inlet[] inlets, int[] inletOwners, Outlet[] outlets, int[] outletOwners)
{
if (inlets.Length != inletOwners.Length)
throw new ArgumentException("'inlets' and 'inletOwners' must have the same length.", nameof(inletOwners));
if (inletOwners.Length != outlets.Length)
throw new ArgumentException("'inletOwners' and 'outlets' must have the same length.", nameof(outlets));
if (outlets.Length != outletOwners.Length)
throw new ArgumentException("'outlets' and 'outletOwners' must have the same length.", nameof(outletOwners));
Stages = stages;
OriginalAttributes = originalAttributes;
Inlets = inlets;
InletOwners = inletOwners;
Outlets = outlets;
OutletOwners = outletOwners;
}
public int ConnectionCount => Inlets.Length;
/// <summary>
/// Takes an interpreter and returns three arrays required by the interpreter containing the input, output port
/// handlers and the stage logic instances.
///
/// <para>Returns a tuple of</para>
/// <para/> - lookup table for InHandlers
/// <para/> - lookup table for OutHandlers
/// <para/> - array of the logics
/// <para/> - materialized value
/// </summary>
public Tuple<Connection[], GraphStageLogic[]> Materialize(
Attributes inheritedAttributes,
IModule[] copiedModules,
IDictionary<IModule, object> materializedValues,
Action<IMaterializedValueSource> register)
{
var logics = new GraphStageLogic[Stages.Length];
for (var i = 0; i < Stages.Length; i++)
{
// Port initialization loops, these must come first
var shape = Stages[i].Shape;
var idx = 0;
var inletEnumerator = shape.Inlets.GetEnumerator();
while (inletEnumerator.MoveNext())
{
var inlet = inletEnumerator.Current;
if (inlet.Id != -1 && inlet.Id != idx)
throw new ArgumentException($"Inlet {inlet} was shared among multiple stages. That is illegal.");
inlet.Id = idx;
idx++;
}
idx = 0;
var outletEnumerator = shape.Outlets.GetEnumerator();
while (outletEnumerator.MoveNext())
{
var outlet = outletEnumerator.Current;
if (outlet.Id != -1 && outlet.Id != idx)
throw new ArgumentException($"Outlet {outlet} was shared among multiple stages. That is illegal.");
outlet.Id = idx;
idx++;
}
var stage = Stages[i];
if (stage is IMaterializedValueSource)
{
var copy = ((IMaterializedValueSource) stage).CopySource();
register(copy);
stage = (IGraphStageWithMaterializedValue<Shape, object>)copy;
}
var logicAndMaterialized = stage.CreateLogicAndMaterializedValue(inheritedAttributes.And(OriginalAttributes[i]));
materializedValues[copiedModules[i]] = logicAndMaterialized.MaterializedValue;
logics[i] = logicAndMaterialized.Logic;
}
var connections = new Connection[ConnectionCount];
for (var i = 0; i < ConnectionCount; i++)
{
var connection = new Connection(i, InletOwners[i],
InletOwners[i] == Boundary ? null : logics[InletOwners[i]], OutletOwners[i],
OutletOwners[i] == Boundary ? null : logics[OutletOwners[i]], null, null);
connections[i] = connection;
var inlet = Inlets[i];
if (inlet != null)
{
var owner = InletOwners[i];
var logic = logics[owner];
var h = logic.Handlers[inlet.Id] as IInHandler;
if (h == null) throw new IllegalStateException($"No handler defined in stage {logic} for port {inlet}");
connection.InHandler = h;
logic.PortToConn[inlet.Id] = connection;
}
var outlet = Outlets[i];
if (outlet != null)
{
var owner = OutletOwners[i];
var logic = logics[owner];
var inCount = logic.InCount;
var h = logic.Handlers[outlet.Id + inCount] as IOutHandler;
if (h == null) throw new IllegalStateException($"No handler defined in stage {logic} for port {outlet}");
connection.OutHandler = h;
logic.PortToConn[outlet.Id + inCount] = connection;
}
}
return Tuple.Create(connections, logics);
}
public override string ToString()
{
return "GraphAssembly\n " +
"Stages: [" + string.Join<IGraphStageWithMaterializedValue<Shape, object>>(",", Stages) + "]\n " +
"Attributes: [" + string.Join<Attributes>(",", OriginalAttributes) + "]\n " +
"Inlets: [" + string.Join<Inlet>(",", Inlets) + "]\n " +
"InOwners: [" + string.Join(",", InletOwners) + "]\n " +
"Outlets: [" + string.Join<Outlet>(",", Outlets) + "]\n " +
"OutOwners: [" + string.Join(",", OutletOwners) + "]";
}
}
}
| |
/*
* 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.Text;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mono.Addins;
using Mono.Addins.Setup;
using Mono.Addins.Description;
using OpenSim.Framework;
namespace OpenSim.Framework
{
/// <summary>
/// Manager for registries and plugins
/// </summary>
public class PluginManager : SetupService
{
public AddinRegistry PluginRegistry;
public PluginManager(AddinRegistry registry): base (registry)
{
PluginRegistry = registry;
}
/// <summary>
/// Installs the plugin.
/// </summary>
/// <returns>
/// The plugin.
/// </returns>
/// <param name='args'>
/// Arguments.
/// </param>
public bool InstallPlugin(int ndx, out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
PackageCollection pack = new PackageCollection();
PackageCollection toUninstall;
DependencyCollection unresolved;
IProgressStatus ps = new ConsoleProgressStatus(false);
AddinRepositoryEntry[] available = GetSortedAvailbleAddins();
if (ndx > (available.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
result = res;
return false;
}
AddinRepositoryEntry aentry = available[ndx];
Package p = Package.FromRepository(aentry);
pack.Add(p);
ResolveDependencies(ps, pack, out toUninstall, out unresolved);
// Attempt to install the plugin disabled
if (Install(ps, pack) == true)
{
MainConsole.Instance.Output("Ignore the following error...");
PluginRegistry.Update(ps);
Addin addin = PluginRegistry.GetAddin(aentry.Addin.Id);
PluginRegistry.DisableAddin(addin.Id);
addin.Enabled = false;
MainConsole.Instance.Output("Installation Success");
ListInstalledAddins(out res);
result = res;
return true;
}
else
{
MainConsole.Instance.Output("Installation Failed");
result = res;
return false;
}
}
// Remove plugin
/// <summary>
/// Uns the install.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void UnInstall(int ndx)
{
Addin[] addins = GetSortedAddinList("RobustPlugin");
if (ndx > (addins.Length -1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
Addin addin = addins[ndx];
MainConsole.Instance.OutputFormat("Uninstalling plugin {0}", addin.Id);
AddinManager.Registry.DisableAddin(addin.Id);
addin.Enabled = false;
IProgressStatus ps = new ConsoleProgressStatus(false);
Uninstall(ps, addin.Id);
MainConsole.Instance.Output("Uninstall Success - restart to complete operation");
return;
}
/// <summary>
/// Checks the installed.
/// </summary>
/// <returns>
/// The installed.
/// </returns>
public string CheckInstalled()
{
return "CheckInstall";
}
/// <summary>
/// Lists the installed addins.
/// </summary>
/// <param name='result'>
/// Result.
/// </param>
public void ListInstalledAddins(out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
Addin[] addins = GetSortedAddinList("RobustPlugin");
if(addins.Count() < 1)
{
MainConsole.Instance.Output("Error!");
}
int count = 0;
foreach (Addin addin in addins)
{
Dictionary<string, object> r = new Dictionary<string, object>();
r["enabled"] = addin.Enabled == true ? true : false;
r["name"] = addin.LocalId;
r["version"] = addin.Version;
res.Add(count.ToString(), r);
count++;
}
result = res;
return;
}
// List compatible plugins in registered repositories
/// <summary>
/// Lists the available.
/// </summary>
/// <param name='result'>
/// Result.
/// </param>
public void ListAvailable(out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
AddinRepositoryEntry[] addins = GetSortedAvailbleAddins();
int count = 0;
foreach (AddinRepositoryEntry addin in addins)
{
Dictionary<string, object> r = new Dictionary<string, object>();
r["name"] = addin.Addin.Name;
r["version"] = addin.Addin.Version;
r["repository"] = addin.RepositoryName;
res.Add(count.ToString(), r);
count++;
}
result = res;
return;
}
// List available updates ** 1
/// <summary>
/// Lists the updates.
/// </summary>
public void ListUpdates()
{
IProgressStatus ps = new ConsoleProgressStatus(true);
Console.WriteLine ("Looking for updates...");
Repositories.UpdateAllRepositories (ps);
Console.WriteLine ("Available add-in updates:");
bool found = false;
AddinRepositoryEntry[] entries = Repositories.GetAvailableUpdates();
foreach (AddinRepositoryEntry entry in entries)
{
Console.WriteLine(String.Format("{0}",entry.Addin.Id));
}
}
// Sync to repositories
/// <summary>
/// Update this instance.
/// </summary>
public string Update()
{
IProgressStatus ps = new ConsoleProgressStatus(true);
Repositories.UpdateAllRepositories(ps);
return "Update";
}
// Register a repository
/// <summary>
/// Register a repository with our server.
/// </summary>
/// <returns>
/// result of the action
/// </returns>
/// <param name='repo'>
/// The URL of the repository we want to add
/// </param>
public bool AddRepository(string repo)
{
Repositories.RegisterRepository(null, repo, true);
PluginRegistry.Rebuild(null);
return true;
}
/// <summary>
/// Gets the repository.
/// </summary>
public void GetRepository()
{
Repositories.UpdateAllRepositories(new ConsoleProgressStatus(false));
}
// Remove a repository from the list
/// <summary>
/// Removes the repository.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void RemoveRepository(string[] args)
{
AddinRepository[] reps = Repositories.GetRepositories();
Array.Sort(reps, (r1,r2) => r1.Title.CompareTo(r2.Title));
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int n = Convert.ToInt16(args[2]);
if (n > (reps.Length -1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
AddinRepository rep = reps[n];
Repositories.RemoveRepository(rep.Url);
return;
}
// Enable repository
/// <summary>
/// Enables the repository.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void EnableRepository(string[] args)
{
AddinRepository[] reps = Repositories.GetRepositories();
Array.Sort(reps, (r1,r2) => r1.Title.CompareTo(r2.Title));
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int n = Convert.ToInt16(args[2]);
if (n > (reps.Length -1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
AddinRepository rep = reps[n];
Repositories.SetRepositoryEnabled(rep.Url, true);
return;
}
// Disable a repository
/// <summary>
/// Disables the repository.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void DisableRepository(string[] args)
{
AddinRepository[] reps = Repositories.GetRepositories();
Array.Sort(reps, (r1,r2) => r1.Title.CompareTo(r2.Title));
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int n = Convert.ToInt16(args[2]);
if (n > (reps.Length -1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
AddinRepository rep = reps[n];
Repositories.SetRepositoryEnabled(rep.Url, false);
return;
}
// List registered repositories
/// <summary>
/// Lists the repositories.
/// </summary>
/// <param name='result'>
/// Result.
/// </param>
public void ListRepositories(out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
result = res;
AddinRepository[] reps = GetSortedAddinRepo();
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int count = 0;
foreach (AddinRepository rep in reps)
{
Dictionary<string, object> r = new Dictionary<string, object>();
r["enabled"] = rep.Enabled == true ? true : false;
r["name"] = rep.Name;
r["url"] = rep.Url;
res.Add(count.ToString(), r);
count++;
}
return;
}
/// <summary>
/// Updates the registry.
/// </summary>
public void UpdateRegistry()
{
PluginRegistry.Update();
}
// Show plugin info
/// <summary>
/// Addins the info.
/// </summary>
/// <returns>
/// The info.
/// </returns>
/// <param name='args'>
/// Arguments.
/// </param>
public bool AddinInfo(int ndx, out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
result = res;
Addin[] addins = GetSortedAddinList("RobustPlugin");
if (ndx > (addins.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return false;
}
// author category description
Addin addin = addins[ndx];
res["author"] = addin.Description.Author;
res["category"] = addin.Description.Category;
res["description"] = addin.Description.Description;
res["name"] = addin.Name;
res["url"] = addin.Description.Url;
res["file_name"] = addin.Description.FileName;
result = res;
return true;
}
// Disable a plugin
/// <summary>
/// Disables the plugin.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void DisablePlugin(string[] args)
{
Addin[] addins = GetSortedAddinList("RobustPlugin");
int n = Convert.ToInt16(args[2]);
if (n > (addins.Length -1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
Addin addin = addins[n];
AddinManager.Registry.DisableAddin(addin.Id);
addin.Enabled = false;
return;
}
// Enable plugin
/// <summary>
/// Enables the plugin.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void EnablePlugin(string[] args)
{
Addin[] addins = GetSortedAddinList("RobustPlugin");
int n = Convert.ToInt16(args[2]);
if (n > (addins.Length -1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
Addin addin = addins[n];
addin.Enabled = true;
AddinManager.Registry.EnableAddin(addin.Id);
// AddinManager.Registry.Update();
if(PluginRegistry.IsAddinEnabled(addin.Id))
{
ConsoleProgressStatus ps = new ConsoleProgressStatus(false);
if (!AddinManager.AddinEngine.IsAddinLoaded(addin.Id))
{
MainConsole.Instance.Output("Ignore the following error...");
AddinManager.Registry.Rebuild(ps);
AddinManager.AddinEngine.LoadAddin(ps, addin.Id);
}
}
else
{
MainConsole.Instance.OutputFormat("Not Enabled in this domain {0}", addin.Name);
}
return;
}
#region Util
private void Testing()
{
Addin[] list = Registry.GetAddins();
var addins = list.Where( a => a.Description.Category == "RobustPlugin");
foreach (Addin addin in addins)
{
MainConsole.Instance.OutputFormat("Addin {0}", addin.Name);
}
}
// These will let us deal with numbered lists instead
// of needing to type in the full ids
private AddinRepositoryEntry[] GetSortedAvailbleAddins()
{
ArrayList list = new ArrayList();
list.AddRange(Repositories.GetAvailableAddins());
AddinRepositoryEntry[] addins = list.ToArray(typeof(AddinRepositoryEntry)) as AddinRepositoryEntry[];
Array.Sort(addins,(r1,r2) => r1.Addin.Id.CompareTo(r2.Addin.Id));
return addins;
}
private AddinRepository[] GetSortedAddinRepo()
{
ArrayList list = new ArrayList();
list.AddRange(Repositories.GetRepositories());
AddinRepository[] repos = list.ToArray(typeof(AddinRepository)) as AddinRepository[];
Array.Sort (repos,(r1,r2) => r1.Name.CompareTo(r2.Name));
return repos;
}
private Addin[] GetSortedAddinList(string category)
{
ArrayList xlist = new ArrayList();
ArrayList list = new ArrayList();
try
{
list.AddRange(PluginRegistry.GetAddins());
}
catch(Exception e)
{
Addin[] x = xlist.ToArray(typeof(Addin)) as Addin[];
return x;
}
foreach (Addin addin in list)
{
if (addin.Description.Category == category)
xlist.Add(addin);
}
Addin[] addins = xlist.ToArray(typeof(Addin)) as Addin[];
Array.Sort(addins,(r1,r2) => r1.Id.CompareTo(r2.Id));
return addins;
}
#endregion Util
}
}
| |
using ModestTree;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Zenject
{
public static class TypeAnalyzer
{
static Dictionary<Type, ZenjectTypeInfo> _typeInfo = new Dictionary<Type, ZenjectTypeInfo>();
public static ZenjectTypeInfo GetInfo<T>()
{
return GetInfo(typeof(T));
}
public static ZenjectTypeInfo GetInfo(Type type)
{
#if UNITY_EDITOR && ZEN_PROFILING_ENABLED
using (ProfileBlock.Start("Zenject Reflection"))
#endif
{
Assert.That(!type.IsAbstract(),
"Tried to analyze abstract type '{0}'. This is not currently allowed.", type);
ZenjectTypeInfo info;
#if ZEN_MULTITHREADING
lock (_typeInfo)
#endif
{
if (!_typeInfo.TryGetValue(type, out info))
{
info = CreateTypeInfo(type);
_typeInfo.Add(type, info);
}
}
return info;
}
}
static ZenjectTypeInfo CreateTypeInfo(Type type)
{
var constructor = GetInjectConstructor(type);
return new ZenjectTypeInfo(
type,
GetPostInjectMethods(type),
constructor,
GetFieldInjectables(type).ToList(),
GetPropertyInjectables(type).ToList(),
GetConstructorInjectables(type, constructor).ToList());
}
static IEnumerable<InjectableInfo> GetConstructorInjectables(Type parentType, ConstructorInfo constructorInfo)
{
if (constructorInfo == null)
{
return Enumerable.Empty<InjectableInfo>();
}
return constructorInfo.GetParameters().Select(
paramInfo => CreateInjectableInfoForParam(parentType, paramInfo));
}
static InjectableInfo CreateInjectableInfoForParam(
Type parentType, ParameterInfo paramInfo)
{
var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType);
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault;
return new InjectableInfo(
isOptionalWithADefaultValue || isOptional,
identifier,
paramInfo.Name,
paramInfo.ParameterType,
parentType,
null,
isOptionalWithADefaultValue ? paramInfo.DefaultValue : null,
sourceType);
}
static List<PostInjectableInfo> GetPostInjectMethods(Type type)
{
// Note that unlike with fields and properties we use GetCustomAttributes
// This is so that we can ignore inherited attributes, which is necessary
// otherwise a base class method marked with [Inject] would cause all overridden
// derived methods to be added as well
var methods = type.GetAllInstanceMethods()
.Where(x => x.GetCustomAttributes(typeof(InjectAttribute), false).Any()).ToList();
var heirarchyList = type.Yield().Concat(type.GetParentTypes()).Reverse().ToList();
// Order by base classes first
// This is how constructors work so it makes more sense
var values = methods.OrderBy(x => heirarchyList.IndexOf(x.DeclaringType));
var postInjectInfos = new List<PostInjectableInfo>();
foreach (var methodInfo in values)
{
var paramsInfo = methodInfo.GetParameters();
var injectAttr = methodInfo.AllAttributes<InjectAttribute>().Single();
Assert.That(!injectAttr.Optional && injectAttr.Id == null && injectAttr.Source == InjectSources.Any,
"Parameters of InjectAttribute do not apply to constructors and methods");
postInjectInfos.Add(
new PostInjectableInfo(
methodInfo,
paramsInfo.Select(paramInfo =>
CreateInjectableInfoForParam(type, paramInfo)).ToList()));
}
return postInjectInfos;
}
static IEnumerable<InjectableInfo> GetPropertyInjectables(Type type)
{
var propInfos = type.GetAllInstanceProperties()
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var propInfo in propInfos)
{
yield return CreateForMember(propInfo, type);
}
}
static IEnumerable<InjectableInfo> GetFieldInjectables(Type type)
{
var fieldInfos = type.GetAllInstanceFields()
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var fieldInfo in fieldInfos)
{
yield return CreateForMember(fieldInfo, type);
}
}
#if !(UNITY_WSA && ENABLE_DOTNET) || UNITY_EDITOR
private static IEnumerable<FieldInfo> GetAllFields(Type t, BindingFlags flags)
{
if (t == null)
{
return Enumerable.Empty<FieldInfo>();
}
return t.GetFields(flags).Concat(GetAllFields(t.BaseType, flags)).Distinct();
}
private static Action<object, object> GetOnlyPropertySetter(
Type parentType,
string propertyName)
{
Assert.That(parentType != null);
Assert.That(!string.IsNullOrEmpty(propertyName));
var allFields = GetAllFields(
parentType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).ToList();
var writeableFields = allFields.Where(f => f.Name == string.Format("<{0}>k__BackingField", propertyName)).ToList();
if (!writeableFields.Any())
{
throw new ZenjectException(string.Format(
"Can't find backing field for get only property {0} on {1}.\r\n{2}",
propertyName, parentType.FullName, string.Join(";", allFields.Select(f => f.Name).ToArray())));
}
return (injectable, value) => writeableFields.ForEach(f => f.SetValue(injectable, value));
}
#endif
static InjectableInfo CreateForMember(MemberInfo memInfo, Type parentType)
{
var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType);
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
Type memberType;
Action<object, object> setter;
if (memInfo is FieldInfo)
{
var fieldInfo = (FieldInfo)memInfo;
setter = ((object injectable, object value) => fieldInfo.SetValue(injectable, value));
memberType = fieldInfo.FieldType;
}
else
{
Assert.That(memInfo is PropertyInfo);
var propInfo = (PropertyInfo)memInfo;
memberType = propInfo.PropertyType;
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null));
#else
if (propInfo.CanWrite)
{
setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null));
}
else
{
setter = GetOnlyPropertySetter(parentType, propInfo.Name);
}
#endif
}
return new InjectableInfo(
isOptional,
identifier,
memInfo.Name,
memberType,
parentType,
setter,
null,
sourceType);
}
static ConstructorInfo GetInjectConstructor(Type parentType)
{
var constructors = parentType.Constructors();
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
// WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy))
// So just ignore that
constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray();
#endif
if (constructors.IsEmpty())
{
return null;
}
if (constructors.HasMoreThan(1))
{
var explicitConstructor = (from c in constructors where c.HasAttribute<InjectAttribute>() select c).SingleOrDefault();
if (explicitConstructor != null)
{
return explicitConstructor;
}
// If there is only one public constructor then use that
// This makes decent sense but is also necessary on WSA sometimes since the WSA generated
// constructor can sometimes be private with zero parameters
var singlePublicConstructor = constructors.Where(x => !x.IsPrivate).OnlyOrDefault();
if (singlePublicConstructor != null)
{
return singlePublicConstructor;
}
return null;
}
return constructors[0];
}
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
static bool IsWp8GeneratedConstructor(ConstructorInfo c)
{
ParameterInfo[] args = c.GetParameters();
if (args.Length == 1)
{
return args[0].ParameterType == typeof(UIntPtr)
&& (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy");
}
if (args.Length == 2)
{
return args[0].ParameterType == typeof(UIntPtr)
&& args[1].ParameterType == typeof(Int64*)
&& (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy")
&& (string.IsNullOrEmpty(args[1].Name) || args[1].Name == "dummy");
}
return false;
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using WO.Core;
using WOEmu.Packets;
using WOEmu.Misc;
using System.Text;
using System.Security.Cryptography;
//THIS HANDLER NEEDS CLEANING!!
//E.G. : SKILLS NEED BETTER HANDLING
namespace WOEmu.PacketHandlers
{
public static class LoginHandler
{
public static bool Read(Client c, byte[] Packet)
{
#region Packet
PacketReader _reader = new PacketReader(Packet);
_reader.PopByte(); //ID
int magic = _reader.PopInt(); //should be 0xC24FE373 is C22FE3
//real: 0xC2, 0x2F, 0xE3, 0x73, some version change!? :)
byte len = _reader.PopByte();
byte[] UserBuf = new byte[len];
UserBuf = _reader.PopBytes(len);
byte plen = _reader.PopByte();
byte[] PassBuf = new byte[plen];
PassBuf = _reader.PopBytes(plen);
byte zero = _reader.PopByte();
string username = Encoding.ASCII.GetString(UserBuf);
string password = Encoding.ASCII.GetString(PassBuf);
SHA1CryptoServiceProvider sha1Provider = new SHA1CryptoServiceProvider();
string hash = BitConverter.ToString(sha1Provider.ComputeHash(PassBuf)).Replace("-", "");
#endregion
WO.Core.Logger.Logger.printInfo("Client '" + username + "' logging in.");
c.player.Name = username;
Sql query = new Sql(Program.sqlData);
query.ExecuteQuery("SELECT ID FROM accounts WHERE User LIKE '" + c.player.Name + "'");
query.reader.Read();
c.player.AccountID = query.reader.GetInt64(0);
//STUFF TO DO AFTER LOGIN...asdasdasasd
#region POST-LOGIN
Chat.SendTo(c, ":Event", "You will now fight defensively.");
PlayerStats.SetFightMode(c, 2);
PlayerStats.SetStance(c, "Playing WOEmu!");
PlayerStats.SetSpeed(c, 0.0f);
//Stub.
SendSkill.SendTo(c, 18L, 9223372028264841234, "Characteristics", 20.0f, 20.0f);
SendSkill.SendTo(c, 18L, 9223372015379939346, "Religion", 20.0f, 20.0f);
SendSkill.SendTo(c, 18L, 9223372032559808530, "Skills", 20.0f, 20.0f);
SendSkill.SendTo(c, 18L, 9223372006790004754, "Spell effects", 20.0f, 20.0f);
SendSkill.SendTo(c, 9223372028264841234L, 4294967314, "Body", 220.0f, 20.0f);
SendSkill.SendTo(c, 9223372028264841234L, 8589934610, "Mind", 20.0f, 20.0f);
SendSkill.SendTo(c, 9223372028264841234L, 12884901906, "Soul", 20.0f, 20.0f);
SendSkill.SendTo(c, 8589934610L, 429496729618, "Mind logic", 20.0f, 20.0f);
SendSkill.SendTo(c, 8589934610L, 433791696914, "Mind speed", 20.0f, 20.0f);
SendSkill.SendTo(c, 4294967314L, 438086664210, "Body strength", 20.0f, 20.0f);
SendSkill.SendTo(c, 4294967314L, 442381631506, "Body stamina", 20.0f, 20.0f);
SendSkill.SendTo(c, 4294967314L, 446676598802, "Body control", 20.0f, 20.0f);
SendSkill.SendTo(c, 12884901906L, 450971566098, "Soul strength", 20.0f, 20.0f);
SendSkill.SendTo(c, 12884901906L, 455266533394, "Soul depth", 20.0f, 20.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4294967296018, "Swords", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4299262263314, "Knives", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4303557230610, "Shields", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4307852197906, "Axes", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4312147165202, "Mauls", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4316442132498, "Carpentry", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4325032067090, "WoodCutting", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4329327034386, "Mining", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4333622001682, "Digging", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4337916968978, "Firemaking", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4342211936274, "Pottery", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4346506903570, "Tailoring", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4350801870866, "Masonry", 50000.0f, 60000.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4355096838162, "Ropemaking", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4359391805458, "Smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4359391805458L, 4363686772754, "Weapon smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4359391805458L, 4367981740050, "Armour smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4372276707346, "Cooking", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4376571674642, "Nature", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4380866641938, "Miscellaneous items", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4385161609234, "Alchemy", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4389456576530, "Toys", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4393751543826, "Fighting", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4398046511122, "Healing", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4402341478418, "Clubs", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4406636445714, "Religion", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4415226380306, "Thievery", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4419521347602, "War machines", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 4423816314898, "Archery", 1.0f, 1.0f);
SendSkill.SendTo(c, 4316442132498L, 4428111282194, "Bowyery", 1.0f, 1.0f);
SendSkill.SendTo(c, 4316442132498L, 4432406249490, "Fletching", 1.0f, 1.0f);
//
SendSkill.SendTo(c, 4307852197906L, 42953967927314, "SmallAxe", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 42958262894610, "Shovel", 1.0f, 1.0f);
SendSkill.SendTo(c, 4307852197906L, 42962557861906, "Hatchet", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 42966852829202, "Rake", 1.0f, 1.0f);//
SendSkill.SendTo(c, 4294967296018L, 42971147796498, "Longsword", 1.0f, 1.0f);
SendSkill.SendTo(c, 4303557230610L, 42975442763794, "Medium shield", 1.0f, 1.0f);
SendSkill.SendTo(c, 4299262263314L, 42979737731090, "Carving knife", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 42984032698386, "Saw", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 42988327665682, "Pickaxe", 1.0f, 1.0f);
SendSkill.SendTo(c, 4363686772754L, 42992622632978, "Blades smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4363686772754L, 42996917600274, "Weapon heads smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4367981740050L, 43001212567570, "Chain armour smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4367981740050L, 43005507534866, "Plate armour smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4367981740050L, 43009802502162, "Shield smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4359391805458L, 43014097469458, "Blacksmithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4346506903570L, 43018392436754, "Cloth tailoring", 1.0f, 1.0f);
SendSkill.SendTo(c, 4346506903570L, 43022687404050, "Leatherworking", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 43026982371346, "Tracking", 1.0f, 1.0f);
SendSkill.SendTo(c, 4303557230610L, 43035572305938, "Medium wooden shield", 1.0f, 1.0f);
SendSkill.SendTo(c, 4307852197906L, 43052752175122, "Large axe", 1.0f, 1.0f);
SendSkill.SendTo(c, 4307852197906L, 43057047142418, "Huge axe", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 43061342109714, "Hammer", 1.0f, 1.0f);
SendSkill.SendTo(c, 4294967296018L, 43065637077010, "Shortsword", 1.0f, 1.0f);
SendSkill.SendTo(c, 4294967296018L, 43069932044306, "Two handed sword", 1.0f, 1.0f);
SendSkill.SendTo(c, 4299262263314L, 43074227011602, "Butchering knife", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 43078521978898, "Stone chisel", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 43082816946194, "Paving", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 43087111913490, "Prospecting", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43091406880786, "Fishing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4359391805458L, 43095701848082, "Locksmithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 43099996815378, "Repairing", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 43104291782674, "Coal-making", 1.0f, 1.0f);
SendSkill.SendTo(c, 4372276707346L, 43108586749970, "Dairy food making", 1.0f, 1.0f);
SendSkill.SendTo(c, 4372276707346L, 43112881717266, "Hot food cooking", 1.0f, 1.0f);
SendSkill.SendTo(c, 4372276707346L, 43117176684562, "Baking", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 43121471651858, "Milling", 1.0f, 1.0f);
SendSkill.SendTo(c, 4359391805458L, 43125766619154, "Metallurgy", 1.0f, 1.0f);
SendSkill.SendTo(c, 4385161609234L, 43130061586450, "Natural substances", 1.0f, 1.0f);
SendSkill.SendTo(c, 4359391805458L, 43134356553746, "Jewelry smithing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4316442132498L, 43138651521042, "Fine carpentry", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43142946488338, "Gardening", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 43147241455634, "Sickle", 1.0f, 1.0f);
SendSkill.SendTo(c, 4380866641938L, 43151536422930, "Scythe", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43155831390226, "Forestry", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43160126357522, "Farming", 1.0f, 1.0f);
SendSkill.SendTo(c, 4389456576530L, 43164421324818, "Yoyo", 1.0f, 1.0f);
SendSkill.SendTo(c, 4393751543826L, 43173011259410, "Weaponless fighting", 1.0f, 1.0f);
SendSkill.SendTo(c, 4393751543826L, 43177306226706, "Aggressive fighting", 1.0f, 1.0f);
SendSkill.SendTo(c, 4393751543826L, 43181601194002, "Defensive fighting", 1.0f, 1.0f);
SendSkill.SendTo(c, 4393751543826L, 43185896161298, "Normal fighting", 1.0f, 1.0f);
SendSkill.SendTo(c, 4398046511122L, 43190191128594, "First aid", 1.0f, 1.0f);
SendSkill.SendTo(c, 4393751543826L, 43194486095890, "Taunting", 1.0f, 1.0f);
SendSkill.SendTo(c, 4393751543826L, 43198781063186, "Shield bashing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4372276707346L, 43203076030482, "Butchering", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43207370997778, "Milking", 1.0f, 1.0f);
SendSkill.SendTo(c, 4312147165202L, 43211665965074, "Large maul", 1.0f, 1.0f);
SendSkill.SendTo(c, 4312147165202L, 43215960932370, "Medium maul", 1.0f, 1.0f);
SendSkill.SendTo(c, 4402341478418L, 43224550866962, "Huge club", 1.0f, 1.0f);
SendSkill.SendTo(c, 4406636445714L, 43228845834258, "Preaching", 1.0f, 1.0f);
SendSkill.SendTo(c, 4406636445714L, 43233140801554, "Prayer", 1.0f, 1.0f);
SendSkill.SendTo(c, 4406636445714L, 43241730736146, "Exorcism", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43254615638034, "Foraging", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43258910605330, "Botanizing", 1.0f, 1.0f);
SendSkill.SendTo(c, 9223372032559808530L, 43263205572626, "Climbing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4350801870866L, 43267500539922, "Stone cutting", 1.0f, 1.0f);
SendSkill.SendTo(c, 4415226380306L, 43271795507218, "Stealing", 1.0f, 1.0f);
SendSkill.SendTo(c, 4415226380306L, 43276090474514, "Lock picking", 1.0f, 1.0f);
SendSkill.SendTo(c, 4419521347602L, 43280385441810, "Catapults", 1.0f, 1.0f);
SendSkill.SendTo(c, 4376571674642L, 43284680409106, "Animal taming", 1.0f, 1.0f);
SendSkill.SendTo(c, 4423816314898L, 43288975376402, "Short bow", 1.0f, 1.0f);
SendSkill.SendTo(c, 4423816314898L, 43293270343698, "Medium bow", 1.0f, 1.0f);
SendSkill.SendTo(c, 4423816314898L, 43297565310994, "Long bow", 1.0f, 1.0f);
SendSkill.SendTo(c, 4316442132498L, 43301860278290, "Ship building", 1.0f, 1.0f);
//Send MOTD to user:
BMLObject motd = new BMLObject("Motd.bml");
motd.Caption = "Message of the day";
motd.X = 300;
motd.Y = 300;
motd.Closable = true;
motd.Resizable = false;
GUI.SendBML(c, motd);
//Get stuff from database!
#region Database
Sql s = new Sql(Program.sqlData);
s.ExecuteQuery("SELECT * FROM accounts WHERE User = '" + username + "';");
if (!s.reader.HasRows)
{
WO.Core.Logger.Logger.printWarning("USER DOES NOT EXIST!");
return false;
}
while (s.reader.Read())
{
c.accountID = s.reader.GetInt64("ID");
c.Health = s.reader.GetInt16("health");
c.Stamina = s.reader.GetInt16("stamina");
c.Food = s.reader.GetInt16("food");
c.Water = s.reader.GetInt16("water");
c.Dev = (s.reader.GetInt16("Dev") == 1 ? true : false);
c.player.Position.X = s.reader.GetFloat("posX");
if (c.player.Position.X == 0)
c.player.Position.X = float.Parse(Program.configFile.GetValue("spawnX"));
c.player.Position.Y = s.reader.GetFloat("posY");
if (c.player.Position.Y == 0)
c.player.Position.Y = float.Parse(Program.configFile.GetValue("spawnY"));
c.player.Position.Z = s.reader.GetFloat("posZ");
if (c.player.Position.Z == 0)
c.player.Position.Z = float.Parse(Program.configFile.GetValue("spawnZ"));
}
s.Dispose();
#endregion
WOEmu.Packets.PlayerInformation.SendTo(c, c.player);
#endregion
return true;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ODataAsynchronousReader.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Core
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
#endregion Namespaces
/// <summary>
/// Class for reading OData async messages.
/// </summary>
public sealed class ODataAsynchronousReader
{
/// <summary>
/// The input context to read the content from.
/// </summary>
private readonly ODataRawInputContext rawInputContext;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="rawInputContext">The input context to read the content from.</param>
/// <param name="encoding">The encoding for the underlying stream.</param>
internal ODataAsynchronousReader(ODataRawInputContext rawInputContext, Encoding encoding)
{
Debug.Assert(rawInputContext != null, "rawInputContext != null");
// Currently we only support single-byte UTF8 in async reader.
if (encoding != null)
{
ReaderValidationUtils.ValidateEncodingSupportedInAsync(encoding);
}
this.rawInputContext = rawInputContext;
}
/// <summary>
/// Returns a message for reading the content of an async response.
/// </summary>
/// <returns>A response message for reading the content of the async response.</returns>
public ODataAsynchronousResponseMessage CreateResponseMessage()
{
this.VerifyCanCreateResponseMessage(true);
return this.CreateResponseMessageImplementation();
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously returns a message for reading the content of an async response.
/// </summary>
/// <returns>A response message for reading the content of the async response.</returns>
public Task<ODataAsynchronousResponseMessage> CreateResponseMessageAsync()
{
this.VerifyCanCreateResponseMessage(false);
return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateResponseMessageImplementation());
}
#endif
/// <summary>
/// Validates that the async reader is not disposed.
/// </summary>
private void ValidateReaderNotDisposed()
{
this.rawInputContext.VerifyNotDisposed();
}
/// <summary>
/// Verifies that a call is allowed to the reader.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCallAllowed(bool synchronousCall)
{
if (synchronousCall)
{
if (!this.rawInputContext.Synchronous)
{
throw new ODataException(Strings.ODataAsyncReader_SyncCallOnAsyncReader);
}
}
else
{
#if ODATALIB_ASYNC
if (this.rawInputContext.Synchronous)
{
throw new ODataException(Strings.ODataAsyncReader_AsyncCallOnSyncReader);
}
#else
Debug.Assert(false, "Async calls are not allowed in this build.");
#endif
}
}
/// <summary>
/// Verifies that calling CreateResponseMessage is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanCreateResponseMessage(bool synchronousCall)
{
this.ValidateReaderNotDisposed();
this.VerifyCallAllowed(synchronousCall);
if (!this.rawInputContext.ReadingResponse)
{
throw new ODataException(Strings.ODataAsyncReader_CannotCreateResponseWhenNotReadingResponse);
}
}
/// <summary>
/// Returns an <see cref="ODataAsynchronousResponseMessage"/> for reading the content of an async response - implementation of the actual functionality.
/// </summary>
/// <returns>The message that can be used to read the response.</returns>
private ODataAsynchronousResponseMessage CreateResponseMessageImplementation()
{
int statusCode;
IDictionary<string, string> headers;
this.ReadInnerEnvelope(out statusCode, out headers);
return ODataAsynchronousResponseMessage.CreateMessageForReading(this.rawInputContext.Stream, statusCode, headers);
}
/// <summary>
/// Reads the envelope from the inner HTTP message.
/// </summary>
/// <param name="statusCode">The status code to use for the async response message.</param>
/// <param name="headers">The headers to use for the async response message.</param>
private void ReadInnerEnvelope(out int statusCode, out IDictionary<string, string> headers)
{
string responseLine = this.ReadFirstNonEmptyLine();
statusCode = this.ParseResponseLine(responseLine);
headers = this.ReadHeaders();
}
/// <summary>
/// Read and return the next line from the stream, skipping all empty lines.
/// </summary>
/// <returns>The text of the first non-empty line (not including any terminating newline characters).</returns>
private string ReadFirstNonEmptyLine()
{
string line = this.ReadLine();
while (line.Length == 0)
{
line = this.ReadLine();
}
return line;
}
/// <summary>
/// Parses the response line of an async response.
/// </summary>
/// <param name="responseLine">The response line as a string.</param>
/// <returns>The parsed status code from the response line.</returns>
private int ParseResponseLine(string responseLine)
{
Debug.Assert(this.rawInputContext.ReadingResponse, "Must only be called for responses.");
// Async Response: HTTP/1.1 200 Ok
// Since the http status code strings have spaces in them, we cannot use the same
// logic. We need to check for the second space and anything after that is the error
// message.
if (responseLine.Length == 0)
{
// empty line
throw new ODataException(Strings.ODataAsyncReader_InvalidResponseLine(responseLine));
}
int firstSpaceIndex = responseLine.IndexOf(' ');
if (firstSpaceIndex <= 0 || responseLine.Length - 3 <= firstSpaceIndex)
{
// only 1 segment or empty first segment or not enough left for 2nd and 3rd segments
throw new ODataException(Strings.ODataAsyncReader_InvalidResponseLine(responseLine));
}
int secondSpaceIndex = responseLine.IndexOf(' ', firstSpaceIndex + 1);
if (secondSpaceIndex < 0 || secondSpaceIndex - firstSpaceIndex - 1 <= 0 || responseLine.Length - 1 <= secondSpaceIndex)
{
// only 2 segments or empty 2nd or 3rd segments
// only 1 segment or empty first segment or not enough left for 2nd and 3rd segments
throw new ODataException(Strings.ODataAsyncReader_InvalidResponseLine(responseLine));
}
string httpVersionSegment = responseLine.Substring(0, firstSpaceIndex);
string statusCodeSegment = responseLine.Substring(firstSpaceIndex + 1, secondSpaceIndex - firstSpaceIndex - 1);
// Validate HttpVersion
if (string.CompareOrdinal(ODataConstants.HttpVersionInAsync, httpVersionSegment) != 0)
{
throw new ODataException(Strings.ODataAsyncReader_InvalidHttpVersionSpecified(httpVersionSegment, ODataConstants.HttpVersionInAsync));
}
int intResult;
if (!Int32.TryParse(statusCodeSegment, out intResult))
{
throw new ODataException(Strings.ODataAsyncReader_NonIntegerHttpStatusCode(statusCodeSegment));
}
return intResult;
}
/// <summary>
/// Reads the headers of an async response.
/// </summary>
/// <returns>A dictionary of header names to header values; never null.</returns>
private IDictionary<string, string> ReadHeaders()
{
var headers = new Dictionary<string, string>(StringComparer.Ordinal);
// Read all the headers
string headerLine = this.ReadLine();
while (!string.IsNullOrEmpty(headerLine))
{
string headerName, headerValue;
ValidateHeaderLine(headerLine, out headerName, out headerValue);
if (headers.ContainsKey(headerName))
{
throw new ODataException(Strings.ODataAsyncReader_DuplicateHeaderFound(headerName));
}
headers.Add(headerName, headerValue);
headerLine = this.ReadLine();
}
return headers;
}
/// <summary>
/// Parses a header line and validates that it has the correct format.
/// </summary>
/// <param name="headerLine">The header line to validate.</param>
/// <param name="headerName">The name of the header.</param>
/// <param name="headerValue">The value of the header.</param>
private static void ValidateHeaderLine(string headerLine, out string headerName, out string headerValue)
{
Debug.Assert(!string.IsNullOrEmpty(headerLine), "Expected non-empty header line.");
int colon = headerLine.IndexOf(':');
if (colon <= 0)
{
throw new ODataException(Strings.ODataAsyncReader_InvalidHeaderSpecified(headerLine));
}
headerName = headerLine.Substring(0, colon).Trim();
headerValue = headerLine.Substring(colon + 1).Trim();
}
/// <summary>
/// Reads a line from the underlying stream.
/// </summary>
/// <returns>The line read from the stream.</returns>
private string ReadLine()
{
StringBuilder lineBuilder = new StringBuilder();
int ch = this.ReadByte();
while (ch != -1)
{
if (ch == '\n')
{
throw new ODataException(Strings.ODataAsyncReader_InvalidNewLineEncountered('\n'));
}
if (ch == '\r')
{
ch = this.ReadByte();
if (ch != '\n')
{
throw new ODataException(Strings.ODataAsyncReader_InvalidNewLineEncountered('\r'));
}
return lineBuilder.ToString();
}
lineBuilder.Append((char)ch);
ch = this.ReadByte();
}
throw new ODataException(Strings.ODataAsyncReader_UnexpectedEndOfInput);
}
/// <summary>
/// Reads a byte from the underlying stream.
/// </summary>
/// <returns>The byte read from the stream.</returns>
private int ReadByte()
{
return this.rawInputContext.Stream.ReadByte();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.CodeTools
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
// Collect OLE error codes.
static internal class OLECMDERR
{
public const int
OLE_E_LAST = unchecked((int)0x800400FF),
OLECMDERR_E_FIRST = OLE_E_LAST + 1,
OLECMDERR_E_NOTSUPPORTED = OLECMDERR_E_FIRST,
OLECMDERR_E_DISABLED = OLECMDERR_E_FIRST + 1,
OLECMDERR_E_NOHELP = OLECMDERR_E_FIRST + 2,
OLECMDERR_E_CANCELED = OLECMDERR_E_FIRST + 3,
OLECMDERR_E_UNKNOWNGROUP = OLECMDERR_E_FIRST + 4;
}
// The status of a menu item
internal enum MenuStatus
{
Disabled,
Invisible,
Enabled,
Checked,
Unchecked
}
// Basic menu items
internal class MenuItem
{
#region Properties
protected ITaskMenuItem taskMenuItem; // The identifying task menu item
protected List<Task> tasks; // Tasks listening to this menu item
protected MenuStatus status; // The status
internal MenuStatus Status
{
get { return status; }
}
internal string Caption
{
get { return (taskMenuItem == null ? "<root>" : taskMenuItem.Caption); }
}
internal ITaskMenuItem TaskMenuItem
{
get { return taskMenuItem; }
}
#endregion
#region Methods
internal MenuItem(ITaskMenuItem menuItem)
{
this.taskMenuItem = menuItem;
tasks = new List<Task>(1);
status = MenuStatus.Disabled;
}
internal void AddTask(Task task)
{
tasks.Add(task);
}
internal void SetStatus(int totalSelected)
{
if (// disable on errors
tasks == null || taskMenuItem == null ||
// disable if not supported by all selected tasks
tasks.Count == 0 || tasks.Count != totalSelected ||
// disable if null tasks or not enabled by all tasks
tasks.Exists(delegate (Task t) { return (t == null || !t.IsEnabled(taskMenuItem)); })
)
{
status = MenuStatus.Disabled;
}
// Set checkable items (disable if selected tasks disagree on checked state)
else if (taskMenuItem.Kind == TaskMenuKind.Checkable && tasks != null)
{
Task task0 = tasks[0];
if (task0 != null)
{
bool isChecked = task0.IsChecked(taskMenuItem);
if (tasks.TrueForAll(delegate (Task t) { return (t != null && isChecked == t.IsChecked(taskMenuItem)); }))
{
status = (isChecked ? MenuStatus.Checked : MenuStatus.Unchecked);
}
else
{
status = MenuStatus.Disabled;
}
}
else
status = MenuStatus.Disabled;
}
// Disable singular menus if multiple selected tasks
else if (taskMenuItem.Kind == TaskMenuKind.Singular)
{
status = (tasks.Count == 1 ? MenuStatus.Enabled : MenuStatus.Disabled);
}
// normal menu item
else
{
status = MenuStatus.Enabled;
}
}
internal virtual void OnCommand()
{
foreach (Task task in tasks)
{
if (task != null)
{
task.ExecCommand(taskMenuItem);
}
}
}
#endregion
}
// Sub menus extend menu items
internal class SubMenu : MenuItem
{
#region Fields
protected static Guid taskManagerCmdGroup = new Guid("{2CDA027E-722C-4148-B953-6CCE16AA982D}");
protected List<MenuItem> menuItems; // the sub menu items
protected int subMenuCount; // count of submenus in this submenu
protected List<int> indices; // submenu path used to encode the group guid
protected Guid cmdGroup; // the OLE command group
#endregion
#region Construction
public SubMenu(ITaskMenuItem item, List<int> indices) : base(item)
{
this.indices = indices;
// menuItems = null;
// subMenuCount = 0;
// root menu has a single 0 index
if (this.indices == null)
{
this.indices = new List<int>(1);
this.indices.Add(0);
}
// create a command group guid based on the submenu path
// for example, a submenu of a second submenu in the root menu
// gets a path: 0,1,0. The guid will end with this path.
// The CTC file hard-codes these guids
Byte[] cmdGroupBytes = taskManagerCmdGroup.ToByteArray();
if (cmdGroupBytes != null)
{
for (int i = 0; i < this.indices.Count; i++)
{
cmdGroupBytes[16 - this.indices.Count + i] = (Byte)(this.indices[i]);
}
}
cmdGroup = new Guid(cmdGroupBytes);
}
// Force refresh next time
protected virtual void Invalidate()
{
menuItems = null;
subMenuCount = 0;
}
// refresh the item list, possibly reloading the menu information
protected virtual void Refresh()
{
if (menuItems == null)
{
Reload();
}
}
protected void Reload()
{
// Common.Trace("Reload menu info: " + Caption);
// Build a new menu
menuItems = new List<MenuItem>(1);
subMenuCount = 0;
foreach (Task task in tasks)
{
ITaskMenuItem[] taskMenuItems = (task == null ? null : task.GetMenuItems(this.taskMenuItem));
// add to the context menu item list
if (taskMenuItems != null)
{
for (int i = 0; i < taskMenuItems.Length; i++)
{
ITaskMenuItem taskMenuItem = taskMenuItems[i];
if (taskMenuItem != null)
{
// update an existing menu or add a new one
int index = menuItems.FindIndex(delegate (MenuItem inf)
{
return (inf == null ? false : inf.TaskMenuItem == taskMenuItem);
});
MenuItem item;
if (index >= 0)
{
item = menuItems[index];
}
else
{
if (taskMenuItem.Kind == TaskMenuKind.Submenu)
{
List<int> path = new List<int>(indices);
path.Add(subMenuCount);
subMenuCount++;
item = new SubMenu(taskMenuItem, path);
}
else
{
item = new MenuItem(taskMenuItem);
}
menuItems.Add(item);
}
item.AddTask(task);
}
}
}
}
// finally, set the status of each command:
// - disable those menus that are not supported by all selected tasks
// - set checkable menus
// - disable those checkable menus that disagree on the checked state
for (int item = 0; item < menuItems.Count; item++)
{
MenuItem menuItem = menuItems[item];
if (menuItem != null)
menuItem.SetStatus(tasks.Count);
}
}
#endregion
#region Submenus
// Get a menu item at a specified index.
internal MenuItem GetMenuItem(int index, bool refresh)
{
if (refresh)
{
Refresh();
}
if (menuItems != null)
{
for (int i = 0; i < menuItems.Count && index >= 0; i++)
{
MenuItem menuItem = menuItems[i];
if (menuItem != null)
{
ITaskMenuItem taskItem = menuItem.TaskMenuItem;
if (taskItem != null && taskItem.Kind != TaskMenuKind.Submenu)
{
if (index == 0)
{
return menuItem;
}
else
{
index--;
}
}
}
}
}
return null;
}
// Get a submenu item.
internal SubMenu GetSubMenu(int index)
{
Refresh();
if (menuItems != null)
{
for (int i = 0; i < menuItems.Count && index >= 0; i++)
{
MenuItem menuItem = menuItems[i];
if (menuItem != null)
{
ITaskMenuItem taskItem = menuItem.TaskMenuItem;
if (taskItem != null && taskItem.Kind == TaskMenuKind.Submenu)
{
if (index == 0)
{
return menuItem as SubMenu;
}
else
{
index--;
}
}
}
}
}
return null;
}
// Enumerate all submenus.
public IEnumerable<SubMenu> SubMenus(bool refresh)
{
if (refresh) Refresh();
if (menuItems != null)
{
foreach (MenuItem item in menuItems)
{
if (item != null)
{
SubMenu subMenu = item as SubMenu;
if (subMenu != null)
{
yield return subMenu;
}
}
}
}
}
internal override void OnCommand()
{
System.Diagnostics.Debug.Assert(false, "Sub menus have no command handler");
return;
}
#endregion
#region IOleCommandTarget
private const uint customStart = 0x400;
private const uint customMenuStart = 0x1000;
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (pguidCmdGroup == cmdGroup)
{
// A command in this submenu
MenuItem item = GetMenuItem((int)(nCmdID - customStart), false);
if (item != null)
{
item.OnCommand();
Invalidate(); // might cause changed menu items etc.
return 0;
}
else
{
return VSConstants.E_INVALIDARG;
}
}
else
{
foreach (SubMenu subMenu in SubMenus(false))
{
if (subMenu != null)
{
// propagate query to all submenus
int hr = subMenu.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
if (hr != OLECMDERR.OLECMDERR_E_UNKNOWNGROUP)
{
if (hr == 0)
{
// command was executed in submenu;
Invalidate();
}
return hr;
}
}
}
return OLECMDERR.OLECMDERR_E_UNKNOWNGROUP;
}
}
public int QueryStatus(ref Guid guidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
if (prgCmds == null || cCmds != 1)
{
return VSConstants.E_INVALIDARG;
}
else if (guidCmdGroup == cmdGroup)
{
// Common.Trace("QueryStatus: " + Caption + ": " + (prgCmds[0].cmdID - customStart));
prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
bool isSubMenu = prgCmds[0].cmdID >= customMenuStart;
int index = (isSubMenu ? (int)(prgCmds[0].cmdID - customMenuStart)
: (int)(prgCmds[0].cmdID - customStart));
MenuItem item = (isSubMenu ? GetSubMenu(index) : GetMenuItem(index, true));
if (item == null)
{
prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_INVISIBLE);
//We must return S_OK or otherwise all task items show custom menus
//However, we must also say E_NOTSUPPORTED or QueryStatus loops
//So, we just return S_OK for the first 16 queries :-(
return (index > 16 ? OLECMDERR.OLECMDERR_E_NOTSUPPORTED : 0);
}
else
{
switch (item.Status)
{
case MenuStatus.Enabled: prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_ENABLED); break;
case MenuStatus.Checked: prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_LATCHED); break;
case MenuStatus.Unchecked: prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_NINCHED); break;
case MenuStatus.Invisible: prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_INVISIBLE); break;
case MenuStatus.Disabled:
// Submenus somehow do not disable, so we make them invisible..
if (isSubMenu)
{
prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_INVISIBLE); break;
};
break;
default:
break;
}
SetCommandText(pCmdText, item.Caption);
return 0;
}
}
else
{
// Common.Trace("QueryStatus: " + guidCmdGroup + "\n " + Caption + ": " + (prgCmds[0].cmdID - customStart));
foreach (SubMenu subMenu in SubMenus(false))
{
if (subMenu != null)
{
// propagate query to all submenus
int hr = subMenu.QueryStatus(ref guidCmdGroup, cCmds, prgCmds, pCmdText);
if (hr != OLECMDERR.OLECMDERR_E_UNKNOWNGROUP)
{
return hr;
}
}
}
return OLECMDERR.OLECMDERR_E_UNKNOWNGROUP;
}
}
// Custom marshalling to set the text of a menu item
static private bool SetCommandText(IntPtr cmdText, string text)
{
if (cmdText != IntPtr.Zero && text != null)
{
int ofsFlags = 0;
int ofsActualSize = ofsFlags + 4 /* sizeof(UInt32)*/;
int ofsBufSize = ofsActualSize + UIntPtr.Size;
int ofsChar = ofsBufSize + UIntPtr.Size;
int flags = Marshal.ReadInt32(cmdText, ofsFlags);
if (flags == 1)
{
int bufSize = Marshal.ReadInt32(cmdText, ofsBufSize);
int max = (bufSize - 1 > text.Length ? text.Length : bufSize - 1);
for (int i = 0; i < max; i++)
{
Marshal.WriteInt16(cmdText, ofsChar + 2 /* sizeof(Int16) */ * i, text[i]);
}
Marshal.WriteInt16(cmdText, ofsChar + 2 /* sizeof(Int16) */ * max, '\0');
if (UIntPtr.Size == 8)
{
Marshal.WriteInt64(cmdText, ofsActualSize, text.Length);
}
else
{
Marshal.WriteInt32(cmdText, ofsActualSize, text.Length);
}
return true;
}
}
return false;
}
#endregion
}
// Root menu specializes a submenu for the top-level context menu
internal class RootMenu : SubMenu
{
private IVsTaskList2 taskList; // The global task list object
public RootMenu() : base(null, null)
{
taskList = Common.GetService(typeof(SVsErrorList)) as IVsTaskList2;
}
public void Release()
{
taskList = null; // this also disables menu handling
}
// Refresh checks "smartly" if the selected tasks have changed
// or not and only reloads all menu information on a change.
protected override void Refresh()
{
// Check if we really need to reload..
List<Task> selected = GetSelectedTasks(taskList);
if (selected == null || selected.Count == 0)
{
menuItems = null;
tasks = null;
return;
}
// Check if cached info is still the same..
if (menuItems != null && tasks != null && tasks.Count == selected.Count)
{
bool equal = true;
for (int i = 0; i < selected.Count; i++)
{
if (tasks[i] != selected[i])
{
equal = false;
break;
}
}
if (equal) return; // cached information is up-to-date
}
// Otherwise, reload with the new selected tasks
tasks = selected;
Reload();
}
// Get the currently selected task items
static public List<Task> GetSelectedTasks(IVsTaskList2 taskList)
{
if (taskList == null) return null;
int selectedCount = 0;
taskList.GetSelectionCount(out selectedCount);
if (selectedCount <= 0) return null;
IVsEnumTaskItems enumItems;
int hr = taskList.EnumSelectedItems(out enumItems);
if (hr != 0 || enumItems == null) return null;
List<Task> items = new List<Task>(selectedCount);
uint[] fetched = { 0 };
IVsTaskItem[] elems = { null };
do
{
hr = enumItems.Next(1, elems, fetched);
if (fetched[0] == 1)
{
Task task = elems[0] as Task;
items.Add(task); // can add null items
}
}
while (hr == 0 && fetched[0] == 1);
return items;
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests.Cache.Query.Continuous
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cache.Event;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for continuous query.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public abstract class ContinuousQueryAbstractTest
{
/** Cache name: ATOMIC, backup. */
protected const string CACHE_ATOMIC_BACKUP = "atomic_backup";
/** Cache name: ATOMIC, no backup. */
protected const string CACHE_ATOMIC_NO_BACKUP = "atomic_no_backup";
/** Cache name: TRANSACTIONAL, backup. */
protected const string CACHE_TX_BACKUP = "transactional_backup";
/** Cache name: TRANSACTIONAL, no backup. */
protected const string CACHE_TX_NO_BACKUP = "transactional_no_backup";
/** Listener events. */
public static BlockingCollection<CallbackEvent> CB_EVTS = new BlockingCollection<CallbackEvent>();
/** Listener events. */
public static BlockingCollection<FilterEvent> FILTER_EVTS = new BlockingCollection<FilterEvent>();
/** First node. */
private IIgnite grid1;
/** Second node. */
private IIgnite grid2;
/** Cache on the first node. */
private ICache<int, BinarizableEntry> cache1;
/** Cache on the second node. */
private ICache<int, BinarizableEntry> cache2;
/** Cache name. */
private readonly string cacheName;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cacheName">Cache name.</param>
protected ContinuousQueryAbstractTest(string cacheName)
{
this.cacheName = cacheName;
}
/// <summary>
/// Set-up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(BinarizableEntry)),
new BinaryTypeConfiguration(typeof(BinarizableFilter)),
new BinaryTypeConfiguration(typeof(KeepBinaryFilter))
}
},
SpringConfigUrl = Path.Combine("Config", "cache-query-continuous.xml"),
IgniteInstanceName = "grid-1"
};
grid1 = Ignition.Start(cfg);
cache1 = grid1.GetCache<int, BinarizableEntry>(cacheName);
cfg.IgniteInstanceName = "grid-2";
grid2 = Ignition.Start(cfg);
cache2 = grid2.GetCache<int, BinarizableEntry>(cacheName);
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Before-test routine.
/// </summary>
[SetUp]
public void BeforeTest()
{
CB_EVTS = new BlockingCollection<CallbackEvent>();
FILTER_EVTS = new BlockingCollection<FilterEvent>();
AbstractFilter<BinarizableEntry>.res = true;
AbstractFilter<BinarizableEntry>.err = false;
AbstractFilter<BinarizableEntry>.marshErr = false;
AbstractFilter<BinarizableEntry>.unmarshErr = false;
cache1.Remove(PrimaryKey(cache1));
cache1.Remove(PrimaryKey(cache2));
Assert.AreEqual(0, cache1.GetSize());
Assert.AreEqual(0, cache2.GetSize());
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Test arguments validation.
/// </summary>
[Test]
public void TestValidation()
{
Assert.Throws<ArgumentException>(() => { cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(null)); });
}
/// <summary>
/// Test multiple closes.
/// </summary>
[Test]
public void TestMultipleClose()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
Assert.AreNotEqual(key1, key2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
IDisposable qryHnd;
using (qryHnd = cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
qryHnd.Dispose();
}
/// <summary>
/// Test regular callback operations.
/// </summary>
[Test]
public void TestCallback()
{
CheckCallback(false);
}
/// <summary>
/// Check regular callback execution.
/// </summary>
/// <param name="loc"></param>
protected void CheckCallback(bool loc)
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>(), true) :
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckCallbackSingle(key1, Entry(key1), Entry(key1 + 1), CacheEntryEventType.Updated);
cache1.Remove(key1);
CheckCallbackSingle(key1, Entry(key1 + 1), Entry(key1 + 1), CacheEntryEventType.Removed);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2), Entry(key2 + 1), CacheEntryEventType.Updated);
cache1.Remove(key2);
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2 + 1), Entry(key2 + 1), CacheEntryEventType.Removed);
}
cache1.Put(key1, Entry(key1));
CheckNoCallback(100);
cache1.Put(key2, Entry(key2));
CheckNoCallback(100);
}
/// <summary>
/// Test Ignite injection into callback.
/// </summary>
[Test]
public void TestCallbackInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
Assert.IsNull(cb.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb)))
{
Assert.IsNotNull(cb.ignite);
}
}
/// <summary>
/// Tests that <see cref="ContinuousQuery{TK,TV}.IncludeExpired"/> is false by default
/// and expiration events are not delivered.
///
/// - Create a cache with expiry policy
/// - Start a continuous query with default settings
/// - Check that Created events are delivered, but Expired events are not
/// </summary>
[Test]
public void TestIncludeExpiredIsFalseByDefaultAndExpiredEventsAreSkipped()
{
var cache = cache1.WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromMilliseconds(100), null, null));
var cb = new Listener<BinarizableEntry>();
var qry = new ContinuousQuery<int, BinarizableEntry>(cb);
Assert.IsFalse(qry.IncludeExpired);
using (cache.QueryContinuous(qry))
{
cache[1] = Entry(1);
TestUtils.WaitForTrueCondition(() => !cache.ContainsKey(1));
cache[2] = Entry(2);
}
var events = CB_EVTS.SelectMany(e => e.entries).ToList();
Assert.AreEqual(2, events.Count);
Assert.AreEqual(CacheEntryEventType.Created, events[0].EventType);
Assert.AreEqual(CacheEntryEventType.Created, events[1].EventType);
}
/// <summary>
/// Tests that enabling <see cref="ContinuousQuery{TK,TV}.IncludeExpired"/> causes
/// <see cref="CacheEntryEventType.Expired"/> events to be delivered.
///
/// - Create a cache with expiry policy
/// - Start a continuous query with <see cref="ContinuousQuery{TK,TV}.IncludeExpired"/> set to <c>true</c>
/// - Check that Expired events are delivered
/// </summary>
[Test]
public void TestExpiredEventsAreDeliveredWhenIncludeExpiredIsTrue()
{
var cache = cache1.WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromMilliseconds(100), null, null));
var cb = new Listener<BinarizableEntry>();
var qry = new ContinuousQuery<int, BinarizableEntry>(cb)
{
IncludeExpired = true
};
using (cache.QueryContinuous(qry))
{
cache[1] = Entry(2);
TestUtils.WaitForTrueCondition(() => CB_EVTS.Count == 2, 5000);
}
var events = CB_EVTS.SelectMany(e => e.entries).ToList();
Assert.AreEqual(2, events.Count);
Assert.AreEqual(CacheEntryEventType.Created, events[0].EventType);
Assert.AreEqual(CacheEntryEventType.Expired, events[1].EventType);
Assert.IsTrue(events[1].HasValue);
Assert.IsTrue(events[1].HasOldValue);
Assert.AreEqual(2, ((BinarizableEntry)events[1].Value).val);
Assert.AreEqual(2, ((BinarizableEntry)events[1].Value).val);
Assert.AreEqual(1, events[1].Key);
}
/// <summary>
/// Test binarizable filter logic.
/// </summary>
[Test]
public void TestFilterBinarizable()
{
CheckFilter(true, false);
}
/// <summary>
/// Test serializable filter logic.
/// </summary>
[Test]
public void TestFilterSerializable()
{
CheckFilter(false, false);
}
/// <summary>
/// Tests the defaults.
/// </summary>
[Test]
public void TestDefaults()
{
var qry = new ContinuousQuery<int, int>(null);
Assert.AreEqual(ContinuousQuery.DefaultAutoUnsubscribe, qry.AutoUnsubscribe);
Assert.AreEqual(ContinuousQuery.DefaultBufferSize, qry.BufferSize);
Assert.AreEqual(ContinuousQuery.DefaultTimeInterval, qry.TimeInterval);
Assert.IsFalse(qry.Local);
}
/// <summary>
/// Check filter.
/// </summary>
/// <param name="binarizable">Binarizable.</param>
/// <param name="loc">Local cache flag.</param>
protected void CheckFilter(bool binarizable, bool loc)
{
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) :
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
int key2 = PrimaryKey(cache2);
cache1.GetAndPut(key2, Entry(key2));
if (loc)
{
CheckNoFilter(key2);
CheckNoCallback(key2);
}
else
{
CheckFilterSingle(key2, null, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
AbstractFilter<BinarizableEntry>.res = false;
// Ignored put from local node.
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckFilterSingle(key1, Entry(key1), Entry(key1 + 1));
CheckNoCallback(100);
// Ignored put from remote node.
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoFilter(100);
else
CheckFilterSingle(key2, Entry(key2), Entry(key2 + 1));
CheckNoCallback(100);
}
}
/// <summary>
/// Test binarizable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorBinarizable()
{
CheckFilterInvokeError(true);
}
/// <summary>
/// Test serializable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorSerializable()
{
CheckFilterInvokeError(false);
}
/// <summary>
/// Check filter error handling logic during invoke.
/// </summary>
private void CheckFilterInvokeError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.err = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache1), Entry(1)));
// Put from remote node.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache2), Entry(1)));
}
}
/// <summary>
/// Test binarizable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorBinarizable()
{
CheckFilterMarshalError(true);
}
/// <summary>
/// Test serializable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorSerializable()
{
CheckFilterMarshalError(false);
}
/// <summary>
/// Check filter marshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterMarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.marshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>)new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
Assert.Throws<Exception>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
/// <summary>
/// Test non-serializable filter error.
/// </summary>
[Test]
public void TestFilterNonSerializable()
{
CheckFilterNonSerializable(false);
}
/// <summary>
/// Test non-serializable filter behavior.
/// </summary>
/// <param name="loc"></param>
protected void CheckFilterNonSerializable(bool loc)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter = new LocalFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc
? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true)
: new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
if (loc)
{
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
}
}
else
{
Assert.Throws<BinaryObjectException>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
}
/// <summary>
/// Test binarizable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorBinarizable()
{
CheckFilterUnmarshalError(true);
}
/// <summary>
/// Test serializable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorSerializable()
{
CheckFilterUnmarshalError(false);
}
/// <summary>
/// Check filter unmarshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterUnmarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
// Remote put must fail.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache2), Entry(1)));
}
}
/// <summary>
/// Test Ignite injection into filters.
/// </summary>
[Test]
public void TestFilterInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
BinarizableFilter filter = new BinarizableFilter();
Assert.IsNull(filter.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb, filter)))
{
// Local injection.
Assert.IsNotNull(filter.ignite);
// Remote injection.
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, 500));
Assert.IsNotNull(evt.ignite);
}
}
/// <summary>
/// Test "keep-binary" scenario.
/// </summary>
[Test]
public void TestKeepBinary()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
ContinuousQuery<int, IBinaryObject> qry = new ContinuousQuery<int, IBinaryObject>(
new Listener<IBinaryObject>(), new KeepBinaryFilter());
using (cache.QueryContinuous(qry))
{
// 1. Local put.
cache1.GetAndPut(PrimaryKey(cache1), Entry(1));
CallbackEvent cbEvt;
FilterEvent filterEvt;
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache1), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(1), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache1), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(1), (cbEvt.entries.First().Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
// 2. Remote put.
ClearEvents();
cache1.GetAndPut(PrimaryKey(cache2), Entry(2));
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache2), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(2), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache2), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(2),
(cbEvt.entries.First().Value as IBinaryObject).Deserialize<BinarizableEntry>());
}
}
/// <summary>
/// Test value types (special handling is required for nulls).
/// </summary>
[Test]
public void TestValueTypes()
{
var cache = grid1.GetCache<int, int>(cacheName);
var qry = new ContinuousQuery<int, int>(new Listener<int>());
var key = PrimaryKey(cache);
using (cache.QueryContinuous(qry))
{
// First update
cache.Put(key, 1);
CallbackEvent cbEvt;
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
var cbEntry = cbEvt.entries.Single();
Assert.IsFalse(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(null, cbEntry.OldValue);
Assert.AreEqual(1, cbEntry.Value);
// Second update
cache.Put(key, 2);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(1, cbEntry.OldValue);
Assert.AreEqual(2, cbEntry.Value);
// Remove
cache.Remove(key);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(2, cbEntry.OldValue);
Assert.AreEqual(2, cbEntry.Value);
}
}
/// <summary>
/// Test whether buffer size works fine.
/// </summary>
[Test]
public void TestBufferSize()
{
// Put two remote keys in advance.
var rmtKeys = TestUtils.GetPrimaryKeys(cache2.Ignite, cache2.Name).Take(2).ToList();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(1000000);
using (cache1.QueryContinuous(qry))
{
qry.BufferSize = 2;
cache1.GetAndPut(rmtKeys[0], Entry(rmtKeys[0]));
CheckNoCallback(100);
cache1.GetAndPut(rmtKeys[1], Entry(rmtKeys[1]));
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, 1000));
Assert.AreEqual(2, evt.entries.Count);
var entryRmt0 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[0]); });
var entryRmt1 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[1]); });
Assert.AreEqual(rmtKeys[0], entryRmt0.Key);
Assert.IsNull(entryRmt0.OldValue);
Assert.AreEqual(Entry(rmtKeys[0]), entryRmt0.Value);
Assert.AreEqual(rmtKeys[1], entryRmt1.Key);
Assert.IsNull(entryRmt1.OldValue);
Assert.AreEqual(Entry(rmtKeys[1]), entryRmt1.Value);
}
cache1.Remove(rmtKeys[0]);
cache1.Remove(rmtKeys[1]);
}
/// <summary>
/// Test that TimeInterval causes incomplete buffer to be sent when BufferSize is greater than 1.
/// </summary>
[Test]
public void TestTimeInterval()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>())
{
BufferSize = 2,
TimeInterval = TimeSpan.FromMilliseconds(500)
};
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created, 2000);
// Put from remote node.
cache1.GetAndPut(key2, Entry(key2));
CheckNoCallback(100);
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created, 2000);
}
}
/// <summary>
/// Test whether nested Ignite API call from callback works fine.
/// </summary>
[Test]
public void TestNestedCallFromCallback()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
int key = PrimaryKey(cache1);
NestedCallListener cb = new NestedCallListener();
using (cache.QueryContinuous(new ContinuousQuery<int, IBinaryObject>(cb)))
{
cache1.GetAndPut(key, Entry(key));
cb.countDown.Wait();
}
cache.Remove(key);
}
/// <summary>
/// Tests the initial query.
/// </summary>
[Test]
public void TestInitialQuery()
{
// Scan query, GetAll
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.GetAll());
// Scan query, iterator
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.ToList());
// Sql query, GetAll
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.GetAll());
// Sql query, iterator
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.ToList());
// Text query, GetAll
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.GetAll());
// Text query, iterator
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.ToList());
// Test exception: invalid initial query
var ex = Assert.Throws<IgniteException>(
() => TestInitialQuery(new TextQuery(typeof (BinarizableEntry), "*"), cur => cur.GetAll()));
Assert.AreEqual("Cannot parse '*': '*' or '?' not allowed as first character in WildcardQuery", ex.Message);
}
/// <summary>
/// Tests the initial fields query.
/// </summary>
[Test]
public void TestInitialFieldsQuery()
{
var sqlFieldsQuery = new SqlFieldsQuery("select _key, _val, val from BINARIZABLEENTRY where val < 33");
TestInitialQuery(sqlFieldsQuery, cur => cur.GetAll());
TestInitialQuery(sqlFieldsQuery, cur => cur.ToList());
}
/// <summary>
/// Tests fields metadata in the initial fields query.
/// </summary>
[Test]
public void TestInitialFieldsQueryMetadata()
{
var sqlFieldsQuery = new SqlFieldsQuery("select val, _val from BINARIZABLEENTRY where val < 33");
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
using (var contQry = cache1.QueryContinuous(qry, sqlFieldsQuery))
{
var fields = contQry.GetInitialQueryCursor().Fields;
Assert.AreEqual(2, fields.Count);
Assert.AreEqual("VAL", fields[0].Name);
Assert.AreEqual(typeof(int), fields[0].Type);
Assert.AreEqual("_VAL", fields[1].Name);
Assert.AreEqual(typeof(object), fields[1].Type);
}
}
/// <summary>
/// Tests the initial fields query with bad SQL.
/// </summary>
[Test]
public void TestInitialFieldsQueryWithBadSql()
{
// Invalid SQL query.
var ex = Assert.Throws<IgniteException>(() => TestInitialQuery(
new SqlFieldsQuery("select FOO from BAR"), cur => cur.GetAll()));
StringAssert.StartsWith("Failed to parse query. Table \"BAR\" not found;", ex.Message);
}
/// <summary>
/// Tests the initial query.
/// </summary>
private void TestInitialQuery(QueryBase initialQry, Func<IQueryCursor<ICacheEntry<int, BinarizableEntry>>,
IEnumerable<ICacheEntry<int, BinarizableEntry>>> getAllFunc)
{
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
cache1.Put(11, Entry(11));
cache1.Put(12, Entry(12));
cache1.Put(33, Entry(33));
try
{
IContinuousQueryHandle<ICacheEntry<int, BinarizableEntry>> contQry;
using (contQry = cache1.QueryContinuous(qry, initialQry))
{
// Check initial query
var initialEntries =
getAllFunc(contQry.GetInitialQueryCursor()).Distinct().OrderBy(x => x.Key).ToList();
Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor());
Assert.AreEqual(2, initialEntries.Count);
for (int i = 0; i < initialEntries.Count; i++)
{
Assert.AreEqual(i + 11, initialEntries[i].Key);
Assert.AreEqual(i + 11, initialEntries[i].Value.val);
}
// Check continuous query
cache1.Put(44, Entry(44));
CheckCallbackSingle(44, null, Entry(44), CacheEntryEventType.Created);
}
Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor());
contQry.Dispose(); // multiple dispose calls are ok
}
finally
{
cache1.Clear();
}
}
/// <summary>
/// Tests the initial fields query.
/// </summary>
private void TestInitialQuery(SqlFieldsQuery initialQry,
Func<IFieldsQueryCursor, IEnumerable<IList<object>>> getAllFunc)
{
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
cache1.Put(11, Entry(11));
cache1.Put(12, Entry(12));
cache1.Put(33, Entry(33));
try
{
IContinuousQueryHandleFields contQry;
using (contQry = cache1.QueryContinuous(qry, initialQry))
{
// Check initial query
var initialQueryCursor = contQry.GetInitialQueryCursor();
var initialEntries = getAllFunc(initialQueryCursor).OrderBy(x => x[0]).ToList();
Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor());
Assert.AreEqual(2, initialEntries.Count);
Assert.GreaterOrEqual(initialQueryCursor.Fields.Count, 2);
for (int i = 0; i < initialEntries.Count; i++)
{
var key = (int) initialEntries[i][0];
var val = (BinarizableEntry) initialEntries[i][1];
Assert.AreEqual(i + 11, key);
Assert.AreEqual(i + 11, val.val);
}
// Check continuous query
cache1.Put(44, Entry(44));
CheckCallbackSingle(44, null, Entry(44), CacheEntryEventType.Created);
}
Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor());
contQry.Dispose(); // multiple dispose calls are ok
}
finally
{
cache1.Clear();
}
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
private void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal)
{
CheckFilterSingle(expKey, expOldVal, expVal, 1000);
ClearEvents();
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout)
{
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(expKey, evt.entry.Key);
Assert.AreEqual(expOldVal, evt.entry.OldValue);
Assert.AreEqual(expVal, evt.entry.Value);
ClearEvents();
}
/// <summary>
/// Clears the events collection.
/// </summary>
private static void ClearEvents()
{
while (FILTER_EVTS.Count > 0)
FILTER_EVTS.Take();
}
/// <summary>
/// Ensure that no filter events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private static void CheckNoFilter(int timeout)
{
FilterEvent _;
Assert.IsFalse(FILTER_EVTS.TryTake(out _, timeout));
}
/// <summary>
/// Check single callback event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected new value.</param>
/// <param name="expType">Expected type.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal,
CacheEntryEventType expType, int timeout = 1000)
{
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(0, CB_EVTS.Count);
var e = evt.entries.Single();
Assert.AreEqual(expKey, e.Key);
Assert.AreEqual(expOldVal, e.OldValue);
Assert.AreEqual(expVal, e.Value);
Assert.AreEqual(expType, e.EventType);
}
/// <summary>
/// Ensure that no callback events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private void CheckNoCallback(int timeout)
{
CallbackEvent _;
Assert.IsFalse(CB_EVTS.TryTake(out _, timeout));
}
/// <summary>
/// Create entry.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Entry.</returns>
private static BinarizableEntry Entry(int val)
{
return new BinarizableEntry(val);
}
/// <summary>
/// Get primary key for cache.
/// </summary>
/// <param name="cache">Cache.</param>
/// <returns>Primary key.</returns>
private static int PrimaryKey<T>(ICache<int, T> cache)
{
return TestUtils.GetPrimaryKey(cache.Ignite, cache.Name);
}
/// <summary>
/// Creates object-typed event.
/// </summary>
private static ICacheEntryEvent<object, object> CreateEvent<T, V>(ICacheEntryEvent<T,V> e)
{
switch (e.EventType)
{
case CacheEntryEventType.Created:
return new CacheEntryCreateEvent<object, object>(e.Key, e.Value);
case CacheEntryEventType.Updated:
return new CacheEntryUpdateEvent<object, object>(e.Key, e.OldValue, e.Value);
case CacheEntryEventType.Expired:
return new CacheEntryExpireEvent<object, object>(e.Key, e.OldValue);
default:
return new CacheEntryRemoveEvent<object, object>(e.Key, e.OldValue);
}
}
/// <summary>
/// Binarizable entry.
/// </summary>
public class BinarizableEntry
{
/** Value. */
public readonly int val;
/** <inheritDot /> */
public override int GetHashCode()
{
return val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public BinarizableEntry(int val)
{
this.val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
return obj != null && obj is BinarizableEntry && ((BinarizableEntry)obj).val == val;
}
/** <inheritDoc /> */
public override string ToString()
{
return string.Format("BinarizableEntry [Val: {0}]", val);
}
}
/// <summary>
/// Abstract filter.
/// </summary>
[Serializable]
public abstract class AbstractFilter<TV> : ICacheEntryEventFilter<int, TV>
{
/** Result. */
public static volatile bool res = true;
/** Throw error on invocation. */
public static volatile bool err;
/** Throw error during marshalling. */
public static volatile bool marshErr;
/** Throw error during unmarshalling. */
public static volatile bool unmarshErr;
/** Grid. */
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public bool Evaluate(ICacheEntryEvent<int, TV> evt)
{
if (err)
throw new Exception("Filter error.");
FILTER_EVTS.Add(new FilterEvent(ignite, CreateEvent(evt)));
return res;
}
}
/// <summary>
/// Filter which cannot be serialized.
/// </summary>
public class LocalFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
/// Binarizable filter.
/// </summary>
public class BinarizableFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
}
/// <summary>
/// Serializable filter.
/// </summary>
[Serializable]
public class SerializableFilter : AbstractFilter<BinarizableEntry>, ISerializable
{
/// <summary>
/// Constructor.
/// </summary>
public SerializableFilter()
{
// No-op.
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info">Info.</param>
/// <param name="context">Context.</param>
protected SerializableFilter(SerializationInfo info, StreamingContext context)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
}
/// <summary>
/// Filter for "keep-binary" scenario.
/// </summary>
public class KeepBinaryFilter : AbstractFilter<IBinaryObject>
{
// No-op.
}
/// <summary>
/// Listener.
/// </summary>
public class Listener<TV> : ICacheEntryEventListener<int, TV>
{
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public void OnEvent(IEnumerable<ICacheEntryEvent<int, TV>> evts)
{
CB_EVTS.Add(new CallbackEvent(evts.Select(CreateEvent).ToList()));
}
}
/// <summary>
/// Listener with nested Ignite API call.
/// </summary>
public class NestedCallListener : ICacheEntryEventListener<int, IBinaryObject>
{
/** Event. */
public readonly CountdownEvent countDown = new CountdownEvent(1);
public void OnEvent(IEnumerable<ICacheEntryEvent<int, IBinaryObject>> evts)
{
foreach (ICacheEntryEvent<int, IBinaryObject> evt in evts)
{
IBinaryObject val = evt.Value;
IBinaryType meta = val.GetBinaryType();
Assert.AreEqual(typeof(BinarizableEntry).FullName, meta.TypeName);
}
countDown.Signal();
}
}
/// <summary>
/// Filter event.
/// </summary>
public class FilterEvent
{
/** Grid. */
public IIgnite ignite;
/** Entry. */
public ICacheEntryEvent<object, object> entry;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ignite">Grid.</param>
/// <param name="entry">Entry.</param>
public FilterEvent(IIgnite ignite, ICacheEntryEvent<object, object> entry)
{
this.ignite = ignite;
this.entry = entry;
}
}
/// <summary>
/// Callbakc event.
/// </summary>
public class CallbackEvent
{
/** Entries. */
public ICollection<ICacheEntryEvent<object, object>> entries;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="entries">Entries.</param>
public CallbackEvent(ICollection<ICacheEntryEvent<object, object>> entries)
{
this.entries = entries;
}
}
/// <summary>
/// ScanQuery filter for InitialQuery test.
/// </summary>
[Serializable]
private class InitialQueryScanFilter : ICacheEntryFilter<int, BinarizableEntry>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, BinarizableEntry> entry)
{
return entry.Key < 33;
}
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class Agent
{
//////////////////////////////////////////////////////////////////
#region Agent Types/Defaults
// Regularly used agent types to speed up initialization
// and enable conversion between agent types
public enum AgentType { CUSTOM, HUMAN, ZOMBIE, CORPSE, HUMAN_PLAYER, ZOMBIE_PLAYER };
private static Color humanColor = Color.green;
private static Color zombieColor = Color.red;
private static Color corpseColor = Color.cyan;
private static Color humanPlayerColor = Color.yellow;
private static Color zombiePlayerColor = Color.magenta;
#endregion Agent Types/Defaults
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#region Bookkeeping
[SerializeField]
private System.Guid _guid = System.Guid.NewGuid();
public System.Guid Guid { get { return _guid; } }
[SerializeField]
private bool _needsInitialization = true;
[SerializeField]
private AgentRenderer _myRenderer;
public AgentRenderer Renderer { set { _myRenderer = value; } }
[SerializeField]
protected List<AgentPercept> _perceptPool = new List<AgentPercept>();
public List<AgentPercept> PerceptPool { get { return _perceptPool; } }
private int _perceptIndex = 0;
#endregion Bookkeeping
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#region Agent traits
// Several of these wouldn't "const" correctly, so for now non-DRYly
// duplicating the 'defaults' down in configureDefault()
[SerializeField]
private AgentPercept.LivingState _living= AgentPercept.LivingState.ALIVE;
public AgentPercept.LivingState LivingState { get { return _living; } set { _living = value; } }
[SerializeField]
private AgentType _agentType = AgentType.HUMAN;
public AgentType Type { get { return _agentType; } set { _agentType = value; } }
[SerializeField]
private AgentBehavior _behavior = new NoopBehavior();
public AgentBehavior Behavior
{
get { return _behavior; }
set
{
_behavior = value;
value.setAgent(this);
}
}
[SerializeField]
private Color _agentColor = Color.cyan;
public Color AgentColor
{
get { return _agentColor; }
set
{
_agentColor = value;
if(_myRenderer != null)
{
_myRenderer.updateColor();
}
}
}
[SerializeField]
private Vector2 _location = Vector2.zero;
public Vector2 Location
{
get { return _location; }
set
{
_location = value;
if(_myRenderer != null)
{
_myRenderer.updateLocation();
}
}
}
[SerializeField]
private float _direction = 0.0f;
public float Direction
{
get { return _direction; }
set
{
_direction = value;
if(_direction < 0)
{
_direction += 360;
}
if(_direction >= 360)
{
_direction -= 360;
}
if(_myRenderer != null)
{
_myRenderer.recalculateFOVImage();
}
}
}
[SerializeField]
private float _fieldOfView = 0.0f;
public float FieldOfView
{
get { return _fieldOfView; }
set
{
_fieldOfView = value;
if(_myRenderer != null)
{
_myRenderer.recalculateFOVImage();
}
}
}
[SerializeField]
private float _sightRange = 0.0f;
public float SightRange
{
get { return _sightRange; }
set
{
_sightRange = value;
if(_myRenderer != null)
{
_myRenderer.updateFOVScale();
}
}
}
[SerializeField]
private float _convertRange = 0.0f;
public float ConvertRange { get { return _convertRange; } set { _convertRange = value; } }
[SerializeField]
private float _speedMultiplier = 1.0f;
public float SpeedMultiplier { get { return _speedMultiplier; } set { _speedMultiplier = value; } }
[SerializeField]
private float _turnSpeedMultiplier = 1.0f;
public float TurnSpeedMultiplier { get { return _turnSpeedMultiplier; } set { _turnSpeedMultiplier = value; } }
// These are *definitely* going to need iteration. :P
[SerializeField]
private bool _moveInUse = false;
public bool MoveInUse { get { return _moveInUse; } set { _moveInUse = value; } }
[SerializeField]
private bool _lookInUse = false;
public bool LookInUse { get { return _lookInUse; } set { _lookInUse = value; } }
#endregion Agent traits
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#region Constructor/init
public Agent(): this(AgentType.HUMAN){}
public Agent(AgentType newType)
{
configureAs(newType,true);
}
#endregion MonoBehaviour methods
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#region Agent type definitions
// since we don't seem to have defaults in whatever C# I'm getting via Mono...
public void configureAs(AgentType newType)
{
configureAs(newType, false);
}
public void configureAs(AgentType newType, bool resetFirst)
{
if(resetFirst)
{
configureDefault();
}
_needsInitialization = false;
switch(newType)
{
case AgentType.CUSTOM:
configureAsCustom();
break;
case AgentType.CORPSE:
configureAsCorpse();
break;
case AgentType.HUMAN:
configureAsHuman();
break;
case AgentType.HUMAN_PLAYER:
configureAsPlayableHuman();
break;
case AgentType.ZOMBIE:
configureAsZombie();
break;
case AgentType.ZOMBIE_PLAYER:
configureAsPlayableZombie();
break;
}
}
private void configureAsCustom()
{
Type = (AgentType.CUSTOM);
}
private void configureAsCorpse()
{
AgentColor = (corpseColor);
LivingState = (AgentPercept.LivingState.DEAD);
Type = (AgentType.CORPSE);
SightRange = (0.0f);
FieldOfView = (0.0f);
Direction = (Random.Range(-180.0f, 180.0f));
Behavior = (new NoopBehavior());
}
private void configureAsHuman()
{
AgentColor = (humanColor);
LivingState = (AgentPercept.LivingState.ALIVE);
Type = (AgentType.HUMAN);
SightRange = (36.0f);
FieldOfView = (180.0f); // roughly full range of vision
Direction = (Random.Range(-180.0f, 180.0f));
SpeedMultiplier = (1.15f);
FallThroughBehavior tempFTB = new FallThroughBehavior();
tempFTB.addBehavior( new FleeBehavior() );
tempFTB.addBehavior( new WanderBehavior() );
tempFTB.addBehavior( new RandomLookBehavior() );
Behavior = (tempFTB);
// Behavior = new RandomWalkBehavior();
}
private void configureAsPlayableHuman()
{
AgentColor = (humanPlayerColor);
LivingState = (AgentPercept.LivingState.ALIVE);
Type = (AgentType.HUMAN_PLAYER);
SightRange = (49.0f); // longer range to help with reaction time
FieldOfView = (135.0f); // slightly expanded vision range, same
Direction = (Random.Range(-180.0f, 180.0f));
SpeedMultiplier = (1.25f); // and slightly faster
TurnSpeedMultiplier = (2.0f);
FallThroughBehavior tempFTB = new FallThroughBehavior();
tempFTB.addBehavior( new PlayerControlBehavior() );
tempFTB.addBehavior( new ExtractionBehavior() );
tempFTB.addBehavior( new RandomLookBehavior() ); // leaving this in for now, useful.
Behavior = (tempFTB);
}
private void configureAsZombie()
{
AgentColor = (zombieColor);
LivingState = (AgentPercept.LivingState.UNDEAD);
Type = (AgentType.ZOMBIE);
SightRange = (25.0f);
FieldOfView = (120.0f);
Direction = (Random.Range(-180.0f, 180.0f));
SpeedMultiplier = (1.0f);
ConvertRange = (2.0f);
FallThroughBehavior tempFTB = new FallThroughBehavior();
// General Zombie:
tempFTB.addBehavior( new ZombifyBehavior() );
tempFTB.addBehavior( new PursueBehavior() );
tempFTB.addBehavior( new NecrophageBehavior() );
tempFTB.addBehavior( new WanderBehavior() );
tempFTB.addBehavior( new RandomLookBehavior() );
// Boid Zombies
// tempFTB.addBehavior( new BoidsBehavior());
// tempFTB.addBehavior( new WanderBehavior() );
// FieldOfView = (351.0f); // add a "tail wedge" to show direction, until something better is in
Behavior = (tempFTB);
}
private void configureAsPlayableZombie()
{
AgentColor = (zombieColor);
LivingState = (AgentPercept.LivingState.UNDEAD);
Type = (AgentType.ZOMBIE_PLAYER);
SightRange = (36.0f); // slightly expanded, to account for reaction time and lack of overwhelming numbers
FieldOfView = (135.0f); // super zombie
Direction = (Random.Range(-180.0f, 180.0f));
SpeedMultiplier = (1.15f); // same as a human
TurnSpeedMultiplier = (2.0f); // just a lot more responsive this way
ConvertRange = (5.0f); // significant boost, to help account for lag/control timing
FallThroughBehavior tempFTB = new FallThroughBehavior();
tempFTB.addBehavior( new ZombifyBehavior() );
tempFTB.addBehavior( new PlayerControlBehavior() );
tempFTB.addBehavior( new RandomLookBehavior() );
Behavior = (tempFTB);
}
private void configureDefault()
{
LivingState = (AgentPercept.LivingState.ALIVE);
Type = (AgentType.HUMAN);
Behavior = (new NoopBehavior());
AgentColor = (humanColor);
Direction = (0.0f);
FieldOfView = (0.0f);
SightRange = (0.0f);
ConvertRange = (0.0f);
SpeedMultiplier = (1.0f);
TurnSpeedMultiplier = (1.0f);
MoveInUse = (false);
LookInUse = (false);
}
#endregion Agent type definitions
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#region Agent state updates
public void extractSuccess()
{
_myRenderer.gameObject.SetActive(false);
}
public void resetPercepts()
{
_perceptIndex = 0;
}
public AgentPercept getNextPercept()
{
if(_perceptIndex >= _perceptPool.Count)
{
_perceptPool.Add(new AgentPercept());
return _perceptPool[_perceptPool.Count-1];
}
return _perceptPool[_perceptIndex++];
}
#endregion Agent state updates
//////////////////////////////////////////////////////////////////
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.ML.Bayesian.Parse;
using Encog.ML.Bayesian.Query;
using Encog.ML.Bayesian.Query.Enumeration;
using Encog.ML.Data;
using Encog.Util;
using Encog.Util.CSV;
namespace Encog.ML.Bayesian
{
/// <summary>
/// The Bayesian Network is a machine learning method that is based on
/// probability, and particularly Bayes' Rule. The Bayesian Network also forms
/// the basis for the Hidden Markov Model and Naive Bayesian Network. The
/// Bayesian Network is either constructed directly or inferred from training
/// data using an algorithm such as K2.
///
/// http://www.heatonresearch.com/wiki/Bayesian_Network
/// </summary>
[Serializable]
public class BayesianNetwork : BasicML, IMLClassification, IMLResettable, IMLError
{
/// <summary>
/// Default choices for a boolean event.
/// </summary>
public static readonly String[] ChoicesTrueFalse = {"true", "false"};
/// <summary>
/// Mapping between the event string names, and the actual events.
/// </summary>
private readonly IDictionary<String, BayesianEvent> _eventMap = new Dictionary<String, BayesianEvent>();
/// <summary>
/// A listing of all of the events.
/// </summary>
private readonly IList<BayesianEvent> _events = new List<BayesianEvent>();
/// <summary>
/// The probabilities of each classification.
/// </summary>
private double[] _classificationProbabilities;
/// <summary>
/// Specifies the classification target.
/// </summary>
private int _classificationTarget;
/// <summary>
/// Specifies if each input is present.
/// </summary>
private bool[] _inputPresent;
/// <summary>
/// Construct a Bayesian network.
/// </summary>
public BayesianNetwork()
{
Query = new EnumerationQuery(this);
}
/// <summary>
/// The current Bayesian query.
/// </summary>
public IBayesianQuery Query { get; set; }
/// <summary>
/// The mapping from string names to events.
/// </summary>
public IDictionary<String, BayesianEvent> EventMap
{
get { return _eventMap; }
}
/// <summary>
/// The events.
/// </summary>
public IList<BayesianEvent> Events
{
get { return _events; }
}
/// <summary>
/// The contents as a string. Shows both events and dependences.
/// </summary>
public String Contents
{
get
{
var result = new StringBuilder();
bool first = true;
foreach (BayesianEvent e in _events)
{
if (!first)
result.Append(" ");
first = false;
result.Append(e.ToFullString());
}
return result.ToString();
}
set
{
IList<ParsedProbability> list = ParseProbability.ParseProbabilityList(this, value);
IList<String> labelList = new List<String>();
// ensure that all events are there
foreach (ParsedProbability prob in list)
{
ParsedEvent parsedEvent = prob.ChildEvent;
String eventLabel = parsedEvent.Label;
labelList.Add(eventLabel);
// create event, if not already here
BayesianEvent e = GetEvent(eventLabel);
if (e == null)
{
IList<BayesianChoice> cl = parsedEvent.ChoiceList.Select(c => new BayesianChoice(c.Label, c.Min, c.Max)).ToList();
CreateEvent(eventLabel, cl);
}
}
// now remove all events that were not covered
foreach (BayesianEvent e in _events)
{
if (!labelList.Contains(e.Label))
{
RemoveEvent(e);
}
}
// handle dependencies
foreach (ParsedProbability prob in list)
{
ParsedEvent parsedEvent = prob.ChildEvent;
String eventLabel = parsedEvent.Label;
BayesianEvent e = RequireEvent(eventLabel);
// ensure that all "givens" are present
IList<String> givenList = new List<String>();
foreach (ParsedEvent given in prob.GivenEvents)
{
if (!e.HasGiven(given.Label))
{
BayesianEvent givenEvent = RequireEvent(given.Label);
CreateDependency(givenEvent, e);
}
givenList.Add(given.Label);
}
// now remove givens that were not covered
foreach (BayesianEvent event2 in e.Parents)
{
if (!givenList.Contains(event2.Label))
{
RemoveDependency(event2, e);
}
}
}
// finalize the structure
FinalizeStructure();
if (Query != null)
{
Query.FinalizeStructure();
}
}
}
/// <summary>
/// Get the classification target.
/// </summary>
public int ClassificationTarget
{
get { return _classificationTarget; }
}
/// <summary>
/// The classification target.
/// </summary>
public BayesianEvent ClassificationTargetEvent
{
get
{
if (_classificationTarget == -1)
{
throw new BayesianError("No classification target defined.");
}
return _events[_classificationTarget];
}
}
/// <summary>
/// Returns a string representation of the classification structure.
/// Of the form P(a|b,c,d)
/// </summary>
public String ClassificationStructure
{
get
{
var result = new StringBuilder();
result.Append("P(");
bool first = true;
for (int i = 0; i < Events.Count; i++)
{
BayesianEvent e = _events[i];
EventState state = Query.GetEventState(e);
if (state.CurrentEventType == EventType.Outcome)
{
if (!first)
{
result.Append(",");
}
result.Append(e.Label);
first = false;
}
}
result.Append("|");
first = true;
for (int i = 0; i < Events.Count; i++)
{
BayesianEvent e = _events[i];
if (Query.GetEventState(e).CurrentEventType == EventType.Evidence)
{
if (!first)
{
result.Append(",");
}
result.Append(e.Label);
first = false;
}
}
result.Append(")");
return result.ToString();
}
}
/// <summary>
/// True if this network has a valid classification target.
/// </summary>
public bool HasValidClassificationTarget
{
get
{
if (_classificationTarget < 0
|| _classificationTarget >= _events.Count)
{
return false;
}
return true;
}
}
#region IMLClassification Members
/// <inheritdoc/>
public int InputCount
{
get { return _events.Count; }
}
/// <inheritdoc/>
public int OutputCount
{
get { return 1; }
}
/// <summary>
/// Classify the input.
/// </summary>
/// <param name="input">The input to classify.</param>
/// <returns>The classification.</returns>
public int Classify(IMLData input)
{
if (_classificationTarget < 0 || _classificationTarget >= _events.Count)
{
throw new BayesianError("Must specify classification target by calling setClassificationTarget.");
}
int[] d = DetermineClasses(input);
// properly tag all of the events
for (int i = 0; i < _events.Count; i++)
{
BayesianEvent e = _events[i];
if (i == _classificationTarget)
{
Query.DefineEventType(e, EventType.Outcome);
}
else if (_inputPresent[i])
{
Query.DefineEventType(e, EventType.Evidence);
Query.SetEventValue(e, d[i]);
}
else
{
Query.DefineEventType(e, EventType.Hidden);
Query.SetEventValue(e, d[i]);
}
}
// loop over and try each outcome choice
BayesianEvent outcomeEvent = _events[_classificationTarget];
_classificationProbabilities = new double[outcomeEvent.Choices.Count];
for (int i = 0; i < outcomeEvent.Choices.Count; i++)
{
Query.SetEventValue(outcomeEvent, i);
Query.Execute();
_classificationProbabilities[i] = Query.Probability;
}
return EngineArray.MaxIndex(_classificationProbabilities);
}
#endregion
#region IMLError Members
/// <inheritdoc/>
public double CalculateError(IMLDataSet data)
{
if (!HasValidClassificationTarget)
return 1.0;
// Call the following just to thrown an error if there is no classification target
ClassificationTarget.ToString();
int badCount = 0;
int totalCount = 0;
foreach (IMLDataPair pair in data)
{
int c = Classify(pair.Input);
totalCount++;
if (c != pair.Input[_classificationTarget])
{
badCount++;
}
}
return badCount/(double) totalCount;
}
#endregion
#region IMLResettable Members
/// <inheritdoc/>
public void Reset()
{
Reset(0);
}
/// <inheritdoc/>
public void Reset(int seed)
{
foreach (BayesianEvent e in _events)
{
e.Reset();
}
}
#endregion
/// <summary>
/// Get an event based on the string label.
/// </summary>
/// <param name="label">The label to locate.</param>
/// <returns>The event found.</returns>
public BayesianEvent GetEvent(String label)
{
if (!_eventMap.ContainsKey(label))
return null;
return _eventMap[label];
}
/// <summary>
/// Get an event based on label, throw an error if not found.
/// </summary>
/// <param name="label">THe event label to find.</param>
/// <returns>The event.</returns>
public BayesianEvent GetEventError(String label)
{
if (!EventExists(label))
throw (new BayesianError("Undefined label: " + label));
return _eventMap[label];
}
/// <summary>
/// Return true if the specified event exists.
/// </summary>
/// <param name="label">The label we are searching for.</param>
/// <returns>True, if the event exists by label.</returns>
public bool EventExists(String label)
{
return _eventMap.ContainsKey(label);
}
/// <summary>
/// Create, or register, the specified event with this bayesian network.
/// </summary>
/// <param name="theEvent">The event to add.</param>
public void CreateEvent(BayesianEvent theEvent)
{
if (EventExists(theEvent.Label))
{
throw new BayesianError("The label \"" + theEvent.Label
+ "\" has already been defined.");
}
_eventMap[theEvent.Label] = theEvent;
_events.Add(theEvent);
}
/// <summary>
/// Create an event specified on the label and options provided.
/// </summary>
/// <param name="label">The label to create this event as.</param>
/// <param name="options">The options, or states, that this event can have.</param>
/// <returns>The newly created event.</returns>
public BayesianEvent CreateEvent(String label, IList<BayesianChoice> options)
{
if (label == null)
{
throw new BayesianError("Can't create event with null label name");
}
if (EventExists(label))
{
throw new BayesianError("The label \"" + label
+ "\" has already been defined.");
}
BayesianEvent e = options.Count == 0 ? new BayesianEvent(label) : new BayesianEvent(label, options);
CreateEvent(e);
return e;
}
/// <summary>
/// Create the specified events based on a variable number of options, or choices.
/// </summary>
/// <param name="label">The label of the event to create.</param>
/// <param name="options">The states that the event can have.</param>
/// <returns>The newly created event.</returns>
public BayesianEvent CreateEvent(String label, params String[] options)
{
if (label == null)
{
throw new BayesianError("Can't create event with null label name");
}
if (EventExists(label))
{
throw new BayesianError("The label \"" + label
+ "\" has already been defined.");
}
BayesianEvent e = options.Length == 0 ? new BayesianEvent(label) : new BayesianEvent(label, options);
CreateEvent(e);
return e;
}
/// <summary>
/// Create a dependency between two events.
/// </summary>
/// <param name="parentEvent">The parent event.</param>
/// <param name="childEvent">The child event.</param>
public void CreateDependency(BayesianEvent parentEvent,
BayesianEvent childEvent)
{
// does the dependency exist?
if (!HasDependency(parentEvent, childEvent))
{
// create the dependency
parentEvent.AddChild(childEvent);
childEvent.AddParent(parentEvent);
}
}
/// <summary>
/// Determine if the two events have a dependency.
/// </summary>
/// <param name="parentEvent">The parent event.</param>
/// <param name="childEvent">The child event.</param>
/// <returns>True if a dependency exists.</returns>
private static bool HasDependency(BayesianEvent parentEvent,
BayesianEvent childEvent)
{
return (parentEvent.Children.Contains(childEvent));
}
/// <summary>
/// Create a dependency between a parent and multiple children.
/// </summary>
/// <param name="parentEvent">The parent event.</param>
/// <param name="children">The child events.</param>
public void CreateDependency(BayesianEvent parentEvent,
params BayesianEvent[] children)
{
foreach (BayesianEvent childEvent in children)
{
parentEvent.AddChild(childEvent);
childEvent.AddParent(parentEvent);
}
}
/// <summary>
/// Create a dependency between two labels.
/// </summary>
/// <param name="parentEventLabel">The parent event.</param>
/// <param name="childEventLabel">The child event.</param>
public void CreateDependency(String parentEventLabel, String childEventLabel)
{
BayesianEvent parentEvent = GetEventError(parentEventLabel);
BayesianEvent childEvent = GetEventError(childEventLabel);
CreateDependency(parentEvent, childEvent);
}
/// <summary>
/// Remove a dependency, if it it exists.
/// </summary>
/// <param name="parent">The parent event.</param>
/// <param name="child">The child event.</param>
private static void RemoveDependency(BayesianEvent parent, BayesianEvent child)
{
parent.Children.Remove(child);
child.Parents.Remove(parent);
}
/// <summary>
/// Remove the specified event.
/// </summary>
/// <param name="theEvent">The event to remove.</param>
private void RemoveEvent(BayesianEvent theEvent)
{
foreach (BayesianEvent e in theEvent.Parents)
{
e.Children.Remove(theEvent);
}
_eventMap.Remove(theEvent.Label);
_events.Remove(theEvent);
}
/// <inheritdoc/>
public override String ToString()
{
var result = new StringBuilder();
bool first = true;
foreach (BayesianEvent e in _events)
{
if (!first)
result.Append(" ");
first = false;
result.Append(e.ToString());
}
return result.ToString();
}
///<summary>
/// Calculate the parameter count.
///</summary>
///<returns>The number of parameters in this Bayesian network.</returns>
public int CalculateParameterCount()
{
return _eventMap.Values.Sum(e => e.CalculateParameterCount());
}
/// <summary>
/// Finalize the structure of this Bayesian network.
/// </summary>
public void FinalizeStructure()
{
foreach (BayesianEvent e in _eventMap.Values)
{
e.FinalizeStructure();
}
if (Query != null)
{
Query.FinalizeStructure();
}
_inputPresent = new bool[_events.Count];
EngineArray.Fill(_inputPresent, true);
_classificationTarget = -1;
}
/// <summary>
/// Validate the structure of this Bayesian network.
/// </summary>
public void Validate()
{
foreach (BayesianEvent e in _eventMap.Values)
{
e.Validate();
}
}
/// <summary>
/// Determine if one Bayesian event is in an array of others.
/// </summary>
/// <param name="given">The events to check.</param>
/// <param name="e">See if e is amoung given.</param>
/// <returns>True if e is amoung given.</returns>
private static bool IsGiven(IEnumerable<BayesianEvent> given, BayesianEvent e)
{
return given.Any(e2 => e == e2);
}
/// <summary>
/// Determine if one event is a descendant of another.
/// </summary>
/// <param name="a">The event to check.</param>
/// <param name="b">The event that has children.</param>
/// <returns>True if a is amoung b's children.</returns>
public bool IsDescendant(BayesianEvent a, BayesianEvent b)
{
if (a == b)
return true;
return b.Children.Any(e => IsDescendant(a, e));
}
/// <summary>
/// True if this event is given or conditionally dependant on the others.
/// </summary>
/// <param name="given">The others to check.</param>
/// <param name="e">The event to check.</param>
/// <returns>True, if is given or descendant.</returns>
private bool IsGivenOrDescendant(IEnumerable<BayesianEvent> given, BayesianEvent e)
{
return given.Any(e2 => IsDescendant(e2, e));
}
/// <summary>
/// Help determine if one event is conditionally independent of another.
/// </summary>
/// <param name="previousHead">The previous head, as we traverse the list.</param>
/// <param name="a">The event to check.</param>
/// <param name="goal">List of events searched.</param>
/// <param name="searched"></param>
/// <param name="given">Given events.</param>
/// <returns>True if conditionally independent.</returns>
private bool IsCondIndependent(bool previousHead, BayesianEvent a,
BayesianEvent goal, IDictionary<BayesianEvent, Object> searched,
params BayesianEvent[] given)
{
// did we find it?
if (a == goal)
{
return false;
}
// search children
foreach (BayesianEvent e in a.Children)
{
if (!searched.ContainsKey(e) || !IsGiven(given, a))
{
searched[e] = null;
if (!IsCondIndependent(true, e, goal, searched, given))
return false;
}
}
// search parents
foreach (BayesianEvent e in a.Parents)
{
if (!searched.ContainsKey(e))
{
searched[e] = null;
if (!previousHead || IsGivenOrDescendant(given, a))
if (!IsCondIndependent(false, e, goal, searched, given))
return false;
}
}
return true;
}
/// <summary>
/// Determine if two events are conditionally independent.
/// </summary>
/// <param name="a">The first event.</param>
/// <param name="b">The second event.</param>
/// <param name="given">What is "given".</param>
/// <returns>True of they are cond. independent.</returns>
public bool IsCondIndependent(BayesianEvent a, BayesianEvent b,
params BayesianEvent[] given)
{
IDictionary<BayesianEvent, Object> searched = new Dictionary<BayesianEvent, Object>();
return IsCondIndependent(false, a, b, searched, given);
}
/// <inheritdoc/>
public double ComputeProbability(IMLData input)
{
// copy the input to evidence
int inputIndex = 0;
foreach (BayesianEvent e in _events)
{
EventState state = Query.GetEventState(e);
if (state.CurrentEventType == EventType.Evidence)
{
state.Value = ((int) input[inputIndex++]);
}
}
// execute the query
Query.Execute();
return Query.Probability;
}
/// <summary>
/// Define the probability for an event.
/// </summary>
/// <param name="line">The event.</param>
/// <param name="probability">The probability.</param>
public void DefineProbability(String line, double probability)
{
var parse = new ParseProbability(this);
ParsedProbability parsedProbability = parse.Parse(line);
parsedProbability.DefineTruthTable(this, probability);
}
/// <summary>
/// Define a probability.
/// </summary>
/// <param name="line">The line to define the probability.</param>
public void DefineProbability(String line)
{
int index = line.LastIndexOf('=');
bool error = false;
double prob = 0.0;
String left = "";
if (index != -1)
{
left = line.Substring(0, index);
String right = line.Substring(index + 1);
try
{
prob = CSVFormat.EgFormat.Parse(right);
}
catch (FormatException)
{
error = true;
}
}
if (error || index == -1)
{
throw new BayesianError(
"Probability must be of the form \"P(event|condition1,condition2,etc.)=0.5\". Conditions are optional.");
}
DefineProbability(left, prob);
}
/// <summary>
/// Require the specified event, thrown an error if it does not exist.
/// </summary>
/// <param name="label">The label.</param>
/// <returns>The event.</returns>
public BayesianEvent RequireEvent(String label)
{
BayesianEvent result = GetEvent(label);
if (result == null)
{
throw new BayesianError("The event " + label + " is not defined.");
}
return result;
}
/// <summary>
/// Define a relationship.
/// </summary>
/// <param name="line">The relationship to define.</param>
public void DefineRelationship(String line)
{
var parse = new ParseProbability(this);
ParsedProbability parsedProbability = parse.Parse(line);
parsedProbability.DefineRelationships(this);
}
/// <summary>
/// Perform a query.
/// </summary>
/// <param name="line">The query.</param>
/// <returns>The probability.</returns>
public double PerformQuery(String line)
{
if (Query == null)
{
throw new BayesianError("This Bayesian network does not have a query to define.");
}
var parse = new ParseProbability(this);
ParsedProbability parsedProbability = parse.Parse(line);
// create a temp query
IBayesianQuery q = Query.Clone();
// first, mark all events as hidden
q.Reset();
// deal with evidence (input)
foreach (ParsedEvent parsedEvent in parsedProbability.GivenEvents)
{
BayesianEvent e = RequireEvent(parsedEvent.Label);
q.DefineEventType(e, EventType.Evidence);
q.SetEventValue(e, parsedEvent.ResolveValue(e));
}
// deal with outcome (output)
foreach (ParsedEvent parsedEvent in parsedProbability.BaseEvents)
{
BayesianEvent e = RequireEvent(parsedEvent.Label);
q.DefineEventType(e, EventType.Outcome);
q.SetEventValue(e, parsedEvent.ResolveValue(e));
}
q.LocateEventTypes();
q.Execute();
return q.Probability;
}
/// <inheritdoc/>
public override void UpdateProperties()
{
// Not needed
}
///<summary>
/// Get the index of the given event.
///</summary>
///<param name="theEvent">The event to get the index of.</param>
///<returns>The index of the event.</returns>
public int GetEventIndex(BayesianEvent theEvent)
{
for (int i = 0; i < _events.Count; i++)
{
if (theEvent == _events[i])
return i;
}
return -1;
}
/// <summary>
/// Remove all relations between nodes.
/// </summary>
public void RemoveAllRelations()
{
foreach (BayesianEvent e in _events)
{
e.RemoveAllRelations();
}
}
/// <summary>
/// Determine the classes for the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>An array of class indexes.</returns>
public int[] DetermineClasses(IMLData input)
{
var result = new int[input.Count];
for (int i = 0; i < input.Count; i++)
{
BayesianEvent e = _events[i];
int classIndex = e.MatchChoiceToRange(input[i]);
result[i] = classIndex;
}
return result;
}
/// <summary>
/// Determine if the specified input is present.
/// </summary>
/// <param name="idx">The index of the input.</param>
/// <returns>True, if the input is present.</returns>
public bool IsInputPresent(int idx)
{
return _inputPresent[idx];
}
/// <summary>
/// Define a classification structure of the form P(A|B) = P(C)
/// </summary>
/// <param name="line">The structure.</param>
public void DefineClassificationStructure(String line)
{
IList<ParsedProbability> list = ParseProbability.ParseProbabilityList(this, line);
if (list.Count > 1)
{
throw new BayesianError("Must only define a single probability, not a chain.");
}
if (list.Count == 0)
{
throw new BayesianError("Must define at least one probability.");
}
// first define everything to be hidden
foreach (BayesianEvent e in _events)
{
Query.DefineEventType(e, EventType.Hidden);
}
// define the base event
ParsedProbability prob = list[0];
if (prob.BaseEvents.Count == 0)
{
return;
}
BayesianEvent be = GetEvent(prob.ChildEvent.Label);
_classificationTarget = _events.IndexOf(be);
Query.DefineEventType(be, EventType.Outcome);
// define the given events
foreach (ParsedEvent parsedGiven in prob.GivenEvents)
{
BayesianEvent given = GetEvent(parsedGiven.Label);
Query.DefineEventType(given, EventType.Evidence);
}
Query.LocateEventTypes();
// set the values
foreach (ParsedEvent parsedGiven in prob.GivenEvents)
{
BayesianEvent e = GetEvent(parsedGiven.Label);
Query.SetEventValue(e, ParseInt(parsedGiven.Value));
}
Query.SetEventValue(be, ParseInt(prob.BaseEvents[0].Value));
}
private int ParseInt(String str)
{
if (str == null)
{
return 0;
}
try
{
return int.Parse(str);
}
catch (FormatException ex)
{
return 0;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using QuantConnect.Api.Serialization;
// Collection of response objects for QuantConnect Organization/ endpoints
namespace QuantConnect.Api
{
/// <summary>
/// Response wrapper for Organizations/List
/// TODO: The response objects in the array do not contain all Organization Properties; do we need another wrapper object?
/// </summary>
public class OrganizationResponseList : RestResponse
{
/// <summary>
/// List of organizations in the response
/// </summary>
[JsonProperty(PropertyName = "organizations")]
public List<Organization> List { get; set; }
}
/// <summary>
/// Response wrapper for Organizations/Read
/// </summary>
public class OrganizationResponse : RestResponse
{
/// <summary>
/// Organization read from the response
/// </summary>
[JsonProperty(PropertyName = "organization")]
public Organization Organization { get; set; }
}
/// <summary>
/// Object representation of Organization from QuantConnect Api
/// </summary>
public class Organization
{
/// <summary>
/// Organization ID; Used for API Calls
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Seats in Organization
/// </summary>
[JsonProperty(PropertyName = "seats")]
public int Seats { get; set; }
/// <summary>
/// Data Agreement information
/// </summary>
[JsonProperty(PropertyName = "data")]
public DataAgreement DataAgreement { get; set; }
/// <summary>
/// Organization Product Subscriptions
/// </summary>
[JsonProperty(PropertyName = "products")]
public List<Product> Products { get; set; }
/// <summary>
/// Organization Credit Balance and Transactions
/// </summary>
[JsonProperty(PropertyName = "credit")]
public Credit Credit { get; set; }
/// <summary>
/// Alphas
/// </summary>
[JsonProperty(PropertyName = "alpha")]
public Alpha Alpha { get; set; }
}
/// <summary>
/// Alphas
/// </summary>
public class Alpha
{
/// <summary>
/// Current licensed alphas
/// </summary>
public List<AlphaLicense> Licenses { get; set; }
}
/// <summary>
/// An alpha license
/// </summary>
public class AlphaLicense
{
/// <summary>
/// Allocated shares
/// </summary>
public decimal Shares { get; set; }
/// <summary>
/// Gets or sets the alpha id
/// </summary>
public string AlphaId { get; set; }
/// <summary>
/// The start time of this license
/// </summary>
public DateTime Start { get; set; }
/// <summary>
/// The end time of this license
/// </summary>
public DateTime End { get; set; }
}
/// <summary>
/// Organization Data Agreement
/// </summary>
public class DataAgreement
{
/// <summary>
/// Epoch time the Data Agreement was Signed
/// </summary>
[JsonProperty(PropertyName = "signedTime")]
public long? EpochSignedTime { get; set; }
/// <summary>
/// DateTime the agreement was signed.
/// Uses EpochSignedTime converted to a standard datetime.
/// </summary>
public DateTime? SignedTime => EpochSignedTime.HasValue ? DateTimeOffset.FromUnixTimeSeconds(EpochSignedTime.Value).DateTime : null;
/// <summary>
/// True/False if it is currently signed
/// </summary>
[JsonProperty(PropertyName = "current")]
public bool Signed { get; set; }
}
/// <summary>
/// Organization Credit Object
/// </summary>
public class Credit
{
/// <summary>
/// Represents a change in organization credit
/// </summary>
public class Movement
{
/// <summary>
/// Date of the change in credit
/// </summary>
[JsonProperty(PropertyName = "date")]
public DateTime Date { get; set; }
/// <summary>
/// Credit description
/// </summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
/// <summary>
/// Amount of change
/// </summary>
[JsonProperty(PropertyName = "amount")]
public decimal Amount { get; set; }
/// <summary>
/// Ending Balance in QCC after Movement
/// </summary>
[JsonProperty(PropertyName = "balance")]
public decimal Balance { get; set; }
}
/// <summary>
/// QCC Current Balance
/// </summary>
[JsonProperty(PropertyName = "balance")]
public decimal Balance { get; set; }
/// <summary>
/// List of changes to Credit
/// </summary>
[JsonProperty(PropertyName = "movements")]
public List<Movement> Movements { get; set; }
}
/// <summary>
/// QuantConnect Products
/// </summary>
[JsonConverter(typeof(ProductJsonConverter))]
public class Product
{
/// <summary>
/// Product Type
/// </summary>
public ProductType Type { get; set; }
/// <summary>
/// Collection of item subscriptions
/// Nodes/Data/Seats/etc
/// </summary>
public List<ProductItem> Items { get; set; }
}
/// <summary>
/// QuantConnect ProductItem
/// </summary>
public class ProductItem
{
/// <summary>
/// Product Type
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Collection of item subscriptions
/// Nodes/Data/Seats/etc
/// </summary>
[JsonProperty(PropertyName = "quantity")]
public int Quantity { get; set; }
/// <summary>
/// USD Unit price for this item
/// </summary>
[JsonProperty(PropertyName = "unitPrice")]
public int UnitPrice { get; set; }
/// <summary>
/// USD Total price for this product
/// </summary>
[JsonProperty(PropertyName = "total")]
public int TotalPrice { get; set; }
/// <summary>
/// ID for this product
/// </summary>
[JsonProperty(PropertyName = "productId")]
public int Id { get; set; }
}
/// <summary>
/// Product types offered by QuantConnect
/// Used by Product class
/// </summary>
public enum ProductType
{
/// <summary>
/// Professional Seats Subscriptions
/// </summary>
ProfessionalSeats,
/// <summary>
/// Backtest Nodes Subscriptions
/// </summary>
BacktestNode,
/// <summary>
/// Research Nodes Subscriptions
/// </summary>
ResearchNode,
/// <summary>
/// Live Trading Nodes Subscriptions
/// </summary>
LiveNode,
/// <summary>
/// Support Subscriptions
/// </summary>
Support,
/// <summary>
/// Data Subscriptions
/// </summary>
Data,
/// <summary>
/// Modules Subscriptions
/// </summary>
Modules
}
}
| |
// 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.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using Xunit;
[assembly: System.Reflection.CustomAttributesTests.Data.Attr(77, name = "AttrSimple")]
[assembly: System.Reflection.CustomAttributesTests.Data.Int32Attr(77, name = "Int32AttrSimple"),
System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = "Int64AttrSimple"),
System.Reflection.CustomAttributesTests.Data.StringAttr("hello", name = "StringAttrSimple"),
System.Reflection.CustomAttributesTests.Data.EnumAttr(System.Reflection.CustomAttributesTests.Data.MyColorEnum.RED, name = "EnumAttrSimple"),
System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(Object), name = "TypeAttrSimple")]
[assembly: System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]
[assembly: System.Diagnostics.Debuggable((System.Diagnostics.DebuggableAttribute.DebuggingModes)263)]
[assembly: System.CLSCompliant(false)]
namespace System.Reflection.Tests
{
public class AssemblyTests
{
static string sourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAssembly.dll");
static string destTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAssembly", "TestAssembly.dll");
static string loadFromTestPath;
static AssemblyTests()
{
loadFromTestPath = null;
#if !uapaot // Assembly.Location not supported (properly) on uapaot.
// Move TestAssembly.dll to subfolder TestAssembly
Directory.CreateDirectory(Path.GetDirectoryName(destTestAssemblyPath));
if (File.Exists(sourceTestAssemblyPath))
{
File.Delete(destTestAssemblyPath);
File.Move(sourceTestAssemblyPath, destTestAssemblyPath);
}
string currAssemblyPath = typeof(AssemblyTests).Assembly.Location;
loadFromTestPath = Path.Combine(Path.GetDirectoryName(currAssemblyPath), "TestAssembly", Path.GetFileName(currAssemblyPath));
File.Copy(currAssemblyPath, loadFromTestPath, true);
#endif
}
public static IEnumerable<object[]> Equality_TestData()
{
yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), typeof(AssemblyTests).Assembly, false };
}
[Theory]
[MemberData(nameof(Equality_TestData))]
public static void Equality(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1 == assembly2);
Assert.NotEqual(expected, assembly1 != assembly2);
}
[Fact]
public static void GetAssembly_Nullery()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Assembly.GetAssembly(null));
}
public static IEnumerable<object[]> GetAssembly_TestData()
{
yield return new object[] { Assembly.Load(new AssemblyName(typeof(HashSet<int>).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(HashSet<int>)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(int)), true };
yield return new object[] { typeof(AssemblyTests).Assembly, Assembly.GetAssembly(typeof(AssemblyTests)), true };
}
[Theory]
[MemberData(nameof(GetAssembly_TestData))]
public static void GetAssembly(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1.Equals(assembly2));
}
public static IEnumerable<object[]> GetCallingAssembly_TestData()
{
yield return new object[] { typeof(AssemblyTests).Assembly, GetGetCallingAssembly(), true };
yield return new object[] { Assembly.GetCallingAssembly(), GetGetCallingAssembly(), false };
}
[Theory]
[MemberData(nameof(GetCallingAssembly_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "GetCallingAssembly() is not supported on UapAot")]
public static void GetCallingAssembly(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1.Equals(assembly2));
}
[Fact]
public static void GetExecutingAssembly()
{
Assert.True(typeof(AssemblyTests).Assembly.Equals(Assembly.GetExecutingAssembly()));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetSatelliteAssembly() not supported on UapAot")]
public static void GetSatelliteAssemblyNeg()
{
Assert.Throws<ArgumentNullException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(null)));
Assert.Throws<System.IO.FileNotFoundException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(CultureInfo.InvariantCulture)));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.Load(String) not supported on UapAot")]
public static void AssemblyLoadFromString()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
string fullName = an.FullName;
string simpleName = an.Name;
Assembly a1 = Assembly.Load(fullName);
Assert.NotNull(a1);
Assert.Equal(fullName, a1.GetName().FullName);
Assembly a2 = Assembly.Load(simpleName);
Assert.NotNull(a2);
Assert.Equal(fullName, a2.GetName().FullName);
}
[Fact]
public static void AssemblyLoadFromStringNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.Load((string)null));
Assert.Throws<ArgumentException>(() => Assembly.Load(string.Empty));
string emptyCName = new string('\0', 1);
Assert.Throws<ArgumentException>(() => Assembly.Load(emptyCName));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.Load(byte[]) not supported on UapAot")]
public static void AssemblyLoadFromBytes()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
Assembly loadedAssembly = Assembly.Load(aBytes);
Assert.NotNull(loadedAssembly);
Assert.Equal(assembly.FullName, loadedAssembly.FullName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.Load(byte[]) not supported on UapAot")]
public static void AssemblyLoadFromBytesNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.Load((byte[])null));
Assert.Throws<BadImageFormatException>(() => Assembly.Load(new byte[0]));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.Load(byte[]) not supported on UapAot")]
public static void AssemblyLoadFromBytesWithSymbols()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
byte[] symbols = System.IO.File.ReadAllBytes((System.IO.Path.ChangeExtension(assembly.Location, ".pdb")));
Assembly loadedAssembly = Assembly.Load(aBytes, symbols);
Assert.NotNull(loadedAssembly);
Assert.Equal(assembly.FullName, loadedAssembly.FullName);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.ReflectionOnlyLoad() not supported on UapAot")]
public static void AssemblyReflectionOnlyLoadFromString()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
Assert.Throws<NotSupportedException>(() => Assembly.ReflectionOnlyLoad(an.FullName));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.ReflectionOnlyLoad() not supported on UapAot")]
public static void AssemblyReflectionOnlyLoadFromBytes()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
Assert.Throws<NotSupportedException>(() => Assembly.ReflectionOnlyLoad(aBytes));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.ReflectionOnlyLoad() not supported on UapAot")]
public static void AssemblyReflectionOnlyLoadFromNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.ReflectionOnlyLoad((string)null));
Assert.Throws<ArgumentException>(() => Assembly.ReflectionOnlyLoad(string.Empty));
Assert.Throws<ArgumentNullException>(() => Assembly.ReflectionOnlyLoad((byte[])null));
}
public static IEnumerable<object[]> GetModules_TestData()
{
yield return new object[] { LoadSystemCollectionsAssembly() };
yield return new object[] { LoadSystemReflectionAssembly() };
}
[Theory]
[MemberData(nameof(GetModules_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetModules() is not supported on UapAot.")]
public static void GetModules_GetModule(Assembly assembly)
{
Assert.NotEmpty(assembly.GetModules());
foreach (Module module in assembly.GetModules())
{
Assert.Equal(module, assembly.GetModule(module.ToString()));
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetLoadedModules() is not supported on UapAot.")]
public static void GetLoadedModules()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.NotEmpty(assembly.GetLoadedModules());
foreach (Module module in assembly.GetLoadedModules())
{
Assert.NotNull(module);
Assert.Equal(module, assembly.GetModule(module.ToString()));
}
}
public static IEnumerable<object[]> CreateInstance_TestData()
{
yield return new object[] { typeof(AssemblyTests).Assembly, typeof(AssemblyPublicClass).FullName, BindingFlags.CreateInstance, typeof(AssemblyPublicClass) };
yield return new object[] { typeof(int).Assembly, typeof(int).FullName, BindingFlags.Default, typeof(int) };
yield return new object[] { typeof(int).Assembly, typeof(Dictionary<int, string>).FullName, BindingFlags.Default, typeof(Dictionary<int, string>) };
}
[Theory]
[MemberData(nameof(CreateInstance_TestData))]
public static void CreateInstance(Assembly assembly, string typeName, BindingFlags bindingFlags, Type expectedType)
{
Assert.IsType(expectedType, assembly.CreateInstance(typeName, true, bindingFlags, null, null, null, null));
Assert.IsType(expectedType, assembly.CreateInstance(typeName, false, bindingFlags, null, null, null, null));
}
public static IEnumerable<object[]> CreateInstance_Invalid_TestData()
{
yield return new object[] { "", typeof(ArgumentException) };
yield return new object[] { null, typeof(ArgumentNullException) };
yield return new object[] { typeof(AssemblyClassWithPrivateCtor).FullName, typeof(MissingMethodException) };
}
[Theory]
[MemberData(nameof(CreateInstance_Invalid_TestData))]
public static void CreateInstance_Invalid(string typeName, Type exceptionType)
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, true, BindingFlags.Public, null, null, null, null));
Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, false, BindingFlags.Public, null, null, null, null));
}
[Fact]
public static void GetManifestResourceStream()
{
Assert.NotNull(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "EmbeddedImage.png"));
Assert.NotNull(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "EmbeddedTextFile.txt"));
Assert.Null(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "IDontExist"));
}
[Fact]
public static void Test_GlobalAssemblyCache()
{
Assert.False(typeof(AssemblyTests).Assembly.GlobalAssemblyCache);
}
[Fact]
public static void Test_HostContext()
{
Assert.Equal(0, typeof(AssemblyTests).Assembly.HostContext);
}
[Fact]
public static void Test_IsFullyTrusted()
{
Assert.True(typeof(AssemblyTests).Assembly.IsFullyTrusted);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework supports SecurityRuleSet")]
public static void Test_SecurityRuleSet_Netcore()
{
Assert.Equal(SecurityRuleSet.None, typeof(AssemblyTests).Assembly.SecurityRuleSet);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "SecurityRuleSet is ignored in .NET Core")]
public static void Test_SecurityRuleSet_Netfx()
{
Assert.Equal(SecurityRuleSet.Level2, typeof(AssemblyTests).Assembly.SecurityRuleSet);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFile() not supported on UapAot")]
public static void Test_LoadFile()
{
Assembly currentAssembly = typeof(AssemblyTests).Assembly;
const string RuntimeTestsDll = "System.Runtime.Tests.dll";
string fullRuntimeTestsPath = Path.GetFullPath(RuntimeTestsDll);
var loadedAssembly1 = Assembly.LoadFile(fullRuntimeTestsPath);
if (PlatformDetection.IsFullFramework)
{
Assert.Equal(currentAssembly, loadedAssembly1);
}
else
{
Assert.NotEqual(currentAssembly, loadedAssembly1);
}
string dir = Path.GetDirectoryName(fullRuntimeTestsPath);
fullRuntimeTestsPath = Path.Combine(dir, ".", RuntimeTestsDll);
Assembly loadedAssembly2 = Assembly.LoadFile(fullRuntimeTestsPath);
if (PlatformDetection.IsFullFramework)
{
Assert.NotEqual(loadedAssembly1, loadedAssembly2);
}
else
{
Assert.Equal(loadedAssembly1, loadedAssembly2);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The full .NET Framework has a bug and throws a NullReferenceException")]
public static void LoadFile_NullPath_Netcore_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("path", () => Assembly.LoadFile(null));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, ".NET Core fixed a bug where LoadFile(null) throws a NullReferenceException")]
public static void LoadFile_NullPath_Netfx_ThrowsNullReferenceException()
{
Assert.Throws<NullReferenceException>(() => Assembly.LoadFile(null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFile() not supported on UapAot")]
public static void LoadFile_NoSuchPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => Assembly.LoadFile("System.Runtime.Tests.dll"));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The full .NET Framework supports Assembly.LoadFrom")]
public static void Test_LoadFromUsingHashValue_Netcore()
{
Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The implementation of Assembly.LoadFrom is stubbed out in .NET Core")]
public static void Test_LoadFromUsingHashValue_Netfx()
{
Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The full .NET Framework supports more than one module per assembly")]
public static void Test_LoadModule_Netcore()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null));
Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null, null));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr doesn't support more than one module per assembly")]
public static void Test_LoadModule_Netfx()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
AssertExtensions.Throws<ArgumentNullException>(null, () => assembly.LoadModule("abc", null));
AssertExtensions.Throws<ArgumentNullException>(null, () => assembly.LoadModule("abc", null, null));
}
#pragma warning disable 618
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFromWithPartialName() not supported on UapAot")]
public static void Test_LoadWithPartialName()
{
string simplename = typeof(AssemblyTests).Assembly.GetName().Name;
var assem = Assembly.LoadWithPartialName(simplename);
Assert.Equal(typeof(AssemblyTests).Assembly, assem);
}
#pragma warning restore 618
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_SamePath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.LoadFrom(destTestAssemblyPath);
Assembly assembly2 = Assembly.LoadFrom(destTestAssemblyPath);
Assert.Equal(assembly1, assembly2);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_SameIdentityAsAssemblyWithDifferentPath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.LoadFrom(typeof(AssemblyTests).Assembly.Location);
Assert.Equal(assembly1, typeof(AssemblyTests).Assembly);
Assembly assembly2 = Assembly.LoadFrom(loadFromTestPath);
if (PlatformDetection.IsFullFramework)
{
Assert.NotEqual(assembly1, assembly2);
}
else
{
Assert.Equal(assembly1, assembly2);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_NullAssemblyFile_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.LoadFrom(null));
AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.UnsafeLoadFrom(null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_EmptyAssemblyFile_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, (() => Assembly.LoadFrom("")));
AssertExtensions.Throws<ArgumentException>(null, (() => Assembly.UnsafeLoadFrom("")));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_NoSuchFile_ThrowsFileNotFoundException()
{
Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("NoSuchPath"));
Assert.Throws<FileNotFoundException>(() => Assembly.UnsafeLoadFrom("NoSuchPath"));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.UnsafeLoadFrom() not supported on UapAot")]
public void UnsafeLoadFrom_SamePath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.UnsafeLoadFrom(destTestAssemblyPath);
Assembly assembly2 = Assembly.UnsafeLoadFrom(destTestAssemblyPath);
Assert.Equal(assembly1, assembly2);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The implementation of LoadFrom(string, byte[], AssemblyHashAlgorithm is not supported in .NET Core.")]
public void LoadFrom_WithHashValue_NetCoreCore_ThrowsNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom(destTestAssemblyPath, new byte[0], Configuration.Assemblies.AssemblyHashAlgorithm.None));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetFile() not supported on UapAot")]
public void GetFile()
{
Assert.Throws<ArgumentNullException>(() => typeof(AssemblyTests).Assembly.GetFile(null));
Assert.Throws<ArgumentException>(() => typeof(AssemblyTests).Assembly.GetFile(""));
Assert.Null(typeof(AssemblyTests).Assembly.GetFile("NonExistentfile.dll"));
Assert.NotNull(typeof(AssemblyTests).Assembly.GetFile("System.Runtime.Tests.dll"));
Assert.Equal(typeof(AssemblyTests).Assembly.GetFile("System.Runtime.Tests.dll").Name, typeof(AssemblyTests).Assembly.Location);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetFiles() not supported on UapAot")]
public void GetFiles()
{
Assert.NotNull(typeof(AssemblyTests).Assembly.GetFiles());
Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles().Length, 1);
Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles()[0].Name, typeof(AssemblyTests).Assembly.Location);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.CodeBase not supported on UapAot")]
public static void Load_AssemblyNameWithCodeBase()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
Assert.NotNull(an.CodeBase);
Assembly a = Assembly.Load(an);
Assert.Equal(a, typeof(AssemblyTests).Assembly);
}
// Helpers
private static Assembly GetGetCallingAssembly()
{
return Assembly.GetCallingAssembly();
}
private static Assembly LoadSystemCollectionsAssembly()
{
// Force System.collections to be linked statically
List<int> li = new List<int>();
li.Add(1);
return Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName));
}
private static Assembly LoadSystemReflectionAssembly()
{
// Force System.Reflection to be linked statically
return Assembly.Load(new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName));
}
public class AssemblyPublicClass
{
public class PublicNestedClass { }
}
private static class AssemblyPrivateClass { }
public class AssemblyClassWithPrivateCtor
{
private AssemblyClassWithPrivateCtor() { }
}
}
public class AssemblyCustomAttributeTest
{
[Fact]
public void Test_Int32AttrSimple()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int32Attr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int32Attr((Int32)77, name = \"Int32AttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_Int64Attr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int64Attr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = \"Int64AttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_StringAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.StringAttr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.StringAttr(\"hello\", name = \"StringAttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_EnumAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.EnumAttr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.EnumAttr((System.Reflection.CustomAttributesTests.Data.MyColorEnum)1, name = \"EnumAttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_TypeAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.TypeAttr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(System.Object), name = \"TypeAttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_CompilationRelaxationsAttr()
{
bool result = false;
Type attrType = typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute);
string attrstr = "[System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_AssemblyIdentityAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.AssemblyTitleAttribute);
string attrstr = "[System.Reflection.AssemblyTitleAttribute(\"System.Reflection.Tests\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_AssemblyDescriptionAttribute()
{
bool result = false;
Type attrType = typeof(System.Reflection.AssemblyDescriptionAttribute);
string attrstr = "[System.Reflection.AssemblyDescriptionAttribute(\"System.Reflection.Tests\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_AssemblyCompanyAttribute()
{
bool result = false;
Type attrType = typeof(System.Reflection.AssemblyCompanyAttribute);
string attrstr = "[System.Reflection.AssemblyCompanyAttribute(\"Microsoft Corporation\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_CLSCompliantAttribute()
{
bool result = false;
Type attrType = typeof(System.CLSCompliantAttribute);
string attrstr = "[System.CLSCompliantAttribute((Boolean)True)]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_DebuggableAttribute()
{
bool result = false;
Type attrType = typeof(System.Diagnostics.DebuggableAttribute);
string attrstr = "[System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute+DebuggingModes)263)]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_SimpleAttribute()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Attr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.Attr((Int32)77, name = \"AttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
private static bool VerifyCustomAttribute(Type type, String attributeStr)
{
Assembly asm = typeof(AssemblyCustomAttributeTest).Assembly;
foreach (CustomAttributeData cad in asm.GetCustomAttributesData())
{
if (cad.AttributeType.Equals(type))
{
return true;
}
}
return false;
}
}
public static class AssemblyTests_GetTYpe
{
[Fact]
public static void AssemblyGetTypeNoQualifierAllowed()
{
Assembly a = typeof(G<int>).Assembly;
string s = typeof(G<int>).AssemblyQualifiedName;
Assert.Throws<ArgumentException>(() => a.GetType(s, throwOnError: true, ignoreCase: false));
}
[Fact]
public static void AssemblyGetTypeDoesntSearchMscorlib()
{
Assembly a = typeof(AssemblyTests_GetTYpe).Assembly;
Assert.Throws<TypeLoadException>(() => a.GetType("System.Object", throwOnError: true, ignoreCase: false));
Assert.Throws<TypeLoadException>(() => a.GetType("G`1[[System.Object]]", throwOnError: true, ignoreCase: false));
}
[Fact]
public static void AssemblyGetTypeDefaultsToItself()
{
Assembly a = typeof(AssemblyTests_GetTYpe).Assembly;
Type t = a.GetType("G`1[[G`1[[System.Int32, mscorlib]]]]", throwOnError: true, ignoreCase: false);
Assert.Equal(typeof(G<G<int>>), t);
}
}
}
internal class G<T> { }
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Contact Point Phone
///<para>SObject Name: ContactPointPhone</para>
///<para>Custom Object: False</para>
///</summary>
public class SfContactPointPhone : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ContactPointPhone"; }
}
///<summary>
/// Contact Point Phone ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Owner ID
/// <para>Name: OwnerId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "ownerId")]
public string OwnerId { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "name")]
[Updateable(false), Createable(false)]
public string Name { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Last Referenced Date
/// <para>Name: LastReferencedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastReferencedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastReferencedDate { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
public string ParentId { get; set; }
///<summary>
/// Active from Date
/// <para>Name: ActiveFromDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "activeFromDate")]
public DateTime? ActiveFromDate { get; set; }
///<summary>
/// Active to Date
/// <para>Name: ActiveToDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "activeToDate")]
public DateTime? ActiveToDate { get; set; }
///<summary>
/// Best time to contact end time
/// <para>Name: BestTimeToContactEndTime</para>
/// <para>SF Type: time</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestTimeToContactEndTime")]
public string BestTimeToContactEndTime { get; set; }
///<summary>
/// Best time to contact start time
/// <para>Name: BestTimeToContactStartTime</para>
/// <para>SF Type: time</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestTimeToContactStartTime")]
public string BestTimeToContactStartTime { get; set; }
///<summary>
/// Best time to contact time zone
/// <para>Name: BestTimeToContactTimezone</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestTimeToContactTimezone")]
public string BestTimeToContactTimezone { get; set; }
///<summary>
/// Is Primary
/// <para>Name: IsPrimary</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isPrimary")]
public bool? IsPrimary { get; set; }
///<summary>
/// Area code
/// <para>Name: AreaCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "areaCode")]
public string AreaCode { get; set; }
///<summary>
/// Telephone number
/// <para>Name: TelephoneNumber</para>
/// <para>SF Type: phone</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "telephoneNumber")]
public string TelephoneNumber { get; set; }
///<summary>
/// Extension number
/// <para>Name: ExtensionNumber</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "extensionNumber")]
public string ExtensionNumber { get; set; }
///<summary>
/// Phone Type
/// <para>Name: PhoneType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "phoneType")]
public string PhoneType { get; set; }
///<summary>
/// Is SMS capable
/// <para>Name: IsSmsCapable</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isSmsCapable")]
public bool? IsSmsCapable { get; set; }
///<summary>
/// Formatted international phone number
/// <para>Name: FormattedInternationalPhoneNumber</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "formattedInternationalPhoneNumber")]
public string FormattedInternationalPhoneNumber { get; set; }
///<summary>
/// Formatted national phone number
/// <para>Name: FormattedNationalPhoneNumber</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "formattedNationalPhoneNumber")]
public string FormattedNationalPhoneNumber { get; set; }
///<summary>
/// Is fax capable
/// <para>Name: IsFaxCapable</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isFaxCapable")]
public bool? IsFaxCapable { get; set; }
///<summary>
/// Is personal phone
/// <para>Name: IsPersonalPhone</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isPersonalPhone")]
public bool? IsPersonalPhone { get; set; }
///<summary>
/// Is business phone
/// <para>Name: IsBusinessPhone</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isBusinessPhone")]
public bool? IsBusinessPhone { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Palmmedia.ReportGenerator.Core.CodeAnalysis;
using Palmmedia.ReportGenerator.Core.Common;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser;
using Palmmedia.ReportGenerator.Core.Parser.FileReading;
using Palmmedia.ReportGenerator.Core.Parser.Filtering;
using Palmmedia.ReportGenerator.Core.Plugin;
using Palmmedia.ReportGenerator.Core.Properties;
using Palmmedia.ReportGenerator.Core.Reporting;
using Palmmedia.ReportGenerator.Core.Reporting.History;
namespace Palmmedia.ReportGenerator.Core
{
/// <summary>
/// The report generator implementation.
/// </summary>
public class Generator : IReportGenerator
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(Program));
/// <summary>
/// Generates a report using given configuration.
/// </summary>
/// <param name="reportConfiguration">The report configuration.</param>
/// <returns><c>true</c> if report was generated successfully; otherwise <c>false</c>.</returns>
public bool GenerateReport(IReportConfiguration reportConfiguration)
{
if (reportConfiguration == null)
{
throw new ArgumentNullException(nameof(reportConfiguration));
}
try
{
var configuration = this.GetConfiguration();
var settings = new Settings();
configuration.GetSection("settings").Bind(settings);
var riskHotspotsAnalysisThresholds = new RiskHotspotsAnalysisThresholds();
configuration.GetSection("riskHotspotsAnalysisThresholds").Bind(riskHotspotsAnalysisThresholds);
return this.GenerateReport(reportConfiguration, settings, riskHotspotsAnalysisThresholds);
}
catch (Exception ex)
{
Logger.Error(ex.GetExceptionMessageForDisplay());
Logger.Error(ex.StackTrace);
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
Console.ReadKey();
}
#endif
return false;
}
}
/// <summary>
/// Generates a report using given configuration.
/// </summary>
/// <param name="reportConfiguration">The report configuration.</param>
/// <param name="settings">The settings.</param>
/// <param name="riskHotspotsAnalysisThresholds">The risk hotspots analysis thresholds.</param>
/// <returns><c>true</c> if report was generated successfully; otherwise <c>false</c>.</returns>
public bool GenerateReport(
IReportConfiguration reportConfiguration,
Settings settings,
RiskHotspotsAnalysisThresholds riskHotspotsAnalysisThresholds)
{
if (reportConfiguration == null)
{
throw new ArgumentNullException(nameof(reportConfiguration));
}
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
if (riskHotspotsAnalysisThresholds == null)
{
throw new ArgumentNullException(nameof(riskHotspotsAnalysisThresholds));
}
try
{
var pluginLoader = new ReflectionPluginLoader(reportConfiguration.Plugins);
IReportBuilderFactory reportBuilderFactory = new ReportBuilderFactory(pluginLoader);
// Set log level before validation is performed
LoggerFactory.VerbosityLevel = reportConfiguration.VerbosityLevel;
Logger.Debug($"{Resources.Executable}: {typeof(Program).Assembly.Location}");
Logger.Debug($"{Resources.WorkingDirectory}: {Directory.GetCurrentDirectory()}");
if (!new ReportConfigurationValidator(reportBuilderFactory).Validate(reportConfiguration))
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
Console.ReadKey();
}
#endif
return false;
}
Logger.Debug(Resources.Settings);
Logger.Debug(" " + JsonSerializer.ToJsonString(settings));
Logger.Debug(" " + JsonSerializer.ToJsonString(riskHotspotsAnalysisThresholds));
var stopWatch = Stopwatch.StartNew();
var parserResult = new CoverageReportParser(
settings.NumberOfReportsParsedInParallel,
settings.NumberOfReportsMergedInParallel,
settings.ExcludeTestProjects,
reportConfiguration.SourceDirectories,
new DefaultFilter(reportConfiguration.AssemblyFilters),
new DefaultFilter(reportConfiguration.ClassFilters),
new DefaultFilter(reportConfiguration.FileFilters))
.ParseFiles(reportConfiguration.ReportFiles);
Logger.DebugFormat(Resources.ReportParsingTook, stopWatch.ElapsedMilliseconds / 1000d);
this.GenerateReport(
reportConfiguration,
settings,
riskHotspotsAnalysisThresholds,
parserResult);
stopWatch.Stop();
Logger.InfoFormat(Resources.ReportGenerationTook, stopWatch.ElapsedMilliseconds / 1000d);
return true;
}
catch (Exception ex)
{
Logger.Error(ex.GetExceptionMessageForDisplay());
Logger.Error(ex.StackTrace);
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
Console.ReadKey();
}
#endif
return false;
}
}
/// <summary>
/// Executes the report generation.
/// </summary>
/// <param name="reportConfiguration">The report configuration.</param>
/// <param name="parserResult">The parser result generated by <see cref="CoverageReportParser"/>.</param>
public void GenerateReport(
IReportConfiguration reportConfiguration,
ParserResult parserResult)
{
if (reportConfiguration == null)
{
throw new ArgumentNullException(nameof(reportConfiguration));
}
if (parserResult == null)
{
throw new ArgumentNullException(nameof(parserResult));
}
var configuration = this.GetConfiguration();
var settings = new Settings();
configuration.GetSection("settings").Bind(settings);
var riskHotspotsAnalysisThresholds = new RiskHotspotsAnalysisThresholds();
configuration.GetSection("riskHotspotsAnalysisThresholds").Bind(riskHotspotsAnalysisThresholds);
this.GenerateReport(reportConfiguration, settings, riskHotspotsAnalysisThresholds, parserResult);
}
/// <summary>
/// Executes the report generation.
/// </summary>
/// <param name="reportConfiguration">The report configuration.</param>
/// <param name="settings">The settings.</param>
/// <param name="riskHotspotsAnalysisThresholds">The risk hotspots analysis thresholds.</param>
/// <param name="parserResult">The parser result generated by <see cref="CoverageReportParser"/>.</param>
public void GenerateReport(
IReportConfiguration reportConfiguration,
Settings settings,
RiskHotspotsAnalysisThresholds riskHotspotsAnalysisThresholds,
ParserResult parserResult)
{
if (reportConfiguration == null)
{
throw new ArgumentNullException(nameof(reportConfiguration));
}
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
if (riskHotspotsAnalysisThresholds == null)
{
throw new ArgumentNullException(nameof(riskHotspotsAnalysisThresholds));
}
if (parserResult == null)
{
throw new ArgumentNullException(nameof(parserResult));
}
var reportContext = new ReportContext(reportConfiguration, settings);
var pluginLoader = new ReflectionPluginLoader(reportConfiguration.Plugins);
IReportBuilderFactory reportBuilderFactory = new ReportBuilderFactory(pluginLoader);
reportContext.RiskHotspotAnalysisResult = new RiskHotspotsAnalyzer(riskHotspotsAnalysisThresholds, settings.DisableRiskHotspots)
.PerformRiskHotspotAnalysis(parserResult.Assemblies);
var overallHistoricCoverages = new List<Parser.Analysis.HistoricCoverage>();
var historyStorage = new HistoryStorageFactory(pluginLoader).GetHistoryStorage(reportConfiguration);
if (historyStorage != null)
{
new HistoryParser(historyStorage, settings.MaximumNumberOfHistoricCoverageFiles, settings.NumberOfReportsParsedInParallel)
.ApplyHistoricCoverage(parserResult.Assemblies, overallHistoricCoverages);
reportContext.OverallHistoricCoverages = overallHistoricCoverages;
}
DateTime executionTime = DateTime.Now;
new Reporting.ReportGenerator(
new CachingFileReader(new LocalFileReader(reportConfiguration.SourceDirectories), settings.CachingDurationOfRemoteFilesInMinutes, settings.CustomHeadersForRemoteFiles),
parserResult,
reportBuilderFactory.GetReportBuilders(reportContext))
.CreateReport(reportConfiguration.HistoryDirectory != null, overallHistoricCoverages, executionTime, reportConfiguration.Tag);
if (historyStorage != null)
{
new HistoryReportGenerator(historyStorage)
.CreateReport(parserResult.Assemblies, executionTime, reportConfiguration.Tag);
}
}
/// <summary>
/// Get the <see cref="IConfigurationRoot"/>.
/// </summary>
/// <returns>The configuration.</returns>
private IConfigurationRoot GetConfiguration()
{
var args = Environment.GetCommandLineArgs()
.Where(a => !a.StartsWith("-property:"))
.Where(a => !a.StartsWith("-p:"))
.Where(a => !CommandLineArgumentNames.CommandLineParameterRegex.IsMatch(a))
.ToArray();
try
{
var builder = new ConfigurationBuilder()
.SetBasePath(new FileInfo(this.GetType().Assembly.Location).DirectoryName)
.AddJsonFile("appsettings.json")
.AddCommandLine(args);
return builder.Build();
}
catch (IOException)
{
// This can happen when excuted within MSBuild (dotnet msbuild): JSON configuration gets ignored
var builder = new ConfigurationBuilder()
.SetBasePath(new FileInfo(this.GetType().Assembly.Location).DirectoryName)
.AddCommandLine(args);
return builder.Build();
}
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
namespace System.Data.SqlClient
{
internal class TdsParserSessionPool
{
// NOTE: This is a very simplistic, lightweight pooler. It wasn't
// intended to handle huge number of items, just to keep track
// of the session objects to ensure that they're cleaned up in
// a timely manner, to avoid holding on to an unacceptable
// amount of server-side resources in the event that consumers
// let their data readers be GC'd, instead of explicitly
// closing or disposing of them
private const int MaxInactiveCount = 10; // pick something, preferably small...
private readonly TdsParser _parser; // parser that owns us
private readonly List<TdsParserStateObject> _cache; // collection of all known sessions
private TdsParserStateObject[] _freeStateObjects; // collection of all sessions available for reuse
private int _freeStateObjectCount; // Number of available free sessions
internal TdsParserSessionPool(TdsParser parser)
{
_parser = parser;
_cache = new List<TdsParserStateObject>();
_freeStateObjects = new TdsParserStateObject[MaxInactiveCount];
_freeStateObjectCount = 0;
}
private bool IsDisposed => (null == _freeStateObjects);
internal void Deactivate()
{
// When being deactivated, we check all the sessions in the
// cache to make sure they're cleaned up and then we dispose of
// sessions that are past what we want to keep around.
List<TdsParserStateObject> orphanedSessions = null;
lock (_cache)
{
foreach (TdsParserStateObject session in _cache)
{
if (session.IsOrphaned)
{
if (orphanedSessions == null)
{
orphanedSessions = new List<TdsParserStateObject>(_cache.Count);
}
orphanedSessions.Add(session);
}
}
}
if (orphanedSessions != null)
{
foreach (TdsParserStateObject orphanedSession in orphanedSessions)
{
PutSession(orphanedSession);
}
}
}
internal void Dispose()
{
TdsParserStateObject[] freeStateObjects;
int freeStateObjectCount;
List<TdsParserStateObject> orphanedSessions = null;
lock (_cache)
{
freeStateObjects = _freeStateObjects;
freeStateObjectCount = _freeStateObjectCount;
_freeStateObjects = null;
_freeStateObjectCount = 0;
for (int i = 0; i < _cache.Count; i++)
{
if (_cache[i].IsOrphaned)
{
if (orphanedSessions == null)
{
orphanedSessions = new List<TdsParserStateObject>();
}
orphanedSessions.Add(_cache[i]);
}
else
{
// Remove the "initial" callback
_cache[i].DecrementPendingCallbacks();
}
}
_cache.Clear();
// Any active sessions will take care of themselves
// (It's too dangerous to dispose them, as this can cause AVs)
}
// Dispose free sessions
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false);
try
{
for (int i = 0; i < freeStateObjectCount; i++)
{
if (freeStateObjects[i] != null)
{
freeStateObjects[i].Dispose();
}
}
if (orphanedSessions != null)
{
foreach (TdsParserStateObject orphanedSession in orphanedSessions)
{
orphanedSession.Dispose();
}
}
}
finally
{
_parser.Connection._parserLock.Release();
}
}
internal TdsParserStateObject GetSession(object owner)
{
TdsParserStateObject session;
bool createSession = false;
lock (_cache)
{
if (IsDisposed)
{
throw ADP.ClosedConnectionError();
}
else if (_freeStateObjectCount > 0)
{
// Free state object - grab it
_freeStateObjectCount--;
session = _freeStateObjects[_freeStateObjectCount];
_freeStateObjects[_freeStateObjectCount] = null;
Debug.Assert(session != null, "There was a null session in the free session list?");
}
else
{
// No free objects, create a new on
session = null;
createSession = true;
}
}
if (createSession)
{
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false);
try
{
session = _parser.CreateSession();
}
finally
{
_parser.Connection._parserLock.Release();
}
lock (_cache)
{
_cache.Add(session);
}
}
session.Activate(owner);
return session;
}
internal void PutSession(TdsParserStateObject session)
{
Debug.Assert(null != session, "null session?");
bool okToReuse;
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false);
try
{
okToReuse = session.Deactivate();
}
finally
{
_parser.Connection._parserLock.Release();
}
bool disposeSession = false;
lock (_cache)
{
if (IsDisposed)
{
// We're diposed - just clean out the session
Debug.Assert(_cache.Count == 0, "SessionPool is disposed, but there are still sessions in the cache?");
disposeSession = true;
}
else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount))
{
// Session is good to re-use and our cache has space
Debug.Assert(!session._pendingData, "pending data on a pooled session?");
_freeStateObjects[_freeStateObjectCount] = session;
_freeStateObjectCount++;
}
else
{
// Either the session is bad, or we have no cache space - so dispose the session and remove it
bool removed = _cache.Remove(session);
Debug.Assert(removed, "session not in pool?");
disposeSession = true;
}
session.RemoveOwner();
}
if (disposeSession)
{
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false);
try
{
session.Dispose();
}
finally
{
_parser.Connection._parserLock.Release();
}
}
}
internal int ActiveSessionsCount => _cache.Count - _freeStateObjectCount;
}
}
| |
using System;
using OpenTK.Compute.CL10;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
namespace scallion
{
public unsafe class CLDeviceInfo
{
public readonly IntPtr DeviceId;
public readonly uint AddressBits;
public CLDeviceInfo(IntPtr deviceId)
{
DeviceId = deviceId;
AddressBits = GetDeviceInfo_uint(DeviceInfo.DeviceAddressBits);
}
public bool Is64Bit
{
get { return AddressBits == 64; }
}
public static IntPtr[] GetDeviceIds()
{
return GetPlatformIds()
.SelectMany(i=>GetDeviceIds(i, DeviceTypeFlags.DeviceTypeAll))
.ToArray();
}
public static IntPtr[] GetDeviceIds(IntPtr platformId, DeviceTypeFlags deviceType)
{
//get numOfPlatforms
uint num;
CheckError(CL.GetDeviceIDs(platformId, deviceType, 0, (IntPtr*)NullPtr, &num));
//get platforms
IntPtr[] ids = new IntPtr[num];
fixed (IntPtr* idsPtr = ids)
{
CheckError(CL.GetDeviceIDs(platformId, deviceType, num, idsPtr, (uint*)NullPtr));
}
return ids;
}
public static IntPtr[] GetPlatformIds()
{
//get numOfPlatforms
uint numOfPlatforms;
CheckError(CL.GetPlatformIDs(0, (IntPtr*)NullPtr, &numOfPlatforms));
//get platforms
IntPtr[] platformsIds = new IntPtr[numOfPlatforms];
fixed(IntPtr* platformsIdsPtr = platformsIds)
{
CheckError(CL.GetPlatformIDs(numOfPlatforms, platformsIdsPtr, (uint*)NullPtr));
}
return platformsIds;
}
public bool Available
{
get { return (bool)GetDeviceInfo_bool(DeviceInfo.DeviceAvailable);}
}
public bool CompilerAvailable
{
get { return (bool)GetDeviceInfo_bool(DeviceInfo.DeviceCompilerAvailable);}
}
public bool EndianLittle
{
get { return (bool)GetDeviceInfo_bool(DeviceInfo.DeviceEndianLittle);}
}
public bool ErrorCorrectionSupport
{
get { return (bool)GetDeviceInfo_bool(DeviceInfo.DeviceErrorCorrectionSupport);}
}
public DeviceExecCapabilitiesFlags ExecutionCapabilities
{
get { return (DeviceExecCapabilitiesFlags)GetDeviceInfo_long(DeviceInfo.DeviceExecutionCapabilities);}
}
public string Extensions
{
get { return (string)GetDeviceInfo_string(DeviceInfo.DeviceExtensions);}
}
public ulong GlobalMemCacheSize
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceGlobalMemCacheSize);}
}
public DeviceMemCacheType GlobalMemCacheType
{
get { return (DeviceMemCacheType)GetDeviceInfo_long(DeviceInfo.DeviceGlobalMemCacheType);}
}
public uint GlobalMemCachelineSize
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceGlobalMemCachelineSize);}
}
public ulong GlobalMemSize
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceGlobalMemSize);}
}
public bool ImageSupport
{
get { return (bool)GetDeviceInfo_bool(DeviceInfo.DeviceImageSupport);}
}
public ulong Image2dMaxHeight
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceImage2dMaxHeight);}
}
public ulong Image2dMaxWidth
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceImage2dMaxWidth);}
}
public ulong Image3dMaxDepth
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceImage3dMaxDepth);}
}
public ulong Image3dMaxHeight
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceImage3dMaxHeight);}
}
public ulong Image3dMaxWidth
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceImage3dMaxWidth);}
}
public ulong LocalMemSize
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceLocalMemSize);}
}
public DeviceLocalMemType LocalMemType
{
get { return (DeviceLocalMemType)GetDeviceInfo_long(DeviceInfo.DeviceLocalMemType);}
}
public uint MaxClockFrequency
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMaxClockFrequency);}
}
public uint MaxComputeUnits
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMaxComputeUnits);}
}
public uint MaxConstantArgs
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMaxConstantArgs);}
}
public ulong MaxConstantBufferSize
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceMaxConstantBufferSize);}
}
public ulong MaxMemAllocSize
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceMaxMemAllocSize);}
}
public ulong MaxParameterSize
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceMaxParameterSize);}
}
public uint MaxReadImageArgs
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMaxReadImageArgs);}
}
public uint MaxSamplers
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMaxSamplers);}
}
public ulong MaxWorkGroupSize
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceMaxWorkGroupSize);}
}
public uint MaxWorkItemDimensions
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMaxWorkItemDimensions);}
}
public uint MaxWriteImageArgs
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMaxWriteImageArgs);}
}
public uint MemBaseAddrAlign
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMemBaseAddrAlign);}
}
public uint MinDataTypeAlignSize
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceMinDataTypeAlignSize);}
}
public string Name
{
get { return (string)GetDeviceInfo_string(DeviceInfo.DeviceName);}
}
public uint PreferredVectorWidthChar
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DevicePreferredVectorWidthChar);}
}
public uint PreferredVectorWidthShort
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DevicePreferredVectorWidthShort);}
}
public uint PreferredVectorWidthInt
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DevicePreferredVectorWidthInt);}
}
public uint PreferredVectorWidthLong
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DevicePreferredVectorWidthLong);}
}
public uint PreferredVectorWidthFloat
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DevicePreferredVectorWidthFloat);}
}
public uint PreferredVectorWidthDouble
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DevicePreferredVectorWidthDouble);}
}
public string Profile
{
get { return (string)GetDeviceInfo_string(DeviceInfo.DeviceProfile);}
}
public ulong ProfilingTimerResolution
{
get { return (ulong)GetDeviceInfo_ulong(DeviceInfo.DeviceProfilingTimerResolution);}
}
public DeviceTypeFlags Type
{
get { return (DeviceTypeFlags)GetDeviceInfo_ulong(DeviceInfo.DeviceType);}
}
public string Vendor
{
get { return (string)GetDeviceInfo_string(DeviceInfo.DeviceVendor);}
}
public uint VendorId
{
get { return (uint)GetDeviceInfo_uint(DeviceInfo.DeviceVendorId);}
}
public string Version
{
get { return (string)GetDeviceInfo_string(DeviceInfo.DeviceVersion);}
}
private uint GetDeviceInfo_uint(DeviceInfo paramName)
{
uint ret = default(uint);
CheckError(CL.GetDeviceInfo<uint>(DeviceId, paramName, IntSizePtr, ref ret, (IntPtr*)NullPtr));
return ret;
}
private long GetDeviceInfo_long(DeviceInfo paramName)
{
long ret = default(long);
CheckError(CL.GetDeviceInfo<long>(DeviceId, paramName, LongSizePtr, ref ret, (IntPtr*)NullPtr));
return ret;
}
private ulong GetDeviceInfo_ulong(DeviceInfo paramName)
{
ulong ret = default(ulong);
CheckError(CL.GetDeviceInfo<ulong>(DeviceId, paramName, LongSizePtr, ref ret, (IntPtr*)NullPtr));
return ret;
}
private bool GetDeviceInfo_bool(DeviceInfo paramName)
{
uint ret = default(uint);
CheckError(CL.GetDeviceInfo<uint>(DeviceId, paramName, IntSizePtr, ref ret, (IntPtr*)NullPtr));
return (Bool)ret == Bool.True;
}
private ulong GetDeviceInfo_size_t(DeviceInfo paramName)
{
if(AddressBits == 32) return (ulong)GetDeviceInfo_uint(paramName);
else return GetDeviceInfo_ulong(paramName);
}
private string GetDeviceInfo_string(DeviceInfo paramName)
{
//get size
IntPtr parmSizePtr;
CheckError(CL.GetDeviceInfo(DeviceId, paramName, Null, Null, out parmSizePtr));
//get value
byte[] value = new byte[parmSizePtr.ToInt32()];
fixed (byte* valuePtr = value)
{
CheckError(CL.GetDeviceInfo(DeviceId, paramName, parmSizePtr, new IntPtr(valuePtr), (IntPtr*)NullPtr));
}
return Encoding.ASCII.GetString(value).Trim('\0');
}
private static void CheckError(int err)
{
if ((ErrorCode)err != ErrorCode.Success)
{
throw new System.InvalidOperationException(string.Format(" ErrorCode:'{0}'", err));
}
}
private static readonly void* NullPtr = IntPtr.Zero.ToPointer();
private static readonly IntPtr Null = IntPtr.Zero;
private static readonly IntPtr IntSizePtr = new IntPtr(sizeof(int));
private static readonly IntPtr LongSizePtr = new IntPtr(sizeof(long));
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace odatav4webapi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace Animations
{
/// <summary>
/// Class inheriting <see cref="AnimatorBase"/> to animate the
/// <see cref="System.Windows.Forms.Control.BackColor"/> of a <see cref="Control"/>.
/// </summary>
public class ControlBackColorAnimator : AnimatorBase
{
#region Fields
private Control _control;
private Color _startColor;
private Color _endColor;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="container">Container the new instance should be added to.</param>
public ControlBackColorAnimator(IContainer container) : base(container)
{
Initialize();
}
/// <summary>
/// Creates a new instance.
/// </summary>
public ControlBackColorAnimator()
{
Initialize();
}
private void Initialize()
{
_startColor = DefaultStartColor;
_endColor = DefaultEndColor;
}
#endregion
#region Public interface
/// <summary>
/// Gets or sets the starting color for the animation.
/// </summary>
[Browsable(true), Category("Appearance")]
[Description("Gets or sets the starting color for the animation.")]
public Color StartColor
{
get { return _startColor; }
set
{
if (_startColor == value)
return;
_startColor = value;
OnStartValueChanged(EventArgs.Empty);
}
}
/// <summary>
/// Gets or sets the ending Color for the animation.
/// </summary>
[Browsable(true), Category("Appearance")]
[Description("Gets or sets the ending Color for the animation.")]
public Color EndColor
{
get { return _endColor; }
set
{
if (_endColor == value)
return;
_endColor = value;
OnEndValueChanged(EventArgs.Empty);
}
}
/// <summary>
/// Gets or sets the <see cref="Control"/> which
/// <see cref="System.Windows.Forms.Control.BackColor"/> should be animated.
/// </summary>
[Browsable(true), Category("Behavior")]
[DefaultValue(null), RefreshProperties(RefreshProperties.Repaint)]
[Description("Gets or sets which Control should be animated.")]
public virtual Control Control
{
get { return _control; }
set
{
if (_control == value)
return;
if (_control != null)
_control.BackColorChanged -= new EventHandler(OnCurrentValueChanged);
_control = value;
if (_control != null)
_control.BackColorChanged += new EventHandler(OnCurrentValueChanged);
base.ResetValues();
}
}
#endregion
#region Overridden from AnimatorBase
/// <summary>
/// Gets or sets the currently shown value.
/// </summary>
protected override object CurrentValueInternal
{
get { return _control == null ? Color.Empty : _control.BackColor; }
set
{
if (_control != null)
_control.BackColor = (Color)value;
}
}
/// <summary>
/// Gets or sets the starting value for the animation.
/// </summary>
public override object StartValue
{
get { return StartColor; }
set { StartColor = (Color)value; }
}
/// <summary>
/// Gets or sets the ending value for the animation.
/// </summary>
public override object EndValue
{
get { return EndColor; }
set { EndColor = (Color)value; }
}
/// <summary>
/// Calculates an interpolated value between <see cref="StartValue"/> and
/// <see cref="EndValue"/> for a given step in %.
/// Giving 0 will return the <see cref="StartValue"/>.
/// Giving 100 will return the <see cref="EndValue"/>.
/// </summary>
/// <param name="step">Animation step in %</param>
/// <returns>Interpolated value for the given step.</returns>
protected override object GetValueForStep(double step)
{
if (_startColor == Color.Empty || _endColor == Color.Empty)
return CurrentValue;
return InterpolateColors(_startColor, _endColor, step);
}
#endregion
#region Protected
/// <summary>
/// Gets the default value of the <see cref="StartColor"/> property.
/// </summary>
protected virtual Color DefaultStartColor
{
get { return Color.Empty; }
}
/// <summary>
/// Gets the default value of the <see cref="EndColor"/> property.
/// </summary>
protected virtual Color DefaultEndColor
{
get { return Color.Empty; }
}
/// <summary>
/// Indicates the designer whether <see cref="StartColor"/> needs
/// to be serialized.
/// </summary>
protected virtual bool ShouldSerializeStartColor()
{
return _startColor != DefaultStartColor;
}
/// <summary>
/// Indicates the designer whether <see cref="EndColor"/> needs
/// to be serialized.
/// </summary>
protected virtual bool ShouldSerializeEndColor()
{
return _endColor != DefaultEndColor;
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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 System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A virtual network
/// First published in XenServer 4.0.
/// </summary>
public partial class Network : XenObject<Network>
{
public Network()
{
}
public Network(string uuid,
string name_label,
string name_description,
List<network_operations> allowed_operations,
Dictionary<string, network_operations> current_operations,
List<XenRef<VIF>> VIFs,
List<XenRef<PIF>> PIFs,
long MTU,
Dictionary<string, string> other_config,
string bridge,
bool managed,
Dictionary<string, XenRef<Blob>> blobs,
string[] tags,
network_default_locking_mode default_locking_mode,
Dictionary<XenRef<VIF>, string> assigned_ips)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VIFs = VIFs;
this.PIFs = PIFs;
this.MTU = MTU;
this.other_config = other_config;
this.bridge = bridge;
this.managed = managed;
this.blobs = blobs;
this.tags = tags;
this.default_locking_mode = default_locking_mode;
this.assigned_ips = assigned_ips;
}
/// <summary>
/// Creates a new Network from a Proxy_Network.
/// </summary>
/// <param name="proxy"></param>
public Network(Proxy_Network proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Network update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VIFs = update.VIFs;
PIFs = update.PIFs;
MTU = update.MTU;
other_config = update.other_config;
bridge = update.bridge;
managed = update.managed;
blobs = update.blobs;
tags = update.tags;
default_locking_mode = update.default_locking_mode;
assigned_ips = update.assigned_ips;
}
internal void UpdateFromProxy(Proxy_Network proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<network_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_network_operations(proxy.current_operations);
VIFs = proxy.VIFs == null ? null : XenRef<VIF>.Create(proxy.VIFs);
PIFs = proxy.PIFs == null ? null : XenRef<PIF>.Create(proxy.PIFs);
MTU = proxy.MTU == null ? 0 : long.Parse((string)proxy.MTU);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
bridge = proxy.bridge == null ? null : (string)proxy.bridge;
managed = (bool)proxy.managed;
blobs = proxy.blobs == null ? null : Maps.convert_from_proxy_string_XenRefBlob(proxy.blobs);
tags = proxy.tags == null ? new string[] {} : (string [])proxy.tags;
default_locking_mode = proxy.default_locking_mode == null ? (network_default_locking_mode) 0 : (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)proxy.default_locking_mode);
assigned_ips = proxy.assigned_ips == null ? null : Maps.convert_from_proxy_XenRefVIF_string(proxy.assigned_ips);
}
public Proxy_Network ToProxy()
{
Proxy_Network result_ = new Proxy_Network();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {};
result_.current_operations = Maps.convert_to_proxy_string_network_operations(current_operations);
result_.VIFs = (VIFs != null) ? Helper.RefListToStringArray(VIFs) : new string[] {};
result_.PIFs = (PIFs != null) ? Helper.RefListToStringArray(PIFs) : new string[] {};
result_.MTU = MTU.ToString();
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.bridge = (bridge != null) ? bridge : "";
result_.managed = managed;
result_.blobs = Maps.convert_to_proxy_string_XenRefBlob(blobs);
result_.tags = tags;
result_.default_locking_mode = network_default_locking_mode_helper.ToString(default_locking_mode);
result_.assigned_ips = Maps.convert_to_proxy_XenRefVIF_string(assigned_ips);
return result_;
}
/// <summary>
/// Creates a new Network from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Network(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
allowed_operations = Helper.StringArrayToEnumList<network_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
current_operations = Maps.convert_from_proxy_string_network_operations(Marshalling.ParseHashTable(table, "current_operations"));
VIFs = Marshalling.ParseSetRef<VIF>(table, "VIFs");
PIFs = Marshalling.ParseSetRef<PIF>(table, "PIFs");
MTU = Marshalling.ParseLong(table, "MTU");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
bridge = Marshalling.ParseString(table, "bridge");
managed = Marshalling.ParseBool(table, "managed");
blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs"));
tags = Marshalling.ParseStringArray(table, "tags");
default_locking_mode = (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), Marshalling.ParseString(table, "default_locking_mode"));
assigned_ips = Maps.convert_from_proxy_XenRefVIF_string(Marshalling.ParseHashTable(table, "assigned_ips"));
}
public bool DeepEquals(Network other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VIFs, other._VIFs) &&
Helper.AreEqual2(this._PIFs, other._PIFs) &&
Helper.AreEqual2(this._MTU, other._MTU) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._bridge, other._bridge) &&
Helper.AreEqual2(this._managed, other._managed) &&
Helper.AreEqual2(this._blobs, other._blobs) &&
Helper.AreEqual2(this._tags, other._tags) &&
Helper.AreEqual2(this._default_locking_mode, other._default_locking_mode) &&
Helper.AreEqual2(this._assigned_ips, other._assigned_ips);
}
public override string SaveChanges(Session session, string opaqueRef, Network server)
{
if (opaqueRef == null)
{
Proxy_Network p = this.ToProxy();
return session.proxy.network_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
Network.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
Network.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_MTU, server._MTU))
{
Network.set_MTU(session, opaqueRef, _MTU);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Network.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_tags, server._tags))
{
Network.set_tags(session, opaqueRef, _tags);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Network get_record(Session session, string _network)
{
return new Network((Proxy_Network)session.proxy.network_get_record(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get a reference to the network instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Network> get_by_uuid(Session session, string _uuid)
{
return XenRef<Network>.Create(session.proxy.network_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new network instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Network> create(Session session, Network _record)
{
return XenRef<Network>.Create(session.proxy.network_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new network instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, Network _record)
{
return XenRef<Task>.Create(session.proxy.async_network_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified network instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static void destroy(Session session, string _network)
{
session.proxy.network_destroy(session.uuid, (_network != null) ? _network : "").parse();
}
/// <summary>
/// Destroy the specified network instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static XenRef<Task> async_destroy(Session session, string _network)
{
return XenRef<Task>.Create(session.proxy.async_network_destroy(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get all the network instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Network>> get_by_name_label(Session session, string _label)
{
return XenRef<Network>.Create(session.proxy.network_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_uuid(Session session, string _network)
{
return (string)session.proxy.network_get_uuid(session.uuid, (_network != null) ? _network : "").parse();
}
/// <summary>
/// Get the name/label field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_name_label(Session session, string _network)
{
return (string)session.proxy.network_get_name_label(session.uuid, (_network != null) ? _network : "").parse();
}
/// <summary>
/// Get the name/description field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_name_description(Session session, string _network)
{
return (string)session.proxy.network_get_name_description(session.uuid, (_network != null) ? _network : "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<network_operations> get_allowed_operations(Session session, string _network)
{
return Helper.StringArrayToEnumList<network_operations>(session.proxy.network_get_allowed_operations(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the current_operations field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, network_operations> get_current_operations(Session session, string _network)
{
return Maps.convert_from_proxy_string_network_operations(session.proxy.network_get_current_operations(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the VIFs field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<XenRef<VIF>> get_VIFs(Session session, string _network)
{
return XenRef<VIF>.Create(session.proxy.network_get_vifs(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the PIFs field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<XenRef<PIF>> get_PIFs(Session session, string _network)
{
return XenRef<PIF>.Create(session.proxy.network_get_pifs(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the MTU field of the given network.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static long get_MTU(Session session, string _network)
{
return long.Parse((string)session.proxy.network_get_mtu(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, string> get_other_config(Session session, string _network)
{
return Maps.convert_from_proxy_string_string(session.proxy.network_get_other_config(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the bridge field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_bridge(Session session, string _network)
{
return (string)session.proxy.network_get_bridge(session.uuid, (_network != null) ? _network : "").parse();
}
/// <summary>
/// Get the managed field of the given network.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static bool get_managed(Session session, string _network)
{
return (bool)session.proxy.network_get_managed(session.uuid, (_network != null) ? _network : "").parse();
}
/// <summary>
/// Get the blobs field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, XenRef<Blob>> get_blobs(Session session, string _network)
{
return Maps.convert_from_proxy_string_XenRefBlob(session.proxy.network_get_blobs(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the tags field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string[] get_tags(Session session, string _network)
{
return (string [])session.proxy.network_get_tags(session.uuid, (_network != null) ? _network : "").parse();
}
/// <summary>
/// Get the default_locking_mode field of the given network.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static network_default_locking_mode get_default_locking_mode(Session session, string _network)
{
return (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)session.proxy.network_get_default_locking_mode(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Get the assigned_ips field of the given network.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<XenRef<VIF>, string> get_assigned_ips(Session session, string _network)
{
return Maps.convert_from_proxy_XenRefVIF_string(session.proxy.network_get_assigned_ips(session.uuid, (_network != null) ? _network : "").parse());
}
/// <summary>
/// Set the name/label field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _network, string _label)
{
session.proxy.network_set_name_label(session.uuid, (_network != null) ? _network : "", (_label != null) ? _label : "").parse();
}
/// <summary>
/// Set the name/description field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _network, string _description)
{
session.proxy.network_set_name_description(session.uuid, (_network != null) ? _network : "", (_description != null) ? _description : "").parse();
}
/// <summary>
/// Set the MTU field of the given network.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_mtu">New value to set</param>
public static void set_MTU(Session session, string _network, long _mtu)
{
session.proxy.network_set_mtu(session.uuid, (_network != null) ? _network : "", _mtu.ToString()).parse();
}
/// <summary>
/// Set the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _network, Dictionary<string, string> _other_config)
{
session.proxy.network_set_other_config(session.uuid, (_network != null) ? _network : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _network, string _key, string _value)
{
session.proxy.network_add_to_other_config(session.uuid, (_network != null) ? _network : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given network. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _network, string _key)
{
session.proxy.network_remove_from_other_config(session.uuid, (_network != null) ? _network : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Set the tags field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_tags">New value to set</param>
public static void set_tags(Session session, string _network, string[] _tags)
{
session.proxy.network_set_tags(session.uuid, (_network != null) ? _network : "", _tags).parse();
}
/// <summary>
/// Add the given value to the tags field of the given network. If the value is already in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">New value to add</param>
public static void add_tags(Session session, string _network, string _value)
{
session.proxy.network_add_tags(session.uuid, (_network != null) ? _network : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given value from the tags field of the given network. If the value is not in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">Value to remove</param>
public static void remove_tags(Session session, string _network, string _value)
{
session.proxy.network_remove_tags(session.uuid, (_network != null) ? _network : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type)
{
return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.uuid, (_network != null) ? _network : "", (_name != null) ? _name : "", (_mime_type != null) ? _mime_type : "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type)
{
return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.uuid, (_network != null) ? _network : "", (_name != null) ? _name : "", (_mime_type != null) ? _mime_type : "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public)
{
return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.uuid, (_network != null) ? _network : "", (_name != null) ? _name : "", (_mime_type != null) ? _mime_type : "", _public).parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public)
{
return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.uuid, (_network != null) ? _network : "", (_name != null) ? _name : "", (_mime_type != null) ? _mime_type : "", _public).parse());
}
/// <summary>
/// Set the default locking mode for VIFs attached to this network
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The default locking mode for VIFs attached to this network.</param>
public static void set_default_locking_mode(Session session, string _network, network_default_locking_mode _value)
{
session.proxy.network_set_default_locking_mode(session.uuid, (_network != null) ? _network : "", network_default_locking_mode_helper.ToString(_value)).parse();
}
/// <summary>
/// Set the default locking mode for VIFs attached to this network
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The default locking mode for VIFs attached to this network.</param>
public static XenRef<Task> async_set_default_locking_mode(Session session, string _network, network_default_locking_mode _value)
{
return XenRef<Task>.Create(session.proxy.async_network_set_default_locking_mode(session.uuid, (_network != null) ? _network : "", network_default_locking_mode_helper.ToString(_value)).parse());
}
/// <summary>
/// Return a list of all the networks known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Network>> get_all(Session session)
{
return XenRef<Network>.Create(session.proxy.network_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the network Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Network>, Network> get_all_records(Session session)
{
return XenRef<Network>.Create<Proxy_Network>(session.proxy.network_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<network_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<network_operations> _allowed_operations;
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, network_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, network_operations> _current_operations;
/// <summary>
/// list of connected vifs
/// </summary>
public virtual List<XenRef<VIF>> VIFs
{
get { return _VIFs; }
set
{
if (!Helper.AreEqual(value, _VIFs))
{
_VIFs = value;
Changed = true;
NotifyPropertyChanged("VIFs");
}
}
}
private List<XenRef<VIF>> _VIFs;
/// <summary>
/// list of connected pifs
/// </summary>
public virtual List<XenRef<PIF>> PIFs
{
get { return _PIFs; }
set
{
if (!Helper.AreEqual(value, _PIFs))
{
_PIFs = value;
Changed = true;
NotifyPropertyChanged("PIFs");
}
}
}
private List<XenRef<PIF>> _PIFs;
/// <summary>
/// MTU in octets
/// First published in XenServer 5.6.
/// </summary>
public virtual long MTU
{
get { return _MTU; }
set
{
if (!Helper.AreEqual(value, _MTU))
{
_MTU = value;
Changed = true;
NotifyPropertyChanged("MTU");
}
}
}
private long _MTU;
/// <summary>
/// additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
/// <summary>
/// name of the bridge corresponding to this network on the local host
/// </summary>
public virtual string bridge
{
get { return _bridge; }
set
{
if (!Helper.AreEqual(value, _bridge))
{
_bridge = value;
Changed = true;
NotifyPropertyChanged("bridge");
}
}
}
private string _bridge;
/// <summary>
/// true if the bridge is managed by xapi
/// First published in .
/// </summary>
public virtual bool managed
{
get { return _managed; }
set
{
if (!Helper.AreEqual(value, _managed))
{
_managed = value;
Changed = true;
NotifyPropertyChanged("managed");
}
}
}
private bool _managed;
/// <summary>
/// Binary blobs associated with this network
/// First published in XenServer 5.0.
/// </summary>
public virtual Dictionary<string, XenRef<Blob>> blobs
{
get { return _blobs; }
set
{
if (!Helper.AreEqual(value, _blobs))
{
_blobs = value;
Changed = true;
NotifyPropertyChanged("blobs");
}
}
}
private Dictionary<string, XenRef<Blob>> _blobs;
/// <summary>
/// user-specified tags for categorization purposes
/// First published in XenServer 5.0.
/// </summary>
public virtual string[] tags
{
get { return _tags; }
set
{
if (!Helper.AreEqual(value, _tags))
{
_tags = value;
Changed = true;
NotifyPropertyChanged("tags");
}
}
}
private string[] _tags;
/// <summary>
/// The network will use this value to determine the behaviour of all VIFs where locking_mode = default
/// First published in XenServer 6.1.
/// </summary>
public virtual network_default_locking_mode default_locking_mode
{
get { return _default_locking_mode; }
set
{
if (!Helper.AreEqual(value, _default_locking_mode))
{
_default_locking_mode = value;
Changed = true;
NotifyPropertyChanged("default_locking_mode");
}
}
}
private network_default_locking_mode _default_locking_mode;
/// <summary>
/// The IP addresses assigned to VIFs on networks that have active xapi-managed DHCP
/// First published in XenServer 6.5.
/// </summary>
public virtual Dictionary<XenRef<VIF>, string> assigned_ips
{
get { return _assigned_ips; }
set
{
if (!Helper.AreEqual(value, _assigned_ips))
{
_assigned_ips = value;
Changed = true;
NotifyPropertyChanged("assigned_ips");
}
}
}
private Dictionary<XenRef<VIF>, string> _assigned_ips;
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// A chain shape is a free form sequence of line segments.
/// The chain has two-sided collision, so you can use inside and outside collision.
/// Therefore, you may use any winding order.
/// Connectivity information is used to create smooth collisions.
/// WARNING: The chain will not collide properly if there are self-intersections.
/// </summary>
public class ChainShape : Shape
{
/// <summary>
/// The vertices. These are not owned/freed by the chain Shape.
/// </summary>
public Vertices Vertices;
public override int ChildCount => Vertices.Count - 1;
/// <summary>
/// Establish connectivity to a vertex that precedes the first vertex.
/// Don't call this for loops.
/// </summary>
public Vector2 PrevVertex
{
get => _prevVertex;
set
{
_prevVertex = value;
_hasPrevVertex = true;
}
}
/// <summary>
/// Establish connectivity to a vertex that follows the last vertex.
/// Don't call this for loops.
/// </summary>
public Vector2 NextVertex
{
get => _nextVertex;
set
{
_nextVertex = value;
_hasNextVertex = true;
}
}
Vector2 _prevVertex, _nextVertex;
bool _hasPrevVertex, _hasNextVertex;
static EdgeShape _edgeShape = new EdgeShape();
/// <summary>
/// Constructor for ChainShape. By default have 0 in density.
/// </summary>
public ChainShape() : base(0)
{
ShapeType = ShapeType.Chain;
_radius = Settings.PolygonRadius;
}
/// <summary>
/// Create a new chainshape from the vertices.
/// </summary>
/// <param name="vertices">The vertices to use. Must contain 2 or more vertices.</param>
/// <param name="createLoop">Set to true to create a closed loop. It connects the first vertice to the last, and automatically adjusts connectivity to create smooth collisions along the chain.</param>
public ChainShape(Vertices vertices, bool createLoop = false) : base(0)
{
ShapeType = ShapeType.Chain;
_radius = Settings.PolygonRadius;
SetVertices(vertices, createLoop);
}
/// <summary>
/// This method has been optimized to reduce garbage.
/// </summary>
/// <param name="edge">The cached edge to set properties on.</param>
/// <param name="index">The index.</param>
internal void GetChildEdge(EdgeShape edge, int index)
{
Debug.Assert(0 <= index && index < Vertices.Count - 1);
Debug.Assert(edge != null);
edge.ShapeType = ShapeType.Edge;
edge._radius = _radius;
edge.Vertex1 = Vertices[index + 0];
edge.Vertex2 = Vertices[index + 1];
if (index > 0)
{
edge.Vertex0 = Vertices[index - 1];
edge.HasVertex0 = true;
}
else
{
edge.Vertex0 = _prevVertex;
edge.HasVertex0 = _hasPrevVertex;
}
if (index < Vertices.Count - 2)
{
edge.Vertex3 = Vertices[index + 2];
edge.HasVertex3 = true;
}
else
{
edge.Vertex3 = _nextVertex;
edge.HasVertex3 = _hasNextVertex;
}
}
/// <summary>
/// Get a child edge.
/// </summary>
/// <param name="index">The index.</param>
public EdgeShape GetChildEdge(int index)
{
var edgeShape = new EdgeShape();
GetChildEdge(edgeShape, index);
return edgeShape;
}
public void SetVertices(Vertices vertices, bool createLoop = false)
{
Debug.Assert(vertices != null && vertices.Count >= 3);
Debug.Assert(vertices[0] !=
vertices[
vertices.Count -
1]); // FPE. See http://www.box2d.org/forum/viewtopic.php?f=4&t=7973&p=35363
for (int i = 1; i < vertices.Count; ++i)
{
var v1 = vertices[i - 1];
var v2 = vertices[i];
// If the code crashes here, it means your vertices are too close together.
Debug.Assert(Vector2.DistanceSquared(v1, v2) > Settings.LinearSlop * Settings.LinearSlop);
}
this.Vertices = vertices;
if (createLoop)
{
this.Vertices.Add(vertices[0]);
PrevVertex =
this.Vertices
[this.Vertices.Count - 2]; // FPE: We use the properties instead of the private fields here.
NextVertex = this.Vertices[1]; // FPE: We use the properties instead of the private fields here.
}
}
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
return false;
}
public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform,
int childIndex)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
i2 = 0;
_edgeShape.Vertex1 = Vertices[i1];
_edgeShape.Vertex2 = Vertices[i2];
return _edgeShape.RayCast(out output, ref input, ref transform, 0);
}
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
i2 = 0;
var v1 = MathUtils.Mul(ref transform, Vertices[i1]);
var v2 = MathUtils.Mul(ref transform, Vertices[i2]);
aabb.LowerBound = Vector2.Min(v1, v2);
aabb.UpperBound = Vector2.Max(v1, v2);
}
protected override void ComputeProperties()
{
//Does nothing. Chain shapes don't have properties.
}
public override float ComputeSubmergedArea(ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
return 0;
}
/// <summary>
/// Compare the chain to another chain
/// </summary>
/// <param name="shape">The other chain</param>
/// <returns>True if the two chain shapes are the same</returns>
public bool CompareTo(ChainShape shape)
{
if (Vertices.Count != shape.Vertices.Count)
return false;
for (int i = 0; i < Vertices.Count; i++)
{
if (Vertices[i] != shape.Vertices[i])
return false;
}
return PrevVertex == shape.PrevVertex && NextVertex == shape.NextVertex;
}
public override Shape Clone()
{
var clone = new ChainShape();
clone.ShapeType = ShapeType;
clone._density = _density;
clone._radius = _radius;
clone.PrevVertex = _prevVertex;
clone.NextVertex = _nextVertex;
clone._hasNextVertex = _hasNextVertex;
clone._hasPrevVertex = _hasPrevVertex;
clone.Vertices = new Vertices(Vertices);
clone.MassData = MassData;
return clone;
}
}
}
| |
// XmlAttributeCollectionTests.cs : Tests for the XmlAttributeCollection class
//
// Author: Matt Hunter <xrkune@tconl.com>
// Author: Martin Willemoes Hansen <mwh@sysrq.dk>
//
// (C) 2002 Matt Hunter
// (C) 2003 Martin Willemoes Hansen
using System;
using System.Xml;
using System.Text;
using System.IO;
using System.Collections;
using NUnit.Framework;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XmlAttributeCollectionTests
{
private XmlDocument document;
[SetUp]
public void GetReady()
{
document = new XmlDocument ();
}
[Test]
public void RemoveAll ()
{
StringBuilder xml = new StringBuilder ();
xml.Append ("<?xml version=\"1.0\" ?><library><book type=\"non-fiction\" price=\"34.95\"> ");
xml.Append ("<title type=\"intro\">XML Fun</title> " );
xml.Append ("<author>John Doe</author></book></library>");
MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml.ToString ()));
document = new XmlDocument ();
document.Load (memoryStream);
XmlNodeList bookList = document.GetElementsByTagName ("book");
XmlNode xmlNode = bookList.Item (0);
XmlElement xmlElement = xmlNode as XmlElement;
XmlAttributeCollection attributes = xmlElement.Attributes;
attributes.RemoveAll ();
Assert.AreEqual (false, xmlElement.HasAttribute ("type"), "not all attributes removed.");
}
[Test]
public void Append ()
{
XmlDocument xmlDoc = new XmlDocument ();
XmlElement xmlEl = xmlDoc.CreateElement ("TestElement");
XmlAttribute xmlAttribute = xmlEl.SetAttributeNode ("attr1", "namespace1");
XmlNode xmlNode = xmlDoc.CreateNode (XmlNodeType.Attribute, "attr3", "namespace1");
XmlAttribute xmlAttribute3 = xmlNode as XmlAttribute;
XmlAttributeCollection attributeCol = xmlEl.Attributes;
xmlAttribute3 = attributeCol.Append (xmlAttribute3);
Assert.AreEqual (true, xmlAttribute3.Name.Equals ("attr3"), "attribute name not properly created.");
Assert.AreEqual (true, xmlAttribute3.NamespaceURI.Equals ("namespace1"), "attribute namespace not properly created.");
}
[Test]
public void CopyTo ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root a1='garnet' a2='amethyst' a3='Bloodstone' a4='diamond' a5='emerald' a6='pearl' a7='ruby' a8='sapphire' a9='moonstone' a10='opal' a11='topaz' a12='turquoize' />");
XmlAttributeCollection col = xmlDoc.DocumentElement.Attributes;
XmlAttribute[] array = new XmlAttribute[24];
col.CopyTo(array, 0);
Assert.AreEqual ("garnet", array[0].Value);
Assert.AreEqual ("moonstone", array[8].Value);
Assert.AreEqual ("turquoize", array[11].Value);
col.CopyTo(array, 12);
Assert.AreEqual ("garnet", array[12].Value);
Assert.AreEqual ("moonstone", array[20].Value);
Assert.AreEqual ("turquoize", array[23].Value);
}
[Test]
public void SetNamedItem ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root />");
XmlElement el = xmlDoc.DocumentElement;
XmlAttributeCollection col = xmlDoc.DocumentElement.Attributes;
XmlAttribute attr = xmlDoc.CreateAttribute("b3");
attr.Value = "bloodstone";
col.SetNamedItem(attr);
Assert.AreEqual ("bloodstone", el.GetAttribute("b3"), "SetNamedItem.Normal");
attr = xmlDoc.CreateAttribute("b3");
attr.Value = "aquamaline";
col.SetNamedItem(attr);
Assert.AreEqual ("aquamaline", el.GetAttribute("b3"), "SetNamedItem.Override");
Assert.AreEqual (1, el.Attributes.Count, "SetNamedItem.Override.Count.1");
Assert.AreEqual (1, col.Count, "SetNamedItem.Override.Count.2");
}
[Test]
public void InsertBeforeAfterPrepend ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root b2='amethyst' />");
XmlElement el = xmlDoc.DocumentElement;
XmlAttributeCollection col = xmlDoc.DocumentElement.Attributes;
XmlAttribute attr = xmlDoc.CreateAttribute("b1");
attr.Value = "garnet";
col.InsertAfter(attr, null);
Assert.AreEqual ("garnet", el.GetAttributeNode("b1").Value, "InsertAfterNull");
Assert.AreEqual (el.GetAttribute("b1"), col[0].Value, "InsertAfterNull.Pos");
attr = xmlDoc.CreateAttribute("b3");
attr.Value = "bloodstone";
col.InsertAfter(attr, el.GetAttributeNode("b2"));
Assert.AreEqual ("bloodstone", el.GetAttributeNode("b3").Value, "InsertAfterAttr");
Assert.AreEqual (el.GetAttribute("b3"), col[2].Value, "InsertAfterAttr.Pos");
attr = xmlDoc.CreateAttribute("b4");
attr.Value = "diamond";
col.InsertBefore(attr, null);
Assert.AreEqual ("diamond", el.GetAttributeNode("b4").Value, "InsertBeforeNull");
Assert.AreEqual (el.GetAttribute("b4"), col[3].Value, "InsertBeforeNull.Pos");
attr = xmlDoc.CreateAttribute("warning");
attr.Value = "mixed modern and traditional;-)";
col.InsertBefore(attr, el.GetAttributeNode("b1"));
Assert.AreEqual ("mixed modern and traditional;-)", el.GetAttributeNode("warning").Value, "InsertBeforeAttr");
Assert.AreEqual (el.GetAttributeNode("warning").Value, col[0].Value, "InsertBeforeAttr.Pos");
attr = xmlDoc.CreateAttribute("about");
attr.Value = "lists of birthstone.";
col.Prepend(attr);
Assert.AreEqual ("lists of birthstone.", col[0].Value, "Prepend");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void InsertAfterError ()
{
this.document.LoadXml ("<root><elem a='1'/></root>");
XmlAttribute attr = document.CreateAttribute ("foo");
attr.Value = "test";
document.DocumentElement.Attributes.InsertAfter (attr, document.DocumentElement.FirstChild.Attributes [0]);
}
[Test]
public void InsertAfterReplacesInCorrectOrder ()
{
XmlDocument testDoc = new XmlDocument ();
XmlElement testElement = testDoc.CreateElement ("TestElement" );
testDoc.AppendChild (testElement);
XmlAttribute testAttr1 = testDoc.CreateAttribute ("TestAttribute1");
testAttr1.Value = "First attribute";
testElement.Attributes.Prepend (testAttr1);
XmlAttribute testAttr2 = testDoc.CreateAttribute ("TestAttribute2");
testAttr2.Value = "Second attribute";
testElement.Attributes.InsertAfter (testAttr2, testAttr1);
XmlAttribute testAttr3 = testDoc.CreateAttribute ("TestAttribute3");
testAttr3.Value = "Third attribute";
testElement.Attributes.InsertAfter (testAttr3, testAttr2);
XmlAttribute outOfOrder = testDoc.CreateAttribute ("TestAttribute2");
outOfOrder.Value = "Should still be second attribute";
testElement.Attributes.InsertAfter (outOfOrder, testElement.Attributes [0]);
Assert.AreEqual ("First attribute", testElement.Attributes [0].Value);
Assert.AreEqual ("Should still be second attribute", testElement.Attributes [1].Value);
Assert.AreEqual ("Third attribute", testElement.Attributes [2].Value);
}
[Test]
public void Remove ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root a1='garnet' a2='amethyst' a3='bloodstone' a4='diamond' a5='emerald' a6='pearl' a7='ruby' a8='sapphire' a9='moonstone' a10='opal' a11='topaz' a12='turquoize' />");
XmlElement el = xmlDoc.DocumentElement;
XmlAttributeCollection col = el.Attributes;
// Remove
XmlAttribute attr = col.Remove(el.GetAttributeNode("a12"));
Assert.AreEqual (11, col.Count, "Remove");
Assert.AreEqual ("a12", attr.Name, "Remove.Removed");
// RemoveAt
attr = col.RemoveAt(5);
Assert.AreEqual (null, el.GetAttributeNode("a6"), "RemoveAt");
Assert.AreEqual ("pearl", attr.Value, "Remove.Removed");
}
[Test]
#if NET_2_0
[Category ("NotDotNet")] // enbug
#endif
public void RemoveDefaultAttribute ()
{
string dtd = "<!DOCTYPE root [<!ELEMENT root EMPTY><!ATTLIST root attr CDATA 'default'>]>";
string xml = dtd + "<root/>";
XmlDocument doc = new XmlDocument();
doc.LoadXml (xml);
doc.DocumentElement.Attributes ["attr"].Value = "modified";
doc.DocumentElement.RemoveAttribute("attr");
XmlAttribute defAttr = doc.DocumentElement.Attributes ["attr"];
Assert.IsNotNull (defAttr);
Assert.AreEqual ("default", defAttr.Value);
defAttr.Value = "default"; // same value as default
Assert.AreEqual (true, defAttr.Specified);
}
[Test]
public void AddIdenticalAttrToTheSameNode ()
{
XmlDocument doc = new XmlDocument ();
doc.LoadXml (@"<blah><br><mynode txt='blah/drinks1'/></br><br><mynode txt='hello world'/></br></blah>");
XmlAttribute a = doc.CreateAttribute ("MyAttribute");
doc.SelectNodes ("//mynode") [0].Attributes.Append (a);
doc.SelectNodes ("//mynode") [0].Attributes.Append (a);
}
[Test]
public void AddIdentityDuplicate ()
{
XmlDocument doc = new XmlDocument ();
doc.LoadXml (@"
<!DOCTYPE eticGlossList [<!ELEMENT item (item*)><!ATTLIST item id ID #IMPLIED>]>
<group><item></item><item id=""tom""><f/></item></group>");
XmlNodeList nodes = doc.SelectNodes ("group/item");
int n = 1;
foreach (XmlNode node in nodes) {
XmlAttribute idAttr = doc.CreateAttribute ("id");
idAttr.Value = "id";
node.Attributes.Append (idAttr);
Assert.AreEqual (1, node.Attributes.Count, "#" + n++);
}
}
}
}
| |
using UnityEngine;
namespace Assets.Common.StandardAssets.Characters.ThirdPersonCharacter.Scripts
{
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Animator))]
[AddComponentMenu("Scripts/Standard Assets/Characters/Third Person/Third Person Character")]
public class ThirdPersonCharacter : MonoBehaviour
{
[SerializeField] float m_MovingTurnSpeed = 360;
[SerializeField] float m_StationaryTurnSpeed = 180;
[SerializeField] float m_JumpPower = 12f;
[Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
[SerializeField] float m_RunCycleLegOffset = 0.2f; // specific to the character in sample assets, will need to be modified to work with others
[SerializeField] float m_MoveSpeedMultiplier = 1f;
[SerializeField] float m_AnimSpeedMultiplier = 1f;
[SerializeField] float m_GroundCheckDistance = 0.1f;
Rigidbody m_Rigidbody;
Animator m_Animator;
bool m_IsGrounded;
float m_OrigGroundCheckDistance;
const float k_Half = 0.5f;
float m_TurnAmount;
float m_ForwardAmount;
Vector3 m_GroundNormal;
float m_CapsuleHeight;
Vector3 m_CapsuleCenter;
CapsuleCollider m_Capsule;
bool m_Crouching;
void Start()
{
m_Animator = GetComponent<Animator>();
m_Rigidbody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
m_CapsuleHeight = m_Capsule.height;
m_CapsuleCenter = m_Capsule.center;
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
m_OrigGroundCheckDistance = m_GroundCheckDistance;
}
public void Move(Vector3 move, bool crouch, bool jump)
{
// convert the world relative moveInput vector into a local-relative
// turn amount and forward amount required to head in the desired
// direction.
if (move.magnitude > 1f) move.Normalize();
move = transform.InverseTransformDirection(move);
CheckGroundStatus();
move = Vector3.ProjectOnPlane(move, m_GroundNormal);
m_TurnAmount = Mathf.Atan2(move.x, move.z);
m_ForwardAmount = move.z;
ApplyExtraTurnRotation();
// control and velocity handling is different when grounded and airborne:
if (m_IsGrounded)
{
HandleGroundedMovement(crouch, jump);
}
else
{
HandleAirborneMovement();
}
ScaleCapsuleForCrouching(crouch);
PreventStandingInLowHeadroom();
// send input and other state parameters to the animator
UpdateAnimator(move);
}
void ScaleCapsuleForCrouching(bool crouch)
{
if (m_IsGrounded && crouch)
{
if (m_Crouching) return;
m_Capsule.height = m_Capsule.height / 2f;
m_Capsule.center = m_Capsule.center / 2f;
m_Crouching = true;
}
else
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
return;
}
m_Capsule.height = m_CapsuleHeight;
m_Capsule.center = m_CapsuleCenter;
m_Crouching = false;
}
}
void PreventStandingInLowHeadroom()
{
// prevent standing up in crouch-only zones
if (!m_Crouching)
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
}
}
}
void UpdateAnimator(Vector3 move)
{
// update the animator parameters
m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
m_Animator.SetBool("Crouch", m_Crouching);
m_Animator.SetBool("OnGround", m_IsGrounded);
if (!m_IsGrounded)
{
m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
}
// calculate which leg is behind, so as to leave that leg trailing in the jump animation
// (This code is reliant on the specific run cycle offset in our animations,
// and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
float runCycle =
Mathf.Repeat(
m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
if (m_IsGrounded)
{
m_Animator.SetFloat("JumpLeg", jumpLeg);
}
// the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
// which affects the movement speed because of the root motion.
if (m_IsGrounded && move.magnitude > 0)
{
m_Animator.speed = m_AnimSpeedMultiplier;
}
else
{
// don't use that while airborne
m_Animator.speed = 1;
}
}
void HandleAirborneMovement()
{
// apply extra gravity from multiplier:
Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
m_Rigidbody.AddForce(extraGravityForce);
m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
}
void HandleGroundedMovement(bool crouch, bool jump)
{
// check whether conditions are right to allow a jump:
if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
{
// jump!
m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
m_IsGrounded = false;
m_Animator.applyRootMotion = false;
m_GroundCheckDistance = 0.1f;
}
}
void ApplyExtraTurnRotation()
{
// help the character turn faster (this is in addition to root rotation in the animation)
float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
}
public void OnAnimatorMove()
{
// we implement this function to override the default root motion.
// this allows us to modify the positional speed before it's applied.
if (m_IsGrounded && Time.deltaTime > 0)
{
Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;
// we preserve the existing y part of the current velocity.
v.y = m_Rigidbody.velocity.y;
m_Rigidbody.velocity = v;
}
}
void CheckGroundStatus() {
RaycastHit hitInfo;
#if UNITY_EDITOR
// helper to visualise the ground check ray in the scene view
Debug.DrawLine(
transform.position + (Vector3.up * 0.1f),
transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
#endif
// 0.1f is a small offset to start the ray from inside the character
// it is also good to note that the transform position in the sample assets is at the base of the character
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance)) {
m_GroundNormal = hitInfo.normal;
m_IsGrounded = true;
m_Animator.applyRootMotion = true;
} else {
m_IsGrounded = false;
m_GroundNormal = Vector3.up;
m_Animator.applyRootMotion = false;
}
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Text;
using System.Drawing;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// MatrixView: builds a simplfied representation of the matrix so that it
/// can be drawn or hit test in a simplified fashion.
/// </summary>
internal class MatrixView
{
DesignXmlDraw _Draw;
XmlNode _MatrixNode;
int _Rows;
int _HeaderRows;
int _Columns;
int _HeaderColumns;
float _Height;
float _Width;
MatrixItem[,] _MatrixView;
string _ViewBuilt=null;
internal MatrixView(DesignXmlDraw dxDraw, XmlNode matrix)
{
_Draw = dxDraw;
_MatrixNode = matrix;
try
{
BuildView();
}
catch (Exception e)
{
_ViewBuilt = e.Message;
}
}
internal MatrixItem this[int row, int column]
{
get {return _MatrixView[row, column]; }
}
internal int Columns
{
get {return _Columns;}
}
internal int Rows
{
get {return _Rows;}
}
internal int HeaderColumns
{
get {return _HeaderColumns;}
}
internal int HeaderRows
{
get {return _HeaderRows;}
}
internal float Height
{
get {return _Height;}
}
internal float Width
{
get {return _Width;}
}
void BuildView()
{
CountRowColumns(); // get the total count of rows and columns
_MatrixView = new MatrixItem[_Rows, _Columns]; // allocate the 2-dimensional array
FillMatrix();
}
void CountRowColumns()
{
int mcc = CountMatrixColumns();
int mrc = CountMatrixRows();
int iColumnGroupings = this.CountColumnGroupings();
int iRowGroupings = this.CountRowGroupings();
_Rows = mrc + this.CountColumnGroupings() +
CountRowGroupingSubtotals() * mrc;
_Columns = mcc + iRowGroupings +
CountColumnGroupingSubtotals() * mcc;
_HeaderRows = iColumnGroupings;
_HeaderColumns = iRowGroupings;
}
void FillMatrix()
{
FillMatrixColumnGroupings();
FillMatrixRowGroupings();
FillMatrixCorner();
FillMatrixCells();
FillMatrixHeights();
FillMatrixWidths();
FillMatrixCornerHeightWidth();
}
void FillMatrixHeights()
{
// fill out the heights for each row
this._Height = 0;
for (int row=0; row < this.Rows; row++)
{
float height=0;
for (int col= 0; col < this.Columns; col++)
{
MatrixItem mi = _MatrixView[row,col];
height = Math.Max(height, mi.Height);
}
for (int col= 0; col < this.Columns; col++)
_MatrixView[row,col].Height = height;
this._Height += height;
}
}
void FillMatrixWidths()
{
// fill out the widths for each column
this._Width = 0;
for (int col=0; col < this.Columns; col++)
{
float width=0;
for (int row= 0; row < this.Rows; row++)
{
MatrixItem mi = _MatrixView[row,col];
width = Math.Max(width, mi.Width);
}
for (int row= 0; row < this.Rows; row++)
_MatrixView[row,col].Width = width;
this._Width += width;
}
}
void FillMatrixCornerHeightWidth()
{
if (this.Columns == 0 || this.Rows == 0)
return;
// set the height and width for the corner
MatrixItem mi = _MatrixView[0,0];
mi.Height = 0;
for (int row=0; row < this._HeaderRows; row++)
mi.Height += _MatrixView[row, 1].Height;
mi.Width = 0;
for (int col=0; col < this._HeaderColumns; col++)
mi.Width += _MatrixView[1, col].Width;
}
void FillMatrixCells()
{
// get a collection with the matrix cells
int staticRows = this.CountMatrixRows();
int staticCols = this.CountMatrixColumns();
XmlNode[,] rc = new XmlNode[staticRows, staticCols];
XmlNode mrows = DesignXmlDraw.FindNextInHierarchy(_MatrixNode, "MatrixRows");
int ri=0;
foreach (XmlNode mrow in mrows.ChildNodes)
{
int ci=0;
XmlNode mcells = DesignXmlDraw.FindNextInHierarchy(mrow, "MatrixCells");
foreach (XmlNode mcell in mcells.ChildNodes)
{
// obtain the matrix cell
XmlNode repi = DesignXmlDraw.FindNextInHierarchy(mcell, "ReportItems");
rc[ri,ci] = repi;
ci++;
}
ri++;
}
// now fill out the rest of the matrix with empty entries
MatrixItem mi;
// Fill the middle (MatrixCells) with the contents of MatrixCells repeated
for (int row=_HeaderRows; row < this.Rows; row++)
{
int rowcell = staticRows == 0? 0: (row - _HeaderRows) % staticRows;
int mcellCount=0;
for (int col= _HeaderColumns; col < this.Columns; col++)
{
if (_MatrixView[row, col] == null)
{
float width = GetMatrixColumnWidth(mcellCount);
float height = GetMatrixRowHeight(rowcell);
XmlNode n = rc[rowcell, mcellCount++] as XmlNode;
if (mcellCount >= staticCols)
mcellCount=0;
mi = new MatrixItem(n);
mi.Width = width;
mi.Height = height;
_MatrixView[row, col] = mi;
}
}
}
// Make sure we have no null entries
for (int row=0; row < this.Rows; row++)
{
for (int col= 0; col < this.Columns; col++)
{
if (_MatrixView[row, col] == null)
{
mi = new MatrixItem(null);
_MatrixView[row, col] = mi;
}
}
}
}
void FillMatrixCorner()
{
XmlNode corner = _Draw.GetNamedChildNode(_MatrixNode, "Corner");
if (corner == null)
return;
XmlNode ris = DesignXmlDraw.FindNextInHierarchy(corner, "ReportItems");
MatrixItem mi = new MatrixItem(ris);
_MatrixView[0,0] = mi;
}
float GetMatrixColumnWidth(int count)
{
XmlNode mcs = DesignXmlDraw.FindNextInHierarchy(_MatrixNode, "MatrixColumns");
foreach (XmlNode c in mcs.ChildNodes)
{
if (c.Name != "MatrixColumn")
continue;
if (count == 0)
return _Draw.GetSize(c, "Width");
count--;
}
return 0;
}
void FillMatrixColumnGroupings()
{
XmlNode cGroupings = _Draw.GetNamedChildNode(_MatrixNode, "ColumnGroupings");
if (cGroupings == null)
return;
int rows=0;
int cols=this._HeaderColumns;
MatrixItem mi;
XmlNode ris; // work variable to hold reportitems
int staticCols = this.CountMatrixColumns();
int subTotalCols=DesignXmlDraw.CountChildren(cGroupings, "ColumnGrouping", "DynamicColumns", "Subtotal");
foreach (XmlNode c in cGroupings.ChildNodes)
{
if (c.Name != "ColumnGrouping")
continue;
XmlNode scol = DesignXmlDraw.FindNextInHierarchy(c, "StaticColumns");
if (scol != null)
{ // Static columns
int ci=0;
foreach (XmlNode sc in scol.ChildNodes)
{
if (sc.Name != "StaticColumn")
continue;
ris = DesignXmlDraw.FindNextInHierarchy(sc, "ReportItems");
mi = new MatrixItem(ris);
mi.Height = _Draw.GetSize(c, "Height");
mi.Width = GetMatrixColumnWidth(ci);
_MatrixView[rows, _HeaderColumns+ci] = mi;
ci++;
}
}
else
{ // Dynamic Columns
ris = DesignXmlDraw.FindNextInHierarchy(c, "DynamicColumns", "ReportItems");
mi = new MatrixItem(ris);
mi.Height = _Draw.GetSize(c, "Height");
mi.Width = GetMatrixColumnWidth(0);
_MatrixView[rows, _HeaderColumns] = mi;
XmlNode subtotal = DesignXmlDraw.FindNextInHierarchy(c, "DynamicColumns", "Subtotal");
if (subtotal != null)
{
ris = DesignXmlDraw.FindNextInHierarchy(subtotal, "ReportItems");
mi = new MatrixItem(ris);
mi.Height = _Draw.GetSize(c, "Height");
mi.Width = GetMatrixColumnWidth(0); // TODO this is wrong!! should be total of all static widths
_MatrixView[rows, _HeaderColumns+(staticCols-1)+subTotalCols] = mi;
subTotalCols--;
}
}
rows++; // add a row per ColumnGrouping
}
}
float GetMatrixRowHeight(int count)
{
XmlNode mcs = DesignXmlDraw.FindNextInHierarchy(_MatrixNode, "MatrixRows");
foreach (XmlNode c in mcs.ChildNodes)
{
if (c.Name != "MatrixRow")
continue;
if (count == 0)
return _Draw.GetSize(c, "Height");
count--;
}
return 0;
}
void FillMatrixRowGroupings()
{
XmlNode rGroupings = _Draw.GetNamedChildNode(_MatrixNode, "RowGroupings");
if (rGroupings == null)
return;
float height = _Draw.GetSize(
DesignXmlDraw.FindNextInHierarchy(_MatrixNode, "MatrixRows", "MatrixRow"),
"Height");
int cols = 0;
int staticRows = this.CountMatrixRows();
int subtotalrows= DesignXmlDraw.CountChildren(rGroupings, "RowGrouping", "DynamicRows", "Subtotal");
MatrixItem mi;
foreach (XmlNode c in rGroupings.ChildNodes)
{
if (c.Name != "RowGrouping")
continue;
XmlNode srow = DesignXmlDraw.FindNextInHierarchy(c, "StaticRows");
if (srow != null)
{ // Static rows
int ri=0;
foreach (XmlNode sr in srow.ChildNodes)
{
if (sr.Name != "StaticRow")
continue;
XmlNode ris = DesignXmlDraw.FindNextInHierarchy(sr, "ReportItems");
mi = new MatrixItem(ris);
mi.Width = _Draw.GetSize(c, "Width");
mi.Height = GetMatrixRowHeight(ri);
_MatrixView[_HeaderRows+ri, cols] = mi;
ri++;
}
}
else
{
XmlNode ris = DesignXmlDraw.FindNextInHierarchy(c, "DynamicRows", "ReportItems");
mi = new MatrixItem(ris);
mi.Width = _Draw.GetSize(c, "Width");
mi.Height = height;
_MatrixView[_HeaderRows, cols] = mi;
XmlNode subtotal = DesignXmlDraw.FindNextInHierarchy(c, "DynamicRows", "Subtotal");
if (subtotal != null)
{
ris = DesignXmlDraw.FindNextInHierarchy(subtotal, "ReportItems");
mi = new MatrixItem(ris);
mi.Width = _Draw.GetSize(c, "Width");
mi.Height = height;
_MatrixView[_HeaderRows+(staticRows-1)+subtotalrows, cols] = mi;
subtotalrows--; // these go backwards
}
}
cols++; // add a column per RowGrouping
}
}
/// <summary>
/// Returns the count of static columns or 1
/// </summary>
/// <returns></returns>
int CountMatrixColumns()
{
XmlNode cGroupings = _Draw.GetNamedChildNode(_MatrixNode, "ColumnGroupings");
if (cGroupings == null)
return 1; // 1 column
// Get the number of static columns
foreach (XmlNode c in cGroupings.ChildNodes)
{
if (c.Name != "ColumnGrouping")
continue;
XmlNode scol = DesignXmlDraw.FindNextInHierarchy(c, "StaticColumns");
if (scol == null) // must be dynamic column
continue;
int ci=0;
foreach (XmlNode sc in scol.ChildNodes)
{
if (sc.Name == "StaticColumn")
ci++;
}
return ci; // only one StaticColumns allowed in a column grouping
}
return 1; // 1 column
}
/// <summary>
/// Returns the count of static rows or 1
/// </summary>
/// <returns></returns>
int CountMatrixRows()
{
XmlNode rGroupings = _Draw.GetNamedChildNode(_MatrixNode, "RowGroupings");
if (rGroupings == null)
return 1; // 1 row
// Get the number of static columns
foreach (XmlNode c in rGroupings.ChildNodes)
{
if (c.Name != "RowGrouping")
continue;
XmlNode scol = DesignXmlDraw.FindNextInHierarchy(c, "StaticRows");
if (scol == null) // must be dynamic column
continue;
int ci=0;
foreach (XmlNode sc in scol.ChildNodes)
{
if (sc.Name == "StaticRow")
ci++;
}
return ci; // only one StaticRows allowed in a row grouping
}
return 1; // 1 row
}
/// <summary>
/// Returns the count of ColumnGroupings
/// </summary>
/// <returns></returns>
int CountColumnGroupings()
{
XmlNode cGroupings = _Draw.GetNamedChildNode(_MatrixNode, "ColumnGroupings");
if (cGroupings == null)
return 0;
// Get the number of column groups
int ci=0;
foreach (XmlNode c in cGroupings.ChildNodes)
{
if (c.Name != "ColumnGrouping")
continue;
ci++;
}
return ci;
}
/// <summary>
/// Returns the count of row grouping
/// </summary>
/// <returns></returns>
int CountRowGroupings()
{
XmlNode rGroupings = _Draw.GetNamedChildNode(_MatrixNode, "RowGroupings");
if (rGroupings == null)
return 0; // 1 row
// Get the number of row groupings
int ri=0;
foreach (XmlNode c in rGroupings.ChildNodes)
{
if (c.Name != "RowGrouping")
continue;
ri++;
}
return ri; // row groupings
}
/// <summary>
/// Returns the count of ColumnGroupings with subtotals
/// </summary>
/// <returns></returns>
int CountColumnGroupingSubtotals()
{
XmlNode cGroupings = _Draw.GetNamedChildNode(_MatrixNode, "ColumnGroupings");
if (cGroupings == null)
return 0;
// Get the number of column groups with subtotals
int ci=0;
foreach (XmlNode c in cGroupings.ChildNodes)
{
if (c.Name != "ColumnGrouping")
continue;
XmlNode subtotal = DesignXmlDraw.FindNextInHierarchy(c, "DynamicColumns", "Subtotal");
if (subtotal != null)
ci++;
}
return ci;
}
/// <summary>
/// Returns the count of row grouping subtotals
/// </summary>
/// <returns></returns>
int CountRowGroupingSubtotals()
{
XmlNode rGroupings = _Draw.GetNamedChildNode(_MatrixNode, "RowGroupings");
if (rGroupings == null)
return 0; // 1 row
// Get the number of row groupings
int ri=0;
foreach (XmlNode c in rGroupings.ChildNodes)
{
if (c.Name != "RowGrouping")
continue;
XmlNode subtotal = DesignXmlDraw.FindNextInHierarchy(c, "DynamicRows", "Subtotal");
if (subtotal != null)
ri++;
}
return ri; // row grouping subtotals
}
}
class MatrixItem
{
XmlNode _ReportItem;
float _Width;
float _Height;
internal MatrixItem(XmlNode ri)
{
_ReportItem = ri;
}
internal XmlNode ReportItem
{
get {return _ReportItem;}
set {_ReportItem = value;}
}
internal float Width
{
get {return _Width;}
set {_Width = value;}
}
internal float Height
{
get {return _Height;}
set {_Height = value;}
}
}
}
| |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
using System;
using System.Linq.Expressions;
using System.Reflection;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Utilities;
namespace Remotion.Linq.Parsing
{
/// <summary>
/// Implements an <see cref="RelinqExpressionVisitor"/> that throws an exception for every expression type that is not explicitly supported.
/// Inherit from this class to ensure that an exception is thrown when an expression is passed
/// </summary>
public abstract partial class ThrowingExpressionVisitor : RelinqExpressionVisitor
{
#if !NET_3_5
private static readonly Assembly s_systemLinqAssembly = typeof (Expression).GetTypeInfo().Assembly;
#endif
protected abstract Exception CreateUnhandledItemException<T> (T unhandledItem, string visitMethod);
#if !NET_3_5
public override Expression Visit (Expression expression)
{
if (expression == null)
return base.Visit ((Expression) null);
var isCustomExpression = !ReferenceEquals (s_systemLinqAssembly, expression.GetType().GetTypeInfo().Assembly);
if (isCustomExpression)
return base.Visit (expression);
var isWellKnownStandardExpression = IsWellKnownStandardExpression (expression);
if (isWellKnownStandardExpression)
return base.Visit (expression);
return VisitUnknownStandardExpression (expression, "Visit" + expression.NodeType, base.Visit);
}
protected virtual Expression VisitUnknownStandardExpression (Expression expression, string visitMethod, Func<Expression, Expression> baseBehavior)
{
ArgumentUtility.CheckNotNull ("expression", expression);
throw CreateUnhandledItemException (expression, visitMethod);
}
private bool IsWellKnownStandardExpression (Expression expression)
{
if (expression is UnaryExpression)
return true;
if (expression is BinaryExpression)
return true;
if (expression is TypeBinaryExpression)
return true;
if (expression is ConstantExpression)
return true;
if (expression is ConditionalExpression)
return true;
if (expression is ParameterExpression)
return true;
if (expression is LambdaExpression)
return true;
if (expression is MethodCallExpression)
return true;
if (expression is InvocationExpression)
return true;
if (expression is MemberExpression)
return true;
if (expression is NewExpression)
return true;
if (expression is NewArrayExpression)
return true;
if (expression is MemberInitExpression)
return true;
if (expression is ListInitExpression)
return true;
if (expression is BlockExpression)
return true;
if (expression is DebugInfoExpression)
return true;
if (expression is DefaultExpression)
return true;
if (expression is GotoExpression)
return true;
if (expression is IndexExpression)
return true;
if (expression is LabelExpression)
return true;
if (expression is LoopExpression)
return true;
if (expression is RuntimeVariablesExpression)
return true;
if (expression is SwitchExpression)
return true;
if (expression is TryExpression)
return true;
return false;
}
#endif
/// <summary>
/// Called when an unhandled item is visited. This method provides the item the visitor cannot handle (<paramref name="unhandledItem"/>),
/// the <paramref name="visitMethod"/> that is not implemented in the visitor, and a delegate that can be used to invoke the
/// <paramref name="baseBehavior"/> of the <see cref="RelinqExpressionVisitor"/> class. The default behavior of this method is to call the
/// <see cref="CreateUnhandledItemException{T}"/> method, but it can be overridden to do something else.
/// </summary>
/// <typeparam name="TItem">The type of the item that could not be handled. Either an <see cref="Expression"/> type, a <see cref="MemberBinding"/>
/// type, or <see cref="ElementInit"/>.</typeparam>
/// <typeparam name="TResult">The result type expected for the visited <paramref name="unhandledItem"/>.</typeparam>
/// <param name="unhandledItem">The unhandled item.</param>
/// <param name="visitMethod">The visit method that is not implemented.</param>
/// <param name="baseBehavior">The behavior exposed by <see cref="RelinqExpressionVisitor"/> for this item type.</param>
/// <returns>An object to replace <paramref name="unhandledItem"/> in the expression tree. Alternatively, the method can throw any exception.</returns>
protected virtual TResult VisitUnhandledItem<TItem, TResult> (TItem unhandledItem, string visitMethod, Func<TItem, TResult> baseBehavior)
where TItem: TResult
{
ArgumentUtility.CheckNotNull ("unhandledItem", unhandledItem);
ArgumentUtility.CheckNotNullOrEmpty ("visitMethod", visitMethod);
ArgumentUtility.CheckNotNull ("baseBehavior", baseBehavior);
throw CreateUnhandledItemException (unhandledItem, visitMethod);
}
#if !NET_3_5
protected override Expression VisitExtension (Expression expression)
{
if (expression.CanReduce)
return Visit (expression.ReduceAndCheck());
else
return VisitUnhandledItem<Expression, Expression> (expression, "VisitExtension", BaseVisitExtension);
}
protected Expression BaseVisitExtension (Expression expression)
{
return base.VisitExtension (expression);
}
#else
protected internal override Expression VisitExtension (ExtensionExpression expression)
{
if (expression.CanReduce)
return Visit (expression.ReduceAndCheck());
else
return VisitUnhandledItem<ExtensionExpression, Expression> (expression, "VisitExtension", BaseVisitExtension);
}
protected Expression BaseVisitExtension (ExtensionExpression expression)
{
return base.VisitExtension (expression);
}
#endif
protected override Expression VisitUnary (UnaryExpression expression)
{
return VisitUnhandledItem<UnaryExpression, Expression> (expression, "VisitUnary", BaseVisitUnary);
}
protected Expression BaseVisitUnary (UnaryExpression expression)
{
return base.VisitUnary (expression);
}
protected override Expression VisitBinary (BinaryExpression expression)
{
return VisitUnhandledItem<BinaryExpression, Expression> (expression, "VisitBinary", BaseVisitBinary);
}
protected Expression BaseVisitBinary (BinaryExpression expression)
{
return base.VisitBinary (expression);
}
protected override Expression VisitTypeBinary (TypeBinaryExpression expression)
{
return VisitUnhandledItem<TypeBinaryExpression, Expression> (expression, "VisitTypeBinary", BaseVisitTypeBinary);
}
protected Expression BaseVisitTypeBinary (TypeBinaryExpression expression)
{
return base.VisitTypeBinary (expression);
}
protected override Expression VisitConstant (ConstantExpression expression)
{
return VisitUnhandledItem<ConstantExpression, Expression> (expression, "VisitConstant", BaseVisitConstant);
}
protected Expression BaseVisitConstant (ConstantExpression expression)
{
return base.VisitConstant (expression);
}
protected override Expression VisitConditional (ConditionalExpression expression)
{
return VisitUnhandledItem<ConditionalExpression, Expression> (expression, "VisitConditional", BaseVisitConditional);
}
protected Expression BaseVisitConditional (ConditionalExpression arg)
{
return base.VisitConditional (arg);
}
protected override Expression VisitParameter (ParameterExpression expression)
{
return VisitUnhandledItem<ParameterExpression, Expression> (expression, "VisitParameter", BaseVisitParameter);
}
protected Expression BaseVisitParameter (ParameterExpression expression)
{
return base.VisitParameter (expression);
}
#if !NET_3_5
protected override Expression VisitLambda<T> (Expression<T> expression)
{
return VisitUnhandledItem<Expression<T>, Expression> (expression, "VisitLambda", BaseVisitLambda);
}
protected Expression BaseVisitLambda<T> (Expression<T> expression)
{
return base.VisitLambda (expression);
}
#else
protected override Expression VisitLambda (LambdaExpression expression)
{
return VisitUnhandledItem<LambdaExpression, Expression> (expression, "VisitLambda", BaseVisitLambda);
}
protected Expression BaseVisitLambda (LambdaExpression expression)
{
return base.VisitLambda (expression);
}
#endif
protected override Expression VisitMethodCall (MethodCallExpression expression)
{
return VisitUnhandledItem<MethodCallExpression, Expression> (expression, "VisitMethodCall", BaseVisitMethodCall);
}
protected Expression BaseVisitMethodCall (MethodCallExpression expression)
{
return base.VisitMethodCall (expression);
}
protected override Expression VisitInvocation (InvocationExpression expression)
{
return VisitUnhandledItem<InvocationExpression, Expression> (expression, "VisitInvocation", BaseVisitInvocation);
}
protected Expression BaseVisitInvocation (InvocationExpression expression)
{
return base.VisitInvocation (expression);
}
protected override Expression VisitMember (MemberExpression expression)
{
return VisitUnhandledItem<MemberExpression, Expression> (expression, "VisitMember", BaseVisitMember);
}
protected Expression BaseVisitMember (MemberExpression expression)
{
return base.VisitMember (expression);
}
protected override Expression VisitNew (NewExpression expression)
{
return VisitUnhandledItem<NewExpression, Expression> (expression, "VisitNew", BaseVisitNew);
}
protected Expression BaseVisitNew (NewExpression expression)
{
return base.VisitNew (expression);
}
protected override Expression VisitNewArray (NewArrayExpression expression)
{
return VisitUnhandledItem<NewArrayExpression, Expression> (expression, "VisitNewArray", BaseVisitNewArray);
}
protected Expression BaseVisitNewArray (NewArrayExpression expression)
{
return base.VisitNewArray (expression);
}
protected override Expression VisitMemberInit (MemberInitExpression expression)
{
return VisitUnhandledItem<MemberInitExpression, Expression> (expression, "VisitMemberInit", BaseVisitMemberInit);
}
protected Expression BaseVisitMemberInit (MemberInitExpression expression)
{
return base.VisitMemberInit (expression);
}
protected override Expression VisitListInit (ListInitExpression expression)
{
return VisitUnhandledItem<ListInitExpression, Expression> (expression, "VisitListInit", BaseVisitListInit);
}
protected Expression BaseVisitListInit (ListInitExpression expression)
{
return base.VisitListInit (expression);
}
#if !NET_3_5
protected override Expression VisitBlock (BlockExpression expression)
{
return VisitUnhandledItem<BlockExpression, Expression> (expression, "VisitBlock", BaseVisitBlock);
}
protected Expression BaseVisitBlock (BlockExpression expression)
{
return base.VisitBlock (expression);
}
protected override Expression VisitDebugInfo (DebugInfoExpression expression)
{
return VisitUnhandledItem<DebugInfoExpression, Expression> (expression, "VisitDebugInfo", BaseVisitDebugInfo);
}
protected Expression BaseVisitDebugInfo (DebugInfoExpression expression)
{
return base.VisitDebugInfo (expression);
}
protected override Expression VisitDefault (DefaultExpression expression)
{
return VisitUnhandledItem<DefaultExpression, Expression> (expression, "VisitDefault", BaseVisitDefault);
}
protected Expression BaseVisitDefault (DefaultExpression expression)
{
return base.VisitDefault (expression);
}
protected override Expression VisitGoto (GotoExpression expression)
{
return VisitUnhandledItem<GotoExpression, Expression> (expression, "VisitGoto", BaseVisitGoto);
}
protected Expression BaseVisitGoto (GotoExpression expression)
{
return base.VisitGoto (expression);
}
protected override Expression VisitIndex (IndexExpression expression)
{
return VisitUnhandledItem<IndexExpression, Expression> (expression, "VisitIndex", BaseVisitIndex);
}
protected Expression BaseVisitIndex (IndexExpression expression)
{
return base.VisitIndex (expression);
}
protected override Expression VisitLabel (LabelExpression expression)
{
return VisitUnhandledItem<LabelExpression, Expression> (expression, "VisitLabel", BaseVisitLabel);
}
protected Expression BaseVisitLabel (LabelExpression expression)
{
return base.VisitLabel (expression);
}
protected override Expression VisitLoop (LoopExpression expression)
{
return VisitUnhandledItem<LoopExpression, Expression> (expression, "VisitLoop", BaseVisitLoop);
}
protected Expression BaseVisitLoop (LoopExpression expression)
{
return base.VisitLoop (expression);
}
protected override Expression VisitRuntimeVariables (RuntimeVariablesExpression expression)
{
return VisitUnhandledItem<RuntimeVariablesExpression, Expression> (expression, "VisitRuntimeVariables", BaseVisitRuntimeVariables);
}
protected Expression BaseVisitRuntimeVariables (RuntimeVariablesExpression expression)
{
return base.VisitRuntimeVariables (expression);
}
protected override Expression VisitSwitch (SwitchExpression expression)
{
return VisitUnhandledItem<SwitchExpression, Expression> (expression, "VisitSwitch", BaseVisitSwitch);
}
protected Expression BaseVisitSwitch (SwitchExpression expression)
{
return base.VisitSwitch (expression);
}
protected override Expression VisitTry (TryExpression expression)
{
return VisitUnhandledItem<TryExpression, Expression> (expression, "VisitTry", BaseVisitTry);
}
protected Expression BaseVisitTry (TryExpression expression)
{
return base.VisitTry (expression);
}
#endif
#if !NET_3_5
protected override MemberBinding VisitMemberBinding (MemberBinding expression)
{
// Base-implementation will already delegate all variations of MemberBinding to dedicated Vist-methods.
// Therefor, the VisitMemberBinding-method should not throw an exception on its own.
return BaseVisitMemberBinding (expression);
}
protected MemberBinding BaseVisitMemberBinding (MemberBinding expression)
{
return base.VisitMemberBinding (expression);
}
#endif
protected override ElementInit VisitElementInit (ElementInit elementInit)
{
return VisitUnhandledItem<ElementInit, ElementInit> (elementInit, "VisitElementInit", BaseVisitElementInit);
}
protected ElementInit BaseVisitElementInit (ElementInit elementInit)
{
return base.VisitElementInit (elementInit);
}
protected override MemberAssignment VisitMemberAssignment (MemberAssignment memberAssigment)
{
return VisitUnhandledItem<MemberAssignment, MemberAssignment> (memberAssigment, "VisitMemberAssignment", BaseVisitMemberAssignment);
}
protected MemberAssignment BaseVisitMemberAssignment (MemberAssignment memberAssigment)
{
return base.VisitMemberAssignment (memberAssigment);
}
protected override MemberMemberBinding VisitMemberMemberBinding (MemberMemberBinding binding)
{
return VisitUnhandledItem<MemberMemberBinding, MemberMemberBinding> (binding, "VisitMemberMemberBinding", BaseVisitMemberMemberBinding);
}
protected MemberMemberBinding BaseVisitMemberMemberBinding (MemberMemberBinding binding)
{
return base.VisitMemberMemberBinding (binding);
}
protected override MemberListBinding VisitMemberListBinding (MemberListBinding listBinding)
{
return VisitUnhandledItem<MemberListBinding, MemberListBinding> (listBinding, "VisitMemberListBinding", BaseVisitMemberListBinding);
}
protected MemberListBinding BaseVisitMemberListBinding (MemberListBinding listBinding)
{
return base.VisitMemberListBinding (listBinding);
}
#if !NET_3_5
protected override CatchBlock VisitCatchBlock (CatchBlock expression)
{
return VisitUnhandledItem<CatchBlock, CatchBlock> (expression, "VisitCatchBlock", BaseVisitCatchBlock);
}
protected CatchBlock BaseVisitCatchBlock (CatchBlock expression)
{
return base.VisitCatchBlock (expression);
}
protected override LabelTarget VisitLabelTarget (LabelTarget expression)
{
return VisitUnhandledItem<LabelTarget, LabelTarget> (expression, "VisitLabelTarget", BaseVisitLabelTarget);
}
protected LabelTarget BaseVisitLabelTarget (LabelTarget expression)
{
return base.VisitLabelTarget (expression);
}
protected override SwitchCase VisitSwitchCase (SwitchCase expression)
{
return VisitUnhandledItem<SwitchCase, SwitchCase> (expression, "VisitSwitchCase", BaseVisitSwitchCase);
}
protected SwitchCase BaseVisitSwitchCase (SwitchCase expression)
{
return base.VisitSwitchCase (expression);
}
#endif
protected internal override Expression VisitSubQuery (SubQueryExpression expression)
{
return VisitUnhandledItem<SubQueryExpression, Expression> (expression, "VisitSubQuery", BaseVisitSubQuery);
}
protected Expression BaseVisitSubQuery (SubQueryExpression expression)
{
return base.VisitSubQuery (expression);
}
protected internal override Expression VisitQuerySourceReference (QuerySourceReferenceExpression expression)
{
return VisitUnhandledItem<QuerySourceReferenceExpression, Expression> (expression, "VisitQuerySourceReference", BaseVisitQuerySourceReference);
}
protected Expression BaseVisitQuerySourceReference (QuerySourceReferenceExpression expression)
{
return base.VisitQuerySourceReference (expression);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>;
namespace System.Collections.Immutable.Tests
{
public abstract partial class ImmutableSetTest : ImmutablesTestBase
{
[Fact]
public void AddTest()
{
this.AddTestHelper(this.Empty<int>(), 3, 5, 4, 3);
}
[Fact]
public void AddDuplicatesTest()
{
var arrayWithDuplicates = Enumerable.Range(1, 100).Concat(Enumerable.Range(1, 100)).ToArray();
this.AddTestHelper(this.Empty<int>(), arrayWithDuplicates);
}
[Fact]
public void RemoveTest()
{
this.RemoveTestHelper(this.Empty<int>().Add(3).Add(5), 5, 3);
}
[Fact]
public void AddRemoveLoadTest()
{
var data = this.GenerateDummyFillData();
this.AddRemoveLoadTestHelper(Empty<double>(), data);
}
[Fact]
public void RemoveNonExistingTest()
{
this.RemoveNonExistingTest(this.Empty<int>());
}
[Fact]
public void AddBulkFromImmutableToEmpty()
{
var set = this.Empty<int>().Add(5);
var empty2 = this.Empty<int>();
Assert.Same(set, empty2.Union(set)); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set."
}
/// <summary>
/// Verifies that Except *does* enumerate its argument if the collection is empty.
/// </summary>
/// <remarks>
/// While this would seem an implementation detail and simply lack of an optimization,
/// it turns out that changing this behavior now *could* represent a breaking change
/// because if the enumerable were to throw an exception, that exception would be
/// observed previously, but would no longer be thrown if this behavior changed.
/// So this is a test to lock the behavior in place or be thoughtful if adding the optimization.
/// </remarks>
/// <seealso cref="ImmutableListTest.RemoveRangeDoesNotEnumerateSequenceIfThisIsEmpty"/>
[Fact]
public void ExceptDoesEnumerateSequenceIfThisIsEmpty()
{
bool enumerated = false;
Empty<int>().Except(Enumerable.Range(1, 1).Select(n => { enumerated = true; return n; }));
Assert.True(enumerated);
}
[Fact]
public void SetEqualsTest()
{
Assert.True(this.Empty<int>().SetEquals(this.Empty<int>()));
var nonEmptySet = this.Empty<int>().Add(5);
Assert.True(nonEmptySet.SetEquals(nonEmptySet));
this.SetCompareTestHelper(s => s.SetEquals, s => s.SetEquals, this.GetSetEqualsScenarios());
}
[Fact]
public void IsProperSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSubsetOf, s => s.IsProperSubsetOf, this.GetIsProperSubsetOfScenarios());
}
[Fact]
public void IsProperSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSupersetOf, s => s.IsProperSupersetOf, this.GetIsProperSubsetOfScenarios().Select(Flip));
}
[Fact]
public void IsSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsSubsetOf, s => s.IsSubsetOf, this.GetIsSubsetOfScenarios());
}
[Fact]
public void IsSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsSupersetOf, s => s.IsSupersetOf, this.GetIsSubsetOfScenarios().Select(Flip));
}
[Fact]
public void OverlapsTest()
{
this.SetCompareTestHelper(s => s.Overlaps, s => s.Overlaps, this.GetOverlapsScenarios());
}
[Fact]
public void EqualsTest()
{
Assert.False(Empty<int>().Equals(null));
Assert.False(Empty<int>().Equals("hi"));
Assert.True(Empty<int>().Equals(Empty<int>()));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3).Add(5)));
}
[Fact]
public void GetHashCodeTest()
{
// verify that get hash code is the default address based one.
Assert.Equal(EqualityComparer<object>.Default.GetHashCode(Empty<int>()), Empty<int>().GetHashCode());
}
[Fact]
public void ClearTest()
{
var originalSet = this.Empty<int>();
var nonEmptySet = originalSet.Add(5);
var clearedSet = nonEmptySet.Clear();
Assert.Same(originalSet, clearedSet);
}
[Fact]
public void ISetMutationMethods()
{
var set = (ISet<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(0));
Assert.Throws<NotSupportedException>(() => set.ExceptWith(null));
Assert.Throws<NotSupportedException>(() => set.UnionWith(null));
Assert.Throws<NotSupportedException>(() => set.IntersectWith(null));
Assert.Throws<NotSupportedException>(() => set.SymmetricExceptWith(null));
}
[Fact]
public void ICollectionOfTMembers()
{
var set = (ICollection<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(1));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove(1));
Assert.True(set.IsReadOnly);
}
[Fact]
public void ICollectionMethods()
{
ICollection builder = (ICollection)this.Empty<string>();
string[] array = new string[0];
builder.CopyTo(array, 0);
builder = (ICollection)this.Empty<string>().Add("a");
array = new string[builder.Count + 1];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a" }, array);
Assert.True(builder.IsSynchronized);
Assert.NotNull(builder.SyncRoot);
Assert.Same(builder.SyncRoot, builder.SyncRoot);
}
[Fact]
public void NullHandling()
{
var empty = this.Empty<string>();
var set = empty.Add(null);
Assert.True(set.Contains(null));
Assert.True(set.TryGetValue(null, out var @null));
Assert.Null(@null);
Assert.Equal(empty, set.Remove(null));
set = empty.Union(new[] { null, "a" });
Assert.True(set.IsSupersetOf(new[] { null, "a" }));
Assert.True(set.IsSubsetOf(new[] { null, "a" }));
Assert.True(set.IsProperSupersetOf(new[] { default(string) }));
Assert.True(set.IsProperSubsetOf(new[] { null, "a", "b" }));
Assert.True(set.Overlaps(new[] { null, "b" }));
Assert.True(set.SetEquals(new[] { null, null, "a", "a" }));
set = set.Intersect(new[] { default(string) });
Assert.Equal(1, set.Count);
set = set.Except(new[] { default(string) });
Assert.False(set.Contains(null));
}
protected abstract bool IncludesGetHashCodeDerivative { get; }
internal static List<T> ToListNonGeneric<T>(System.Collections.IEnumerable sequence)
{
Assert.NotNull(sequence);
var list = new List<T>();
var enumerator = sequence.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add((T)enumerator.Current);
}
return list;
}
protected abstract IImmutableSet<T> Empty<T>();
protected abstract ISet<T> EmptyMutable<T>();
protected IImmutableSet<T> SetWith<T>(params T[] items)
{
return this.Empty<T>().Union(items);
}
protected void CustomSortTestHelper<T>(IImmutableSet<T> emptySet, bool matchOrder, T[] injectedValues, T[] expectedValues)
{
Assert.NotNull(emptySet);
Assert.NotNull(injectedValues);
Assert.NotNull(expectedValues);
var set = emptySet;
foreach (T value in injectedValues)
{
set = set.Add(value);
}
Assert.Equal(expectedValues.Length, set.Count);
if (matchOrder)
{
Assert.Equal<T>(expectedValues, set.ToList());
}
else
{
CollectionAssertAreEquivalent(expectedValues, set.ToList());
}
}
/// <summary>
/// Tests various aspects of a set. This should be called only from the unordered or sorted overloads of this method.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
protected void EmptyTestHelper<T>(IImmutableSet<T> emptySet)
{
Assert.NotNull(emptySet);
Assert.Equal(0, emptySet.Count); //, "Empty set should have a Count of 0");
Assert.Equal(0, emptySet.Count()); //, "Enumeration of an empty set yielded elements.");
Assert.Same(emptySet, emptySet.Clear());
}
private IEnumerable<SetTriad> GetSetEqualsScenarios()
{
return new List<SetTriad>
{
new SetTriad(SetWith<int>(), new int[] { }, true),
new SetTriad(SetWith<int>(5), new int[] { 5 }, true),
new SetTriad(SetWith<int>(5), new int[] { 5, 5 }, true),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 7 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 8 }, true),
new SetTriad(SetWith<int>(5), new int[] { }, false),
new SetTriad(SetWith<int>(), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5), new int[] { 5, 8 }, false),
new SetTriad(SetWith<int>(5, 8), SetWith<int>(5, 8), true),
};
}
private IEnumerable<SetTriad> GetIsProperSubsetOfScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { }, new int[] { 1 }, true),
};
}
private IEnumerable<SetTriad> GetIsSubsetOfScenarios()
{
var results = new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
};
// By definition, any proper subset is also a subset.
// But because a subset may not be a proper subset, we filter the proper- scenarios.
results.AddRange(this.GetIsProperSubsetOfScenarios().Where(s => s.Item3));
return results;
}
private IEnumerable<SetTriad> GetOverlapsScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { }, new int[] { 1 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1, 2 }, new int[] { 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 2, 3, 4 }, true),
};
}
private void SetCompareTestHelper<T>(Func<IImmutableSet<T>, Func<IEnumerable<T>, bool>> operation, Func<ISet<T>, Func<IEnumerable<T>, bool>> baselineOperation, IEnumerable<Tuple<IEnumerable<T>, IEnumerable<T>, bool>> scenarios)
{
//const string message = "Scenario #{0}: Set 1: {1}, Set 2: {2}";
int iteration = 0;
foreach (var scenario in scenarios)
{
iteration++;
// Figure out the response expected based on the BCL mutable collections.
var baselineSet = this.EmptyMutable<T>();
baselineSet.UnionWith(scenario.Item1);
var expectedFunc = baselineOperation(baselineSet);
bool expected = expectedFunc(scenario.Item2);
Assert.Equal(expected, scenario.Item3); //, "Test scenario has an expected result that is inconsistent with BCL mutable collection behavior.");
var actualFunc = operation(this.SetWith(scenario.Item1.ToArray()));
var args = new object[] { iteration, ToStringDeferred(scenario.Item1), ToStringDeferred(scenario.Item2) };
Assert.Equal(scenario.Item3, actualFunc(this.SetWith(scenario.Item2.ToArray()))); //, message, args);
Assert.Equal(scenario.Item3, actualFunc(scenario.Item2)); //, message, args);
}
}
private static Tuple<IEnumerable<T>, IEnumerable<T>, bool> Flip<T>(Tuple<IEnumerable<T>, IEnumerable<T>, bool> scenario)
{
return new Tuple<IEnumerable<T>, IEnumerable<T>, bool>(scenario.Item2, scenario.Item1, scenario.Item3);
}
private void RemoveTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Assert.NotNull(set);
Assert.NotNull(values);
Assert.Same(set, set.Except(Enumerable.Empty<T>()));
int initialCount = set.Count;
int removedCount = 0;
foreach (T value in values)
{
var nextSet = set.Remove(value);
Assert.NotSame(set, nextSet);
Assert.Equal(initialCount - removedCount, set.Count);
Assert.Equal(initialCount - removedCount - 1, nextSet.Count);
Assert.Same(nextSet, nextSet.Remove(value)); //, "Removing a non-existing element should not change the set reference.");
removedCount++;
set = nextSet;
}
Assert.Equal(initialCount - removedCount, set.Count);
}
private void RemoveNonExistingTest(IImmutableSet<int> emptySet)
{
Assert.Same(emptySet, emptySet.Remove(5));
// Also fill up a set with many elements to build up the tree, then remove from various places in the tree.
const int Size = 200;
var set = emptySet;
for (int i = 0; i < Size; i += 2)
{ // only even numbers!
set = set.Add(i);
}
// Verify that removing odd numbers doesn't change anything.
for (int i = 1; i < Size; i += 2)
{
var setAfterRemoval = set.Remove(i);
Assert.Same(set, setAfterRemoval);
}
}
private void AddRemoveLoadTestHelper<T>(IImmutableSet<T> set, T[] data)
{
Assert.NotNull(set);
Assert.NotNull(data);
foreach (T value in data)
{
var newSet = set.Add(value);
Assert.NotSame(set, newSet);
set = newSet;
}
foreach (T value in data)
{
Assert.True(set.Contains(value));
}
foreach (T value in data)
{
var newSet = set.Remove(value);
Assert.NotSame(set, newSet);
set = newSet;
}
}
protected void EnumeratorTestHelper<T>(IImmutableSet<T> emptySet, IComparer<T> comparer, params T[] values)
{
var set = emptySet;
foreach (T value in values)
{
set = set.Add(value);
}
var nonGenericEnumerableList = ToListNonGeneric<T>(set);
CollectionAssertAreEquivalent(nonGenericEnumerableList, values);
var list = set.ToList();
CollectionAssertAreEquivalent(list, values);
if (comparer != null)
{
Array.Sort(values, comparer);
Assert.Equal<T>(values, list);
}
// Apply some less common uses to the enumerator to test its metal.
IEnumerator<T> enumerator;
using (enumerator = set.GetEnumerator())
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset(); // reset isn't usually called before MoveNext
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.False(enumerator.MoveNext()); // call it again to make sure it still returns false
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// this time only partially enumerate
enumerator.Reset();
enumerator.MoveNext();
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
}
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
}
private void AddTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Assert.NotNull(set);
Assert.NotNull(values);
Assert.Same(set, set.Union(Enumerable.Empty<T>()));
int initialCount = set.Count;
var uniqueValues = new HashSet<T>(values);
var enumerateAddSet = set.Union(values);
Assert.Equal(initialCount + uniqueValues.Count, enumerateAddSet.Count);
foreach (T value in values)
{
Assert.True(enumerateAddSet.Contains(value));
}
int addedCount = 0;
foreach (T value in values)
{
bool duplicate = set.Contains(value);
var nextSet = set.Add(value);
Assert.True(nextSet.Count > 0);
Assert.Equal(initialCount + addedCount, set.Count);
int expectedCount = initialCount + addedCount;
if (!duplicate)
{
expectedCount++;
}
Assert.Equal(expectedCount, nextSet.Count);
Assert.Equal(duplicate, set.Contains(value));
Assert.True(nextSet.Contains(value));
if (!duplicate)
{
addedCount++;
}
// Next assert temporarily disabled because Roslyn's set doesn't follow this rule.
Assert.Same(nextSet, nextSet.Add(value)); //, "Adding duplicate value {0} should keep the original reference.", value);
set = nextSet;
}
}
}
}
| |
//
// X520.cs: X.520 related stuff (attributes, RDN)
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://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.
//
using System;
using System.Globalization;
using System.Text;
using Mono.Security;
namespace Mono.Security.X509 {
// References:
// 1. Information technology - Open Systems Interconnection - The Directory: Selected attribute types
// http://www.itu.int/rec/recommendation.asp?type=folders&lang=e&parent=T-REC-X.520
// 2. Internet X.509 Public Key Infrastructure Certificate and CRL Profile
// http://www.ietf.org/rfc/rfc3280.txt
// 3. A Summary of the X.500(96) User Schema for use with LDAPv3
// http://www.faqs.org/rfcs/rfc2256.html
// 4. RFC 2247 - Using Domains in LDAP/X.500 Distinguished Names
// http://www.faqs.org/rfcs/rfc2247.html
/*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue
* }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY DEFINED BY AttributeType
*/
internal class X520 {
public abstract class AttributeTypeAndValue {
private string oid;
private string attrValue;
private int upperBound;
private byte encoding;
protected AttributeTypeAndValue (string oid, int upperBound)
{
this.oid = oid;
this.upperBound = upperBound;
this.encoding = 0xFF;
}
protected AttributeTypeAndValue (string oid, int upperBound, byte encoding)
{
this.oid = oid;
this.upperBound = upperBound;
this.encoding = encoding;
}
public string Value {
get { return attrValue; }
set {
if ((attrValue != null) && (attrValue.Length > upperBound)) {
string msg = Locale.GetText ("Value length bigger than upperbound ({0}).");
throw new FormatException (String.Format (msg, upperBound));
}
attrValue = value;
}
}
public ASN1 ASN1 {
get { return GetASN1 (); }
}
internal ASN1 GetASN1 (byte encoding)
{
byte encode = encoding;
if (encode == 0xFF)
encode = SelectBestEncoding ();
ASN1 asn1 = new ASN1 (0x30);
asn1.Add (ASN1Convert.FromOid (oid));
switch (encode) {
case 0x13:
// PRINTABLESTRING
asn1.Add (new ASN1 (0x13, Encoding.ASCII.GetBytes (attrValue)));
break;
case 0x16:
// IA5STRING
asn1.Add (new ASN1 (0x16, Encoding.ASCII.GetBytes (attrValue)));
break;
case 0x1E:
// BMPSTRING
asn1.Add (new ASN1 (0x1E, Encoding.BigEndianUnicode.GetBytes (attrValue)));
break;
}
return asn1;
}
internal ASN1 GetASN1 ()
{
return GetASN1 (encoding);
}
public byte[] GetBytes (byte encoding)
{
return GetASN1 (encoding) .GetBytes ();
}
public byte[] GetBytes ()
{
return GetASN1 () .GetBytes ();
}
private byte SelectBestEncoding ()
{
foreach (char c in attrValue) {
switch (c) {
case '@':
case '_':
return 0x1E; // BMPSTRING
default:
if (c > 127)
return 0x1E; // BMPSTRING
break;
}
}
return 0x13; // PRINTABLESTRING
}
}
public class Name : AttributeTypeAndValue {
public Name () : base ("2.5.4.41", 32768)
{
}
}
public class CommonName : AttributeTypeAndValue {
public CommonName () : base ("2.5.4.3", 64)
{
}
}
// RFC2256, Section 5.6
public class SerialNumber : AttributeTypeAndValue {
// max length 64 bytes, Printable String only
public SerialNumber ()
: base ("2.5.4.5", 64, 0x13)
{
}
}
public class LocalityName : AttributeTypeAndValue {
public LocalityName () : base ("2.5.4.7", 128)
{
}
}
public class StateOrProvinceName : AttributeTypeAndValue {
public StateOrProvinceName () : base ("2.5.4.8", 128)
{
}
}
public class OrganizationName : AttributeTypeAndValue {
public OrganizationName () : base ("2.5.4.10", 64)
{
}
}
public class OrganizationalUnitName : AttributeTypeAndValue {
public OrganizationalUnitName () : base ("2.5.4.11", 64)
{
}
}
// NOTE: Not part of RFC2253
public class EmailAddress : AttributeTypeAndValue {
public EmailAddress () : base ("1.2.840.113549.1.9.1", 128, 0x16)
{
}
}
// RFC2247, Section 4
public class DomainComponent : AttributeTypeAndValue {
// no maximum length defined
public DomainComponent ()
: base ("0.9.2342.19200300.100.1.25", Int32.MaxValue, 0x16)
{
}
}
// RFC1274, Section 9.3.1
public class UserId : AttributeTypeAndValue {
public UserId ()
: base ("0.9.2342.19200300.100.1.1", 256)
{
}
}
public class Oid : AttributeTypeAndValue {
public Oid (string oid)
: base (oid, Int32.MaxValue)
{
}
}
/* -- Naming attributes of type X520Title
* id-at-title AttributeType ::= { id-at 12 }
*
* X520Title ::= CHOICE {
* teletexString TeletexString (SIZE (1..ub-title)),
* printableString PrintableString (SIZE (1..ub-title)),
* universalString UniversalString (SIZE (1..ub-title)),
* utf8String UTF8String (SIZE (1..ub-title)),
* bmpString BMPString (SIZE (1..ub-title))
* }
*/
public class Title : AttributeTypeAndValue {
public Title () : base ("2.5.4.12", 64)
{
}
}
public class CountryName : AttributeTypeAndValue {
// (0x13) PRINTABLESTRING
public CountryName () : base ("2.5.4.6", 2, 0x13)
{
}
}
public class DnQualifier : AttributeTypeAndValue {
// (0x13) PRINTABLESTRING
public DnQualifier () : base ("2.5.4.46", 2, 0x13)
{
}
}
public class Surname : AttributeTypeAndValue {
public Surname () : base ("2.5.4.4", 32768)
{
}
}
public class GivenName : AttributeTypeAndValue {
public GivenName () : base ("2.5.4.42", 16)
{
}
}
public class Initial : AttributeTypeAndValue {
public Initial () : base ("2.5.4.43", 5)
{
}
}
}
/* From RFC3280
* -- specifications of Upper Bounds MUST be regarded as mandatory
* -- from Annex B of ITU-T X.411 Reference Definition of MTS Parameter
*
* -- Upper Bounds
*
* ub-name INTEGER ::= 32768
* ub-common-name INTEGER ::= 64
* ub-locality-name INTEGER ::= 128
* ub-state-name INTEGER ::= 128
* ub-organization-name INTEGER ::= 64
* ub-organizational-unit-name INTEGER ::= 64
* ub-title INTEGER ::= 64
* ub-serial-number INTEGER ::= 64
* ub-match INTEGER ::= 128
* ub-emailaddress-length INTEGER ::= 128
* ub-common-name-length INTEGER ::= 64
* ub-country-name-alpha-length INTEGER ::= 2
* ub-country-name-numeric-length INTEGER ::= 3
* ub-domain-defined-attributes INTEGER ::= 4
* ub-domain-defined-attribute-type-length INTEGER ::= 8
* ub-domain-defined-attribute-value-length INTEGER ::= 128
* ub-domain-name-length INTEGER ::= 16
* ub-extension-attributes INTEGER ::= 256
* ub-e163-4-number-length INTEGER ::= 15
* ub-e163-4-sub-address-length INTEGER ::= 40
* ub-generation-qualifier-length INTEGER ::= 3
* ub-given-name-length INTEGER ::= 16
* ub-initials-length INTEGER ::= 5
* ub-integer-options INTEGER ::= 256
* ub-numeric-user-id-length INTEGER ::= 32
* ub-organization-name-length INTEGER ::= 64
* ub-organizational-unit-name-length INTEGER ::= 32
* ub-organizational-units INTEGER ::= 4
* ub-pds-name-length INTEGER ::= 16
* ub-pds-parameter-length INTEGER ::= 30
* ub-pds-physical-address-lines INTEGER ::= 6
* ub-postal-code-length INTEGER ::= 16
* ub-pseudonym INTEGER ::= 128
* ub-surname-length INTEGER ::= 40
* ub-terminal-id-length INTEGER ::= 24
* ub-unformatted-address-length INTEGER ::= 180
* ub-x121-address-length INTEGER ::= 16
*
* -- Note - upper bounds on string types, such as TeletexString, are
* -- measured in characters. Excepting PrintableString or IA5String, a
* -- significantly greater number of octets will be required to hold
* -- such a value. As a minimum, 16 octets, or twice the specified
* -- upper bound, whichever is the larger, should be allowed for
* -- TeletexString. For UTF8String or UniversalString at least four
* -- times the upper bound should be allowed.
*/
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Storage;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
namespace Orleans.Runtime
{
/// <summary>
/// Maintains additional per-activation state that is required for Orleans internal operations.
/// MUST lock this object for any concurrent access
/// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc.
/// </summary>
internal class ActivationData : IActivationData, IInvokable
{
// This class is used for activations that have extension invokers. It keeps a dictionary of
// invoker objects to use with the activation, and extend the default invoker
// defined for the grain class.
// Note that in all cases we never have more than one copy of an actual invoker;
// we may have a ExtensionInvoker per activation, in the worst case.
private class ExtensionInvoker : IGrainMethodInvoker, IGrainExtensionMap
{
// Because calls to ExtensionInvoker are allways made within the activation context,
// we rely on the single-threading guarantee of the runtime and do not protect the map with a lock.
private Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>> extensionMap; // key is the extension interface ID
/// <summary>
/// Try to add an extension for the specific interface ID.
/// Fail and return false if there is already an extension for that interface ID.
/// Note that if an extension invoker handles multiple interface IDs, it can only be associated
/// with one of those IDs when added, and so only conflicts on that one ID will be detected and prevented.
/// </summary>
/// <param name="invoker"></param>
/// <param name="handler"></param>
/// <returns></returns>
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension handler)
{
if (extensionMap == null)
{
extensionMap = new Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>>(1);
}
if (extensionMap.ContainsKey(invoker.InterfaceId)) return false;
extensionMap.Add(invoker.InterfaceId, new Tuple<IGrainExtension, IGrainExtensionMethodInvoker>(handler, invoker));
return true;
}
/// <summary>
/// Removes all extensions for the specified interface id.
/// Returns true if the chained invoker no longer has any extensions and may be safely retired.
/// </summary>
/// <param name="extension"></param>
/// <returns>true if the chained invoker is now empty, false otherwise</returns>
public bool Remove(IGrainExtension extension)
{
int interfaceId = 0;
foreach(int iface in extensionMap.Keys)
if (extensionMap[iface].Item1 == extension)
{
interfaceId = iface;
break;
}
if (interfaceId == 0) // not found
throw new InvalidOperationException(String.Format("Extension {0} is not installed",
extension.GetType().FullName));
extensionMap.Remove(interfaceId);
return extensionMap.Count == 0;
}
public bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
if (extensionMap == null) return false;
foreach (var ext in extensionMap.Values)
if (extensionType == ext.Item1.GetType())
{
result = ext.Item1;
return true;
}
return false;
}
/// <summary>
/// Invokes the appropriate grain or extension method for the request interface ID and method ID.
/// First each extension invoker is tried; if no extension handles the request, then the base
/// invoker is used to handle the request.
/// The base invoker will throw an appropriate exception if the request is not recognized.
/// </summary>
/// <param name="grain"></param>
/// <param name="request"></param>
/// <returns></returns>
public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request)
{
if (extensionMap == null || !extensionMap.ContainsKey(request.InterfaceId))
throw new InvalidOperationException(
String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", request.InterfaceId));
var invoker = extensionMap[request.InterfaceId].Item2;
var extension = extensionMap[request.InterfaceId].Item1;
return invoker.Invoke(extension, request);
}
public bool IsExtensionInstalled(int interfaceId)
{
return extensionMap != null && extensionMap.ContainsKey(interfaceId);
}
public int InterfaceId
{
get { return 0; } // 0 indicates an extension invoker that may have multiple intefaces inplemented by extensions.
}
/// <summary>
/// Gets the extension from this instance if it is available.
/// </summary>
/// <param name="interfaceId">The interface id.</param>
/// <param name="extension">The extension.</param>
/// <returns>
/// <see langword="true"/> if the extension is found, <see langword="false"/> otherwise.
/// </returns>
public bool TryGetExtension(int interfaceId, out IGrainExtension extension)
{
Tuple<IGrainExtension, IGrainExtensionMethodInvoker> value;
if (extensionMap != null && extensionMap.TryGetValue(interfaceId, out value))
{
extension = value.Item1;
}
else
{
extension = null;
}
return extension != null;
}
}
// This is the maximum amount of time we expect a request to continue processing
private static TimeSpan maxRequestProcessingTime;
private static NodeConfiguration nodeConfiguration;
public readonly TimeSpan CollectionAgeLimit;
private IGrainMethodInvoker lastInvoker;
// This is the maximum number of enqueued request messages for a single activation before we write a warning log or reject new requests.
private LimitValue maxEnqueuedRequestsLimit;
private HashSet<GrainTimer> timers;
private readonly Logger logger;
public static void Init(ClusterConfiguration config, NodeConfiguration nodeConfig)
{
// Consider adding a config parameter for this
maxRequestProcessingTime = config.Globals.ResponseTimeout.Multiply(5);
nodeConfiguration = nodeConfig;
}
public ActivationData(ActivationAddress addr, string genericArguments, PlacementStrategy placedUsing, MultiClusterRegistrationStrategy registrationStrategy, IActivationCollector collector, TimeSpan ageLimit)
{
if (null == addr) throw new ArgumentNullException("addr");
if (null == placedUsing) throw new ArgumentNullException("placedUsing");
if (null == collector) throw new ArgumentNullException("collector");
logger = LogManager.GetLogger("ActivationData", LoggerType.Runtime);
ResetKeepAliveRequest();
Address = addr;
State = ActivationState.Create;
PlacedUsing = placedUsing;
RegistrationStrategy = registrationStrategy;
if (!Grain.IsSystemTarget && !Constants.IsSystemGrain(Grain))
{
this.collector = collector;
}
CollectionAgeLimit = ageLimit;
GrainReference = GrainReference.FromGrainId(addr.Grain, genericArguments,
Grain.IsSystemTarget ? addr.Silo : null);
}
#region Method invocation
private ExtensionInvoker extensionInvoker;
public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType=null)
{
// Return previous cached invoker, if applicable
if (lastInvoker != null && interfaceId == lastInvoker.InterfaceId) // extension invoker returns InterfaceId==0, so this condition will never be true if an extension is installed
return lastInvoker;
if (extensionInvoker != null && extensionInvoker.IsExtensionInstalled(interfaceId)) // HasExtensionInstalled(interfaceId)
// Shared invoker for all extensions installed on this grain
lastInvoker = extensionInvoker;
else
// Find the specific invoker for this interface / grain type
lastInvoker = RuntimeClient.Current.GetInvoker(interfaceId, genericGrainType);
return lastInvoker;
}
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension extension)
{
if(extensionInvoker == null)
extensionInvoker = new ExtensionInvoker();
return extensionInvoker.TryAddExtension(invoker, extension);
}
internal void RemoveExtension(IGrainExtension extension)
{
if (extensionInvoker != null)
{
if (extensionInvoker.Remove(extension))
extensionInvoker = null;
}
else
throw new InvalidOperationException("Grain extensions not installed.");
}
internal bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
return extensionInvoker != null && extensionInvoker.TryGetExtensionHandler(extensionType, out result);
}
#endregion
public string GrainTypeName
{
get
{
if (GrainInstanceType == null)
{
throw new ArgumentNullException("GrainInstanceType", "GrainInstanceType has not been set.");
}
return GrainInstanceType.FullName;
}
}
internal Type GrainInstanceType { get; private set; }
internal void SetGrainInstance(Grain grainInstance)
{
GrainInstance = grainInstance;
if (grainInstance != null)
{
GrainInstanceType = grainInstance.GetType();
// Don't ever collect system grains or reminder table grain or memory store grains.
bool doNotCollect = typeof(IReminderTableGrain).IsAssignableFrom(GrainInstanceType) || typeof(IMemoryStorageGrain).IsAssignableFrom(GrainInstanceType);
if (doNotCollect)
{
this.collector = null;
}
}
}
public IStorageProvider StorageProvider { get; set; }
private Streams.StreamDirectory streamDirectory;
internal Streams.StreamDirectory GetStreamDirectory()
{
return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory());
}
internal bool IsUsingStreams
{
get { return streamDirectory != null; }
}
internal async Task DeactivateStreamResources()
{
if (streamDirectory == null) return; // No streams - Nothing to do.
if (extensionInvoker == null) return; // No installed extensions - Nothing to do.
if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate)
{
logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this);
return;
}
await streamDirectory.Cleanup(true, false);
}
#region IActivationData
GrainReference IActivationData.GrainReference
{
get { return GrainReference; }
}
public GrainId Identity
{
get { return Grain; }
}
public Grain GrainInstance { get; private set; }
public ActivationId ActivationId { get { return Address.Activation; } }
public ActivationAddress Address { get; private set; }
public IDisposable RegisterTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period)
{
var timer = GrainTimer.FromTaskCallback(asyncCallback, state, dueTime, period);
AddTimer(timer);
timer.Start();
return timer;
}
#endregion
#region Catalog
internal readonly GrainReference GrainReference;
public SiloAddress Silo { get { return Address.Silo; } }
public GrainId Grain { get { return Address.Grain; } }
public ActivationState State { get; private set; }
public void SetState(ActivationState state)
{
State = state;
}
// Don't accept any new messages and stop all timers.
public void PrepareForDeactivation()
{
SetState(ActivationState.Deactivating);
StopAllTimers();
}
/// <summary>
/// If State == Invalid, this may contain a forwarding address for incoming messages
/// </summary>
public ActivationAddress ForwardingAddress { get; set; }
private IActivationCollector collector;
internal bool IsExemptFromCollection
{
get { return collector == null; }
}
public DateTime CollectionTicket { get; private set; }
private bool collectionCancelledFlag;
public bool TrySetCollectionCancelledFlag()
{
lock (this)
{
if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false;
collectionCancelledFlag = true;
return true;
}
}
public void ResetCollectionCancelledFlag()
{
lock (this)
{
collectionCancelledFlag = false;
}
}
public void ResetCollectionTicket()
{
CollectionTicket = default(DateTime);
}
public void SetCollectionTicket(DateTime ticket)
{
if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket");
if (CollectionTicket != default(DateTime))
{
throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket.");
}
CollectionTicket = ticket;
}
#endregion
#region Dispatcher
public PlacementStrategy PlacedUsing { get; private set; }
public MultiClusterRegistrationStrategy RegistrationStrategy { get; private set; }
// Currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy.
internal bool IsStatelessWorker { get { return PlacedUsing is StatelessWorkerPlacement; } }
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
internal bool IsUsingGrainDirectory { get { return !IsStatelessWorker; } }
public Message Running { get; private set; }
// the number of requests that are currently executing on this activation.
// includes reentrant and non-reentrant requests.
private int numRunning;
private DateTime currentRequestStartTime;
private DateTime becameIdle;
public void RecordRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning++;
if (Running != null) return;
// This logic only works for non-reentrant activations
// Consider: Handle long request detection for reentrant activations.
Running = message;
currentRequestStartTime = DateTime.UtcNow;
}
public void ResetRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning--;
if (numRunning == 0)
{
becameIdle = DateTime.UtcNow;
if (!IsExemptFromCollection)
{
collector.TryRescheduleCollection(this);
}
}
// The below logic only works for non-reentrant activations.
if (Running != null && !message.Equals(Running)) return;
Running = null;
currentRequestStartTime = DateTime.MinValue;
}
private long inFlightCount;
private long enqueuedOnDispatcherCount;
/// <summary>
/// Number of messages that are actively being processed [as opposed to being in the Waiting queue].
/// In most cases this will be 0 or 1, but for Reentrant grains can be >1.
/// </summary>
public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } }
/// <summary>
/// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed].
/// </summary>
public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } }
/// <summary>Increment the number of in-flight messages currently being processed.</summary>
public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); }
/// <summary>Decrement the number of in-flight messages currently being processed.</summary>
public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); }
/// <summary>Increment the number of messages currently in the prcess of being received.</summary>
public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); }
/// <summary>Decrement the number of messages currently in the prcess of being received.</summary>
public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); }
/// <summary>
/// grouped by sending activation: responses first, then sorted by id
/// </summary>
private List<Message> waiting;
public int WaitingCount
{
get
{
return waiting == null ? 0 : waiting.Count;
}
}
/// <summary>
/// Insert in a FIFO order
/// </summary>
/// <param name="message"></param>
public bool EnqueueMessage(Message message)
{
lock (this)
{
if (State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message);
return false;
}
// If maxRequestProcessingTime is never set, then we will skip this check
if (maxRequestProcessingTime.TotalMilliseconds > 0 && Running != null)
{
// Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations
var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime;
if (currentRequestActiveTime > maxRequestProcessingTime)
{
logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing,
"Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.",
currentRequestActiveTime, this.ToDetailedString(), Running, message);
}
}
waiting = waiting ?? new List<Message>();
waiting.Add(message);
return true;
}
}
/// <summary>
/// Check whether this activation is overloaded.
/// Returns LimitExceededException if overloaded, otherwise <c>null</c>c>
/// </summary>
/// <param name="log">Logger to use for reporting any overflow condition</param>
/// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns>
public LimitExceededException CheckOverloaded(Logger log)
{
LimitValue limitValue = GetMaxEnqueuedRequestLimit();
int maxRequestsHardLimit = limitValue.HardLimitThreshold;
int maxRequestsSoftLimit = limitValue.SoftLimitThreshold;
if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set
int count = GetRequestCount();
if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit
{
log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests,
String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}",
count, this, maxRequestsHardLimit));
return new LimitExceededException(limitValue.Name, count, maxRequestsHardLimit, this.ToString());
}
if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit
{
log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests,
String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}",
count, this, maxRequestsSoftLimit));
return null;
}
return null;
}
internal int GetRequestCount()
{
lock (this)
{
long numInDispatcher = EnqueuedOnDispatcherCount;
long numActive = InFlightCount;
long numWaiting = WaitingCount;
return (int)(numInDispatcher + numActive + numWaiting);
}
}
private LimitValue GetMaxEnqueuedRequestLimit()
{
if (maxEnqueuedRequestsLimit != null) return maxEnqueuedRequestsLimit;
if (GrainInstanceType != null)
{
string limitName = CodeGeneration.GrainInterfaceUtils.IsStatelessWorker(GrainInstanceType.GetTypeInfo())
? LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER
: LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
maxEnqueuedRequestsLimit = nodeConfiguration.LimitManager.GetLimit(limitName); // Cache for next time
return maxEnqueuedRequestsLimit;
}
return nodeConfiguration.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
}
public Message PeekNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0) return waiting[0];
return null;
}
public void DequeueNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0)
waiting.RemoveAt(0);
}
internal List<Message> DequeueAllWaitingMessages()
{
lock (this)
{
if (waiting == null) return null;
List<Message> tmp = waiting;
waiting = null;
return tmp;
}
}
#endregion
#region Activation collection
public bool IsInactive
{
get
{
return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0);
}
}
public bool IsCurrentlyExecuting
{
get
{
return numRunning > 0 ;
}
}
/// <summary>
/// Returns how long this activation has been idle.
/// </summary>
public TimeSpan GetIdleness(DateTime now)
{
if (now == default(DateTime))
throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now");
return now - becameIdle;
}
/// <summary>
/// Returns whether this activation has been idle long enough to be collected.
/// </summary>
public bool IsStale(DateTime now)
{
return GetIdleness(now) >= CollectionAgeLimit;
}
private DateTime keepAliveUntil;
public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } }
public void DelayDeactivation(TimeSpan timespan)
{
if (timespan <= TimeSpan.Zero)
{
// reset any current keepAliveUntill
ResetKeepAliveRequest();
}
else if (timespan == TimeSpan.MaxValue)
{
// otherwise creates negative time.
keepAliveUntil = DateTime.MaxValue;
}
else
{
keepAliveUntil = DateTime.UtcNow + timespan;
}
}
public void ResetKeepAliveRequest()
{
keepAliveUntil = DateTime.MinValue;
}
public List<Action> OnInactive { get; set; } // ActivationData
public void AddOnInactive(Action action) // ActivationData
{
lock (this)
{
if (OnInactive == null)
{
OnInactive = new List<Action>();
}
OnInactive.Add(action);
}
}
public void RunOnInactive()
{
lock (this)
{
if (OnInactive == null) return;
var actions = OnInactive;
OnInactive = null;
foreach (var action in actions)
{
action();
}
}
}
#endregion
#region In-grain Timers
internal void AddTimer(GrainTimer timer)
{
lock(this)
{
if (timers == null)
{
timers = new HashSet<GrainTimer>();
}
timers.Add(timer);
}
}
private void StopAllTimers()
{
lock (this)
{
if (timers == null) return;
foreach (var timer in timers)
{
timer.Stop();
}
}
}
internal void OnTimerDisposed(GrainTimer orleansTimerInsideGrain)
{
lock (this) // need to lock since dispose can be called on finalizer thread, outside garin context (not single threaded).
{
timers.Remove(orleansTimerInsideGrain);
}
}
internal Task WaitForAllTimersToFinish()
{
lock(this)
{
if (timers == null)
{
return TaskDone.Done;
}
var tasks = new List<Task>();
var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set.
foreach (var timer in timerCopy)
{
// first call dispose, then wait to finish.
Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown");
tasks.Add(timer.GetCurrentlyExecutingTickTask());
}
return Task.WhenAll(tasks);
}
}
#endregion
#region Printing functions
public string DumpStatus()
{
var sb = new StringBuilder();
lock (this)
{
sb.AppendFormat(" {0}", ToDetailedString());
if (Running != null)
{
sb.AppendFormat(" Processing message: {0}", Running);
}
if (waiting!=null && waiting.Count > 0)
{
sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue());
}
}
return sb.ToString();
}
public override string ToString()
{
return String.Format("[Activation: {0}{1}{2}{3} State={4}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString(),
State);
}
internal string ToDetailedString(bool includeExtraDetails = false)
{
return
String.Format(
"[Activation: {0}{1}{2}{3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]",
Silo.ToLongString(),
Grain.ToDetailedString(),
ActivationId,
GetActivationInfoString(),
State, // 4
WaitingCount, // 5 NonReentrancyQueueSize
EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher
InFlightCount, // 7 InFlightCount
numRunning, // 8 NumRunning
GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan
CollectionAgeLimit, // 10 CollectionAgeLimit
(includeExtraDetails && Running != null) ? " CurrentlyExecuting=" + Running : ""); // 11: Running
}
public string Name
{
get
{
return String.Format("[Activation: {0}{1}{2}{3}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString());
}
}
/// <summary>
/// Return string containing dump of the queue of waiting work items
/// </summary>
/// <returns></returns>
/// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks>
internal string PrintWaitingQueue()
{
return Utils.EnumerableToString(waiting);
}
private string GetActivationInfoString()
{
var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty;
return GrainInstanceType == null ? placement :
String.Format(" #GrainType={0} Placement={1}", GrainInstanceType.FullName, placement);
}
#endregion
}
internal static class StreamResourceTestControl
{
internal static bool TestOnlySuppressStreamCleanupOnDeactivate;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
namespace Compute.Tests
{
public class VMScenarioTests : VMTestBase
{
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// GET VM Model View
/// GET VM InstanceView
/// GETVMs in a RG
/// List VMSizes in a RG
/// List VMSizes in an AvailabilitySet
/// Delete RG
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations")]
public void TestVMScenarioOperations()
{
TestVMScenarioOperationsInternal("TestVMScenarioOperations");
}
/// <summary>
/// Covers following Operations for managed disks:
/// Create RG
/// Create Network Resources
/// Create VM with WriteAccelerator enabled OS and Data disk
/// GET VM Model View
/// GET VM InstanceView
/// GETVMs in a RG
/// List VMSizes in a RG
/// List VMSizes in an AvailabilitySet
/// Delete RG
///
/// To record this test case, you need to run it in region which support XMF VMSizeFamily like eastus2.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks")]
public void TestVMScenarioOperations_ManagedDisks()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks", vmSize: VirtualMachineSizeTypes.StandardM64s, hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.PremiumLRS, dataDiskStorageAccountType: StorageAccountTypes.PremiumLRS, writeAcceleratorEnabled: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in region which support local diff disks.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_DiffDisks")]
public void TestVMScenarioOperations_DiffDisks()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_DiffDisks", vmSize: VirtualMachineSizeTypes.StandardDS148V2, hasManagedDisks: true,
hasDiffDisks: true, osDiskStorageAccountType: StorageAccountTypes.StandardLRS);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in region which support Encryption at host
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_EncryptionAtHost")]
public void TestVMScenarioOperations_EncryptionAtHost()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_EncryptionAtHost", vmSize: VirtualMachineSizeTypes.StandardDS1V2, hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.StandardLRS, encryptionAtHostEnabled: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in region which support DiskEncryptionSet resource for the Disks
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet")]
public void TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
string diskEncryptionSetId = getDefaultDiskEncryptionSetId();
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet", vmSize: VirtualMachineSizeTypes.StandardA1V2, hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.StandardLRS, diskEncryptionSetId: diskEncryptionSetId);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// TODO: StandardSSD is currently in preview and is available only in a few regions. Once it goes GA, it can be tested in
/// the default test location.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_StandardSSD")]
public void TestVMScenarioOperations_ManagedDisks_StandardSSD()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_StandardSSD", hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.StandardSSDLRS, dataDiskStorageAccountType: StorageAccountTypes.StandardSSDLRS);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in zone supported regions like eastus2.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_PirImage_Zones")]
public void TestVMScenarioOperations_ManagedDisks_PirImage_Zones()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centralus");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_PirImage_Zones", hasManagedDisks: true, zones: new List<string> { "1" }, callUpdateVM: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in zone supported regions like eastus2euap.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_UltraSSD")]
public void TestVMScenarioOperations_ManagedDisks_UltraSSD()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_UltraSSD", hasManagedDisks: true, zones: new List<string> { "1" },
vmSize: VirtualMachineSizeTypes.StandardE16sV3, osDiskStorageAccountType: StorageAccountTypes.PremiumLRS,
dataDiskStorageAccountType: StorageAccountTypes.UltraSSDLRS, callUpdateVM: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
[Fact]
[Trait("Name", "TestVMScenarioOperations_AutomaticPlacementOnDedicatedHostGroup")]
public void TestVMScenarioOperations_AutomaticPlacementOnDedicatedHostGroup()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "westus");
// This test was recorded in WestUSValidation, where the platform image typically used for recording is not available.
// Hence the following custom image was used.
ImageReference imageReference = new ImageReference
{
Publisher = "AzureRT.PIRCore.TestWAStage",
Offer = "TestUbuntuServer",
Sku = "16.04",
Version = "latest"
};
TestVMScenarioOperationsInternal("TestVMScenarioOperations_AutomaticPlacementOnDedicatedHostGroup",
hasManagedDisks: true, vmSize: VirtualMachineSizeTypes.StandardD2sV3, isAutomaticPlacementOnDedicatedHostGroupScenario: true,
imageReference: imageReference, validateListAvailableSize: false);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in zone supported regions like eastus2euap.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_PpgScenario")]
public void TestVMScenarioOperations_PpgScenario()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_PpgScenario", hasManagedDisks: true, isPpgScenario: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
private void TestVMScenarioOperationsInternal(string methodName, bool hasManagedDisks = false, IList<string> zones = null, string vmSize = "Standard_A0",
string osDiskStorageAccountType = "Standard_LRS", string dataDiskStorageAccountType = "Standard_LRS", bool? writeAcceleratorEnabled = null,
bool hasDiffDisks = false, bool callUpdateVM = false, bool isPpgScenario = false, string diskEncryptionSetId = null, bool? encryptionAtHostEnabled = null,
bool isAutomaticPlacementOnDedicatedHostGroupScenario = false, ImageReference imageReference = null, bool validateListAvailableSize = true)
{
using (MockContext context = MockContext.Start(this.GetType(), methodName))
{
EnsureClientsInitialized(context);
ImageReference imageRef = imageReference ?? GetPlatformVMImage(useWindowsImage: true);
const string expectedOSName = "Windows Server 2012 R2 Datacenter", expectedOSVersion = "Microsoft Windows NT 6.3.9600.0", expectedComputerName = ComputerName;
// Create resource group
var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string asName = ComputeManagementTestUtilities.GenerateName("as");
string ppgName = null, expectedPpgReferenceId = null;
string dedicatedHostGroupName = null, dedicatedHostName = null, dedicatedHostGroupReferenceId = null, dedicatedHostReferenceId = null;
if (isPpgScenario)
{
ppgName = ComputeManagementTestUtilities.GenerateName("ppgtest");
expectedPpgReferenceId = Helpers.GetProximityPlacementGroupRef(m_subId, rgName, ppgName);
}
if (isAutomaticPlacementOnDedicatedHostGroupScenario)
{
dedicatedHostGroupName = ComputeManagementTestUtilities.GenerateName("dhgtest");
dedicatedHostName = ComputeManagementTestUtilities.GenerateName("dhtest");
dedicatedHostGroupReferenceId = Helpers.GetDedicatedHostGroupRef(m_subId, rgName, dedicatedHostGroupName);
dedicatedHostReferenceId = Helpers.GetDedicatedHostRef(m_subId, rgName, dedicatedHostGroupName, dedicatedHostName);
}
VirtualMachine inputVM;
try
{
if (!hasManagedDisks)
{
CreateStorageAccount(rgName, storageAccountName);
}
CreateVM(rgName, asName, storageAccountName, imageRef, out inputVM, hasManagedDisks: hasManagedDisks,hasDiffDisks: hasDiffDisks, vmSize: vmSize, osDiskStorageAccountType: osDiskStorageAccountType,
dataDiskStorageAccountType: dataDiskStorageAccountType, writeAcceleratorEnabled: writeAcceleratorEnabled, zones: zones, ppgName: ppgName,
diskEncryptionSetId: diskEncryptionSetId, encryptionAtHostEnabled: encryptionAtHostEnabled, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId,
dedicatedHostGroupName: dedicatedHostGroupName, dedicatedHostName: dedicatedHostName);
// Instance view is not completely populated just after VM is provisioned. So we wait here for a few minutes to
// allow GA blob to populate.
ComputeManagementTestUtilities.WaitMinutes(5);
var getVMWithInstanceViewResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name, InstanceViewTypes.InstanceView);
Assert.True(getVMWithInstanceViewResponse != null, "VM in Get");
if (diskEncryptionSetId != null)
{
Assert.True(getVMWithInstanceViewResponse.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != null, "OsDisk.ManagedDisk.DiskEncryptionSet is null");
Assert.True(string.Equals(diskEncryptionSetId, getVMWithInstanceViewResponse.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
"OsDisk.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");
Assert.Equal(1, getVMWithInstanceViewResponse.StorageProfile.DataDisks.Count);
Assert.True(getVMWithInstanceViewResponse.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet != null, ".DataDisks.ManagedDisk.DiskEncryptionSet is null");
Assert.True(string.Equals(diskEncryptionSetId, getVMWithInstanceViewResponse.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
"DataDisks.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");
}
ValidateVMInstanceView(inputVM, getVMWithInstanceViewResponse, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion, dedicatedHostReferenceId);
var getVMInstanceViewResponse = m_CrpClient.VirtualMachines.InstanceView(rgName, inputVM.Name);
Assert.True(getVMInstanceViewResponse != null, "VM in InstanceView");
ValidateVMInstanceView(inputVM, getVMInstanceViewResponse, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion, dedicatedHostReferenceId);
bool hasUserDefinedAS = inputVM.AvailabilitySet != null;
string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name);
var listResponse = m_CrpClient.VirtualMachines.List(rgName);
ValidateVM(inputVM, listResponse.FirstOrDefault(x => x.Name == inputVM.Name),
expectedVMReferenceId, hasManagedDisks, hasUserDefinedAS, writeAcceleratorEnabled, hasDiffDisks, expectedPpgReferenceId: expectedPpgReferenceId,
encryptionAtHostEnabled: encryptionAtHostEnabled, expectedDedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId);
if (validateListAvailableSize)
{
var listVMSizesResponse = m_CrpClient.VirtualMachines.ListAvailableSizes(rgName, inputVM.Name);
Helpers.ValidateVirtualMachineSizeListResponse(listVMSizesResponse, hasAZ: zones != null, writeAcceleratorEnabled: writeAcceleratorEnabled,
hasDiffDisks: hasDiffDisks);
listVMSizesResponse = m_CrpClient.AvailabilitySets.ListAvailableSizes(rgName, asName);
Helpers.ValidateVirtualMachineSizeListResponse(listVMSizesResponse, hasAZ: zones != null, writeAcceleratorEnabled: writeAcceleratorEnabled, hasDiffDisks: hasDiffDisks);
}
if(isPpgScenario)
{
ProximityPlacementGroup outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(rgName, ppgName);
string expectedAvSetReferenceId = Helpers.GetAvailabilitySetRef(m_subId, rgName, asName);
Assert.Equal(1, outProximityPlacementGroup.VirtualMachines.Count);
Assert.Equal(1, outProximityPlacementGroup.AvailabilitySets.Count);
Assert.Equal(expectedVMReferenceId, outProximityPlacementGroup.VirtualMachines.First().Id, StringComparer.OrdinalIgnoreCase);
Assert.Equal(expectedAvSetReferenceId, outProximityPlacementGroup.AvailabilitySets.First().Id, StringComparer.OrdinalIgnoreCase);
}
if (callUpdateVM)
{
VirtualMachineUpdate updateParams = new VirtualMachineUpdate()
{
Tags = inputVM.Tags
};
string updateKey = "UpdateTag";
updateParams.Tags.Add(updateKey, "UpdateTagValue");
VirtualMachine updateResponse = m_CrpClient.VirtualMachines.Update(rgName, inputVM.Name, updateParams);
Assert.True(updateResponse.Tags.ContainsKey(updateKey));
}
}
finally
{
// Fire and forget. No need to wait for RG deletion completion
try
{
m_ResourcesClient.ResourceGroups.BeginDelete(rgName);
}
catch (Exception e)
{
// Swallow this exception so that the original exception is thrown
Console.WriteLine(e);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareGreaterThanDouble()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanDouble testClass)
{
var result = Sse2.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__CompareGreaterThanDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareGreaterThan(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareGreaterThan(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareGreaterThanDouble();
var result = Sse2.CompareGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareGreaterThanDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] > right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] > right[i]) ? -1 : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareGreaterThan)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using log4net;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Manages launching threads and keeping watch over them for timeouts
/// </summary>
public static class Watchdog
{
private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>Timer interval in milliseconds for the watchdog timer</summary>
public const double WATCHDOG_INTERVAL_MS = 2500.0d;
/// <summary>Default timeout in milliseconds before a thread is considered dead</summary>
public const int DEFAULT_WATCHDOG_TIMEOUT_MS = 5000;
[System.Diagnostics.DebuggerDisplay("{Thread.Name}")]
public class ThreadWatchdogInfo
{
public Thread Thread { get; private set; }
/// <summary>
/// Approximate tick when this thread was started.
/// </summary>
/// <remarks>
/// Not terribly good since this quickly wraps around.
/// </remarks>
public int FirstTick { get; private set; }
/// <summary>
/// Last time this heartbeat update was invoked
/// </summary>
public int LastTick { get; set; }
/// <summary>
/// Number of milliseconds before we notify that the thread is having a problem.
/// </summary>
public int Timeout { get; set; }
/// <summary>
/// Is this thread considered timed out?
/// </summary>
public bool IsTimedOut { get; set; }
/// <summary>
/// Will this thread trigger the alarm function if it has timed out?
/// </summary>
public bool AlarmIfTimeout { get; set; }
/// <summary>
/// Method execute if alarm goes off. If null then no alarm method is fired.
/// </summary>
public Func<string> AlarmMethod { get; set; }
/// <summary>
/// Stat structure associated with this thread.
/// </summary>
public Stat Stat { get; set; }
public ThreadWatchdogInfo(Thread thread, int timeout, string name)
{
Thread = thread;
Timeout = timeout;
FirstTick = Environment.TickCount & Int32.MaxValue;
LastTick = FirstTick;
Stat
= new Stat(
name,
string.Format("Last update of thread {0}", name),
"",
"ms",
"server",
"thread",
StatType.Pull,
MeasuresOfInterest.None,
stat => stat.Value = Environment.TickCount & Int32.MaxValue - LastTick,
StatVerbosity.Debug);
StatsManager.RegisterStat(Stat);
}
public ThreadWatchdogInfo(ThreadWatchdogInfo previousTwi)
{
Thread = previousTwi.Thread;
FirstTick = previousTwi.FirstTick;
LastTick = previousTwi.LastTick;
Timeout = previousTwi.Timeout;
IsTimedOut = previousTwi.IsTimedOut;
AlarmIfTimeout = previousTwi.AlarmIfTimeout;
AlarmMethod = previousTwi.AlarmMethod;
}
public void Cleanup()
{
StatsManager.DeregisterStat(Stat);
}
}
/// <summary>
/// This event is called whenever a tracked thread is
/// stopped or has not called UpdateThread() in time<
/// /summary>
public static event Action<ThreadWatchdogInfo> OnWatchdogTimeout;
/// <summary>
/// Is this watchdog active?
/// </summary>
public static bool Enabled
{
get { return m_enabled; }
set
{
// m_log.DebugFormat("[MEMORY WATCHDOG]: Setting MemoryWatchdog.Enabled to {0}", value);
if (value == m_enabled)
return;
m_enabled = value;
if (m_enabled)
{
// Set now so we don't get alerted on the first run
LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue;
}
m_watchdogTimer.Enabled = m_enabled;
}
}
private static bool m_enabled;
private static Dictionary<int, ThreadWatchdogInfo> m_threads;
private static System.Timers.Timer m_watchdogTimer;
/// <summary>
/// Last time the watchdog thread ran.
/// </summary>
/// <remarks>
/// Should run every WATCHDOG_INTERVAL_MS
/// </remarks>
public static int LastWatchdogThreadTick { get; private set; }
static Watchdog()
{
m_threads = new Dictionary<int, ThreadWatchdogInfo>();
m_watchdogTimer = new System.Timers.Timer(WATCHDOG_INTERVAL_MS);
m_watchdogTimer.AutoReset = false;
m_watchdogTimer.Elapsed += WatchdogTimerElapsed;
}
public static void Stop()
{
if(m_threads == null)
return;
lock(m_threads)
{
m_enabled = false;
if(m_watchdogTimer != null)
{
m_watchdogTimer.Dispose();
m_watchdogTimer = null;
}
foreach(ThreadWatchdogInfo twi in m_threads.Values)
{
Thread t = twi.Thread;
if(t.IsAlive)
t.Abort();
}
m_threads.Clear();
}
}
/// <summary>
/// Add a thread to the watchdog tracker.
/// </summary>
/// <param name="info">Information about the thread.</info>
/// <param name="info">Name of the thread.</info>
/// <param name="log">If true then creation of thread is logged.</param>
public static void AddThread(ThreadWatchdogInfo info, string name, bool log = true)
{
if (log)
m_log.DebugFormat(
"[WATCHDOG]: Started tracking thread {0}, ID {1}", name, info.Thread.ManagedThreadId);
lock (m_threads)
m_threads.Add(info.Thread.ManagedThreadId, info);
}
/// <summary>
/// Marks the current thread as alive
/// </summary>
public static void UpdateThread()
{
UpdateThread(Thread.CurrentThread.ManagedThreadId);
}
/// <summary>
/// Stops watchdog tracking on the current thread
/// </summary>
/// <param name="log">If true then normal events in thread removal are not logged.</param>
/// <returns>
/// True if the thread was removed from the list of tracked
/// threads, otherwise false
/// </returns>
public static bool RemoveThread(bool log = true)
{
return RemoveThread(Thread.CurrentThread.ManagedThreadId, log);
}
private static bool RemoveThread(int threadID, bool log = true)
{
lock (m_threads)
{
ThreadWatchdogInfo twi;
if (m_threads.TryGetValue(threadID, out twi))
{
if (log)
m_log.DebugFormat(
"[WATCHDOG]: Removing thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId);
twi.Cleanup();
m_threads.Remove(threadID);
return true;
}
else
{
m_log.WarnFormat(
"[WATCHDOG]: Requested to remove thread with ID {0} but this is not being monitored", threadID);
return false;
}
}
}
public static bool AbortThread(int threadID)
{
lock (m_threads)
{
if (m_threads.ContainsKey(threadID))
{
ThreadWatchdogInfo twi = m_threads[threadID];
twi.Thread.Abort();
RemoveThread(threadID);
return true;
}
else
{
return false;
}
}
}
private static void UpdateThread(int threadID)
{
ThreadWatchdogInfo threadInfo;
// Although TryGetValue is not a thread safe operation, we use a try/catch here instead
// of a lock for speed. Adding/removing threads is a very rare operation compared to
// UpdateThread(), and a single UpdateThread() failure here and there won't break
// anything
try
{
if (m_threads.TryGetValue(threadID, out threadInfo))
{
threadInfo.LastTick = Environment.TickCount & Int32.MaxValue;
threadInfo.IsTimedOut = false;
}
else
{
m_log.WarnFormat("[WATCHDOG]: Asked to update thread {0} which is not being monitored", threadID);
}
}
catch { }
}
/// <summary>
/// Get currently watched threads for diagnostic purposes
/// </summary>
/// <returns></returns>
public static ThreadWatchdogInfo[] GetThreadsInfo()
{
lock (m_threads)
return m_threads.Values.ToArray();
}
/// <summary>
/// Return the current thread's watchdog info.
/// </summary>
/// <returns>The watchdog info. null if the thread isn't being monitored.</returns>
public static ThreadWatchdogInfo GetCurrentThreadInfo()
{
lock (m_threads)
{
if (m_threads.ContainsKey(Thread.CurrentThread.ManagedThreadId))
return m_threads[Thread.CurrentThread.ManagedThreadId];
}
return null;
}
/// <summary>
/// Check watched threads. Fire alarm if appropriate.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if(!m_enabled)
return;
int now = Environment.TickCount & Int32.MaxValue;
int msElapsed = now - LastWatchdogThreadTick;
if (msElapsed > WATCHDOG_INTERVAL_MS * 2)
m_log.WarnFormat(
"[WATCHDOG]: {0} ms since Watchdog last ran. Interval should be approximately {1} ms",
msElapsed, WATCHDOG_INTERVAL_MS);
LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue;
Action<ThreadWatchdogInfo> callback = OnWatchdogTimeout;
if (callback != null)
{
List<ThreadWatchdogInfo> callbackInfos = null;
List<ThreadWatchdogInfo> threadsToRemove = null;
const ThreadState thgone = ThreadState.Stopped | ThreadState.Aborted | ThreadState.AbortRequested;
lock (m_threads)
{
foreach(ThreadWatchdogInfo threadInfo in m_threads.Values)
{
if(!m_enabled)
return;
if(!threadInfo.Thread.IsAlive || (threadInfo.Thread.ThreadState & thgone) != 0)
{
if(threadsToRemove == null)
threadsToRemove = new List<ThreadWatchdogInfo>();
threadsToRemove.Add(threadInfo);
/*
if(callbackInfos == null)
callbackInfos = new List<ThreadWatchdogInfo>();
callbackInfos.Add(threadInfo);
*/
}
else if(!threadInfo.IsTimedOut && now - threadInfo.LastTick >= threadInfo.Timeout)
{
threadInfo.IsTimedOut = true;
if(threadInfo.AlarmIfTimeout)
{
if(callbackInfos == null)
callbackInfos = new List<ThreadWatchdogInfo>();
// Send a copy of the watchdog info to prevent race conditions where the watchdog
// thread updates the monitoring info after an alarm has been sent out.
callbackInfos.Add(new ThreadWatchdogInfo(threadInfo));
}
}
}
if(threadsToRemove != null)
foreach(ThreadWatchdogInfo twi in threadsToRemove)
RemoveThread(twi.Thread.ManagedThreadId);
}
if(callbackInfos != null)
foreach (ThreadWatchdogInfo callbackInfo in callbackInfos)
callback(callbackInfo);
}
if (MemoryWatchdog.Enabled)
MemoryWatchdog.Update();
ChecksManager.CheckChecks();
StatsManager.RecordStats();
m_watchdogTimer.Start();
}
}
}
| |
/* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 the ZAP development team
*
* 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.Text;
/*
* This file was automatically generated.
*/
namespace OWASPZAPDotNetAPI.Generated
{
public class Core
{
private ClientApi api = null;
public Core(ClientApi api)
{
this.api = api;
}
/// <summary>
///Gets the name of the hosts accessed through/by ZAP
/// </summary>
/// <returns></returns>
public IApiResponse hosts()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "hosts", parameters);
}
/// <summary>
///Gets the sites accessed through/by ZAP (scheme and domain)
/// </summary>
/// <returns></returns>
public IApiResponse sites()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "sites", parameters);
}
/// <summary>
///Gets the URLs accessed through/by ZAP, optionally filtering by (base) URL.
/// </summary>
/// <returns></returns>
public IApiResponse urls(string baseurl)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("baseurl", baseurl);
return api.CallApi("core", "view", "urls", parameters);
}
/// <summary>
///Gets the child nodes underneath the specified URL in the Sites tree
/// </summary>
/// <returns></returns>
public IApiResponse childNodes(string url)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("url", url);
return api.CallApi("core", "view", "childNodes", parameters);
}
/// <summary>
///Gets the HTTP message with the given ID. Returns the ID, request/response headers and bodies, cookies, note, type, RTT, and timestamp.
/// </summary>
/// <returns></returns>
public IApiResponse message(string id)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("id", id);
return api.CallApi("core", "view", "message", parameters);
}
/// <summary>
///Gets the HTTP messages sent by ZAP, request and response, optionally filtered by URL and paginated with 'start' position and 'count' of messages
/// </summary>
/// <returns></returns>
public IApiResponse messages(string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("core", "view", "messages", parameters);
}
/// <summary>
///Gets the HTTP messages with the given IDs.
/// </summary>
/// <returns></returns>
public IApiResponse messagesById(string ids)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("ids", ids);
return api.CallApi("core", "view", "messagesById", parameters);
}
/// <summary>
///Gets the number of messages, optionally filtering by URL
/// </summary>
/// <returns></returns>
public IApiResponse numberOfMessages(string baseurl)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("baseurl", baseurl);
return api.CallApi("core", "view", "numberOfMessages", parameters);
}
/// <summary>
///Gets the mode
/// </summary>
/// <returns></returns>
public IApiResponse mode()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "mode", parameters);
}
/// <summary>
///Gets ZAP version
/// </summary>
/// <returns></returns>
public IApiResponse version()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "version", parameters);
}
/// <summary>
///Gets the regular expressions, applied to URLs, to exclude from the local proxies.
/// </summary>
/// <returns></returns>
public IApiResponse excludedFromProxy()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "excludedFromProxy", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse homeDirectory()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "homeDirectory", parameters);
}
/// <summary>
///Gets the location of the current session file
/// </summary>
/// <returns></returns>
public IApiResponse sessionLocation()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "sessionLocation", parameters);
}
/// <summary>
///Gets all the domains that are excluded from the outgoing proxy. For each domain the following are shown: the index, the value (domain), if enabled, and if specified as a regex.
/// </summary>
/// <returns></returns>
public IApiResponse proxyChainExcludedDomains()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "proxyChainExcludedDomains", parameters);
}
/// <summary>
///Use view proxyChainExcludedDomains instead.
/// [Obsolete]
/// </summary>
/// <returns></returns>
[Obsolete]
public IApiResponse optionProxyChainSkipName()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyChainSkipName", parameters);
}
/// <summary>
///Use view proxyChainExcludedDomains instead.
/// [Obsolete]
/// </summary>
/// <returns></returns>
[Obsolete]
public IApiResponse optionProxyExcludedDomains()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyExcludedDomains", parameters);
}
/// <summary>
///Use view proxyChainExcludedDomains instead.
/// [Obsolete]
/// </summary>
/// <returns></returns>
[Obsolete]
public IApiResponse optionProxyExcludedDomainsEnabled()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyExcludedDomainsEnabled", parameters);
}
/// <summary>
///Gets the path to ZAP's home directory.
/// </summary>
/// <returns></returns>
public IApiResponse zapHomePath()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "zapHomePath", parameters);
}
/// <summary>
///Gets the maximum number of alert instances to include in a report.
/// </summary>
/// <returns></returns>
public IApiResponse optionMaximumAlertInstances()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionMaximumAlertInstances", parameters);
}
/// <summary>
///Gets whether or not related alerts will be merged in any reports generated.
/// </summary>
/// <returns></returns>
public IApiResponse optionMergeRelatedAlerts()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionMergeRelatedAlerts", parameters);
}
/// <summary>
///Gets the path to the file with alert overrides.
/// </summary>
/// <returns></returns>
public IApiResponse optionAlertOverridesFilePath()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionAlertOverridesFilePath", parameters);
}
/// <summary>
///Gets the alert with the given ID, the corresponding HTTP message can be obtained with the 'messageId' field and 'message' API method
/// [Obsolete] Use the API endpoint with the same name in the 'alert' component instead.
/// </summary>
/// <returns></returns>
[Obsolete("Use the API endpoint with the same name in the 'alert' component instead.")]
public IApiResponse alert(string id)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("id", id);
return api.CallApi("core", "view", "alert", parameters);
}
/// <summary>
///Gets the alerts raised by ZAP, optionally filtering by URL or riskId, and paginating with 'start' position and 'count' of alerts
/// [Obsolete] Use the API endpoint with the same name in the 'alert' component instead.
/// </summary>
/// <returns></returns>
[Obsolete("Use the API endpoint with the same name in the 'alert' component instead.")]
public IApiResponse alerts(string baseurl, string start, string count, string riskid)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
parameters.Add("riskId", riskid);
return api.CallApi("core", "view", "alerts", parameters);
}
/// <summary>
///Gets number of alerts grouped by each risk level, optionally filtering by URL
/// [Obsolete] Use the API endpoint with the same name in the 'alert' component instead.
/// </summary>
/// <returns></returns>
[Obsolete("Use the API endpoint with the same name in the 'alert' component instead.")]
public IApiResponse alertsSummary(string baseurl)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("baseurl", baseurl);
return api.CallApi("core", "view", "alertsSummary", parameters);
}
/// <summary>
///Gets the number of alerts, optionally filtering by URL or riskId
/// [Obsolete] Use the API endpoint with the same name in the 'alert' component instead.
/// </summary>
/// <returns></returns>
[Obsolete("Use the API endpoint with the same name in the 'alert' component instead.")]
public IApiResponse numberOfAlerts(string baseurl, string riskid)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("baseurl", baseurl);
parameters.Add("riskId", riskid);
return api.CallApi("core", "view", "numberOfAlerts", parameters);
}
/// <summary>
///Gets the user agent that ZAP should use when creating HTTP messages (for example, spider messages or CONNECT requests to outgoing proxy).
/// </summary>
/// <returns></returns>
public IApiResponse optionDefaultUserAgent()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionDefaultUserAgent", parameters);
}
/// <summary>
///Gets the TTL (in seconds) of successful DNS queries.
/// </summary>
/// <returns></returns>
public IApiResponse optionDnsTtlSuccessfulQueries()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionDnsTtlSuccessfulQueries", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionHttpState()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionHttpState", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionProxyChainName()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyChainName", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionProxyChainPassword()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyChainPassword", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionProxyChainPort()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyChainPort", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionProxyChainRealm()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyChainRealm", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionProxyChainUserName()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyChainUserName", parameters);
}
/// <summary>
///Gets the connection time out, in seconds.
/// </summary>
/// <returns></returns>
public IApiResponse optionTimeoutInSecs()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionTimeoutInSecs", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionHttpStateEnabled()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionHttpStateEnabled", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionProxyChainPrompt()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionProxyChainPrompt", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionSingleCookieRequestHeader()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionSingleCookieRequestHeader", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionUseProxyChain()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionUseProxyChain", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse optionUseProxyChainAuth()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionUseProxyChainAuth", parameters);
}
/// <summary>
///Gets whether or not the SOCKS proxy should be used.
/// </summary>
/// <returns></returns>
public IApiResponse optionUseSocksProxy()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "view", "optionUseSocksProxy", parameters);
}
/// <summary>
///Convenient and simple action to access a URL, optionally following redirections. Returns the request sent and response received and followed redirections, if any. Other actions are available which offer more control on what is sent, like, 'sendRequest' or 'sendHarRequest'.
/// </summary>
/// <returns></returns>
public IApiResponse accessUrl(string url, string followredirects)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("url", url);
parameters.Add("followRedirects", followredirects);
return api.CallApi("core", "action", "accessUrl", parameters);
}
/// <summary>
///Shuts down ZAP
/// </summary>
/// <returns></returns>
public IApiResponse shutdown()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "shutdown", parameters);
}
/// <summary>
///Creates a new session, optionally overwriting existing files. If a relative path is specified it will be resolved against the "session" directory in ZAP "home" dir.
/// </summary>
/// <returns></returns>
public IApiResponse newSession(string name, string overwrite)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("name", name);
parameters.Add("overwrite", overwrite);
return api.CallApi("core", "action", "newSession", parameters);
}
/// <summary>
///Loads the session with the given name. If a relative path is specified it will be resolved against the "session" directory in ZAP "home" dir.
/// </summary>
/// <returns></returns>
public IApiResponse loadSession(string name)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("name", name);
return api.CallApi("core", "action", "loadSession", parameters);
}
/// <summary>
///Saves the session.
/// </summary>
/// <returns></returns>
public IApiResponse saveSession(string name, string overwrite)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("name", name);
parameters.Add("overwrite", overwrite);
return api.CallApi("core", "action", "saveSession", parameters);
}
/// <summary>
///Snapshots the session, optionally with the given name, and overwriting existing files. If no name is specified the name of the current session with a timestamp appended is used. If a relative path is specified it will be resolved against the "session" directory in ZAP "home" dir.
/// </summary>
/// <returns></returns>
public IApiResponse snapshotSession(string name, string overwrite)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("name", name);
parameters.Add("overwrite", overwrite);
return api.CallApi("core", "action", "snapshotSession", parameters);
}
/// <summary>
///Clears the regexes of URLs excluded from the local proxies.
/// </summary>
/// <returns></returns>
public IApiResponse clearExcludedFromProxy()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "clearExcludedFromProxy", parameters);
}
/// <summary>
///Adds a regex of URLs that should be excluded from the local proxies.
/// </summary>
/// <returns></returns>
public IApiResponse excludeFromProxy(string regex)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
return api.CallApi("core", "action", "excludeFromProxy", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setHomeDirectory(string dir)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("dir", dir);
return api.CallApi("core", "action", "setHomeDirectory", parameters);
}
/// <summary>
///Sets the mode, which may be one of [safe, protect, standard, attack]
/// </summary>
/// <returns></returns>
public IApiResponse setMode(string mode)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("mode", mode);
return api.CallApi("core", "action", "setMode", parameters);
}
/// <summary>
///Generates a new Root CA certificate for the local proxies.
/// </summary>
/// <returns></returns>
public IApiResponse generateRootCA()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "generateRootCA", parameters);
}
/// <summary>
///Sends the HTTP request, optionally following redirections. Returns the request sent and response received and followed redirections, if any. The Mode is enforced when sending the request (and following redirections), custom manual requests are not allowed in 'Safe' mode nor in 'Protected' mode if out of scope.
/// </summary>
/// <returns></returns>
public IApiResponse sendRequest(string request, string followredirects)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("request", request);
parameters.Add("followRedirects", followredirects);
return api.CallApi("core", "action", "sendRequest", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse runGarbageCollection()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "runGarbageCollection", parameters);
}
/// <summary>
///Deletes the site node found in the Sites Tree on the basis of the URL, HTTP method, and post data (if applicable and specified).
/// </summary>
/// <returns></returns>
public IApiResponse deleteSiteNode(string url, string method, string postdata)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("url", url);
parameters.Add("method", method);
parameters.Add("postData", postdata);
return api.CallApi("core", "action", "deleteSiteNode", parameters);
}
/// <summary>
///Adds a domain to be excluded from the outgoing proxy, using the specified value. Optionally sets if the new entry is enabled (default, true) and whether or not the new value is specified as a regex (default, false).
/// </summary>
/// <returns></returns>
public IApiResponse addProxyChainExcludedDomain(string value, string isregex, string isenabled)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("value", value);
parameters.Add("isRegex", isregex);
parameters.Add("isEnabled", isenabled);
return api.CallApi("core", "action", "addProxyChainExcludedDomain", parameters);
}
/// <summary>
///Modifies a domain excluded from the outgoing proxy. Allows to modify the value, if enabled or if a regex. The domain is selected with its index, which can be obtained with the view proxyChainExcludedDomains.
/// </summary>
/// <returns></returns>
public IApiResponse modifyProxyChainExcludedDomain(string idx, string value, string isregex, string isenabled)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("idx", idx);
parameters.Add("value", value);
parameters.Add("isRegex", isregex);
parameters.Add("isEnabled", isenabled);
return api.CallApi("core", "action", "modifyProxyChainExcludedDomain", parameters);
}
/// <summary>
///Removes a domain excluded from the outgoing proxy, with the given index. The index can be obtained with the view proxyChainExcludedDomains.
/// </summary>
/// <returns></returns>
public IApiResponse removeProxyChainExcludedDomain(string idx)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("idx", idx);
return api.CallApi("core", "action", "removeProxyChainExcludedDomain", parameters);
}
/// <summary>
///Enables all domains excluded from the outgoing proxy.
/// </summary>
/// <returns></returns>
public IApiResponse enableAllProxyChainExcludedDomains()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "enableAllProxyChainExcludedDomains", parameters);
}
/// <summary>
///Disables all domains excluded from the outgoing proxy.
/// </summary>
/// <returns></returns>
public IApiResponse disableAllProxyChainExcludedDomains()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "disableAllProxyChainExcludedDomains", parameters);
}
/// <summary>
///Sets the maximum number of alert instances to include in a report. A value of zero is treated as unlimited.
/// </summary>
/// <returns></returns>
public IApiResponse setOptionMaximumAlertInstances(string numberofinstances)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("numberOfInstances", numberofinstances);
return api.CallApi("core", "action", "setOptionMaximumAlertInstances", parameters);
}
/// <summary>
///Sets whether or not related alerts will be merged in any reports generated.
/// </summary>
/// <returns></returns>
public IApiResponse setOptionMergeRelatedAlerts(string enabled)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("enabled", enabled);
return api.CallApi("core", "action", "setOptionMergeRelatedAlerts", parameters);
}
/// <summary>
///Sets (or clears, if empty) the path to the file with alert overrides.
/// </summary>
/// <returns></returns>
public IApiResponse setOptionAlertOverridesFilePath(string filepath)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("filePath", filepath);
return api.CallApi("core", "action", "setOptionAlertOverridesFilePath", parameters);
}
/// <summary>
///Enables use of a PKCS12 client certificate for the certificate with the given file system path, password, and optional index.
/// </summary>
/// <returns></returns>
public IApiResponse enablePKCS12ClientCertificate(string filepath, string password, string index)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("filePath", filepath);
parameters.Add("password", password);
parameters.Add("index", index);
return api.CallApi("core", "action", "enablePKCS12ClientCertificate", parameters);
}
/// <summary>
///Disables the option for use of client certificates.
/// </summary>
/// <returns></returns>
public IApiResponse disableClientCertificate()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "disableClientCertificate", parameters);
}
/// <summary>
///Deletes all alerts of the current session.
/// [Obsolete] Use the API endpoint with the same name in the 'alert' component instead.
/// </summary>
/// <returns></returns>
[Obsolete("Use the API endpoint with the same name in the 'alert' component instead.")]
public IApiResponse deleteAllAlerts()
{
Dictionary<string, string> parameters = null;
return api.CallApi("core", "action", "deleteAllAlerts", parameters);
}
/// <summary>
///Deletes the alert with the given ID.
/// [Obsolete] Use the API endpoint with the same name in the 'alert' component instead.
/// </summary>
/// <returns></returns>
[Obsolete("Use the API endpoint with the same name in the 'alert' component instead.")]
public IApiResponse deleteAlert(string id)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("id", id);
return api.CallApi("core", "action", "deleteAlert", parameters);
}
/// <summary>
///Sets the user agent that ZAP should use when creating HTTP messages (for example, spider messages or CONNECT requests to outgoing proxy).
/// </summary>
/// <returns></returns>
public IApiResponse setOptionDefaultUserAgent(string str)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("String", str);
return api.CallApi("core", "action", "setOptionDefaultUserAgent", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionProxyChainName(string str)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("String", str);
return api.CallApi("core", "action", "setOptionProxyChainName", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionProxyChainPassword(string str)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("String", str);
return api.CallApi("core", "action", "setOptionProxyChainPassword", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionProxyChainRealm(string str)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("String", str);
return api.CallApi("core", "action", "setOptionProxyChainRealm", parameters);
}
/// <summary>
///Use actions [add|modify|remove]ProxyChainExcludedDomain instead.
/// [Obsolete] Option no longer in effective use.
/// </summary>
/// <returns></returns>
[Obsolete("Option no longer in effective use.")]
public IApiResponse setOptionProxyChainSkipName(string str)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("String", str);
return api.CallApi("core", "action", "setOptionProxyChainSkipName", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionProxyChainUserName(string str)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("String", str);
return api.CallApi("core", "action", "setOptionProxyChainUserName", parameters);
}
/// <summary>
///Sets the TTL (in seconds) of successful DNS queries (applies after ZAP restart).
/// </summary>
/// <returns></returns>
public IApiResponse setOptionDnsTtlSuccessfulQueries(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("core", "action", "setOptionDnsTtlSuccessfulQueries", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionHttpStateEnabled(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("core", "action", "setOptionHttpStateEnabled", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionProxyChainPort(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("core", "action", "setOptionProxyChainPort", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionProxyChainPrompt(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("core", "action", "setOptionProxyChainPrompt", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionSingleCookieRequestHeader(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("core", "action", "setOptionSingleCookieRequestHeader", parameters);
}
/// <summary>
///Sets the connection time out, in seconds.
/// </summary>
/// <returns></returns>
public IApiResponse setOptionTimeoutInSecs(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("core", "action", "setOptionTimeoutInSecs", parameters);
}
/// <summary>
///Sets whether or not the outgoing proxy should be used. The address/hostname of the outgoing proxy must be set to enable this option.
/// </summary>
/// <returns></returns>
public IApiResponse setOptionUseProxyChain(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("core", "action", "setOptionUseProxyChain", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IApiResponse setOptionUseProxyChainAuth(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("core", "action", "setOptionUseProxyChainAuth", parameters);
}
/// <summary>
///Sets whether or not the SOCKS proxy should be used.
/// </summary>
/// <returns></returns>
public IApiResponse setOptionUseSocksProxy(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("core", "action", "setOptionUseSocksProxy", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte[] proxypac()
{
Dictionary<string, string> parameters = null;
return api.CallApiOther("core", "other", "proxy.pac", parameters);
}
/// <summary>
///Gets the Root CA certificate used by the local proxies.
/// </summary>
/// <returns></returns>
public byte[] rootcert()
{
Dictionary<string, string> parameters = null;
return api.CallApiOther("core", "other", "rootcert", parameters);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte[] setproxy(string proxy)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("proxy", proxy);
return api.CallApiOther("core", "other", "setproxy", parameters);
}
/// <summary>
///Generates a report in XML format
/// </summary>
/// <returns></returns>
public byte[] xmlreport()
{
Dictionary<string, string> parameters = null;
return api.CallApiOther("core", "other", "xmlreport", parameters);
}
/// <summary>
///Generates a report in HTML format
/// </summary>
/// <returns></returns>
public byte[] htmlreport()
{
Dictionary<string, string> parameters = null;
return api.CallApiOther("core", "other", "htmlreport", parameters);
}
/// <summary>
///Generates a report in JSON format
/// </summary>
/// <returns></returns>
public byte[] jsonreport()
{
Dictionary<string, string> parameters = null;
return api.CallApiOther("core", "other", "jsonreport", parameters);
}
/// <summary>
///Generates a report in Markdown format
/// </summary>
/// <returns></returns>
public byte[] mdreport()
{
Dictionary<string, string> parameters = null;
return api.CallApiOther("core", "other", "mdreport", parameters);
}
/// <summary>
///Gets the message with the given ID in HAR format
/// </summary>
/// <returns></returns>
public byte[] messageHar(string id)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("id", id);
return api.CallApiOther("core", "other", "messageHar", parameters);
}
/// <summary>
///Gets the HTTP messages sent through/by ZAP, in HAR format, optionally filtered by URL and paginated with 'start' position and 'count' of messages
/// </summary>
/// <returns></returns>
public byte[] messagesHar(string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApiOther("core", "other", "messagesHar", parameters);
}
/// <summary>
///Gets the HTTP messages with the given IDs, in HAR format.
/// </summary>
/// <returns></returns>
public byte[] messagesHarById(string ids)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("ids", ids);
return api.CallApiOther("core", "other", "messagesHarById", parameters);
}
/// <summary>
///Sends the first HAR request entry, optionally following redirections. Returns, in HAR format, the request sent and response received and followed redirections, if any. The Mode is enforced when sending the request (and following redirections), custom manual requests are not allowed in 'Safe' mode nor in 'Protected' mode if out of scope.
/// </summary>
/// <returns></returns>
public byte[] sendHarRequest(string request, string followredirects)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("request", request);
parameters.Add("followRedirects", followredirects);
return api.CallApiOther("core", "other", "sendHarRequest", parameters);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qwack.Core.Basic;
using Qwack.Core.Cubes;
using Qwack.Math.Interpolation;
using Qwack.Options.Calibrators;
using Qwack.Transport.BasicTypes;
using Qwack.Transport.TransportObjects.MarketData.VolSurfaces;
namespace Qwack.Options.VolSurfaces
{
public class RiskyFlySurface : GridVolSurface
{
public double[][] Riskies { get; }
public double[][] Flies { get; }
public double[] ATMs { get; }
public double[] WingDeltas { get; }
public double[] Forwards { get; }
public WingQuoteType WingQuoteType { get; }
public AtmVolType AtmVolType { get; }
public RiskyFlySurface(DateTime originDate, double[] ATMVols, DateTime[] expiries, double[] wingDeltas,
double[][] riskies, double[][] flies, double[] fwds, WingQuoteType wingQuoteType, AtmVolType atmVolType,
Interpolator1DType strikeInterpType, Interpolator1DType timeInterpType, string[] pillarLabels = null)
{
if (pillarLabels == null)
PillarLabels = expiries.Select(x => x.ToString("yyyy-MM-dd")).ToArray();
else
PillarLabels = pillarLabels;
if (ATMVols.Length != expiries.Length || expiries.Length != riskies.Length || riskies.Length != flies.Length)
throw new Exception("Inputs do not have consistent time dimensions");
if (wingDeltas.Length != riskies[0].Length || riskies[0].Length != flies[0].Length)
throw new Exception("Inputs do not have consistent strike dimensions");
var strikes = new double[2 * wingDeltas.Length + 1];
var vols = new double[expiries.Length][];
if (riskies.SelectMany(x => x).All(x => x == 0) && flies.SelectMany(x => x).All(x => x == 0))
{
for (var s = 0; s < wingDeltas.Length; s++)
{
strikes[s] = wingDeltas[wingDeltas.Length - 1 - s];
strikes[strikes.Length - 1 - s] = 1.0 - wingDeltas[wingDeltas.Length - 1 - s];
}
for (var t =0;t<expiries.Length;t++)
{
vols[t] = Enumerable.Repeat(ATMVols[t], strikes.Length).ToArray();
}
}
else
{
var atmConstraints = ATMVols.Select(a => new ATMStraddleConstraint
{
ATMVolType = atmVolType,
MarketVol = a
}).ToArray();
var needsFlip = wingDeltas.First() > wingDeltas.Last();
if (needsFlip)
{
for (var s = 0; s < wingDeltas.Length; s++)
{
strikes[s] = wingDeltas[wingDeltas.Length - 1 - s];
strikes[strikes.Length - 1 - s] = 1.0 - wingDeltas[wingDeltas.Length - 1 - s];
}
}
else
{
for (var s = 0; s < wingDeltas.Length; s++)
{
strikes[s] = wingDeltas[s];
strikes[strikes.Length - 1 - s] = 1.0 - wingDeltas[s];
}
}
strikes[wingDeltas.Length] = 0.5;
var wingConstraints = new RRBFConstraint[expiries.Length][];
var f = new AssetSmileSolver();
if (needsFlip)
{
for (var i = 0; i < wingConstraints.Length; i++)
{
var offset = wingDeltas.Length - 1;
wingConstraints[i] = new RRBFConstraint[wingDeltas.Length];
for (var j = 0; j < wingConstraints[i].Length; j++)
{
wingConstraints[i][j] = new RRBFConstraint
{
Delta = wingDeltas[offset - j],
FlyVol = flies[i][offset - j],
RisykVol = riskies[i][offset - j],
WingQuoteType = wingQuoteType,
};
}
vols[i] = f.Solve(atmConstraints[i], wingConstraints[i], originDate, expiries[i], fwds[i], strikes, strikeInterpType);
}
}
else
{
for (var i = 0; i < wingConstraints.Length; i++)
{
wingConstraints[i] = new RRBFConstraint[wingDeltas.Length];
for (var j = 0; j < wingConstraints[i].Length; j++)
{
wingConstraints[i][j] = new RRBFConstraint
{
Delta = wingDeltas[j],
FlyVol = flies[i][j],
RisykVol = riskies[i][j],
WingQuoteType = wingQuoteType,
};
}
vols[i] = f.Solve(atmConstraints[i], wingConstraints[i], originDate, expiries[i], fwds[i], strikes, strikeInterpType);
}
}
}
StrikeInterpolatorType = strikeInterpType;
TimeInterpolatorType = timeInterpType;
Expiries = expiries;
ExpiriesDouble = expiries.Select(x => x.ToOADate()).ToArray();
Strikes = strikes;
StrikeType = StrikeType.ForwardDelta;
ATMs = ATMVols;
Riskies = riskies;
Flies = flies;
WingDeltas = wingDeltas;
Forwards = fwds;
WingQuoteType = wingQuoteType;
AtmVolType = atmVolType;
base.Build(originDate, strikes, expiries, vols);
}
public RiskyFlySurface(TO_RiskyFlySurface transportObject, ICurrencyProvider currencyProvider)
:this(transportObject.OriginDate,transportObject.ATMs, transportObject.Expiries, transportObject.WingDeltas,transportObject.Riskies,
transportObject.Flies,transportObject.Forwards, transportObject.WingQuoteType, transportObject.AtmVolType, transportObject.StrikeInterpolatorType,
transportObject.TimeInterpolatorType, transportObject.PillarLabels)
{
Currency = currencyProvider.GetCurrencySafe(transportObject.Currency);
AssetId = transportObject.AssetId;
Name = transportObject.Name;
}
private int LastIx(DateTime? LastSensitivityDate)
{
var lastExpiry = Expiries.Length;
if (LastSensitivityDate.HasValue)
{
var ix = Array.BinarySearch(Expiries, LastSensitivityDate.Value);
ix = ix < 0 ? ~ix : ix;
ix += 2;
lastExpiry = System.Math.Min(ix, Expiries.Length);
}
return lastExpiry;
}
public new Dictionary<string, IVolSurface> GetATMVegaScenarios(double bumpSize, DateTime? LastSensitivityDate)
{
var o = new Dictionary<string, IVolSurface>();
var lastExpiry = LastIx(LastSensitivityDate);
for (var i = 0; i < lastExpiry; i++)
{
var volsBumped = (double[])ATMs.Clone();
volsBumped[i] += bumpSize;
o.Add(PillarLabels[i], new RiskyFlySurface(OriginDate, volsBumped, Expiries, WingDeltas, Riskies, Flies, Forwards, WingQuoteType, AtmVolType, StrikeInterpolatorType, TimeInterpolatorType, PillarLabels));
}
return o;
}
public Dictionary<string, IVolSurface> GetRegaScenarios(double bumpSize, DateTime? LastSensitivityDate)
{
var o = new Dictionary<string, IVolSurface>();
var lastExpiry = LastIx(LastSensitivityDate);
var highDeltaFirst = WingDeltas.First() > WingDeltas.Last();
for (var i = 0; i < lastExpiry; i++)
{
var volsBumped = (double[][])Riskies.Clone();
if(highDeltaFirst)
{
var ratios = volsBumped[i].Select(x => x / volsBumped[i][0]).ToArray();
volsBumped[i] = ratios.Select(r => (volsBumped[i][0] + bumpSize) * r).ToArray();
}
else
{
var ratios = volsBumped[i].Select(x => x / volsBumped[i].Last()).ToArray();
volsBumped[i] = ratios.Select(r => (volsBumped[i].Last() + bumpSize) * r).ToArray();
}
o.Add(PillarLabels[i], new RiskyFlySurface(OriginDate, ATMs, Expiries, WingDeltas, volsBumped, Flies, Forwards, WingQuoteType, AtmVolType, StrikeInterpolatorType, TimeInterpolatorType, PillarLabels));
}
return o;
}
public Dictionary<string, IVolSurface> GetRegaScenariosOuterWing(double bumpSize, DateTime? LastSensitivityDate)
{
var o = new Dictionary<string, IVolSurface>();
var lastExpiry = LastIx(LastSensitivityDate);
var highDeltaFirst = WingDeltas.First() > WingDeltas.Last();
var outerWingIx = WingDeltas.Length - 1;
for (var i = 0; i < lastExpiry; i++)
{
var volsBumped = (double[][])Riskies.Clone();
if (highDeltaFirst)
volsBumped[i][outerWingIx] += bumpSize;
else
volsBumped[i][0] += bumpSize;
o.Add(PillarLabels[i], new RiskyFlySurface(OriginDate, ATMs, Expiries, WingDeltas, volsBumped, Flies, Forwards, WingQuoteType, AtmVolType, StrikeInterpolatorType, TimeInterpolatorType, PillarLabels));
}
return o;
}
public Dictionary<string, IVolSurface> GetSegaScenarios(double bumpSize, DateTime? LastSensitivityDate)
{
var o = new Dictionary<string, IVolSurface>();
var lastExpiry = LastIx(LastSensitivityDate);
var highDeltaFirst = WingDeltas.First() > WingDeltas.Last();
for (var i = 0; i < lastExpiry; i++)
{
var volsBumped = (double[][])Flies.Clone();
if (highDeltaFirst)
{
var ratios = volsBumped[i].Select(x => x / volsBumped[i][0]).ToArray();
volsBumped[i] = ratios.Select(r => (volsBumped[i][0] + bumpSize) * r).ToArray();
}
else
{
var ratios = volsBumped[i].Select(x => x / volsBumped[i].Last()).ToArray();
volsBumped[i] = ratios.Select(r => (volsBumped[i].Last() + bumpSize) * r).ToArray();
}
o.Add(PillarLabels[i], new RiskyFlySurface(OriginDate, ATMs, Expiries, WingDeltas, Riskies, volsBumped, Forwards, WingQuoteType, AtmVolType, StrikeInterpolatorType, TimeInterpolatorType, PillarLabels));
}
return o;
}
public Dictionary<string, IVolSurface> GetSegaScenariosOuterWing(double bumpSize, DateTime? LastSensitivityDate)
{
var o = new Dictionary<string, IVolSurface>();
var lastExpiry = LastIx(LastSensitivityDate);
var highDeltaFirst = WingDeltas.First() > WingDeltas.Last();
var outerWingIx = WingDeltas.Length - 1;
for (var i = 0; i < lastExpiry; i++)
{
var volsBumped = (double[][])Flies.Clone();
if (highDeltaFirst)
{
volsBumped[i][outerWingIx] += bumpSize;
}
else
{
volsBumped[i][0] += bumpSize;
}
o.Add(PillarLabels[i], new RiskyFlySurface(OriginDate, ATMs, Expiries, WingDeltas, Riskies, volsBumped, Forwards, WingQuoteType, AtmVolType, StrikeInterpolatorType, TimeInterpolatorType, PillarLabels));
}
return o;
}
public ICube ToCube()
{
var cube = new ResultCube();
var dataTypes = new Dictionary<string, Type>
{
{ "PointDate", typeof(DateTime) },
{ "PointType", typeof(string) },
{ "QuoteType", typeof(string) },
{ "PointDelta", typeof(double) },
};
cube.Initialize(dataTypes);
for (var i = 0; i < Expiries.Length; i++)
{
var rowF = new Dictionary<string, object>
{
{ "PointDate", Expiries[i] },
{ "PointType", "Forward" },
{ "QuoteType", string.Empty },
{ "PointDelta", 0.5 },
};
cube.AddRow(rowF, Forwards[i]);
var rowA = new Dictionary<string, object>
{
{ "PointDate", Expiries[i] },
{ "PointType", "ATM" },
{ "QuoteType", AtmVolType.ToString() },
{ "PointDelta", 0.5 },
};
cube.AddRow(rowA, ATMs[i]);
for (var j = 0; j < WingDeltas.Length; j++)
{
var rowRR = new Dictionary<string, object>
{
{ "PointDate", Expiries[i] },
{ "PointType", "RR" },
{ "QuoteType", WingQuoteType.ToString() },
{ "PointDelta", WingDeltas[j] },
};
cube.AddRow(rowRR, Riskies[i][j]);
var rowBF = new Dictionary<string, object>
{
{ "PointDate", Expiries[i] },
{ "PointType", "BF" },
{ "QuoteType", WingQuoteType.ToString() },
{ "PointDelta", WingDeltas[j] },
};
cube.AddRow(rowBF, Flies[i][j]);
}
}
return cube;
}
public static RiskyFlySurface FromCube(ICube cube, DateTime buildDate, Interpolator1DType strikeInterpType = Interpolator1DType.GaussianKernel, Interpolator1DType timeInterpType = Interpolator1DType.LinearInVariance)
{
var rows = cube.GetAllRows();
var deltas = cube.KeysForField("PointDelta")
.Where(x => (double)x != 0.5)
.Select(x => (double)x)
.OrderBy(x => x)
.ToList();
var fwds = new Dictionary<DateTime, double>();
var atms = new Dictionary<DateTime, double>();
var rrs = new Dictionary<DateTime, double[]>();
var bfs = new Dictionary<DateTime, double[]>();
var quoteType = WingQuoteType.Simple;
var atmType = AtmVolType.ZeroDeltaStraddle;
foreach (var row in rows)
{
var r = row.ToDictionary(cube.DataTypes.Keys.ToArray());
var d = (DateTime)r["PointDate"];
switch ((string)r["PointType"])
{
case "Forward":
fwds[d] = row.Value;
break;
case "ATM":
atms[d] = row.Value;
atmType = (AtmVolType)Enum.Parse(typeof(AtmVolType), (string)r["QuoteType"]);
break;
case "RR":
var delta = (double)r["PointDelta"];
if (!rrs.ContainsKey(d))
rrs[d] = new double[deltas.Count];
var dIx = deltas.IndexOf(delta);
rrs[d][dIx] = row.Value;
quoteType = (WingQuoteType)Enum.Parse(typeof(WingQuoteType), (string)r["QuoteType"]);
break;
case "BF":
var delta2 = (double)r["PointDelta"];
if (!bfs.ContainsKey(d))
bfs[d] = new double[deltas.Count];
var dIx2 = deltas.IndexOf(delta2);
bfs[d][dIx2] = row.Value;
break;
}
}
var expArr = atms.OrderBy(x => x.Key).Select(x => x.Key).ToArray();
var atmArr = atms.OrderBy(x => x.Key).Select(x => x.Value).ToArray();
var fwdArr = fwds.OrderBy(x => x.Key).Select(x => x.Value).ToArray();
var rrArr = rrs.OrderBy(x => x.Key).Select(x => x.Value).ToArray();
var bfArr = bfs.OrderBy(x => x.Key).Select(x => x.Value).ToArray();
return new RiskyFlySurface(buildDate, atmArr, expArr, deltas.ToArray(), rrArr, bfArr, fwdArr, quoteType, atmType, strikeInterpType, timeInterpType);
}
public object[,] DisplayQuotes()
{
var o = new object[Expiries.Length + 1, 2 + 2 * WingDeltas.Length];
//headers
o[0, 0] = "Expiry";
o[0, 1] = "ATM";
for(var i=0;i<WingDeltas.Length;i++)
{
o[0, 2 + i] = "RR~" + WingDeltas[i];
o[0, 2 + WingDeltas.Length + i] = "BF~" + WingDeltas[i];
}
//data
for(var i=0;i<Expiries.Length;i++)
{
o[1 + i, 0] = Expiries[i];
o[1 + i, 1] = ATMs[i];
for (var j = 0; j < WingDeltas.Length; j++)
{
o[1 + i, 2 + j] = Riskies[i][j];
o[1 + i, 2 + WingDeltas.Length + j] = Flies[i][j];
}
}
return o;
}
private readonly bool rollUpATM = false;
public override IVolSurface RollSurface(DateTime newOrigin)
{
//_suppressVarianceErrors = true;
var newMaturities = Expiries.Where(x => x > newOrigin).ToArray();
var newVols = new double[newMaturities.Length][];
var newATMs = newMaturities.Select(m => rollUpATM ? GetForwardATMVol(newOrigin, m) : GetVolForDeltaStrike(0.5,m,1.0)).ToArray();
//var newATMs = new double[newMaturities.Length];
var newRRs = new double[newMaturities.Length][];
var newBFs = new double[newMaturities.Length][];
var numDropped = Expiries.Length - newMaturities.Length;
var newFwds = Forwards.Skip(numDropped).ToArray();
var newLabels = PillarLabels.Skip(numDropped).ToArray();
for (var i = 0; i < newMaturities.Length; i++)
{
newRRs[i] = Riskies[i + numDropped];
newBFs[i] = Flies[i + numDropped];
//newATMs[i] = GetVolForDeltaStrike(0.5, newMaturities[i], newFwds[i]);
}
if (newATMs.Length == 0)
return new ConstantVolSurface(OriginDate, 0.32)
{
Name = Name,
AssetId = AssetId,
Currency = Currency,
};
return new RiskyFlySurface(newOrigin, newATMs, newMaturities, WingDeltas, newRRs, newBFs, newFwds, WingQuoteType, AtmVolType, StrikeInterpolatorType, TimeInterpolatorType, newLabels)
{
AssetId = AssetId,
Currency = Currency,
Name = Name,
};
}
public new TO_RiskyFlySurface GetTransportObject() => new()
{
AssetId = AssetId,
Name = Name,
OriginDate = OriginDate,
ATMs = ATMs,
AtmVolType = AtmVolType,
Currency = Currency,
Expiries = Expiries,
FlatDeltaPoint = FlatDeltaPoint,
FlatDeltaSmileInExtreme = FlatDeltaSmileInExtreme,
OverrideSpotLag = OverrideSpotLag.ToString(),
Riskies = new MultiDimArray<double>(Riskies),
Flies = new MultiDimArray<double>(Flies),
Forwards = Forwards,
PillarLabels = PillarLabels,
StrikeInterpolatorType = StrikeInterpolatorType,
StrikeType = StrikeType,
TimeBasis = TimeBasis,
TimeInterpolatorType = TimeInterpolatorType,
WingDeltas = WingDeltas,
WingQuoteType = WingQuoteType
};
}
}
| |
using System;
using Obscur.Core.Cryptography.Support;
namespace Obscur.Core.Cryptography.Authentication.Primitives
{
#if INCLUDE_SHA1
/**
* implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
*
* It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
* is the "endienness" of the word processing!
*/
public class Sha1Digest
: GeneralDigest
{
private const int OutputLength = 20;
private uint H1, H2, H3, H4, H5;
private uint[] X = new uint[80];
private int xOff;
public Sha1Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha1Digest(Sha1Digest t)
: base(t)
{
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
/// <summary>
/// Enumerated function identity.
/// </summary>
public override HashFunction Identity { get { return HashFunction.Sha1; } }
public override string AlgorithmName
{
get { return "SHA-1"; }
}
public override int OutputSize {
get { return OutputLength; }
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
if (++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE(H1, output, outOff);
Pack.UInt32_To_BE(H2, output, outOff + 4);
Pack.UInt32_To_BE(H3, output, outOff + 8);
Pack.UInt32_To_BE(H4, output, outOff + 12);
Pack.UInt32_To_BE(H5, output, outOff + 16);
Reset();
return OutputLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
xOff = 0;
Array.Clear(X, 0, X.Length);
}
//
// Additive constants
//
private const uint Y1 = 0x5a827999;
private const uint Y2 = 0x6ed9eba1;
private const uint Y3 = 0x8f1bbcdc;
private const uint Y4 = 0xca62c1d6;
private static uint F(uint u, uint v, uint w)
{
return (u & v) | (~u & w);
}
private static uint H(uint u, uint v, uint w)
{
return u ^ v ^ w;
}
private static uint G(uint u, uint v, uint w)
{
return (u & v) | (u & w) | (v & w);
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 80 word block.
//
for (int i = 16; i < 80; i++)
{
uint t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >> 31;
}
//
// set up working variables.
//
uint A = H1;
uint B = H2;
uint C = H3;
uint D = H4;
uint E = H5;
//
// round 1
//
int idx = 0;
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1;
C = C << 30 | (C >> 2);
}
//
// round 2
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2;
C = C << 30 | (C >> 2);
}
//
// round 3
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3;
C = C << 30 | (C >> 2);
}
//
// round 4
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4;
C = C << 30 | (C >> 2);
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
}
}
#endif
}
| |
// 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.Azure.AcceptanceTestsHeadExceptions
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
/// <summary>
/// HeadExceptionOperations operations.
/// </summary>
internal partial class HeadExceptionOperations : IServiceOperations<AutoRestHeadExceptionTestService>, IHeadExceptionOperations
{
/// <summary>
/// Initializes a new instance of the HeadExceptionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal HeadExceptionOperations(AutoRestHeadExceptionTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHeadExceptionTestService
/// </summary>
public AutoRestHeadExceptionTestService Client { get; private set; }
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Head200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Head204", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/204").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 404 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Head404", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/404").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// TaxDistrictResponse
/// </summary>
[DataContract]
public partial class TaxDistrictResponse : IEquatable<TaxDistrictResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="TaxDistrictResponse" /> class.
/// </summary>
/// <param name="ObjectId">ObjectId.</param>
/// <param name="Confidence">Confidence.</param>
/// <param name="Jurisdiction">Jurisdiction.</param>
/// <param name="NumOfIpdsFound">NumOfIpdsFound.</param>
/// <param name="Ipds">Ipds.</param>
/// <param name="MatchedAddress">MatchedAddress.</param>
public TaxDistrictResponse(string ObjectId = null, double? Confidence = null, IPDTaxJurisdiction Jurisdiction = null, int? NumOfIpdsFound = null, List<Ipd> Ipds = null, MatchedAddress MatchedAddress = null)
{
this.ObjectId = ObjectId;
this.Confidence = Confidence;
this.Jurisdiction = Jurisdiction;
this.NumOfIpdsFound = NumOfIpdsFound;
this.Ipds = Ipds;
this.MatchedAddress = MatchedAddress;
}
/// <summary>
/// Gets or Sets ObjectId
/// </summary>
[DataMember(Name="objectId", EmitDefaultValue=false)]
public string ObjectId { get; set; }
/// <summary>
/// Gets or Sets Confidence
/// </summary>
[DataMember(Name="confidence", EmitDefaultValue=false)]
public double? Confidence { get; set; }
/// <summary>
/// Gets or Sets Jurisdiction
/// </summary>
[DataMember(Name="jurisdiction", EmitDefaultValue=false)]
public IPDTaxJurisdiction Jurisdiction { get; set; }
/// <summary>
/// Gets or Sets NumOfIpdsFound
/// </summary>
[DataMember(Name="numOfIpdsFound", EmitDefaultValue=false)]
public int? NumOfIpdsFound { get; set; }
/// <summary>
/// Gets or Sets Ipds
/// </summary>
[DataMember(Name="ipds", EmitDefaultValue=false)]
public List<Ipd> Ipds { get; set; }
/// <summary>
/// Gets or Sets MatchedAddress
/// </summary>
[DataMember(Name="matchedAddress", EmitDefaultValue=false)]
public MatchedAddress MatchedAddress { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TaxDistrictResponse {\n");
sb.Append(" ObjectId: ").Append(ObjectId).Append("\n");
sb.Append(" Confidence: ").Append(Confidence).Append("\n");
sb.Append(" Jurisdiction: ").Append(Jurisdiction).Append("\n");
sb.Append(" NumOfIpdsFound: ").Append(NumOfIpdsFound).Append("\n");
sb.Append(" Ipds: ").Append(Ipds).Append("\n");
sb.Append(" MatchedAddress: ").Append(MatchedAddress).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as TaxDistrictResponse);
}
/// <summary>
/// Returns true if TaxDistrictResponse instances are equal
/// </summary>
/// <param name="other">Instance of TaxDistrictResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TaxDistrictResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ObjectId == other.ObjectId ||
this.ObjectId != null &&
this.ObjectId.Equals(other.ObjectId)
) &&
(
this.Confidence == other.Confidence ||
this.Confidence != null &&
this.Confidence.Equals(other.Confidence)
) &&
(
this.Jurisdiction == other.Jurisdiction ||
this.Jurisdiction != null &&
this.Jurisdiction.Equals(other.Jurisdiction)
) &&
(
this.NumOfIpdsFound == other.NumOfIpdsFound ||
this.NumOfIpdsFound != null &&
this.NumOfIpdsFound.Equals(other.NumOfIpdsFound)
) &&
(
this.Ipds == other.Ipds ||
this.Ipds != null &&
this.Ipds.SequenceEqual(other.Ipds)
) &&
(
this.MatchedAddress == other.MatchedAddress ||
this.MatchedAddress != null &&
this.MatchedAddress.Equals(other.MatchedAddress)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ObjectId != null)
hash = hash * 59 + this.ObjectId.GetHashCode();
if (this.Confidence != null)
hash = hash * 59 + this.Confidence.GetHashCode();
if (this.Jurisdiction != null)
hash = hash * 59 + this.Jurisdiction.GetHashCode();
if (this.NumOfIpdsFound != null)
hash = hash * 59 + this.NumOfIpdsFound.GetHashCode();
if (this.Ipds != null)
hash = hash * 59 + this.Ipds.GetHashCode();
if (this.MatchedAddress != null)
hash = hash * 59 + this.MatchedAddress.GetHashCode();
return hash;
}
}
}
}
| |
#region license
// Copyright 2004-2012 Castle Project, Henrik Feldt &contributors - https://github.com/castleproject
//
// 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.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace Castle.Transactions
{
/// <summary>
/// Static helper class for creating Maybe monads.
/// </summary>
public static class Maybe
{
/// <summary>
/// Creates a new maybe monad with a value.
/// </summary>
/// <typeparam name = "TSome">The type of the value to set the monad to contain.</typeparam>
/// <param name = "item">The item</param>
/// <returns>A non-null maybe instance of the maybe monad.</returns>
[Pure]
public static Maybe<TSome> Some<TSome>(TSome item)
{
Contract.Ensures(Contract.Result<Maybe<TSome>>() != null);
Contract.Ensures(Contract.Result<Maybe<TSome>>().HasValue);
//Contract.Ensures(Contract.Result<Maybe<TSome>>().Value.Equals(item)); // this line is also required to crash CCChecker
if (!(typeof (TSome).IsValueType || item != null))
throw new ArgumentException("item must be either a value type or non-null");
return new Maybe<TSome>(item);
}
[Pure]
public static Maybe<TNone> None<TNone>()
{
Contract.Ensures(Contract.Result<Maybe<TNone>>() != null);
Contract.Ensures(!Contract.Result<Maybe<TNone>>().HasValue);
return new Maybe<TNone>();
}
/// <summary>
/// Perform an operation f on the maybe, where f might or mightn't return a Maybe.Some{{T}}.
/// </summary>
/// <typeparam name = "TSome"></typeparam>
/// <param name = "maybe"></param>
/// <param name = "f">A function to continue applying to the monad.</param>
/// <returns>The same monad</returns>
[Pure]
public static Maybe<TSome> Do<TSome>(this Maybe<TSome> maybe, [Pure] Func<TSome, Maybe<TSome>> f)
{
Contract.Requires(maybe != null);
Contract.Requires(f != null);
Contract.Ensures(maybe.HasValue || !Contract.Result<Maybe<TSome>>().HasValue);
return maybe.HasValue ? f(maybe.Value) : maybe;
}
/// <summary>
/// Perform
/// </summary>
/// <typeparam name = "TSome"></typeparam>
/// <param name = "maybe"></param>
/// <param name = "f"></param>
/// <returns></returns>
[Pure]
public static Maybe<TSome> Do<TSome>(this Maybe<TSome> maybe, Func<TSome, TSome> f)
{
Contract.Requires(maybe != null);
Contract.Requires(f != null);
return maybe.HasValue ? Some(f(maybe.Value)) : maybe;
}
/// <summary>
/// </summary>
/// <typeparam name = "TSome"></typeparam>
/// <typeparam name = "TOther"></typeparam>
/// <param name = "maybe"></param>
/// <param name = "f"></param>
/// <returns></returns>
[Pure]
public static Maybe<TOther> Do<TSome, TOther>(this Maybe<TSome> maybe, Func<TSome, Maybe<TOther>> f)
{
return maybe.HasValue ? f(maybe.Value) : None<TOther>();
}
/// <summary>
/// </summary>
/// <typeparam name = "TSome"></typeparam>
/// <typeparam name = "TOther"></typeparam>
/// <param name = "maybe"></param>
/// <param name = "f"></param>
/// <returns></returns>
[Pure]
public static Maybe<TOther> Do<TSome, TOther>(this Maybe<TSome> maybe, Func<TSome, TOther> f)
{
return maybe.HasValue ? Some(f(maybe.Value)) : None<TOther>();
}
/// <summary>
/// Returns the maybe or the default value passed as a parameter.
/// </summary>
/// <typeparam name = "TSome"></typeparam>
/// <param name = "maybe"></param>
/// <param name = "default"></param>
/// <returns>The unwrapped value of the maybe or otherwise the default.</returns>
[Pure]
public static TSome OrDefault<TSome>(this Maybe<TSome> maybe, TSome @default)
{
return maybe.HasValue ? maybe.Value : @default;
}
/// <summary>
/// The <c>Ambient</c> operator, that selects the second option if the first is unavailable.
/// Because C# doesn't support lazy parameters, it's a func, i.e. a factory method for getting the
/// second option.
/// </summary>
/// <typeparam name = "TSome">The type of the maybe</typeparam>
/// <param name = "firstOption">The first maybe, which is returned if it has a value</param>
/// <param name = "secondOption">Evaluation if the first option fails.</param>
/// <returns>Maybe TSome.</returns>
[Pure]
public static Maybe<TSome> Amb<TSome>(this Maybe<TSome> firstOption, Func<Maybe<TSome>> secondOption)
{
return firstOption.HasValue ? firstOption : secondOption();
}
/// <summary>
/// If the maybe doesn't have a value, throws the exception yielded by the func.
/// </summary>
/// <typeparam name = "TSome"></typeparam>
/// <param name = "maybe"></param>
/// <param name = "ex"></param>
/// <returns>The item in the maybe.</returns>
[Pure]
public static TSome OrThrow<TSome>(this Maybe<TSome> maybe, Func<Exception> ex)
{
if (!maybe.HasValue) throw ex();
return maybe.Value;
}
/// <summary>
/// Type-system hack, in leiu of covariant bind (or rather Do in this monad),
/// changes type of the monad from TImpl to TAssignable, where TImpl : TAssignable.
/// The coercion is still statically typed and correct.
/// </summary>
/// <typeparam name = "TImpl">The type to convert FROM</typeparam>
/// <typeparam name = "TAssignable">The type to convert TO</typeparam>
/// <param name = "maybe">The object invoked upon</param>
/// <returns>A new type of the same kind of monad.</returns>
public static Maybe<TAssignable> Coerce<TImpl, TAssignable>(this Maybe<TImpl> maybe)
where TImpl : TAssignable
{
return maybe.HasValue ? new Maybe<TAssignable>(maybe.Value) : None<TAssignable>();
}
}
/// <summary>
/// An implementation of the maybe monad.
/// </summary>
/// <typeparam name = "T"></typeparam>
public sealed class Maybe<T>
{
[ContractPublicPropertyName("Value")] private readonly T _Value;
private readonly bool _HasValue;
internal Maybe()
{
Contract.Ensures(!HasValue);
_Value = default(T);
_HasValue = false;
}
internal Maybe(T value)
{
Contract.Ensures(HasValue);
_Value = value;
_HasValue = true;
Contract.Assume(_Value.Equals(value));
}
/// <summary>
/// Gets whether the maybe has a value.
/// </summary>
[Pure]
public bool HasValue
{
get
{
Contract.Ensures(Contract.Result<bool>() == _HasValue);
return _HasValue;
}
}
/// <summary>
/// Gets the value.
/// </summary>
/// <exception cref = "InvalidOperationException">If <see cref = "HasValue" /> is false.</exception>
public T Value
{
get
{
Contract.EnsuresOnThrow<InvalidOperationException>(!HasValue);
//Contract.Ensures(Contract.Result<T>().Equals(_Value)); //CCChecker's StackOverflowException here
if (!HasValue)
throw new InvalidOperationException("The maybe has no value.");
return _Value;
}
}
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates",
Justification = "The FromXXX and ToXXX methods are on the static Maybe class."),
Pure]
public static implicit operator Maybe<T>(T item)
{
Contract.Ensures(Contract.Result<Maybe<T>>() != null,
"The implicit conversion means that whatever is being implicitly convered, is wrapped in a maybe, no matter what its nullability or defaultness.");
if (typeof (T).IsValueType)
{
return Maybe.Some(item);
}
// ReSharper disable CompareNonConstrainedGenericWithNull
return item == null ? Maybe.None<T>() : Maybe.Some(item);
// ReSharper restore CompareNonConstrainedGenericWithNull
}
}
}
| |
namespace System.Web.UI
{
/// <summary>
/// HtmlBuilderTableTag
/// </summary>
public class HtmlBuilderTableTag
{
public class TableAttrib
{
public int? ColumnCount { get; set; }
public string NullTdBody { get; set; }
public int? RowPitch { get; set; }
public int? ColumnPitch { get; set; }
public string SelectedClass { get; set; }
public string SelectedStyle { get; set; }
public string AlternateClass { get; set; }
public string AlternateStyle { get; set; }
public TableTrCloseMethod? TrCloseMethod { get; set; }
public TableAlternateOrientation? AlternateOrientation { get; set; }
}
public enum TableStage
{
Undefined,
Colgroup,
TheadTfoot,
Tbody,
}
public enum TableTrCloseMethod
{
Undefined,
Td,
TdColspan
}
public enum TableAlternateOrientation
{
Column,
Row
}
public HtmlBuilderTableTag(HtmlBuilder b, TableAttrib attrib)
{
if (attrib != null)
{
int? columnCount = attrib.ColumnCount;
ColumnCount = (columnCount != null ? columnCount.Value : 0);
NullTdBody = attrib.NullTdBody;
int? rowPitch = attrib.RowPitch;
RowPitch = (rowPitch != null ? rowPitch.Value : 1);
int? columnPitch = attrib.ColumnPitch;
ColumnPitch = (columnPitch != null ? columnPitch.Value : 1);
SelectedClass = attrib.SelectedClass;
SelectedStyle = attrib.SelectedStyle;
AlternateClass = attrib.AlternateClass;
AlternateStyle = attrib.AlternateStyle;
TableTrCloseMethod? trCloseMethod = attrib.TrCloseMethod;
TrCloseMethod = (trCloseMethod != null ? trCloseMethod.Value : TableTrCloseMethod.Undefined);
TableAlternateOrientation? alternateOrientation = attrib.AlternateOrientation;
AlternateOrientation = (alternateOrientation != null ? alternateOrientation.Value : TableAlternateOrientation.Row);
}
else
{
ColumnCount = 0;
NullTdBody = string.Empty;
RowPitch = 1;
ColumnPitch = 1;
SelectedClass = string.Empty;
SelectedStyle = string.Empty;
AlternateClass = string.Empty;
AlternateStyle = string.Empty;
TrCloseMethod = TableTrCloseMethod.Undefined;
AlternateOrientation = TableAlternateOrientation.Row;
}
}
protected internal virtual void AddAttribute(HtmlBuilder b, HtmlTextWriterEx w, HtmlTag tag, Nattrib attrib)
{
bool isSelected;
string appendStyle;
bool isStyleDefined;
string appendClass;
bool isClassDefined;
if (attrib != null)
{
isSelected = attrib.Slice<bool>("selected");
appendStyle = attrib.Slice<string>("appendStyle");
isStyleDefined = attrib.Exists("style");
appendClass = attrib.Slice<string>("appendClass");
isClassDefined = attrib.Exists("class");
if (tag == HtmlTag.Tr)
IsTrHeader = attrib.Slice<bool>("header");
if (attrib.Count > 0)
b.AddAttribute(attrib, null);
}
else
{
isSelected = false;
appendStyle = string.Empty;
isStyleDefined = false;
appendClass = string.Empty;
isClassDefined = false;
}
// only apply remaining to td/th
if ((tag == HtmlTag.Td) || (tag == HtmlTag.Th))
{
// style
if (!isStyleDefined)
{
string effectiveStyle;
if ((isSelected) && (!string.IsNullOrEmpty(SelectedStyle)))
{
effectiveStyle = (appendStyle.Length == 0 ? SelectedStyle : SelectedStyle + " " + appendStyle);
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, effectiveStyle);
}
else if (!string.IsNullOrEmpty(AlternateStyle))
{
effectiveStyle = (appendStyle.Length == 0 ? AlternateStyle : AlternateStyle + " " + appendStyle);
switch (AlternateOrientation)
{
case TableAlternateOrientation.Column:
if ((((ColumnIndex - ColumnOffset - 1 + ColumnPitch) / ColumnPitch) % 2) == 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, effectiveStyle);
else if (appendStyle.Length > 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, appendStyle);
break;
case TableAlternateOrientation.Row:
if ((((RowIndex - RowOffset - 1 + RowPitch) / RowPitch) % 2) == 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, effectiveStyle);
else if (appendStyle.Length > 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, appendStyle);
break;
default:
throw new InvalidOperationException();
}
}
else if (appendStyle.Length > 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, appendStyle);
}
// class
if (!isClassDefined)
{
string effectiveClass;
if ((isSelected) && (!string.IsNullOrEmpty(SelectedClass)))
{
effectiveClass = (appendClass.Length == 0 ? SelectedClass : SelectedClass + " " + appendClass);
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, effectiveClass);
}
else if (!string.IsNullOrEmpty(AlternateClass))
{
effectiveClass = (appendClass.Length == 0 ? AlternateClass : AlternateClass + " " + appendClass);
switch (AlternateOrientation)
{
case TableAlternateOrientation.Column:
if ((((ColumnIndex - ColumnOffset - 1 + ColumnPitch) / ColumnPitch) % 2) == 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, effectiveClass);
else if (appendClass.Length > 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, appendClass);
break;
case TableAlternateOrientation.Row:
if ((((RowIndex - RowOffset - 1 + RowPitch) / RowPitch) % 2) == 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, effectiveClass);
else if (appendClass.Length > 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, appendClass);
break;
default:
throw new InvalidOperationException();
}
}
else if (appendClass.Length > 0)
w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, appendClass);
}
}
}
public string AlternateClass { get; set; }
public string AlternateStyle { get; set; }
public TableAlternateOrientation AlternateOrientation { get; set; }
public int ColumnCount { get; internal set; }
public int ColumnIndex { get; internal set; }
public int ColumnOffset { get; set; }
public int ColumnPitch { get; set; }
internal bool IsTrHeader { get; set; }
public string NullTdBody { get; set; }
public int RowIndex { get; internal set; }
public int RowOffset { get; set; }
public int RowPitch { get; set; }
public string SelectedClass { get; set; }
public string SelectedStyle { get; set; }
internal TableStage Stage { get; set; }
public object Tag { get; set; }
public TableTrCloseMethod TrCloseMethod { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using SFML;
using SFML.Graphics;
using SFML.Window;
using SFML.System;
namespace shader
{
/// <summary>Base class for effects</summary>
abstract class Effect : Drawable
{
protected Effect(string name)
{
myName = name;
}
public string Name
{
get {return myName;}
}
public void Update(float time, float x, float y)
{
if (Shader.IsAvailable)
OnUpdate(time, x, y);
}
public void Draw(RenderTarget target, RenderStates states)
{
if (Shader.IsAvailable)
{
OnDraw(target, states);
}
else
{
Text error = new Text("Shader not\nsupported", GetFont());
error.Position = new Vector2f(320, 200);
error.CharacterSize = 36;
target.Draw(error, states);
}
}
public static void SetFont(Font font)
{
ourFont = font;
}
protected abstract void OnUpdate(float time, float x, float y);
protected abstract void OnDraw(RenderTarget target, RenderStates states);
protected Font GetFont()
{
return ourFont;
}
private string myName;
private static Font ourFont = null;
}
/// <summary>"Pixelate" fragment shader</summary>
class Pixelate : Effect
{
public Pixelate() : base("pixelate")
{
// Load the texture and initialize the sprite
myTexture = new Texture("resources/background.jpg");
mySprite = new Sprite(myTexture);
// Load the shader
myShader = new Shader(null, "resources/pixelate.frag");
myShader.SetParameter("texture", Shader.CurrentTexture);
}
protected override void OnUpdate(float time, float x, float y)
{
myShader.SetParameter("pixel_threshold", (x + y) / 30);
}
protected override void OnDraw(RenderTarget target, RenderStates states)
{
states = new RenderStates(states);
states.Shader = myShader;
target.Draw(mySprite, states);
}
private Texture myTexture = null;
private Sprite mySprite = null;
private Shader myShader = null;
}
/// <summary>"Wave" vertex shader + "blur" fragment shader</summary>
class WaveBlur : Effect
{
public WaveBlur() : base("wave + blur")
{
// Create the text
myText = new Text();
myText.DisplayedString = "Praesent suscipit augue in velit pulvinar hendrerit varius purus aliquam.\n" +
"Mauris mi odio, bibendum quis fringilla a, laoreet vel orci. Proin vitae vulputate tortor.\n" +
"Praesent cursus ultrices justo, ut feugiat ante vehicula quis.\n" +
"Donec fringilla scelerisque mauris et viverra.\n" +
"Maecenas adipiscing ornare scelerisque. Nullam at libero elit.\n" +
"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n" +
"Nullam leo urna, tincidunt id semper eget, ultricies sed mi.\n" +
"Morbi mauris massa, commodo id dignissim vel, lobortis et elit.\n" +
"Fusce vel libero sed neque scelerisque venenatis.\n" +
"Integer mattis tincidunt quam vitae iaculis.\n" +
"Vivamus fringilla sem non velit venenatis fermentum.\n" +
"Vivamus varius tincidunt nisi id vehicula.\n" +
"Integer ullamcorper, enim vitae euismod rutrum, massa nisl semper ipsum,\n" +
"vestibulum sodales sem ante in massa.\n" +
"Vestibulum in augue non felis convallis viverra.\n" +
"Mauris ultricies dolor sed massa convallis sed aliquet augue fringilla.\n" +
"Duis erat eros, porta in accumsan in, blandit quis sem.\n" +
"In hac habitasse platea dictumst. Etiam fringilla est id odio dapibus sit amet semper dui laoreet.\n";
myText.Font = GetFont();
myText.CharacterSize = 22;
myText.Position = new Vector2f(30, 20);
// Load the shader
myShader = new Shader("resources/wave.vert", "resources/blur.frag");
}
protected override void OnUpdate(float time, float x, float y)
{
myShader.SetParameter("wave_phase", time);
myShader.SetParameter("wave_amplitude", x * 40, y * 40);
myShader.SetParameter("blur_radius", (x + y) * 0.008F);
}
protected override void OnDraw(RenderTarget target, RenderStates states)
{
states = new RenderStates(states);
states.Shader = myShader;
target.Draw(myText, states);
}
private Text myText = null;
private Shader myShader = null;
}
/// <summary>"Storm" vertex shader + "blink" fragment shader</summary>
class StormBlink : Effect
{
public StormBlink() : base("storm + blink")
{
Random random = new Random();
// Create the points
myPoints = new VertexArray(PrimitiveType.Points);
for (int i = 0; i < 40000; ++i)
{
float x = (float)random.Next(0, 800);
float y = (float)random.Next(0, 600);
byte r = (byte)random.Next(0, 255);
byte g = (byte)random.Next(0, 255);
byte b = (byte)random.Next(0, 255);
myPoints.Append(new Vertex(new Vector2f(x, y), new Color(r, g, b)));
}
// Load the shader
myShader = new Shader("resources/storm.vert", "resources/blink.frag");
}
protected override void OnUpdate(float time, float x, float y)
{
float radius = 200 + (float)Math.Cos(time) * 150;
myShader.SetParameter("storm_position", x * 800, y * 600);
myShader.SetParameter("storm_inner_radius", radius / 3);
myShader.SetParameter("storm_total_radius", radius);
myShader.SetParameter("blink_alpha", 0.5F + (float)Math.Cos(time * 3) * 0.25F);
}
protected override void OnDraw(RenderTarget target, RenderStates states)
{
states = new RenderStates(states);
states.Shader = myShader;
target.Draw(myPoints, states);
}
private VertexArray myPoints = null;
private Shader myShader = null;
}
/// <summary>"Edge" post-effect fragment shader</summary>
class Edge : Effect
{
public Edge() : base("edge post-effect")
{
// Create the off-screen surface
mySurface = new RenderTexture(800, 600);
mySurface.Smooth = true;
// Load the textures
myBackgroundTexture = new Texture("resources/sfml.png");
myBackgroundTexture.Smooth = true;
myEntityTexture = new Texture("resources/devices.png");
myEntityTexture.Smooth = true;
// Initialize the background sprite
myBackgroundSprite = new Sprite(myBackgroundTexture);
myBackgroundSprite.Position = new Vector2f(135, 100);
// Load the moving entities
myEntities = new Sprite[6];
for (int i = 0; i < myEntities.Length; ++i)
{
myEntities[i] = new Sprite(myEntityTexture, new IntRect(96 * i, 0, 96, 96));
}
// Load the shader
myShader = new Shader(null, "resources/edge.frag");
myShader.SetParameter("texture", Shader.CurrentTexture);
}
protected override void OnUpdate(float time, float x, float y)
{
myShader.SetParameter("edge_threshold", 1 - (x + y) / 2);
// Update the position of the moving entities
for (int i = 0; i < myEntities.Length; ++i)
{
float posX = (float)Math.Cos(0.25F * (time * i + (myEntities.Length - i))) * 300 + 350;
float posY = (float)Math.Sin(0.25F * (time * (myEntities.Length - i) + i)) * 200 + 250;
myEntities[i].Position = new Vector2f(posX, posY);
}
// Render the updated scene to the off-screen surface
mySurface.Clear(Color.White);
mySurface.Draw(myBackgroundSprite);
foreach (Sprite entity in myEntities)
mySurface.Draw(entity);
mySurface.Display();
}
protected override void OnDraw(RenderTarget target, RenderStates states)
{
states = new RenderStates(states);
states.Shader = myShader;
target.Draw(new Sprite(mySurface.Texture), states);
}
private RenderTexture mySurface = null;
private Texture myBackgroundTexture = null;
private Texture myEntityTexture = null;
private Sprite myBackgroundSprite = null;
Sprite[] myEntities = null;
private Shader myShader = null;
}
static class Program
{
private static Effect[] effects;
private static int current;
private static Text description;
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
// Create the main window
RenderWindow window = new RenderWindow(new VideoMode(800, 600), "SFML.Net Shader");
window.SetVerticalSyncEnabled(true);
// Setup event handlers
window.Closed += new EventHandler(OnClosed);
window.KeyPressed += new EventHandler<KeyEventArgs>(OnKeyPressed);
// Load the application font and pass it to the Effect class
Font font = new Font("resources/sansation.ttf");
Effect.SetFont(font);
// Create the effects
effects = new Effect[]
{
new Pixelate(),
new WaveBlur(),
new StormBlink(),
new Edge()
};
current = 0;
// Create the messages background
Texture textBackgroundTexture = new Texture("resources/text-background.png");
Sprite textBackground = new Sprite(textBackgroundTexture);
textBackground.Position = new Vector2f(0, 520);
textBackground.Color = new Color(255, 255, 255, 200);
// Create the description text
description = new Text("Current effect: " + effects[current].Name, font, 20);
description.Position = new Vector2f(10, 530);
description.Color = new Color(80, 80, 80);
// Create the instructions text
Text instructions = new Text("Press left and right arrows to change the current shader", font, 20);
instructions.Position = new Vector2f(280, 555);
instructions.Color = new Color(80, 80, 80);
// Start the game loop
Clock clock = new Clock();
while (window.IsOpen)
{
// Process events
window.DispatchEvents();
// Update the current example
float x = (float)Mouse.GetPosition(window).X / window.Size.X;
float y = (float)Mouse.GetPosition(window).Y / window.Size.Y;
effects[current].Update(clock.ElapsedTime.AsSeconds(), x, y);
// Clear the window
window.Clear(new Color(255, 128, 0));
// Draw the current example
window.Draw(effects[current]);
// Draw the text
window.Draw(textBackground);
window.Draw(instructions);
window.Draw(description);
// Finally, display the rendered frame on screen
window.Display();
}
}
/// <summary>
/// Function called when the window is closed
/// </summary>
static void OnClosed(object sender, EventArgs e)
{
RenderWindow window = (RenderWindow)sender;
window.Close();
}
/// <summary>
/// Function called when a key is pressed
/// </summary>
static void OnKeyPressed(object sender, KeyEventArgs e)
{
RenderWindow window = (RenderWindow)sender;
// Escape key : exit
if (e.Code == Keyboard.Key.Escape)
{
window.Close();
}
// Left arrow key: previous shader
if (e.Code == Keyboard.Key.Left)
{
if (current == 0)
current = effects.Length - 1;
else
current--;
description.DisplayedString = "Current effect: " + effects[current].Name;
}
// Right arrow key: next shader
if (e.Code == Keyboard.Key.Right)
{
if (current == effects.Length - 1)
current = 0;
else
current++;
description.DisplayedString = "Current effect: " + effects[current].Name;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Recommender.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedRecommenderClientTest
{
[xunit::FactAttribute]
public void GetInsightRequestObject()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetInsightRequest request = new GetInsightRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.GetInsight(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight response = client.GetInsight(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInsightRequestObjectAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetInsightRequest request = new GetInsightRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.GetInsightAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Insight>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight responseCallSettings = await client.GetInsightAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Insight responseCancellationToken = await client.GetInsightAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInsight()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetInsightRequest request = new GetInsightRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.GetInsight(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight response = client.GetInsight(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInsightAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetInsightRequest request = new GetInsightRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.GetInsightAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Insight>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight responseCallSettings = await client.GetInsightAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Insight responseCancellationToken = await client.GetInsightAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInsightResourceNames()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetInsightRequest request = new GetInsightRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.GetInsight(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight response = client.GetInsight(request.InsightName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInsightResourceNamesAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetInsightRequest request = new GetInsightRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.GetInsightAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Insight>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight responseCallSettings = await client.GetInsightAsync(request.InsightName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Insight responseCancellationToken = await client.GetInsightAsync(request.InsightName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkInsightAcceptedRequestObject()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkInsightAcceptedRequest request = new MarkInsightAcceptedRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.MarkInsightAccepted(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight response = client.MarkInsightAccepted(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkInsightAcceptedRequestObjectAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkInsightAcceptedRequest request = new MarkInsightAcceptedRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.MarkInsightAcceptedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Insight>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight responseCallSettings = await client.MarkInsightAcceptedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Insight responseCancellationToken = await client.MarkInsightAcceptedAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkInsightAccepted()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkInsightAcceptedRequest request = new MarkInsightAcceptedRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.MarkInsightAccepted(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight response = client.MarkInsightAccepted(request.Name, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkInsightAcceptedAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkInsightAcceptedRequest request = new MarkInsightAcceptedRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.MarkInsightAcceptedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Insight>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight responseCallSettings = await client.MarkInsightAcceptedAsync(request.Name, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Insight responseCancellationToken = await client.MarkInsightAcceptedAsync(request.Name, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkInsightAcceptedResourceNames()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkInsightAcceptedRequest request = new MarkInsightAcceptedRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.MarkInsightAccepted(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight response = client.MarkInsightAccepted(request.InsightName, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkInsightAcceptedResourceNamesAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkInsightAcceptedRequest request = new MarkInsightAcceptedRequest
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Insight expectedResponse = new Insight
{
InsightName = InsightName.FromProjectLocationInsightTypeInsight("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"),
Description = "description2cf9da67",
Content = new wkt::Struct(),
LastRefreshTime = new wkt::Timestamp(),
ObservationPeriod = new wkt::Duration(),
StateInfo = new InsightStateInfo(),
Category = Insight.Types.Category.Unspecified,
AssociatedRecommendations =
{
new Insight.Types.RecommendationReference(),
},
TargetResources =
{
"target_resources1e810c06",
},
InsightSubtype = "insight_subtype87faa4e7",
Etag = "etage8ad7218",
Severity = Insight.Types.Severity.High,
};
mockGrpcClient.Setup(x => x.MarkInsightAcceptedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Insight>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Insight responseCallSettings = await client.MarkInsightAcceptedAsync(request.InsightName, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Insight responseCancellationToken = await client.MarkInsightAcceptedAsync(request.InsightName, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRecommendationRequestObject()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetRecommendationRequest request = new GetRecommendationRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.GetRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.GetRecommendation(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRecommendationRequestObjectAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetRecommendationRequest request = new GetRecommendationRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.GetRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.GetRecommendationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.GetRecommendationAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRecommendation()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetRecommendationRequest request = new GetRecommendationRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.GetRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.GetRecommendation(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRecommendationAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetRecommendationRequest request = new GetRecommendationRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.GetRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.GetRecommendationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.GetRecommendationAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRecommendationResourceNames()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetRecommendationRequest request = new GetRecommendationRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.GetRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.GetRecommendation(request.RecommendationName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRecommendationResourceNamesAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
GetRecommendationRequest request = new GetRecommendationRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.GetRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.GetRecommendationAsync(request.RecommendationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.GetRecommendationAsync(request.RecommendationName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationClaimedRequestObject()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationClaimedRequest request = new MarkRecommendationClaimedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationClaimed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationClaimed(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationClaimedRequestObjectAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationClaimedRequest request = new MarkRecommendationClaimedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationClaimedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationClaimedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationClaimedAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationClaimed()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationClaimedRequest request = new MarkRecommendationClaimedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationClaimed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationClaimed(request.Name, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationClaimedAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationClaimedRequest request = new MarkRecommendationClaimedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationClaimedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationClaimedAsync(request.Name, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationClaimedAsync(request.Name, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationClaimedResourceNames()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationClaimedRequest request = new MarkRecommendationClaimedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationClaimed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationClaimed(request.RecommendationName, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationClaimedResourceNamesAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationClaimedRequest request = new MarkRecommendationClaimedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationClaimedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationClaimedAsync(request.RecommendationName, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationClaimedAsync(request.RecommendationName, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationSucceededRequestObject()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationSucceededRequest request = new MarkRecommendationSucceededRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationSucceeded(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationSucceeded(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationSucceededRequestObjectAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationSucceededRequest request = new MarkRecommendationSucceededRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationSucceededAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationSucceededAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationSucceededAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationSucceeded()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationSucceededRequest request = new MarkRecommendationSucceededRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationSucceeded(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationSucceeded(request.Name, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationSucceededAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationSucceededRequest request = new MarkRecommendationSucceededRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationSucceededAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationSucceededAsync(request.Name, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationSucceededAsync(request.Name, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationSucceededResourceNames()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationSucceededRequest request = new MarkRecommendationSucceededRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationSucceeded(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationSucceeded(request.RecommendationName, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationSucceededResourceNamesAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationSucceededRequest request = new MarkRecommendationSucceededRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationSucceededAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationSucceededAsync(request.RecommendationName, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationSucceededAsync(request.RecommendationName, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationFailedRequestObject()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationFailedRequest request = new MarkRecommendationFailedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationFailed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationFailed(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationFailedRequestObjectAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationFailedRequest request = new MarkRecommendationFailedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationFailedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationFailedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationFailedAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationFailed()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationFailedRequest request = new MarkRecommendationFailedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationFailed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationFailed(request.Name, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationFailedAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationFailedRequest request = new MarkRecommendationFailedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationFailedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationFailedAsync(request.Name, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationFailedAsync(request.Name, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void MarkRecommendationFailedResourceNames()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationFailedRequest request = new MarkRecommendationFailedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationFailed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation response = client.MarkRecommendationFailed(request.RecommendationName, request.StateMetadata, request.Etag);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task MarkRecommendationFailedResourceNamesAsync()
{
moq::Mock<Recommender.RecommenderClient> mockGrpcClient = new moq::Mock<Recommender.RecommenderClient>(moq::MockBehavior.Strict);
MarkRecommendationFailedRequest request = new MarkRecommendationFailedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
Recommendation expectedResponse = new Recommendation
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
Description = "description2cf9da67",
LastRefreshTime = new wkt::Timestamp(),
PrimaryImpact = new Impact(),
AdditionalImpact = { new Impact(), },
Content = new RecommendationContent(),
StateInfo = new RecommendationStateInfo(),
Etag = "etage8ad7218",
RecommenderSubtype = "recommender_subtype6a5b10f9",
AssociatedInsights =
{
new Recommendation.Types.InsightReference(),
},
Priority = Recommendation.Types.Priority.P1,
XorGroupId = "xor_group_id40c40796",
};
mockGrpcClient.Setup(x => x.MarkRecommendationFailedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
Recommendation responseCallSettings = await client.MarkRecommendationFailedAsync(request.RecommendationName, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Recommendation responseCancellationToken = await client.MarkRecommendationFailedAsync(request.RecommendationName, request.StateMetadata, request.Etag, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.Concurrent;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.IO.Pipelines.Text.Primitives;
using System.Text.Formatting;
using System.Buffers.Text;
namespace System.IO.Pipelines.Samples
{
public abstract class PipelineHttpClientHandler : HttpClientHandler
{
private ConcurrentDictionary<string, ConnectionState> _connectionPool = new ConcurrentDictionary<string, ConnectionState>();
public PipelineHttpClientHandler()
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var key = request.RequestUri.GetComponents(UriComponents.HostAndPort, UriFormat.SafeUnescaped);
var path = request.RequestUri.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped);
var state = _connectionPool.GetOrAdd(key, k => GetConnection(request));
var connection = await state.ConnectionTask;
var requestBuffer = connection.Output.Alloc();
var output = requestBuffer.AsOutput();
output.Append($"{request.Method} {path} HTTP/1.1", SymbolTable.InvariantUtf8);
WriteHeaders(request.Headers, ref output);
// End of the headers
output.Append("\r\n\r\n", SymbolTable.InvariantUtf8);
if (request.Method != HttpMethod.Get && request.Method != HttpMethod.Head)
{
WriteHeaders(request.Content.Headers, ref output);
await requestBuffer.FlushAsync();
// Copy the body to the input
var body = await request.Content.ReadAsStreamAsync();
await body.CopyToAsync(connection.Output);
}
else
{
await requestBuffer.FlushAsync();
}
var response = new HttpResponseMessage();
response.Content = new PipelineHttpContent(connection.Input);
await ProduceResponse(state, connection, response);
// Get off the libuv thread
await Task.Yield();
return response;
}
private static async Task ProduceResponse(ConnectionState state, IPipeConnection connection, HttpResponseMessage response)
{
// TODO: pipelining support!
while (true)
{
var result = await connection.Input.ReadAsync();
var responseBuffer = result.Buffer;
var consumed = responseBuffer.Start;
var needMoreData = true;
try
{
if (consumed == state.Consumed)
{
var oldBody = responseBuffer.Slice(0, state.PreviousContentLength);
if (oldBody.Length != state.PreviousContentLength)
{
// Not enough data
continue;
}
// The caller didn't read the body
responseBuffer = responseBuffer.Slice(state.PreviousContentLength);
consumed = responseBuffer.Start;
state.Consumed = default;
}
if (responseBuffer.IsEmpty && result.IsCompleted)
{
break;
}
ReadCursor delim;
ReadableBuffer responseLine;
if (!responseBuffer.TrySliceTo((byte)'\r', (byte)'\n', out responseLine, out delim))
{
continue;
}
responseBuffer = responseBuffer.Slice(delim).Slice(2);
ReadableBuffer httpVersion;
if (!responseLine.TrySliceTo((byte)' ', out httpVersion, out delim))
{
// Bad request
throw new InvalidOperationException();
}
consumed = responseBuffer.Start;
responseLine = responseLine.Slice(delim).Slice(1);
ReadableBuffer statusCode;
if (!responseLine.TrySliceTo((byte)' ', out statusCode, out delim))
{
// Bad request
throw new InvalidOperationException();
}
response.StatusCode = (HttpStatusCode)statusCode.GetUInt32();
responseLine = responseLine.Slice(delim).Slice(1);
ReadableBuffer remaining;
if (!responseLine.TrySliceTo((byte)' ', out remaining, out delim))
{
// Bad request
throw new InvalidOperationException();
}
while (!responseBuffer.IsEmpty)
{
if (responseBuffer.Length == 0)
{
break;
}
int ch = responseBuffer.First.Span[0];
if (ch == '\r')
{
// Check for final CRLF.
responseBuffer = responseBuffer.Slice(1);
if (responseBuffer.Length == 0)
{
break;
}
ch = responseBuffer.First.Span[0];
responseBuffer = responseBuffer.Slice(1);
if (ch == '\n')
{
consumed = responseBuffer.Start;
needMoreData = false;
break;
}
// Headers don't end in CRLF line.
throw new Exception();
}
var headerName = default(ReadableBuffer);
var headerValue = default(ReadableBuffer);
// End of the header
// \n
ReadableBuffer headerPair;
if (!responseBuffer.TrySliceTo((byte)'\n', out headerPair, out delim))
{
break;
}
responseBuffer = responseBuffer.Slice(delim).Slice(1);
// :
if (!headerPair.TrySliceTo((byte)':', out headerName, out delim))
{
throw new Exception();
}
headerName = headerName.TrimStart();
headerPair = headerPair.Slice(headerName.End).Slice(1);
// \r
if (!headerPair.TrySliceTo((byte)'\r', out headerValue, out delim))
{
// Bad request
throw new Exception();
}
headerValue = headerValue.TrimStart();
var hKey = headerName.GetAsciiString();
var hValue = headerValue.GetAsciiString();
if (!response.Content.Headers.TryAddWithoutValidation(hKey, hValue))
{
response.Headers.TryAddWithoutValidation(hKey, hValue);
}
// Move the consumed
consumed = responseBuffer.Start;
}
}
catch (Exception ex)
{
// Close the connection
connection.Output.Complete(ex);
break;
}
finally
{
connection.Input.Advance(consumed);
}
if (needMoreData)
{
continue;
}
// Only handle content length for now
var length = response.Content.Headers.ContentLength;
if (!length.HasValue)
{
throw new NotSupportedException();
}
checked
{
// BAD but it's a proof of concept ok?
state.PreviousContentLength = (int)length.Value;
((PipelineHttpContent)response.Content).ContentLength = (int)length;
state.Consumed = consumed;
}
break;
}
}
private static void WriteHeaders(HttpHeaders headers, ref WritableBufferOutput buffer)
{
foreach (var header in headers)
{
buffer.Append($"{header.Key}:{string.Join(",", header.Value)}\r\n", SymbolTable.InvariantUtf8);
}
}
private ConnectionState GetConnection(HttpRequestMessage request)
{
var state = new ConnectionState
{
ConnectionTask = ConnectAsync(request)
};
return state;
}
private async Task<IPipeConnection> ConnectAsync(HttpRequestMessage request)
{
var addresses = await Dns.GetHostAddressesAsync(request.RequestUri.Host);
var port = request.RequestUri.Port;
var address = addresses.First(a => a.AddressFamily == AddressFamily.InterNetwork);
return await ConnectAsync(new IPEndPoint(address, port));
}
protected abstract Task<IPipeConnection> ConnectAsync(IPEndPoint ipEndpoint);
protected override void Dispose(bool disposing)
{
foreach (var state in _connectionPool)
{
state.Value.ConnectionTask.GetAwaiter().GetResult().Output.Complete();
}
base.Dispose(disposing);
}
private class ConnectionState
{
public Task<IPipeConnection> ConnectionTask { get; set; }
public int PreviousContentLength { get; set; }
public ReadCursor Consumed { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractUInt32()
{
var test = new SimpleBinaryOpTest__SubtractUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractUInt32
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[ElementCount];
private static UInt32[] _data2 = new UInt32[ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32> _dataTable;
static SimpleBinaryOpTest__SubtractUInt32()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__SubtractUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32>(_data1, _data2, new UInt32[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Subtract(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Subtract(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Subtract(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__SubtractUInt32();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[ElementCount];
UInt32[] inArray2 = new UInt32[ElementCount];
UInt32[] outArray = new UInt32[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[ElementCount];
UInt32[] inArray2 = new UInt32[ElementCount];
UInt32[] outArray = new UInt32[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(left[0] - right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((uint)(left[i] - right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<UInt32>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using System.Collections.Generic;
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "ReadJournal_Request", IsSet = false)]
public class ReadJournal_Request : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(ReadJournal_Request));
private EntryToStartAfterSequenceType entryToStartAfter_;
private bool entryToStartAfter_present;
private ObjectName journalName_;
private ICollection<string> listOfVariables_;
private bool listOfVariables_present;
private RangeStartSpecificationChoiceType rangeStartSpecification_;
private bool rangeStartSpecification_present;
private RangeStopSpecificationChoiceType rangeStopSpecification_;
private bool rangeStopSpecification_present;
[ASN1Element(Name = "journalName", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public ObjectName JournalName
{
get
{
return journalName_;
}
set
{
journalName_ = value;
}
}
[ASN1Element(Name = "rangeStartSpecification", IsOptional = true, HasTag = true, Tag = 1, HasDefaultValue = false)]
public RangeStartSpecificationChoiceType RangeStartSpecification
{
get
{
return rangeStartSpecification_;
}
set
{
rangeStartSpecification_ = value;
rangeStartSpecification_present = true;
}
}
[ASN1Element(Name = "rangeStopSpecification", IsOptional = true, HasTag = true, Tag = 2, HasDefaultValue = false)]
public RangeStopSpecificationChoiceType RangeStopSpecification
{
get
{
return rangeStopSpecification_;
}
set
{
rangeStopSpecification_ = value;
rangeStopSpecification_present = true;
}
}
[ASN1String(Name = "",
StringType = UniversalTags.VisibleString, IsUCS = false)]
[ASN1SequenceOf(Name = "listOfVariables", IsSetOf = false)]
[ASN1Element(Name = "listOfVariables", IsOptional = true, HasTag = true, Tag = 4, HasDefaultValue = false)]
public ICollection<string> ListOfVariables
{
get
{
return listOfVariables_;
}
set
{
listOfVariables_ = value;
listOfVariables_present = true;
}
}
[ASN1Element(Name = "entryToStartAfter", IsOptional = true, HasTag = true, Tag = 5, HasDefaultValue = false)]
public EntryToStartAfterSequenceType EntryToStartAfter
{
get
{
return entryToStartAfter_;
}
set
{
entryToStartAfter_ = value;
entryToStartAfter_present = true;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isRangeStartSpecificationPresent()
{
return rangeStartSpecification_present;
}
public bool isRangeStopSpecificationPresent()
{
return rangeStopSpecification_present;
}
public bool isListOfVariablesPresent()
{
return listOfVariables_present;
}
public bool isEntryToStartAfterPresent()
{
return entryToStartAfter_present;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "entryToStartAfter", IsSet = false)]
public class EntryToStartAfterSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(EntryToStartAfterSequenceType));
private byte[] entrySpecification_;
private TimeOfDay timeSpecification_;
[ASN1Element(Name = "timeSpecification", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public TimeOfDay TimeSpecification
{
get
{
return timeSpecification_;
}
set
{
timeSpecification_ = value;
}
}
[ASN1OctetString(Name = "")]
[ASN1Element(Name = "entrySpecification", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public byte[] EntrySpecification
{
get
{
return entrySpecification_;
}
set
{
entrySpecification_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "rangeStartSpecification")]
public class RangeStartSpecificationChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(RangeStartSpecificationChoiceType));
private byte[] startingEntry_;
private bool startingEntry_selected;
private TimeOfDay startingTime_;
private bool startingTime_selected;
[ASN1Element(Name = "startingTime", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public TimeOfDay StartingTime
{
get
{
return startingTime_;
}
set
{
selectStartingTime(value);
}
}
[ASN1OctetString(Name = "")]
[ASN1Element(Name = "startingEntry", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public byte[] StartingEntry
{
get
{
return startingEntry_;
}
set
{
selectStartingEntry(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isStartingTimeSelected()
{
return startingTime_selected;
}
public void selectStartingTime(TimeOfDay val)
{
startingTime_ = val;
startingTime_selected = true;
startingEntry_selected = false;
}
public bool isStartingEntrySelected()
{
return startingEntry_selected;
}
public void selectStartingEntry(byte[] val)
{
startingEntry_ = val;
startingEntry_selected = true;
startingTime_selected = false;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "rangeStopSpecification")]
public class RangeStopSpecificationChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(RangeStopSpecificationChoiceType));
private TimeOfDay endingTime_;
private bool endingTime_selected;
private Integer32 numberOfEntries_;
private bool numberOfEntries_selected;
[ASN1Element(Name = "endingTime", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public TimeOfDay EndingTime
{
get
{
return endingTime_;
}
set
{
selectEndingTime(value);
}
}
[ASN1Element(Name = "numberOfEntries", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public Integer32 NumberOfEntries
{
get
{
return numberOfEntries_;
}
set
{
selectNumberOfEntries(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isEndingTimeSelected()
{
return endingTime_selected;
}
public void selectEndingTime(TimeOfDay val)
{
endingTime_ = val;
endingTime_selected = true;
numberOfEntries_selected = false;
}
public bool isNumberOfEntriesSelected()
{
return numberOfEntries_selected;
}
public void selectNumberOfEntries(Integer32 val)
{
numberOfEntries_ = val;
numberOfEntries_selected = true;
endingTime_selected = false;
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
namespace UltraSFV.Core
{
/// <summary>
/// Component wrapping access to the Browse For Folder common dialog box.
/// Call the ShowDialog() method to bring the dialog box up.
/// </summary>
public sealed class FolderBrowser : Component
{
private static readonly int MAX_PATH = 260;
// Root node of the tree view.
private FolderID startLocation = FolderID.Desktop;
// Browse info options.
private int publicOptions = (int)Win32API.Shell32.BffStyles.RestrictToFilesystem |
(int)Win32API.Shell32.BffStyles.RestrictToDomain;
private int privateOptions = (int)Win32API.Shell32.BffStyles.NewDialogStyle;
// Description text to show.
private string descriptionText = "Please select a folder below:";
// Folder chosen by the user.
private string directoryPath = String.Empty;
/// <summary>
/// Enum of CSIDLs identifying standard shell folders.
/// </summary>
public enum FolderID
{
Desktop = 0x0000,
Printers = 0x0004,
MyDocuments = 0x0005,
Favorites = 0x0006,
Recent = 0x0008,
SendTo = 0x0009,
StartMenu = 0x000b,
MyComputer = 0x0011,
NetworkNeighborhood = 0x0012,
Templates = 0x0015,
MyPictures = 0x0027,
NetAndDialUpConnections = 0x0031,
}
/// <summary>
/// Helper function that returns the IMalloc interface used by the shell.
/// </summary>
private static Win32API.IMalloc GetSHMalloc()
{
Win32API.IMalloc malloc;
Win32API.Shell32.SHGetMalloc(out malloc);
return malloc;
}
/// <summary>
/// Shows the folder browser dialog box.
/// </summary>
public DialogResult ShowDialog()
{
return ShowDialog(null);
}
/// <summary>
/// Shows the folder browser dialog box with the specified owner window.
/// </summary>
public DialogResult ShowDialog(IWin32Window owner)
{
IntPtr pidlRoot = IntPtr.Zero;
// Get/find an owner HWND for this dialog.
IntPtr hWndOwner;
if (owner != null)
{
hWndOwner = owner.Handle;
}
else
{
hWndOwner = Win32API.GetActiveWindow();
}
// Get the IDL for the specific startLocation.
Win32API.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int)startLocation, out pidlRoot);
if (pidlRoot == IntPtr.Zero)
{
return DialogResult.Cancel;
}
int mergedOptions = (int)publicOptions | (int)privateOptions;
if ((mergedOptions & (int)Win32API.Shell32.BffStyles.NewDialogStyle) != 0)
{
if (System.Threading.ApartmentState.MTA == Application.OleRequired())
mergedOptions = mergedOptions & (~(int)Win32API.Shell32.BffStyles.NewDialogStyle);
}
IntPtr pidlRet = IntPtr.Zero;
try
{
// Construct a BROWSEINFO.
Win32API.Shell32.BROWSEINFO bi = new Win32API.Shell32.BROWSEINFO();
IntPtr buffer = Marshal.AllocHGlobal(MAX_PATH);
bi.pidlRoot = pidlRoot;
bi.hwndOwner = hWndOwner;
bi.pszDisplayName = buffer;
bi.lpszTitle = descriptionText;
bi.ulFlags = mergedOptions;
// The rest of the fields are initialized to zero by the constructor.
// bi.lpfn = null; bi.lParam = IntPtr.Zero; bi.iImage = 0;
// Show the dialog.
pidlRet = Win32API.Shell32.SHBrowseForFolder(ref bi);
// Free the buffer you've allocated on the global heap.
Marshal.FreeHGlobal(buffer);
if (pidlRet == IntPtr.Zero)
{
// User clicked Cancel.
return DialogResult.Cancel;
}
// Then retrieve the path from the IDList.
StringBuilder sb = new StringBuilder(MAX_PATH);
if (0 == Win32API.Shell32.SHGetPathFromIDList(pidlRet, sb))
{
return DialogResult.Cancel;
}
// Convert to a string.
directoryPath = sb.ToString();
}
finally
{
Win32API.IMalloc malloc = GetSHMalloc();
malloc.Free(pidlRoot);
if (pidlRet != IntPtr.Zero)
{
malloc.Free(pidlRet);
}
}
return DialogResult.OK;
}
/// <summary>
/// Helper function used to set and reset bits in the publicOptions bitfield.
/// </summary>
private void SetOptionField(int mask, bool turnOn)
{
if (turnOn)
publicOptions |= mask;
else
publicOptions &= ~mask;
}
/// <summary>
/// Only return file system directories. If the user selects folders
/// that are not part of the file system, the OK button is unavailable.
/// </summary>
[Category("Navigation")]
[Description("Only return file system directories. If the user selects folders " +
"that are not part of the file system, the OK button is unavailable.")]
[DefaultValue(true)]
public bool OnlyFilesystem
{
get
{
return (publicOptions & (int)Win32API.Shell32.BffStyles.RestrictToFilesystem) != 0;
}
set
{
SetOptionField((int)Win32API.Shell32.BffStyles.RestrictToFilesystem, value);
}
}
/// <summary>
/// Location of the root folder from which to start browsing. Only the specified
/// folder and any folders beneath it in the namespace hierarchy appear
/// in the dialog box.
/// </summary>
[Category("Navigation")]
[Description("Location of the root folder from which to start browsing. Only the specified " +
"folder and any folders beneath it in the namespace hierarchy appear " +
"in the dialog box.")]
[DefaultValue(typeof(FolderID), "0")]
public FolderID StartLocation
{
get
{
return startLocation;
}
set
{
new UIPermission(UIPermissionWindow.AllWindows).Demand();
startLocation = value;
}
}
/// <summary>
/// Full path to the folder selected by the user.
/// </summary>
[Category("Navigation")]
[Description("Full path to the folder slected by the user.")]
public string DirectoryPath
{
get
{
return directoryPath;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.GrainReferences;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime
{
/// <summary>
/// Base class for various system services, such as grain directory, reminder service, etc.
/// Made public for GrainSerive to inherit from it.
/// Can be turned to internal after a refactoring that would remove the inheritance relation.
/// </summary>
public abstract class SystemTarget : ISystemTarget, ISystemTargetBase, IGrainContext, IGrainExtensionBinder
{
private readonly SystemTargetGrainId id;
private GrainReference selfReference;
private Message running;
private Dictionary<Type, object> _components = new Dictionary<Type, object>();
/// <summary>Silo address of the system target.</summary>
public SiloAddress Silo { get; }
internal ActivationAddress ActivationAddress { get; }
GrainId ISystemTargetBase.GrainId => id.GrainId;
internal ActivationId ActivationId { get; set; }
private ISiloRuntimeClient runtimeClient;
private readonly ILogger timerLogger;
internal ISiloRuntimeClient RuntimeClient
{
get
{
if (this.runtimeClient == null)
throw new OrleansException(
$"{nameof(this.RuntimeClient)} has not been set on {this.GetType()}. Most likely, this means that the system target was not registered.");
return this.runtimeClient;
}
set { this.runtimeClient = value; }
}
IGrainReferenceRuntime ISystemTargetBase.GrainReferenceRuntime => this.RuntimeClient.GrainReferenceRuntime;
public GrainReference GrainReference => selfReference ??= this.RuntimeClient.ServiceProvider.GetRequiredService<GrainReferenceActivator>().CreateReference(this.id.GrainId, default);
GrainId IGrainContext.GrainId => this.id.GrainId;
IAddressable IGrainContext.GrainInstance => this;
ActivationId IGrainContext.ActivationId => this.ActivationId;
ActivationAddress IGrainContext.Address => this.ActivationAddress;
/// <summary>Only needed to make Reflection happy.</summary>
protected SystemTarget()
{
}
internal SystemTarget(GrainType grainType, SiloAddress silo, ILoggerFactory loggerFactory)
: this(SystemTargetGrainId.Create(grainType, silo), silo, false, loggerFactory)
{
}
internal SystemTarget(GrainType grainType, SiloAddress silo, bool lowPriority, ILoggerFactory loggerFactory)
: this(SystemTargetGrainId.Create(grainType, silo), silo, lowPriority, loggerFactory)
{
}
internal SystemTarget(SystemTargetGrainId grainId, SiloAddress silo, bool lowPriority, ILoggerFactory loggerFactory)
{
this.id = grainId;
this.Silo = silo;
this.ActivationAddress = ActivationAddress.GetAddress(this.Silo, this.id.GrainId, this.ActivationId);
this.IsLowPriority = lowPriority;
this.ActivationId = ActivationId.GetDeterministic(grainId.GrainId);
this.timerLogger = loggerFactory.CreateLogger<GrainTimer>();
}
public bool IsLowPriority { get; }
internal WorkItemGroup WorkItemGroup { get; set; }
public IServiceProvider ActivationServices => this.RuntimeClient.ServiceProvider;
IGrainLifecycle IGrainContext.ObservableLifecycle => throw new NotImplementedException("IGrainContext.ObservableLifecycle is not implemented by SystemTarget");
public TComponent GetComponent<TComponent>()
{
TComponent result;
if (this is TComponent instanceResult)
{
result = instanceResult;
}
else if (_components.TryGetValue(typeof(TComponent), out var resultObj))
{
result = (TComponent)resultObj;
}
else
{
result = default;
}
return result;
}
public void SetComponent<TComponent>(TComponent instance)
{
if (this is TComponent)
{
throw new ArgumentException("Cannot override a component which is implemented by this grain");
}
if (instance == null)
{
_components?.Remove(typeof(TComponent));
return;
}
if (_components is null) _components = new Dictionary<Type, object>();
_components[typeof(TComponent)] = instance;
}
internal void HandleNewRequest(Message request)
{
running = request;
this.RuntimeClient.Invoke(this, request).Ignore();
}
internal void HandleResponse(Message response)
{
running = response;
this.RuntimeClient.ReceiveResponse(response);
}
/// <summary>
/// Register a timer to send regular callbacks to this grain.
/// This timer will keep the current grain from being deactivated.
/// </summary>
/// <param name="asyncCallback"></param>
/// <param name="state"></param>
/// <param name="dueTime"></param>
/// <param name="period"></param>
/// <param name="name"></param>
/// <returns></returns>
public IDisposable RegisterTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name = null)
{
var ctxt = RuntimeContext.CurrentGrainContext;
this.RuntimeClient.Scheduler.CheckSchedulingContextValidity(ctxt);
name = name ?? ctxt.GrainId + "Timer";
var timer = GrainTimer.FromTaskCallback(this.RuntimeClient.Scheduler, this.timerLogger, asyncCallback, state, dueTime, period, name);
timer.Start();
return timer;
}
/// <summary>Override of object.ToString()</summary>
public override string ToString()
{
return String.Format("[{0}SystemTarget: {1}{2}{3}]",
IsLowPriority ? "LowPriority" : string.Empty,
Silo,
this.id,
this.ActivationId);
}
/// <summary>Adds details about message currently being processed</summary>
internal string ToDetailedString()
{
return String.Format("{0} CurrentlyExecuting={1}", ToString(), running != null ? running.ToString() : "null");
}
bool IEquatable<IGrainContext>.Equals(IGrainContext other) => ReferenceEquals(this, other);
public (TExtension, TExtensionInterface) GetOrSetExtension<TExtension, TExtensionInterface>(Func<TExtension> newExtensionFunc)
where TExtension : TExtensionInterface
where TExtensionInterface : IGrainExtension
{
TExtension implementation;
if (this.GetComponent<TExtensionInterface>() is object existing)
{
if (existing is TExtension typedResult)
{
implementation = typedResult;
}
else
{
throw new InvalidCastException($"Cannot cast existing extension of type {existing.GetType()} to target type {typeof(TExtension)}");
}
}
else
{
implementation = newExtensionFunc();
this.SetComponent<TExtensionInterface>(implementation);
}
var reference = this.GrainReference.Cast<TExtensionInterface>();
return (implementation, reference);
}
public TExtensionInterface GetExtension<TExtensionInterface>()
where TExtensionInterface : IGrainExtension
{
if (this.GetComponent<TExtensionInterface>() is TExtensionInterface result)
{
return result;
}
var implementation = this.ActivationServices.GetServiceByKey<Type, IGrainExtension>(typeof(TExtensionInterface));
if (!(implementation is TExtensionInterface typedResult))
{
throw new GrainExtensionNotInstalledException($"No extension of type {typeof(TExtensionInterface)} is installed on this instance and no implementations are registered for automated install");
}
this.SetComponent<TExtensionInterface>(typedResult);
return typedResult;
}
}
}
| |
/*
* @(#) InkML2ISF.cs 1.0 06-08-2007 author: Manoj Prasad
*************************************************************************
* Copyright (c) 2008 Hewlett-Packard Development Company, L.P.
* 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.
**************************************************************************/
/************************************************************************
* SVN MACROS
*
* $Revision: 244 $
* $Author: mnab $
* $LastChangedDate: 2008-07-04 13:57:50 +0530 (Fri, 04 Jul 2008) $
************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Ink;
using InkML;
namespace InkMLConverters
{
/// <summary>
///
/// </summary>
public class InkML2ISF
{
#region Fields
private InkInterpreter inkmlInterpreter;
private Dictionary<string,Guid> mapChannelGuid;
private Microsoft.Ink.Ink ISFink;
/// <summary>
/// Gets the Microsoft.Ink object
/// </summary>
public Microsoft.Ink.Ink ISFInk
{
get { return ISFink; }
}
#endregion Fields
#region Constructor
public InkML2ISF()
{
try
{
ReInitialize();
Initialize();
}
catch(FileNotFoundException)
{
}
}
/// <summary>
/// Function to re initialise the object
/// </summary>
public void ReInitialize()
{
inkmlInterpreter = new InkInterpreter();
ISFink = new Microsoft.Ink.Ink();
}
/// <summary>
/// Function to Initialise the Map between various channels in InkML to Guid if channels supported by the ISF
/// </summary>
private void Initialize()
{
mapChannelGuid = new Dictionary<string,Guid>();
mapChannelGuid.Add("X",PacketProperty.X);
mapChannelGuid.Add("Y",PacketProperty.Y);
mapChannelGuid.Add("Z",PacketProperty.Z);
mapChannelGuid.Add("T",PacketProperty.TimerTick);
mapChannelGuid.Add("F",PacketProperty.NormalPressure);
mapChannelGuid.Add("OTX",PacketProperty.XTiltOrientation);
mapChannelGuid.Add("OTY",PacketProperty.YTiltOrientation);
mapChannelGuid.Add("OR",PacketProperty.RollRotation);
mapChannelGuid.Add("OA",PacketProperty.YawRotation);
mapChannelGuid.Add("OE",PacketProperty.PitchRotation);
mapChannelGuid.Add("E",PacketProperty.AltitudeOrientation);
mapChannelGuid.Add("A",PacketProperty.AzimuthOrientation);
mapChannelGuid.Add("B",PacketProperty.ButtonPressure);
mapChannelGuid.Add("PacketStatus",PacketProperty.PacketStatus);
mapChannelGuid.Add("S.NO",PacketProperty.SerialNumber);
mapChannelGuid.Add("TP",PacketProperty.TangentPressure);
mapChannelGuid.Add("TO",PacketProperty.TwistOrientation);
}
#endregion Constructor
#region Converter and Save Functions
/// <summary>
/// Function to convert Input InkML File to MS.Ink Object.
/// This function can be used to render the InkML file with TabletPC SDK
/// </summary>
/// <param name="inputFileName">InkML file to be converted to the MS.ink Object</param>
public void ConvertToInk(string inputFileName)
{
try
{
inkmlInterpreter.LoadInkFile(inputFileName);
ISFink = new Microsoft.Ink.Ink();
Conversion(inkmlInterpreter.Ink);
}
catch (Exception)
{
}
}
/// <summary>
/// Function to convert InkML file to ISF file.
/// </summary>
/// <param name="inputFileName">InkML File to be Converted To ISF</param>
/// <param name="outputFileName">Output ISF file</param>
public void ConvertToISF(string inputFileName, string outputFileName)
{
try
{
inkmlInterpreter.LoadInkFile(inputFileName);
ConvertToISF(inkmlInterpreter.Ink,outputFileName);
}
catch (Exception)
{
}
}
public string ConvertToISF(string inputFileName)
{
try
{
inkmlInterpreter.LoadInkFile(inputFileName);
return ConvertToISF(inkmlInterpreter.Ink);
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// Function to Convert the InkML.Ink object to ISF file.
/// Calls the Conversion function to the MS.Ink Object.
/// Then Saves the MS.Ink object to the ISF file.
/// </summary>
/// <param name="inputInk">InkML Ink Object to be converted to ISF</param>
/// <param name="outputFileName">output ISF FILE</param>
public void ConvertToISF(InkML.Ink inputInk, string outputFileName)
{
try
{
ISFink = new Microsoft.Ink.Ink();
Conversion(inputInk);
SaveISF(outputFileName);
}
catch (Exception)
{
}
}
/// <summary>
/// Function to Convert the InkML.Ink object to ISF file.
/// Calls the Conversion function to the MS.Ink Object.
/// Then Saves the MS.Ink object to the ISF file.
/// </summary>
/// <param name="inputInk">InkML Ink Object to be converted to ISF</param>
/// <param name="outputFileName">output ISF FILE</param>
public string ConvertToISF(InkML.Ink inputInk)
{
try
{
ISFink = new Microsoft.Ink.Ink();
Conversion(inputInk);
return Convert.ToBase64String(ISFink.Save(PersistenceFormat.InkSerializedFormat));
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// Function to save the MS.Ink object to ISF file.
/// </summary>
/// <param name="outputFileName"></param>
private void SaveISF(string outputFileName)
{
FileStream fsTemp = new FileStream(outputFileName, FileMode.Create);
fsTemp.Write(ISFink.Save(PersistenceFormat.InkSerializedFormat), 0, ISFink.Save(PersistenceFormat.InkSerializedFormat).Length);
fsTemp.Close();
}
#endregion Load and Save Functions
#region Convert/Add Functions
/// <summary>
/// Main Conversion Function to convert InkML Ink object to Microsoft.Ink object.
/// Converts Trace to Stroke Objects and adds it to MS.Ink object
/// Converts Annotation/AnnotationXML to MS.Ink.ExtendedProperties.
/// TODO : Converting TraceGroup to the Strokes object.
/// Add the Recognition Result from the Annotation/ AnnotationXML element in the TraceGroup
/// </summary>
/// <param name="inkmlinput">InkML Ink object to be converted to the MS.Ink object</param>
private void Conversion(InkML.Ink inkmlinput)
{
List<InkElement>.Enumerator inkmlEnumerator = inkmlinput.GetInkElements();
while (inkmlEnumerator.MoveNext())
{
InkElement inkmlElement = inkmlEnumerator.Current;
if (inkmlElement.TagName.Equals("trace"))
{
AddStroke(inkmlElement as Trace);
}
if (inkmlElement.TagName.Equals("traceGroup"))
{
//TODO :Add a function to convert to convert TraceGroup to Strokes object
// Add the Strokes object to the ISFink object.
// Add the Strokes object to the ISFink.customstrokes.
}
if(inkmlElement.TagName.Equals("annotation"))
{
AddExtendedProperty(inkmlElement as Annotation);
}
if(inkmlElement.TagName.Equals("annotationXML"))
{
AddExtendedProperty(inkmlElement as AnnotationXML);
}
}
}
/// <summary>
/// Function to Add a Stroke corresponding to a Trace in the InkML.
/// This function adds the TraceData of the TraceObject to the Stroke object.
/// Calls the GetDrawingAttributes function to convert the AssociatedBrush Element
/// to the drawingAttributes and assigns it to the drawing attribute of the stroke. ///
/// </summary>
/// <param name="inkmlTrace"></param>
private void AddStroke(Trace inkmlTrace)
{
System.Drawing.Point[] strokePoints = new System.Drawing.Point[inkmlTrace.GetTraceData("X").Count];
List<string> channels = inkmlTrace.GetChannelNames();
int x, y;
TraceFormat traceFormat;
if (inkmlTrace.AssociatedContext.InksourceElement.TraceFormat != null)
traceFormat = inkmlTrace.AssociatedContext.InksourceElement.TraceFormat;
else
traceFormat = inkmlTrace.AssociatedContext.TraceFormatElement;
string X_unit = traceFormat.GetChannel("X").Units;
string Y_unit = traceFormat.GetChannel("Y").Units;
for (int i = 0; i < inkmlTrace.GetTraceData("X").Count; i++)
{
double xTransformFactor = 1.00, yTransformFactor = 1.00;
// convert the trace data to the device ("dev") unit which is -
// HIMETRIC unit for TabletPC SDK and hence for the ISF format.
// 1 HIMETRIC = 0.01 mm = 25.4/0.01 inches.
// Finaly the data is divided by 96 PPI which is the typical screen resolution,
if (X_unit.Equals("inch"))
xTransformFactor = (25.4 / 0.01);
else if (X_unit.Equals("dev"))
xTransformFactor = 1.00;
else if (X_unit == "cm")
xTransformFactor = (10.0 / 0.01);
x = Convert.ToInt32(Convert.ToDouble(inkmlTrace.GetTraceData("X")[i]) * xTransformFactor);
if (Y_unit.Equals("inch"))
yTransformFactor = (25.4 / 0.01);
else if (Y_unit.Equals("dev"))
yTransformFactor = 1.00;
else if (Y_unit == "cm")
yTransformFactor = (10 / .01);
y = Convert.ToInt32(Convert.ToDouble(inkmlTrace.GetTraceData("Y")[i]) * yTransformFactor);
strokePoints[i] = new System.Drawing.Point(x, y);
}
Microsoft.Ink.Stroke isfStroke = ISFink.CreateStroke(strokePoints);
foreach (string channel in channels)
{
if (!channel.Equals("X") && !channel.Equals("Y"))
{
var ret = inkmlTrace.GetTraceData(channel);
int[] array = (int[])ret.ToArray(typeof(int));
try
{
isfStroke.SetPacketValuesByProperty(mapChannelGuid[channel], 0, array.Length, array);
}
catch (Exception e) { Console.WriteLine("Could not set pressure"); }
}
}
if (inkmlTrace.AssociatedBrush != null)
{
isfStroke.DrawingAttributes = GetDrawingAttributes(inkmlTrace.AssociatedBrush);
}
else
{
isfStroke.DrawingAttributes = new DrawingAttributes();
}
ISFink.Strokes.Add(isfStroke);
}
/// <summary>
/// Function to convert InkML AnnotationXML to ExtendedProperty element in MicroSoft.Ink
/// This function adds the XmlElement corresponding to the AnnotationXML to the
/// ExtendedProperties element of the Ink Object.
/// </summary>
/// <param name="inkmlAnnotationXML">AnnotationXML Element to be added to the Ink Object</param>
private void AddExtendedProperty(AnnotationXML inkmlAnnotationXML)
{
Guid temp;
if (!inkmlAnnotationXML.GetAttribute("id").Equals(""))
{
temp = new Guid(inkmlAnnotationXML.GetAttribute("id"));
ISFink.ExtendedProperties.Add(temp, inkmlAnnotationXML.AnnotationElement);
}
}
/// <summary>
/// Function to convert InkML Annotation to ExtendedProperty element in MicroSoft.Ink
/// This function adds the XmlElement corresponding to the Annotation to the
/// ExtendedProperties element of the Ink Object.
///
/// </summary>
/// <param name="inkmlAnnotation">Annotation Element to be added to the Ink Object</param>
private void AddExtendedProperty(Annotation inkmlAnnotation)
{
Guid temp;
if (!inkmlAnnotation.GetAttribute("id").Equals(""))
{
temp = new Guid(inkmlAnnotation.GetAttribute("id"));
ISFink.ExtendedProperties.Add(temp, inkmlAnnotation.AnnotationElement);
}
}
/// <summary>
/// Function to convert the Brush element of InkML to DrawingAttributes of a stroke.
/// * Maps the Elements Value to the various Drawing Attributes.
/// * Fixed elements of the ISF are supported.Need to extend it for the
/// Extended property of the Drawing Attribute.
/// - Run a Loop to know all the elements and attribute in the Annotation/AnnotationXML
/// - Add each attribute and element to the Extended Attribute as the Data object with
/// a unique Guid.
/// </summary>
/// <param name="inkmlBrush">InkML Brush Element to be converted to the DrawingAttribute</param>
/// <returns>Drawing Attributes Object</returns>
private DrawingAttributes GetDrawingAttributes(Brush inkmlBrush)
{
DrawingAttributes result = new DrawingAttributes();
AnnotationXML bAnnotation = inkmlBrush.BrushAnnotationXML;
if (bAnnotation == null)
return result;
if (bAnnotation.GetProperty("color")!=null)
{
result.Color = System.Drawing.Color.FromName(bAnnotation.GetProperty("color"));
}
if (bAnnotation.GetProperty("width") != null)
{
result.Width = System.Convert.ToInt32(bAnnotation.GetProperty("width"));
}
if (bAnnotation.GetProperty("transparency") != null)
{
result.Transparency = System.Convert.ToByte(bAnnotation.GetProperty("transparency"));
}
if (bAnnotation.GetProperty("antialiased") != null)
{
result.AntiAliased = System.Convert.ToBoolean(bAnnotation.GetProperty("antialiased"));
}
if (bAnnotation.GetProperty("fittocurve") != null)
{
result.FitToCurve = System.Convert.ToBoolean(bAnnotation.GetProperty("fittocurve"));
}
if (bAnnotation.GetProperty("height") != null)
{
result.Height = System.Convert.ToInt32(bAnnotation.GetProperty("height"));
}
if (bAnnotation.GetProperty("ignorePressure") != null)
{
result.IgnorePressure = System.Convert.ToBoolean(bAnnotation.GetProperty("ignorePressure"));
}
if (bAnnotation.GetProperty("pentip") != null)
{
result.PenTip = (PenTip)System.Enum.Parse(typeof(PenTip), bAnnotation.GetProperty("pentip"));
}
return result;
}
#endregion Convert/Add Functions
}
}
| |
/*
* 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.Binary
{
using System;
using System.Collections;
/// <summary>
/// binary object builder. Provides ability to build binary objects dynamically
/// without having class definitions.
/// <para />
/// Note that type ID is required in order to build binary object. Usually it is
/// enough to provide a simple type name and Ignite will generate the type ID
/// automatically.
/// </summary>
public interface IBinaryObjectBuilder
{
/// <summary>
/// Get object field value. If value is another binary object, then
/// builder for this object will be returned. If value is a container
/// for other objects (array, ICollection, IDictionary), then container
/// will be returned with primitive types in deserialized form and
/// binary objects as builders. Any change in builder or collection
/// returned through this method will be reflected in the resulting
/// binary object after build.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <returns>Field value.</returns>
T GetField<T>(string fieldName);
/// <summary>
/// Set object field value. Value can be of any type including other
/// <see cref="IBinaryObject"/> and other builders.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Field value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetField<T>(string fieldName, T val);
/// <summary>
/// Remove object field.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder RemoveField(string fieldName);
/// <summary>
/// Set explicit hash code. If builder creating object from scratch,
/// then hash code initially set to 0. If builder is created from
/// exising binary object, then hash code of that object is used
/// as initial value.
/// </summary>
/// <param name="hashCode">Hash code.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetHashCode(int hashCode);
/// <summary>
/// Build the object.
/// </summary>
/// <returns>Resulting binary object.</returns>
IBinaryObject Build();
/// <summary>
/// Sets the array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetArrayField<T>(string fieldName, T[] val);
/// <summary>
/// Sets the boolean field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetBooleanField(string fieldName, bool val);
/// <summary>
/// Sets the boolean array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetBooleanArrayField(string fieldName, bool[] val);
/// <summary>
/// Sets the byte field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetByteField(string fieldName, byte val);
/// <summary>
/// Sets the byte array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetByteArrayField(string fieldName, byte[] val);
/// <summary>
/// Sets the char field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetCharField(string fieldName, char val);
/// <summary>
/// Sets the char array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetCharArrayField(string fieldName, char[] val);
/// <summary>
/// Sets the collection field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetCollectionField(string fieldName, ICollection val);
/// <summary>
/// Sets the decimal field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetDecimalField(string fieldName, decimal? val);
/// <summary>
/// Sets the decimal array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetDecimalArrayField(string fieldName, decimal?[] val);
/// <summary>
/// Sets the dictionary field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetDictionaryField(string fieldName, IDictionary val);
/// <summary>
/// Sets the double field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetDoubleField(string fieldName, double val);
/// <summary>
/// Sets the double array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetDoubleArrayField(string fieldName, double[] val);
/// <summary>
/// Sets the enum field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetEnumField<T>(string fieldName, T val);
/// <summary>
/// Sets the enum array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetEnumArrayField<T>(string fieldName, T[] val);
/// <summary>
/// Sets the float field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetFloatField(string fieldName, float val);
/// <summary>
/// Sets the float array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetFloatArrayField(string fieldName, float[] val);
/// <summary>
/// Sets the guid field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetGuidField(string fieldName, Guid? val);
/// <summary>
/// Sets the guid array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetGuidArrayField(string fieldName, Guid?[] val);
/// <summary>
/// Sets the int field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetIntField(string fieldName, int val);
/// <summary>
/// Sets the int array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetIntArrayField(string fieldName, int[] val);
/// <summary>
/// Sets the long field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetLongField(string fieldName, long val);
/// <summary>
/// Sets the long array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetLongArrayField(string fieldName, long[] val);
/// <summary>
/// Sets the short field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetShortField(string fieldName, short val);
/// <summary>
/// Sets the short array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetShortArrayField(string fieldName, short[] val);
/// <summary>
/// Sets the string field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetStringField(string fieldName, string val);
/// <summary>
/// Sets the string array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetStringArrayField(string fieldName, string[] val);
/// <summary>
/// Sets the timestamp field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetTimestampField(string fieldName, DateTime? val);
/// <summary>
/// Sets the timestamp array field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="val">The value.</param>
/// <returns>Current builder instance.</returns>
IBinaryObjectBuilder SetTimestampArrayField(string fieldName, DateTime?[] val);
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web.UI;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestUtilities;
using NUnit.Tests.Assemblies;
namespace NUnit.Framework.Api
{
// Functional tests of the FrameworkController and all subordinate classes
public class FrameworkControllerTests
{
private const string MOCK_ASSEMBLY_FILE = "mock-assembly.dll";
private const string BAD_FILE = "mock-assembly.pdb";
private const string MISSING_FILE = "junk.dll";
private const string MISSING_NAME = "junk";
private const string EMPTY_FILTER = "<filter/>";
private const string FIXTURE_CAT_FILTER = "<filter><cat>FixtureCategory</cat></filter>";
private static readonly string MOCK_ASSEMBLY_NAME = typeof(MockAssembly).GetTypeInfo().Assembly.FullName;
private static readonly string EXPECTED_NAME = MOCK_ASSEMBLY_FILE;
private static readonly string MOCK_ASSEMBLY_PATH = Path.Combine(TestContext.CurrentContext.TestDirectory, MOCK_ASSEMBLY_FILE);
private readonly IDictionary _settings = new Dictionary<string, object>();
private FrameworkController _controller;
private ICallbackEventHandler _handler;
public static IEnumerable EmptyFilters
{
get
{
yield return new TestCaseData(null);
yield return new TestCaseData("");
yield return new TestCaseData(EMPTY_FILTER);
}
}
public class FixtureCategoryTester
{
[Category("FixtureCategory")]
[Test]
public void TestInFixtureCategory()
{
}
[Test]
public void TestOutOfFixtureCategory()
{
}
}
[SetUp]
public void CreateController()
{
_controller = new FrameworkController(MOCK_ASSEMBLY_PATH, "ID", _settings);
_handler = new CallbackEventHandler();
}
#region SettingsElement Tests
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_MixedSettings_CreatesCorrectSubNodes(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["key1"] = "value1",
["key2"] = new Dictionary<string, object> { ["innerkey"] = value }
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
#if PARALLEL
// in parallel, an additional node is added with number of test workers
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(3));
#else
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(2));
#endif
Assert.That(inserted.ChildNodes[0].Attributes["name"], Is.EqualTo("key1"));
Assert.That(inserted.ChildNodes[0].Attributes["value"], Is.EqualTo("value1"));
var innerNode = inserted.ChildNodes[1].FirstChild;
Assert.That(innerNode.Attributes["key"], Is.EqualTo("innerkey"));
Assert.That(innerNode.Attributes["value"], Is.EqualTo(value));
}
[Test]
public void InsertSettingsElement_SettingIsValue_CreatesASettingElementPerKey()
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["key1"] = "value1",
["key2"] = "value2"
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
#if PARALLEL
// in parallel, an additional node is added with number of test workers
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(3));
#else
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(2));
#endif
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsValue_SetsKeyAndValueAsAttributes(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["key1"] = "value1",
["key2"] = value
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
Assert.That(inserted.ChildNodes[0].Attributes["name"], Is.EqualTo("key1"));
Assert.That(inserted.ChildNodes[0].Attributes["value"], Is.EqualTo("value1"));
Assert.That(inserted.ChildNodes[1].Attributes["name"], Is.EqualTo("key2"));
Assert.That(inserted.ChildNodes[1].Attributes["value"], Is.EqualTo(value));
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsDictionary_CreatesEntriesForDictionaryElements(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["outerkey"] = new Dictionary<string, object> { { "key1", "value1" }, { "key2", value } }
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
var settingNode = inserted.FirstChild;
Assert.That(settingNode.ChildNodes.Count, Is.EqualTo(2));
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsDictionary_CreatesValueAttributeForDictionaryElements(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["outerkey"] = new Dictionary<string, object> { { "key1", "value1" }, { "key2", value } }
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
var settingNode = inserted.FirstChild;
Assert.That(settingNode.ChildNodes.Count, Is.EqualTo(2));
Assert.That(settingNode.Attributes["value"], Is.EqualTo($"[key1, value1], [key2, {value}]"));
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsDictionary_CreatesEntriesWithKeysAndValuesFromDictionary(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>();
testSettings.Add("outerkey", new Dictionary<string, object> { { "key1", "value1" }, { "key2", value } });
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
var settingNode = inserted.FirstChild;
var key1Node = settingNode.ChildNodes[0];
Assert.That(key1Node.Attributes["key"], Is.EqualTo("key1"));
Assert.That(key1Node.Attributes["value"], Is.EqualTo("value1"));
var key2Node = settingNode.ChildNodes[1];
Assert.That(key2Node.Attributes["key"], Is.EqualTo("key2"));
Assert.That(key2Node.Attributes["value"], Is.EqualTo(value));
}
[Test]
public void InsertSettingsElement_SettingIsDictionaryHasNull_CreatesEntriesWithKeysAndValuesFromDictionary()
{
string value = "test";
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>();
testSettings.Add("outerkey", new Dictionary<string, object> { { "key1", null }, { "key2", value } });
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
var settingNode = inserted.FirstChild;
var key1Node = settingNode.ChildNodes[0];
Assert.That(key1Node.Attributes["key"], Is.EqualTo("key1"));
Assert.That(key1Node.Attributes["value"], Is.EqualTo(string.Empty));
var key2Node = settingNode.ChildNodes[1];
Assert.That(key2Node.Attributes["key"], Is.EqualTo("key2"));
Assert.That(key2Node.Attributes["value"], Is.EqualTo(value));
}
public static IEnumerable SettingsData()
{
yield return new TestCaseData("value");
yield return new TestCaseData("");
yield return new TestCaseData("<value>");
yield return new TestCaseData("\"value\"");
yield return new TestCaseData("'value'");
yield return new TestCaseData("value1;value2");
}
#endregion
#region Construction Test
[Test]
public void ConstructController()
{
Assert.That(_controller.Builder, Is.TypeOf<DefaultTestAssemblyBuilder>());
Assert.That(_controller.Runner, Is.TypeOf<NUnitTestAssemblyRunner>());
Assert.That(_controller.AssemblyNameOrPath, Is.EqualTo(MOCK_ASSEMBLY_PATH));
Assert.That(_controller.Settings, Is.SameAs(_settings));
}
#endregion
#region LoadTestsAction
[Test]
public void LoadTestsAction_GoodFile_ReturnsRunnableSuite()
{
new FrameworkController.LoadTestsAction(_controller, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void LoadTestsAction_Assembly_ReturnsRunnableSuite()
{
_controller = new FrameworkController(typeof(MockAssembly).GetTypeInfo().Assembly, "ID", _settings);
new FrameworkController.LoadTestsAction(_controller, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME).IgnoreCase);
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void LoadTestsAction_FileNotFound_ReturnsNonRunnableSuite()
{
new FrameworkController.LoadTestsAction(new FrameworkController(MISSING_FILE, "ID", _settings), _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
#if NETCOREAPP1_1
Assert.That(GetSkipReason(result), Contains.Substring("The system cannot find the file specified."));
#else
Assert.That(GetSkipReason(result), Contains.Substring(MISSING_NAME));
#endif
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void LoadTestsAction_BadFile_ReturnsNonRunnableSuite()
{
new FrameworkController.LoadTestsAction(new FrameworkController(BAD_FILE, "ID", _settings), _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
// Minimal check here to allow for platform differences
Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
#endregion
#region ExploreTestsAction
[Test]
public void ExploreTestsAction_FilterCategory_ReturnsTests()
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.ExploreTestsAction(_controller, FIXTURE_CAT_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockTestFixture.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.GreaterThan(0), "Explore result should have child tests");
}
[TestCaseSource(nameof(EmptyFilters))]
public void ExploreTestsAction_AfterLoad_ReturnsRunnableSuite(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.ExploreTestsAction(_controller, filter, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.GreaterThan(0), "Explore result should have child tests");
}
[TestCase(FIXTURE_CAT_FILTER)]
[TestCase(EMPTY_FILTER)]
public void ExploreTestsAction_AfterLoad_ReturnsSameCount(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.ExploreTestsAction(_controller, filter, _handler);
var exploreResult = TNode.FromXml(_handler.GetCallbackResult());
var exploreTestCount = exploreResult.Attributes["testcasecount"];
new FrameworkController.CountTestsAction(_controller, filter, _handler);
var countResult = _handler.GetCallbackResult();
Assert.That(exploreTestCount, Is.EqualTo(countResult));
}
[Test]
public void ExploreTestsAction_WithoutLoad_ThrowsInvalidOperationException()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.ExploreTestsAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The Explore method was called but no test has been loaded"));
}
[Test]
public void ExploreTestsAction_FileNotFound_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.ExploreTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
#if NETCOREAPP1_1
Assert.That(GetSkipReason(result), Contains.Substring("The system cannot find the file specified."));
#else
Assert.That(GetSkipReason(result), Contains.Substring(MISSING_NAME));
#endif
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Result should not have child tests");
}
[Test]
public void ExploreTestsAction_BadFile_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.ExploreTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Result should not have child tests");
}
#endregion
#region CountTestsAction
[TestCaseSource(nameof(EmptyFilters))]
public void CountTestsAction_AfterLoad_ReturnsCorrectCount(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.CountTestsAction(_controller, filter, _handler);
Assert.That(_handler.GetCallbackResult(), Is.EqualTo(MockAssembly.Tests.ToString()));
}
[Test]
public void CountTestsAction_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.CountTestsAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded"));
}
[Test]
public void CountTestsAction_FileNotFound_ReturnsZero()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.CountTestsAction(controller, EMPTY_FILTER, _handler);
Assert.That(_handler.GetCallbackResult(), Is.EqualTo("0"));
}
[Test]
public void CountTestsAction_BadFile_ReturnsZero()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.CountTestsAction(controller, EMPTY_FILTER, _handler);
Assert.That(_handler.GetCallbackResult(), Is.EqualTo("0"));
}
#endregion
#region RunTestsAction
[TestCaseSource(nameof(EmptyFilters))]
public void RunTestsAction_AfterLoad_ReturnsRunnableSuite(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.RunTestsAction(_controller, filter, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
// TODO: Any failure here throws an exception because the call to RunTestsAction
// has destroyed the test context. We need to figure out how to execute the run
// in a cleaner way, perhaps on another thread or in a process.
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.Attributes["result"], Is.EqualTo("Failed"));
Assert.That(result.Attributes["passed"], Is.EqualTo(MockAssembly.Passed.ToString()));
Assert.That(result.Attributes["failed"], Is.EqualTo(MockAssembly.Failed.ToString()));
Assert.That(result.Attributes["warnings"], Is.EqualTo(MockAssembly.Warnings.ToString()));
Assert.That(result.Attributes["skipped"], Is.EqualTo(MockAssembly.Skipped.ToString()));
Assert.That(result.Attributes["inconclusive"], Is.EqualTo(MockAssembly.Inconclusive.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.GreaterThan(0), "Run result should have child tests");
}
[Test]
public void RunTestsAction_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.RunTestsAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void RunTestsAction_FileNotFound_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
#if NETCOREAPP1_1
Assert.That(GetSkipReason(result), Contains.Substring("The system cannot find the file specified."));
#else
Assert.That(GetSkipReason(result), Contains.Substring(MISSING_NAME));
#endif
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void RunTestsAction_BadFile_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
#endregion
#region RunAsyncAction
[TestCaseSource(nameof(EmptyFilters))]
public void RunAsyncAction_AfterLoad_ReturnsRunnableSuite(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.RunAsyncAction(_controller, filter, _handler);
//var result = TNode.FromXml(_handler.GetCallbackResult());
//Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
//Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
//Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
//Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
//Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
//Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
//Assert.That(result.Attributes["result"], Is.EqualTo("Failed"));
//Assert.That(result.Attributes["passed"], Is.EqualTo(MockAssembly.Success.ToString()));
//Assert.That(result.Attributes["failed"], Is.EqualTo(MockAssembly.ErrorsAndFailures.ToString()));
//Assert.That(result.Attributes["skipped"], Is.EqualTo((MockAssembly.NotRunnable + MockAssembly.Ignored).ToString()));
//Assert.That(result.Attributes["inconclusive"], Is.EqualTo(MockAssembly.Inconclusive.ToString()));
//Assert.That(result.FindDescendants("test-suite").Count, Is.GreaterThan(0), "Run result should have child tests");
}
[Test]
public void RunAsyncAction_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.RunAsyncAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void RunAsyncAction_FileNotFound_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunAsyncAction(controller, EMPTY_FILTER, _handler);
//var result = TNode.FromXml(_handler.GetCallbackResult());
//Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
//Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
//Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
//Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
//Assert.That(GetSkipReason(result), Contains.Substring(MISSING_FILE));
//Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void RunAsyncAction_BadFile_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunAsyncAction(controller, EMPTY_FILTER, _handler);
//var result = TNode.FromXml(_handler.GetCallbackResult());
//Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
//Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
//Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
//Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
//Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
//Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
#endregion
#region Helper Methods
private static string GetSkipReason(TNode result)
{
var propNode = result.SelectSingleNode(string.Format("properties/property[@name='{0}']", PropertyNames.SkipReason));
return propNode == null ? null : propNode.Attributes["value"];
}
#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 System.Diagnostics;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using Internal.TypeSystem;
namespace Internal.TypeSystem.Ecma
{
public sealed partial class EcmaField : FieldDesc, EcmaModule.IEntityHandleObject
{
private static class FieldFlags
{
public const int BasicMetadataCache = 0x0001;
public const int Static = 0x0002;
public const int InitOnly = 0x0004;
public const int Literal = 0x0008;
public const int HasRva = 0x0010;
public const int AttributeMetadataCache = 0x0100;
public const int ThreadStatic = 0x0200;
};
private EcmaType _type;
private FieldDefinitionHandle _handle;
// Cached values
private ThreadSafeFlags _fieldFlags;
private TypeDesc _fieldType;
private string _name;
internal EcmaField(EcmaType type, FieldDefinitionHandle handle)
{
_type = type;
_handle = handle;
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
EntityHandle EcmaModule.IEntityHandleObject.Handle
{
get
{
return _handle;
}
}
public override TypeSystemContext Context
{
get
{
return _type.Module.Context;
}
}
public override DefType OwningType
{
get
{
return _type;
}
}
public EcmaModule Module
{
get
{
return _type.EcmaModule;
}
}
public MetadataReader MetadataReader
{
get
{
return _type.MetadataReader;
}
}
public FieldDefinitionHandle Handle
{
get
{
return _handle;
}
}
private TypeDesc InitializeFieldType()
{
var metadataReader = MetadataReader;
BlobReader signatureReader = metadataReader.GetBlobReader(metadataReader.GetFieldDefinition(_handle).Signature);
EcmaSignatureParser parser = new EcmaSignatureParser(Module, signatureReader);
var fieldType = parser.ParseFieldSignature();
return (_fieldType = fieldType);
}
public override TypeDesc FieldType
{
get
{
if (_fieldType == null)
return InitializeFieldType();
return _fieldType;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int InitializeFieldFlags(int mask)
{
int flags = 0;
if ((mask & FieldFlags.BasicMetadataCache) != 0)
{
var fieldAttributes = Attributes;
if ((fieldAttributes & FieldAttributes.Static) != 0)
flags |= FieldFlags.Static;
if ((fieldAttributes & FieldAttributes.InitOnly) != 0)
flags |= FieldFlags.InitOnly;
if ((fieldAttributes & FieldAttributes.Literal) != 0)
flags |= FieldFlags.Literal;
if ((fieldAttributes & FieldAttributes.HasFieldRVA) != 0)
flags |= FieldFlags.HasRva;
flags |= FieldFlags.BasicMetadataCache;
}
// Fetching custom attribute based properties is more expensive, so keep that under
// a separate cache that might not be accessed very frequently.
if ((mask & FieldFlags.AttributeMetadataCache) != 0)
{
var metadataReader = this.MetadataReader;
var fieldDefinition = metadataReader.GetFieldDefinition(_handle);
foreach (var attributeHandle in fieldDefinition.GetCustomAttributes())
{
StringHandle namespaceHandle, nameHandle;
if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle))
continue;
if (metadataReader.StringComparer.Equals(namespaceHandle, "System"))
{
if (metadataReader.StringComparer.Equals(nameHandle, "ThreadStaticAttribute"))
{
flags |= FieldFlags.ThreadStatic;
}
}
}
flags |= FieldFlags.AttributeMetadataCache;
}
Debug.Assert((flags & mask) != 0);
_fieldFlags.AddFlags(flags);
Debug.Assert((flags & mask) != 0);
return flags & mask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetFieldFlags(int mask)
{
int flags = _fieldFlags.Value & mask;
if (flags != 0)
return flags;
return InitializeFieldFlags(mask);
}
public override bool IsStatic
{
get
{
return (GetFieldFlags(FieldFlags.BasicMetadataCache | FieldFlags.Static) & FieldFlags.Static) != 0;
}
}
public override bool IsThreadStatic
{
get
{
return IsStatic &&
(GetFieldFlags(FieldFlags.AttributeMetadataCache | FieldFlags.ThreadStatic) & FieldFlags.ThreadStatic) != 0;
}
}
public override bool IsInitOnly
{
get
{
return (GetFieldFlags(FieldFlags.BasicMetadataCache | FieldFlags.InitOnly) & FieldFlags.InitOnly) != 0;
}
}
public override bool HasRva
{
get
{
return (GetFieldFlags(FieldFlags.BasicMetadataCache | FieldFlags.HasRva) & FieldFlags.HasRva) != 0;
}
}
public override bool IsLiteral
{
get
{
return (GetFieldFlags(FieldFlags.BasicMetadataCache | FieldFlags.Literal) & FieldFlags.Literal) != 0;
}
}
public FieldAttributes Attributes
{
get
{
return MetadataReader.GetFieldDefinition(_handle).Attributes;
}
}
private string InitializeName()
{
var metadataReader = MetadataReader;
var name = metadataReader.GetString(metadataReader.GetFieldDefinition(_handle).Name);
return (_name = name);
}
public override string Name
{
get
{
if (_name == null)
return InitializeName();
return _name;
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return !MetadataReader.GetCustomAttributeHandle(MetadataReader.GetFieldDefinition(_handle).GetCustomAttributes(),
attributeNamespace, attributeName).IsNil;
}
public override string ToString()
{
return _type.ToString() + "." + Name;
}
}
public static class EcmaFieldExtensions
{
/// <summary>
/// Retrieves the data associated with an RVA mapped field from the PE module.
/// </summary>
public static byte[] GetFieldRvaData(this EcmaField field)
{
Debug.Assert(field.HasRva);
int addr = field.MetadataReader.GetFieldDefinition(field.Handle).GetRelativeVirtualAddress();
var memBlock = field.Module.PEReader.GetSectionData(addr).GetContent();
int size = field.FieldType.GetElementSize().AsInt;
if (size > memBlock.Length)
throw new BadImageFormatException();
byte[] result = new byte[size];
memBlock.CopyTo(0, result, 0, result.Length);
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace Microsoft.AspNetCore.Razor.Language.Syntax
{
internal abstract class GreenNode
{
private static readonly RazorDiagnostic[] EmptyDiagnostics = Array.Empty<RazorDiagnostic>();
private static readonly SyntaxAnnotation[] EmptyAnnotations = Array.Empty<SyntaxAnnotation>();
private static readonly ConditionalWeakTable<GreenNode, RazorDiagnostic[]> DiagnosticsTable =
new ConditionalWeakTable<GreenNode, RazorDiagnostic[]>();
private static readonly ConditionalWeakTable<GreenNode, SyntaxAnnotation[]> AnnotationsTable =
new ConditionalWeakTable<GreenNode, SyntaxAnnotation[]>();
private byte _slotCount;
protected GreenNode(SyntaxKind kind)
{
Kind = kind;
}
protected GreenNode(SyntaxKind kind, int fullWidth)
: this(kind)
{
FullWidth = fullWidth;
}
protected GreenNode(SyntaxKind kind, RazorDiagnostic[] diagnostics, SyntaxAnnotation[] annotations)
: this(kind, 0, diagnostics, annotations)
{
}
protected GreenNode(SyntaxKind kind, int fullWidth, RazorDiagnostic[] diagnostics, SyntaxAnnotation[] annotations)
: this(kind, fullWidth)
{
if (diagnostics?.Length > 0)
{
Flags |= NodeFlags.ContainsDiagnostics;
DiagnosticsTable.Add(this, diagnostics);
}
if (annotations?.Length > 0)
{
foreach (var annotation in annotations)
{
if (annotation == null)
{
throw new ArgumentException("Annotation cannot be null", nameof(annotations));
}
}
Flags |= NodeFlags.ContainsAnnotations;
AnnotationsTable.Add(this, annotations);
}
}
protected void AdjustFlagsAndWidth(GreenNode node)
{
if (node == null)
{
return;
}
Flags |= (node.Flags & NodeFlags.InheritMask);
FullWidth += node.FullWidth;
}
#region Kind
internal SyntaxKind Kind { get; }
internal virtual bool IsList => false;
internal virtual bool IsToken => false;
internal virtual bool IsTrivia => false;
#endregion
#region Slots
public int SlotCount
{
get
{
int count = _slotCount;
if (count == byte.MaxValue)
{
count = GetSlotCount();
}
return count;
}
protected set
{
_slotCount = (byte)value;
}
}
internal abstract GreenNode GetSlot(int index);
// for slot counts >= byte.MaxValue
protected virtual int GetSlotCount()
{
return _slotCount;
}
public virtual int GetSlotOffset(int index)
{
var offset = 0;
for (var i = 0; i < index; i++)
{
var child = GetSlot(i);
if (child != null)
offset += child.FullWidth;
}
return offset;
}
public virtual int FindSlotIndexContainingOffset(int offset)
{
Debug.Assert(0 <= offset && offset < FullWidth);
int i;
var accumulatedWidth = 0;
for (i = 0; ; i++)
{
Debug.Assert(i < SlotCount);
var child = GetSlot(i);
if (child != null)
{
accumulatedWidth += child.FullWidth;
if (offset < accumulatedWidth)
{
break;
}
}
}
return i;
}
#endregion
#region Flags
public NodeFlags Flags { get; protected set; }
internal void SetFlags(NodeFlags flags)
{
Flags |= flags;
}
internal void ClearFlags(NodeFlags flags)
{
Flags &= ~flags;
}
internal virtual bool IsMissing => (Flags & NodeFlags.IsMissing) != 0;
public bool ContainsDiagnostics
{
get
{
return (Flags & NodeFlags.ContainsDiagnostics) != 0;
}
}
public bool ContainsAnnotations
{
get
{
return (Flags & NodeFlags.ContainsAnnotations) != 0;
}
}
#endregion
#region Spans
internal int FullWidth { get; private set; }
public virtual int Width
{
get
{
return FullWidth - GetLeadingTriviaWidth() - GetTrailingTriviaWidth();
}
}
public virtual int GetLeadingTriviaWidth()
{
return FullWidth != 0 ? GetFirstTerminal().GetLeadingTriviaWidth() : 0;
}
public virtual int GetTrailingTriviaWidth()
{
return FullWidth != 0 ? GetLastTerminal().GetTrailingTriviaWidth() : 0;
}
public bool HasLeadingTrivia
{
get
{
return GetLeadingTriviaWidth() != 0;
}
}
public bool HasTrailingTrivia
{
get
{
return GetTrailingTriviaWidth() != 0;
}
}
#endregion
#region Diagnostics
internal abstract GreenNode SetDiagnostics(RazorDiagnostic[] diagnostics);
internal RazorDiagnostic[] GetDiagnostics()
{
if (ContainsDiagnostics)
{
if (DiagnosticsTable.TryGetValue(this, out var diagnostics))
{
return diagnostics;
}
}
return EmptyDiagnostics;
}
#endregion
#region Annotations
internal abstract GreenNode SetAnnotations(SyntaxAnnotation[] annotations);
internal SyntaxAnnotation[] GetAnnotations()
{
if (ContainsAnnotations)
{
if (AnnotationsTable.TryGetValue(this, out var annotations))
{
Debug.Assert(annotations.Length != 0, "There cannot be an empty annotation entry.");
return annotations;
}
}
return EmptyAnnotations;
}
#endregion
#region Text
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(CultureInfo.InvariantCulture, "{0}<{1}>", GetType().Name, Kind);
return builder.ToString();
}
public virtual string ToFullString()
{
var builder = new StringBuilder();
var writer = new StringWriter(builder, System.Globalization.CultureInfo.InvariantCulture);
WriteTo(writer);
return builder.ToString();
}
public virtual void WriteTo(TextWriter writer)
{
WriteTo(writer, leading: true, trailing: true);
}
protected internal void WriteTo(TextWriter writer, bool leading, bool trailing)
{
// Use an actual Stack so we can write out deeply recursive structures without overflowing.
var stack = new Stack<StackEntry>();
stack.Push(new StackEntry(this, leading, trailing));
// Separated out stack processing logic so that it does not unintentionally refer to
// "this", "leading" or "trailing.
ProcessStack(writer, stack);
}
protected virtual void WriteTriviaTo(TextWriter writer)
{
throw new NotImplementedException();
}
protected virtual void WriteTokenTo(TextWriter writer, bool leading, bool trailing)
{
throw new NotImplementedException();
}
#endregion
#region Tokens
public virtual object GetValue()
{
return null;
}
public virtual string GetValueText()
{
return string.Empty;
}
public virtual GreenNode GetLeadingTrivia()
{
return null;
}
public virtual GreenNode GetTrailingTrivia()
{
return null;
}
public virtual GreenNode WithLeadingTrivia(GreenNode trivia)
{
return this;
}
public virtual GreenNode WithTrailingTrivia(GreenNode trivia)
{
return this;
}
public InternalSyntax.SyntaxToken GetFirstToken()
{
return (InternalSyntax.SyntaxToken)GetFirstTerminal();
}
public InternalSyntax.SyntaxToken GetLastToken()
{
return (InternalSyntax.SyntaxToken)GetLastTerminal();
}
internal GreenNode GetFirstTerminal()
{
var node = this;
do
{
GreenNode firstChild = null;
for (int i = 0, n = node.SlotCount; i < n; i++)
{
var child = node.GetSlot(i);
if (child != null && child.FullWidth > 0)
{
firstChild = child;
break;
}
}
node = firstChild;
} while (node?._slotCount > 0);
return node;
}
internal GreenNode GetLastTerminal()
{
var node = this;
do
{
GreenNode lastChild = null;
for (var i = node.SlotCount - 1; i >= 0; i--)
{
var child = node.GetSlot(i);
if (child != null && child.FullWidth > 0)
{
lastChild = child;
break;
}
}
node = lastChild;
} while (node?._slotCount > 0);
return node;
}
#endregion
#region Equivalence
public virtual bool IsEquivalentTo(GreenNode other)
{
if (this == other)
{
return true;
}
if (other == null)
{
return false;
}
return EquivalentToInternal(this, other);
}
private static bool EquivalentToInternal(GreenNode node1, GreenNode node2)
{
if (node1.Kind != node2.Kind)
{
// A single-element list is usually represented as just a single node,
// but can be represented as a List node with one child. Move to that
// child if necessary.
if (node1.IsList && node1.SlotCount == 1)
{
node1 = node1.GetSlot(0);
}
if (node2.IsList && node2.SlotCount == 1)
{
node2 = node2.GetSlot(0);
}
if (node1.Kind != node2.Kind)
{
return false;
}
}
if (node1.FullWidth != node2.FullWidth)
{
return false;
}
var n = node1.SlotCount;
if (n != node2.SlotCount)
{
return false;
}
for (var i = 0; i < n; i++)
{
var node1Child = node1.GetSlot(i);
var node2Child = node2.GetSlot(i);
if (node1Child != null && node2Child != null && !node1Child.IsEquivalentTo(node2Child))
{
return false;
}
}
return true;
}
#endregion
#region Factories
public virtual GreenNode CreateList(IEnumerable<GreenNode> nodes, bool alwaysCreateListNode = false)
{
if (nodes == null)
{
return null;
}
var list = nodes.ToArray();
switch (list.Length)
{
case 0:
return null;
case 1:
if (alwaysCreateListNode)
{
goto default;
}
else
{
return list[0];
}
case 2:
return InternalSyntax.SyntaxList.List(list[0], list[1]);
case 3:
return InternalSyntax.SyntaxList.List(list[0], list[1], list[2]);
default:
return InternalSyntax.SyntaxList.List(list);
}
}
public SyntaxNode CreateRed()
{
return CreateRed(null, 0);
}
internal abstract SyntaxNode CreateRed(SyntaxNode parent, int position);
#endregion
public abstract TResult Accept<TResult>(InternalSyntax.SyntaxVisitor<TResult> visitor);
public abstract void Accept(InternalSyntax.SyntaxVisitor visitor);
#region StaticMethods
private static void ProcessStack(TextWriter writer,
Stack<StackEntry> stack)
{
while (stack.Count > 0)
{
var current = stack.Pop();
var currentNode = current.Node;
var currentLeading = current.Leading;
var currentTrailing = current.Trailing;
if (currentNode.IsToken)
{
currentNode.WriteTokenTo(writer, currentLeading, currentTrailing);
continue;
}
if (currentNode.IsTrivia)
{
currentNode.WriteTriviaTo(writer);
continue;
}
var firstIndex = GetFirstNonNullChildIndex(currentNode);
var lastIndex = GetLastNonNullChildIndex(currentNode);
for (var i = lastIndex; i >= firstIndex; i--)
{
var child = currentNode.GetSlot(i);
if (child != null)
{
var first = i == firstIndex;
var last = i == lastIndex;
stack.Push(new StackEntry(child, currentLeading | !first, currentTrailing | !last));
}
}
}
}
private static int GetFirstNonNullChildIndex(GreenNode node)
{
int n = node.SlotCount;
int firstIndex = 0;
for (; firstIndex < n; firstIndex++)
{
var child = node.GetSlot(firstIndex);
if (child != null)
{
break;
}
}
return firstIndex;
}
private static int GetLastNonNullChildIndex(GreenNode node)
{
int n = node.SlotCount;
int lastIndex = n - 1;
for (; lastIndex >= 0; lastIndex--)
{
var child = node.GetSlot(lastIndex);
if (child != null)
{
break;
}
}
return lastIndex;
}
private struct StackEntry
{
public StackEntry(GreenNode node, bool leading, bool trailing)
{
Node = node;
Leading = leading;
Trailing = trailing;
}
public GreenNode Node { get; }
public bool Leading { get; }
public bool Trailing { get; }
}
#endregion
}
}
| |
using J2N.Text;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using WritableArrayAttribute = Lucene.Net.Support.WritableArrayAttribute;
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>
/// Represents <see cref="T:byte[]"/>, as a slice (offset + length) into an
/// existing <see cref="T:byte[]"/>. The <see cref="Bytes"/> property should never be <c>null</c>;
/// use <see cref="EMPTY_BYTES"/> if necessary.
///
/// <para/><b>Important note:</b> Unless otherwise noted, Lucene uses this class to
/// represent terms that are encoded as <b>UTF8</b> bytes in the index. To
/// convert them to a .NET <see cref="string"/> (which is UTF16), use <see cref="Utf8ToString()"/>.
/// Using code like <c>new String(bytes, offset, length)</c> to do this
/// is <b>wrong</b>, as it does not respect the correct character set
/// and may return wrong results (depending on the platform's defaults)!
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public sealed class BytesRef : IComparable<BytesRef>, IComparable, IEquatable<BytesRef> // LUCENENET specific - implemented IComparable for FieldComparator, IEquatable<BytesRef>
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
/// <summary>
/// An empty byte array for convenience </summary>
public static readonly byte[] EMPTY_BYTES = Arrays.Empty<byte>();
/// <summary>
/// The contents of the BytesRef. Should never be <c>null</c>.
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public byte[] Bytes
{
get => bytes;
set => bytes = value; // LUCENENET NOTE: Although the comments state this cannot be null, some of the tests depend on setting it to null!
}
private byte[] bytes;
/// <summary>
/// Offset of first valid byte.
/// </summary>
public int Offset { get; set; }
/// <summary>
/// Length of used bytes.
/// </summary>
public int Length { get; set; }
/// <summary>
/// Create a <see cref="BytesRef"/> with <see cref="EMPTY_BYTES"/> </summary>
public BytesRef()
: this(EMPTY_BYTES)
{
}
/// <summary>
/// This instance will directly reference <paramref name="bytes"/> w/o making a copy.
/// <paramref name="bytes"/> should not be <c>null</c>.
/// </summary>
public BytesRef(byte[] bytes, int offset, int length)
{
this.bytes = bytes;
this.Offset = offset;
this.Length = length;
if (Debugging.AssertsEnabled) Debugging.Assert(IsValid());
}
/// <summary>
/// This instance will directly reference <paramref name="bytes"/> w/o making a copy.
/// <paramref name="bytes"/> should not be <c>null</c>.
/// </summary>
public BytesRef(byte[] bytes)
: this(bytes, 0, bytes.Length)
{
}
/// <summary>
/// Create a <see cref="BytesRef"/> pointing to a new array of size <paramref name="capacity"/>.
/// Offset and length will both be zero.
/// </summary>
public BytesRef(int capacity)
{
this.bytes = new byte[capacity];
}
/// <summary>
/// Initialize the <see cref="T:byte[]"/> from the UTF8 bytes
/// for the provided <see cref="ICharSequence"/>.
/// </summary>
/// <param name="text"> This must be well-formed
/// unicode text, with no unpaired surrogates. </param>
public BytesRef(ICharSequence text)
: this()
{
CopyChars(text);
}
/// <summary>
/// Initialize the <see cref="T:byte[]"/> from the UTF8 bytes
/// for the provided <see cref="string"/>.
/// </summary>
/// <param name="text"> This must be well-formed
/// unicode text, with no unpaired surrogates. </param>
public BytesRef(string text)
: this()
{
CopyChars(text);
}
/// <summary>
/// Copies the UTF8 bytes for this <see cref="ICharSequence"/>.
/// </summary>
/// <param name="text"> Must be well-formed unicode text, with no
/// unpaired surrogates or invalid UTF16 code units. </param>
public void CopyChars(ICharSequence text)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Offset == 0); // TODO broken if offset != 0
UnicodeUtil.UTF16toUTF8(text, 0, text.Length, this);
}
/// <summary>
/// Copies the UTF8 bytes for this <see cref="string"/>.
/// </summary>
/// <param name="text"> Must be well-formed unicode text, with no
/// unpaired surrogates or invalid UTF16 code units. </param>
public void CopyChars(string text)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Offset == 0); // TODO broken if offset != 0
UnicodeUtil.UTF16toUTF8(text, 0, text.Length, this);
}
/// <summary>
/// Expert: Compares the bytes against another <see cref="BytesRef"/>,
/// returning <c>true</c> if the bytes are equal.
/// <para/>
/// @lucene.internal
/// </summary>
/// <param name="other"> Another <see cref="BytesRef"/>, should not be <c>null</c>. </param>
public bool BytesEquals(BytesRef other)
{
if (Debugging.AssertsEnabled) Debugging.Assert(other != null);
if (Length == other.Length)
{
var otherUpto = other.Offset;
var otherBytes = other.bytes;
var end = Offset + Length;
for (int upto = Offset; upto < end; upto++, otherUpto++)
{
if (bytes[upto] != otherBytes[otherUpto])
{
return false;
}
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Returns a shallow clone of this instance (the underlying bytes are
/// <b>not</b> copied and will be shared by both the returned object and this
/// object.
/// </summary>
/// <seealso cref="DeepCopyOf(BytesRef)"/>
public object Clone()
{
return new BytesRef(bytes, Offset, Length);
}
/// <summary>
/// Calculates the hash code as required by <see cref="Index.TermsHash"/> during indexing.
/// <para/> This is currently implemented as MurmurHash3 (32
/// bit), using the seed from
/// <see cref="StringHelper.GOOD_FAST_HASH_SEED"/>, but is subject to
/// change from release to release.
/// </summary>
public override int GetHashCode()
{
return StringHelper.Murmurhash3_x86_32(this, StringHelper.GOOD_FAST_HASH_SEED);
}
public override bool Equals(object other)
{
if (other == null)
return false;
if (other is BytesRef otherBytes)
return this.BytesEquals(otherBytes);
return false;
}
bool IEquatable<BytesRef>.Equals(BytesRef other) // LUCENENET specific - implemented IEquatable<BytesRef>
=> BytesEquals(other);
/// <summary>
/// Interprets stored bytes as UTF8 bytes, returning the
/// resulting <see cref="string"/>.
/// </summary>
public string Utf8ToString()
{
CharsRef @ref = new CharsRef(Length);
UnicodeUtil.UTF8toUTF16(bytes, Offset, Length, @ref);
return @ref.ToString();
}
/// <summary>
/// Returns hex encoded bytes, eg [0x6c 0x75 0x63 0x65 0x6e 0x65] </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
int end = Offset + Length;
for (int i = Offset; i < end; i++)
{
if (i > Offset)
{
sb.Append(' ');
}
sb.Append((bytes[i] & 0xff).ToString("x"));
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// Copies the bytes from the given <see cref="BytesRef"/>
/// <para/>
/// NOTE: if this would exceed the array size, this method creates a
/// new reference array.
/// </summary>
public void CopyBytes(BytesRef other)
{
if (Bytes.Length - Offset < other.Length)
{
bytes = new byte[other.Length];
Offset = 0;
}
Array.Copy(other.bytes, other.Offset, bytes, Offset, other.Length);
Length = other.Length;
}
/// <summary>
/// Appends the bytes from the given <see cref="BytesRef"/>
/// <para/>
/// NOTE: if this would exceed the array size, this method creates a
/// new reference array.
/// </summary>
public void Append(BytesRef other)
{
int newLen = Length + other.Length;
if (bytes.Length - Offset < newLen)
{
var newBytes = new byte[newLen];
Array.Copy(bytes, Offset, newBytes, 0, Length);
Offset = 0;
bytes = newBytes;
}
Array.Copy(other.bytes, other.Offset, bytes, Length + Offset, other.Length);
Length = newLen;
}
/// <summary>
/// Used to grow the reference array.
/// <para/>
/// In general this should not be used as it does not take the offset into account.
/// <para/>
/// @lucene.internal
/// </summary>
public void Grow(int newLength)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Offset == 0); // NOTE: senseless if offset != 0
bytes = ArrayUtil.Grow(bytes, newLength);
}
/// <summary>
/// Unsigned byte order comparison </summary>
public int CompareTo(object other) // LUCENENET specific: Implemented IComparable for FieldComparer
{
BytesRef br = other as BytesRef;
if (Debugging.AssertsEnabled) Debugging.Assert(br != null);
return utf8SortedAsUnicodeSortOrder.Compare(this, br);
}
/// <summary>
/// Unsigned byte order comparison </summary>
public int CompareTo(BytesRef other)
{
return utf8SortedAsUnicodeSortOrder.Compare(this, other);
}
private static readonly IComparer<BytesRef> utf8SortedAsUnicodeSortOrder = Utf8SortedAsUnicodeComparer.Instance;
public static IComparer<BytesRef> UTF8SortedAsUnicodeComparer => utf8SortedAsUnicodeSortOrder;
// LUCENENET NOTE: De-nested Utf8SortedAsUnicodeComparer class to prevent naming conflict
/// @deprecated this comparer is only a transition mechanism
[Obsolete("this comparer is only a transition mechanism")]
private static readonly IComparer<BytesRef> utf8SortedAsUTF16SortOrder = new Utf8SortedAsUtf16Comparer();
/// @deprecated this comparer is only a transition mechanism
[Obsolete("this comparer is only a transition mechanism")]
public static IComparer<BytesRef> UTF8SortedAsUTF16Comparer => utf8SortedAsUTF16SortOrder;
// LUCENENET NOTE: De-nested Utf8SortedAsUtf16Comparer class to prevent naming conflict
/// <summary>
/// Creates a new <see cref="BytesRef"/> that points to a copy of the bytes from
/// <paramref name="other"/>.
/// <para/>
/// The returned <see cref="BytesRef"/> will have a length of <c>other.Length</c>
/// and an offset of zero.
/// </summary>
public static BytesRef DeepCopyOf(BytesRef other)
{
BytesRef copy = new BytesRef();
copy.CopyBytes(other);
return copy;
}
/// <summary>
/// Performs internal consistency checks.
/// Always returns true (or throws <see cref="InvalidOperationException"/>)
/// </summary>
public bool IsValid()
{
if (Bytes == null)
{
throw new InvalidOperationException("bytes is null");
}
if (Length < 0)
{
throw new InvalidOperationException("length is negative: " + Length);
}
if (Length > Bytes.Length)
{
throw new InvalidOperationException("length is out of bounds: " + Length + ",bytes.length=" + Bytes.Length);
}
if (Offset < 0)
{
throw new InvalidOperationException("offset is negative: " + Offset);
}
if (Offset > Bytes.Length)
{
throw new InvalidOperationException("offset out of bounds: " + Offset + ",bytes.length=" + Bytes.Length);
}
if (Offset + Length < 0)
{
throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length);
}
if (Offset + Length > Bytes.Length)
{
throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",bytes.length=" + Bytes.Length);
}
return true;
}
}
internal class Utf8SortedAsUnicodeComparer : IComparer<BytesRef>
{
public static Utf8SortedAsUnicodeComparer Instance = new Utf8SortedAsUnicodeComparer();
// Only singleton
private Utf8SortedAsUnicodeComparer()
{
}
public virtual int Compare(BytesRef a, BytesRef b)
{
var aBytes = a.Bytes;
int aUpto = a.Offset;
var bBytes = b.Bytes;
int bUpto = b.Offset;
int aStop = aUpto + Math.Min(a.Length, b.Length);
while (aUpto < aStop)
{
int aByte = aBytes[aUpto++] & 0xff;
int bByte = bBytes[bUpto++] & 0xff;
int diff = aByte - bByte;
if (diff != 0)
{
return diff;
}
}
// One is a prefix of the other, or, they are equal:
return a.Length - b.Length;
}
}
/// @deprecated this comparer is only a transition mechanism
[Obsolete("this comparer is only a transition mechanism")]
internal class Utf8SortedAsUtf16Comparer : IComparer<BytesRef>
{
// Only singleton
internal Utf8SortedAsUtf16Comparer()
{
}
public virtual int Compare(BytesRef a, BytesRef b)
{
var aBytes = a.Bytes;
int aUpto = a.Offset;
var bBytes = b.Bytes;
int bUpto = b.Offset;
int aStop;
if (a.Length < b.Length)
{
aStop = aUpto + a.Length;
}
else
{
aStop = aUpto + b.Length;
}
while (aUpto < aStop)
{
int aByte = aBytes[aUpto++] & 0xff;
int bByte = bBytes[bUpto++] & 0xff;
if (aByte != bByte)
{
// See http://icu-project.org/docs/papers/utf16_code_point_order.html#utf-8-in-utf-16-order
// We know the terms are not equal, but, we may
// have to carefully fixup the bytes at the
// difference to match UTF16's sort order:
// NOTE: instead of moving supplementary code points (0xee and 0xef) to the unused 0xfe and 0xff,
// we move them to the unused 0xfc and 0xfd [reserved for future 6-byte character sequences]
// this reserves 0xff for preflex's term reordering (surrogate dance), and if unicode grows such
// that 6-byte sequences are needed we have much bigger problems anyway.
if (aByte >= 0xee && bByte >= 0xee)
{
if ((aByte & 0xfe) == 0xee)
{
aByte += 0xe;
}
if ((bByte & 0xfe) == 0xee)
{
bByte += 0xe;
}
}
return aByte - bByte;
}
}
// One is a prefix of the other, or, they are equal:
return a.Length - b.Length;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: supply/room_types/room_type_crud.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Supply.RoomTypes {
/// <summary>Holder for reflection information generated from supply/room_types/room_type_crud.proto</summary>
public static partial class RoomTypeCrudReflection {
#region Descriptor
/// <summary>File descriptor for supply/room_types/room_type_crud.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RoomTypeCrudReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiZzdXBwbHkvcm9vbV90eXBlcy9yb29tX3R5cGVfY3J1ZC5wcm90bxIdaG9s",
"bXMudHlwZXMuc3VwcGx5LnJvb21fdHlwZXMaG3ByaW1pdGl2ZS9jcnVkX2Fj",
"dGlvbi5wcm90bxohc3VwcGx5L3Jvb21fdHlwZXMvcm9vbV90eXBlLnByb3Rv",
"IpUBCgxSb29tVHlwZUNydWQSEQoJal93X3Rva2VuGAEgASgJEjYKC2NydWRf",
"YWN0aW9uGAIgASgOMiEuaG9sbXMudHlwZXMucHJpbWl0aXZlLkNydWRBY3Rp",
"b24SOgoJcm9vbV90eXBlGAMgASgLMicuaG9sbXMudHlwZXMuc3VwcGx5LnJv",
"b21fdHlwZXMuUm9vbVR5cGVCMVoQc3VwcGx5L3Jvb210eXBlc6oCHEhPTE1T",
"LlR5cGVzLlN1cHBseS5Sb29tVHlwZXNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.CrudActionReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RoomTypes.RoomTypeCrud), global::HOLMS.Types.Supply.RoomTypes.RoomTypeCrud.Parser, new[]{ "JWToken", "CrudAction", "RoomType" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class RoomTypeCrud : pb::IMessage<RoomTypeCrud> {
private static readonly pb::MessageParser<RoomTypeCrud> _parser = new pb::MessageParser<RoomTypeCrud>(() => new RoomTypeCrud());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomTypeCrud> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Supply.RoomTypes.RoomTypeCrudReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomTypeCrud() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomTypeCrud(RoomTypeCrud other) : this() {
jWToken_ = other.jWToken_;
crudAction_ = other.crudAction_;
RoomType = other.roomType_ != null ? other.RoomType.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomTypeCrud Clone() {
return new RoomTypeCrud(this);
}
/// <summary>Field number for the "j_w_token" field.</summary>
public const int JWTokenFieldNumber = 1;
private string jWToken_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JWToken {
get { return jWToken_; }
set {
jWToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "crud_action" field.</summary>
public const int CrudActionFieldNumber = 2;
private global::HOLMS.Types.Primitive.CrudAction crudAction_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.CrudAction CrudAction {
get { return crudAction_; }
set {
crudAction_ = value;
}
}
/// <summary>Field number for the "room_type" field.</summary>
public const int RoomTypeFieldNumber = 3;
private global::HOLMS.Types.Supply.RoomTypes.RoomType roomType_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RoomTypes.RoomType RoomType {
get { return roomType_; }
set {
roomType_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomTypeCrud);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomTypeCrud other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JWToken != other.JWToken) return false;
if (CrudAction != other.CrudAction) return false;
if (!object.Equals(RoomType, other.RoomType)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JWToken.Length != 0) hash ^= JWToken.GetHashCode();
if (CrudAction != 0) hash ^= CrudAction.GetHashCode();
if (roomType_ != null) hash ^= RoomType.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (JWToken.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JWToken);
}
if (CrudAction != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) CrudAction);
}
if (roomType_ != null) {
output.WriteRawTag(26);
output.WriteMessage(RoomType);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JWToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JWToken);
}
if (CrudAction != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CrudAction);
}
if (roomType_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomTypeCrud other) {
if (other == null) {
return;
}
if (other.JWToken.Length != 0) {
JWToken = other.JWToken;
}
if (other.CrudAction != 0) {
CrudAction = other.CrudAction;
}
if (other.roomType_ != null) {
if (roomType_ == null) {
roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType();
}
RoomType.MergeFrom(other.RoomType);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
JWToken = input.ReadString();
break;
}
case 16: {
crudAction_ = (global::HOLMS.Types.Primitive.CrudAction) input.ReadEnum();
break;
}
case 26: {
if (roomType_ == null) {
roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType();
}
input.ReadMessage(roomType_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.MessageTemplates
{
using System;
using NLog.MessageTemplates;
using Xunit;
public class ParserTests
{
private static object[] ManyParameters = new object[100];
[Theory]
[InlineData("")]
[InlineData("Hello {0}")]
[InlineData("I like my {car}")]
[InlineData("But when Im drunk I need a {cool} bike")]
[InlineData("I have {0} {1} {2} parameters")]
[InlineData("{0} on front")]
[InlineData(" {0} on front")]
[InlineData("end {1}")]
[InlineData("end {1} ")]
[InlineData("{name} is my name")]
[InlineData(" {name} is my name")]
[InlineData("{multiple}{parameters}")]
[InlineData("I have {{text}} and {{0}}")]
[InlineData("{{text}}{{0}}")]
[InlineData(" {{text}}{{0}} ")]
[InlineData(" {0} ")]
[InlineData(" {1} ")]
[InlineData(" {2} ")]
[InlineData(" {3} {4} {9} {8} {5} {6} {7}")]
[InlineData(" {{ ")]
[InlineData("{{ ")]
[InlineData(" {{")]
[InlineData(" }} ")]
[InlineData("}} ")]
[InlineData(" }}")]
[InlineData("{0:000}")]
[InlineData("{aaa:000}")]
[InlineData(" {@serialize} ")]
[InlineData(" {$stringify} ")]
[InlineData(" {alignment,-10} ")]
[InlineData(" {alignment,10} ")]
[InlineData(" {0,10} ")]
[InlineData(" {0,-10} ")]
[InlineData(" {0,-10:test} ")]
[InlineData("{{{0:d}}}")]
[InlineData("{{{0:0{{}")]
public void ParseAndPrint(string input)
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var templateAuto = logEventInfo.MessageTemplateParameters;
}
[Theory]
[InlineData("{0}", 0, null)]
[InlineData("{001}", 1, null)]
[InlineData("{9}", 9, null)]
[InlineData("{1 }", 1, null)]
[InlineData("{1} {2}", 1, null)]
[InlineData("{@3} {$4}", 3, null)]
[InlineData("{3,6}", 3, null)]
[InlineData("{5:R}", 5, "R")]
[InlineData("{0:0}", 0, "0")]
public void ParsePositional(string input, int index, string format)
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var template = logEventInfo.MessageTemplateParameters;
Assert.True(template.IsPositional);
Assert.True(template.Count >= 1);
Assert.Equal(format, template[0].Format);
Assert.Equal(index, template[0].PositionalIndex);
}
[Theory]
[InlineData("{ 0}")]
[InlineData("{-1}")]
[InlineData("{1.2}")]
[InlineData("{42r}")]
[InlineData("{6} {x}")]
[InlineData("{a} {x}")]
public void ParseNominal(string input)
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var template = logEventInfo.MessageTemplateParameters;
Assert.False(template.IsPositional);
}
[Theory]
[InlineData("{hello}", "hello")]
[InlineData("{@hello}", "hello")]
[InlineData("{$hello}", "hello")]
[InlineData("{#hello}", "#hello")]
[InlineData("{ spaces ,-3}", " spaces ")]
[InlineData("{special!:G})", "special!")]
[InlineData("{noescape_in_name}}}", "noescape_in_name")]
[InlineData("{noescape_in_name{{}", "noescape_in_name{{")]
[InlineData("{0}", "0")]
[InlineData("{18 }", "18 ")]
public void ParseName(string input, string name)
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var template = logEventInfo.MessageTemplateParameters;
Assert.Equal(1, template.Count);
Assert.Equal(name, template[0].Name);
}
[Theory]
[InlineData("{aaa}", "")]
[InlineData("{@a}", "@")]
[InlineData("{@A}", "@")]
[InlineData("{@8}", "@")]
[InlineData("{@aaa}", "@")]
[InlineData("{$a}", "$")]
[InlineData("{$A}", "$")]
[InlineData("{$9}", "$")]
[InlineData("{$aaa}", "$")]
public void ParseHoleType(string input, string holeType)
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var template = logEventInfo.MessageTemplateParameters;
Assert.Equal(1, template.Count);
CaptureType captureType = CaptureType.Normal;
if (holeType == "@")
captureType = CaptureType.Serialize;
else if (holeType == "$")
captureType = CaptureType.Stringify;
Assert.Equal(captureType, template[0].CaptureType);
}
[Theory]
[InlineData(" {0,-10:nl-nl} ", -10, "nl-nl")]
[InlineData(" {0,-10} ", -10, null)]
[InlineData("{0, 36 }", 36, null)]
[InlineData("{0,-36 :x}", -36, "x")]
[InlineData(" {0:nl-nl} ", 0, "nl-nl")]
[InlineData(" {0} ", 0, null)]
public void ParseFormatAndAlignment_numeric(string input, int? alignment, string format)
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var template = logEventInfo.MessageTemplateParameters;
Assert.Equal(1, template.Count);
var hole = template[0];
Assert.Equal("0", hole.Name);
Assert.Equal(0, hole.PositionalIndex);
Assert.Equal(format, hole.Format);
Assert.NotNull(alignment);
}
[Theory]
[InlineData(" {car,-10:nl-nl} ", -10, "nl-nl")]
[InlineData(" {car,-10} ", -10, null)]
[InlineData(" {car:nl-nl} ", 0, "nl-nl")]
[InlineData(" {car} ", 0, null)]
public void ParseFormatAndAlignment_text(string input, int? alignment, string format)
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var template = logEventInfo.MessageTemplateParameters;
Assert.Equal(1, template.Count);
var hole = template[0];
Assert.False(template.IsPositional);
Assert.Equal("car", hole.Name);
Assert.Equal(format, hole.Format);
Assert.NotNull(alignment);
}
[Theory]
[InlineData("Hello {0")]
[InlineData("Hello 0}")]
[InlineData("Hello {a:")]
[InlineData("Hello {a")]
[InlineData("Hello {a,")]
[InlineData("Hello {a,1")]
[InlineData("{")]
[InlineData("}")]
[InlineData("}}}")]
[InlineData("}}}{")]
[InlineData("{}}{")]
[InlineData("{a,-3.5}")]
[InlineData("{a,2x}")]
[InlineData("{a,--2}")]
[InlineData("{a,-2")]
[InlineData("{a,-2 :N0")]
[InlineData("{a,-2.0")]
[InlineData("{a,:N0}")]
[InlineData("{a,}")]
[InlineData("{a,{}")]
[InlineData("{a:{}")]
[InlineData("{a,d{e}")]
[InlineData("{a:d{e}")]
public void ThrowsTemplateParserException(string input)
{
Assert.Throws<TemplateParserException>(() =>
{
var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters);
logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null);
var template = logEventInfo.MessageTemplateParameters;
});
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Threading;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet resumes the jobs that are Job2. Errors are added for each Job that is not Job2.
/// </summary>
#if !CORECLR
[SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")]
[Cmdlet(VerbsLifecycle.Resume, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210611")]
#endif
[OutputType(typeof(Job))]
public class ResumeJobCommand : JobCmdletBase, IDisposable
{
#region Parameters
/// <summary>
/// Specifies the Jobs objects which need to be
/// suspended
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = JobParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Job[] Job
{
get
{
return _jobs;
}
set
{
_jobs = value;
}
}
private Job[] _jobs;
/// <summary>
///
/// </summary>
public override String[] Command
{
get
{
return null;
}
}
/// <summary>
/// Specifies whether to delay returning from the cmdlet until all jobs reach a running state.
/// This could take significant time due to workflow throttling.
/// </summary>
[Parameter(ParameterSetName = ParameterAttribute.AllParameterSets)]
public SwitchParameter Wait { get; set; }
#endregion Parameters
#region Overrides
/// <summary>
/// Resume the Job.
/// </summary>
protected override void ProcessRecord()
{
//List of jobs to resume
List<Job> jobsToResume = null;
switch (ParameterSetName)
{
case NameParameterSet:
{
jobsToResume = FindJobsMatchingByName(true, false, true, false);
}
break;
case InstanceIdParameterSet:
{
jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false);
}
break;
case SessionIdParameterSet:
{
jobsToResume = FindJobsMatchingBySessionId(true, false, true, false);
}
break;
case StateParameterSet:
{
jobsToResume = FindJobsMatchingByState(false);
}
break;
case FilterParameterSet:
{
jobsToResume = FindJobsMatchingByFilter(false);
}
break;
default:
{
jobsToResume = CopyJobsToList(_jobs, false, false);
}
break;
}
_allJobsToResume.AddRange(jobsToResume);
// Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state
// Setting Wait to true so that this cmdlet will wait for the running job state.
if (_allJobsToResume.Count == 1)
Wait = true;
foreach (Job job in jobsToResume)
{
var job2 = job as Job2;
// If the job is not Job2, the resume operation is not supported.
if (job2 == null)
{
WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job));
continue;
}
string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id);
if (ShouldProcess(targetString, VerbsLifecycle.Resume))
{
_cleanUpActions.Add(job2, HandleResumeJobCompleted);
job2.ResumeJobCompleted += HandleResumeJobCompleted;
lock (_syncObject)
{
if (!_pendingJobs.Contains(job2.InstanceId))
{
_pendingJobs.Add(job2.InstanceId);
}
}
job2.ResumeJobAsync();
}
}
}
private bool _warnInvalidState = false;
private readonly HashSet<Guid> _pendingJobs = new HashSet<Guid>();
private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false);
private readonly Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>> _cleanUpActions =
new Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>>();
private readonly List<ErrorRecord> _errorsToWrite = new List<ErrorRecord>();
private readonly List<Job> _allJobsToResume = new List<Job>();
private readonly object _syncObject = new object();
private bool _needToCheckForWaitingJobs;
private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eventArgs)
{
Job job = sender as Job;
if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException)
{
_warnInvalidState = true;
}
var parentJob = job as ContainerParentJob;
if (parentJob != null && parentJob.ExecutionError.Count > 0)
{
foreach (
var e in
parentJob.ExecutionError.Where(e => e.FullyQualifiedErrorId == "ContainerParentJobResumeAsyncError")
)
{
if (e.Exception is InvalidJobStateException)
{
// if any errors were invalid job state exceptions, warn the user.
// This is to support Get-Job | Resume-Job scenarios when many jobs
// are Completed, etc.
_warnInvalidState = true;
}
else
{
_errorsToWrite.Add(e);
}
}
parentJob.ExecutionError.Clear();
}
bool releaseWait = false;
lock (_syncObject)
{
if (_pendingJobs.Contains(job.InstanceId))
{
_pendingJobs.Remove(job.InstanceId);
}
if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0)
releaseWait = true;
}
// end processing has been called
// set waithandle if this is the last one
if (releaseWait)
_waitForJobs.Set();
}
/// <summary>
/// End Processing.
/// </summary>
protected override void EndProcessing()
{
bool jobsPending = false;
lock (_syncObject)
{
_needToCheckForWaitingJobs = true;
if (_pendingJobs.Count > 0)
jobsPending = true;
}
if (Wait && jobsPending)
_waitForJobs.WaitOne();
if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState);
foreach (var e in _errorsToWrite) WriteError(e);
foreach (var j in _allJobsToResume) WriteObject(j);
base.EndProcessing();
}
/// <summary>
///
/// </summary>
protected override void StopProcessing()
{
_waitForJobs.Set();
}
#endregion Overrides
#region Dispose
/// <summary>
///
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
///
/// </summary>
/// <param name="disposing"></param>
protected void Dispose(bool disposing)
{
if (!disposing) return;
foreach (var pair in _cleanUpActions)
{
pair.Key.ResumeJobCompleted -= pair.Value;
}
_waitForJobs.Dispose();
}
#endregion Dispose
}
}
| |
using System;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
using UnityEngine.AssetGraph;
namespace UnityEngine.AssetGraph.DataModel.Version2 {
public class Settings {
/*
if true, ignore .meta files inside AssetBundleGraph.
*/
public const bool IGNORE_META = true;
public const string GUI_TEXT_MENU_BASE = "Window/AssetGraph";
public const string GUI_TEXT_MENU_OPEN = GUI_TEXT_MENU_BASE + "/Open Graph Editor";
public const string GUI_TEXT_MENU_BATCHWINDOW_OPEN = GUI_TEXT_MENU_BASE + "/Open Batch Build Window";
public const string GUI_TEXT_MENU_ASSETLOGWINDOW_OPEN = GUI_TEXT_MENU_BASE + "/Open Asset Log Window";
public const string GUI_TEXT_MENU_PROJECTWINDOW_OPEN = GUI_TEXT_MENU_BASE + "/Open Project Window";
public const string GUI_TEXT_MENU_BUILD = GUI_TEXT_MENU_BASE + "/Build Graph for Current Platform";
public const string GUI_TEXT_MENU_GENERATE = GUI_TEXT_MENU_BASE + "/Create Node Script";
public const string GUI_TEXT_MENU_GENERATE_MODIFIER = GUI_TEXT_MENU_GENERATE + "/Modifier Script";
public const string GUI_TEXT_MENU_GENERATE_PREFABBUILDER = GUI_TEXT_MENU_GENERATE + "/PrefabBuilder Script";
public const string GUI_TEXT_MENU_GENERATE_ASSETGENERATOR = GUI_TEXT_MENU_GENERATE + "/AssetGenerator Script";
public const string GUI_TEXT_MENU_GENERATE_IMPORTSETTINGSCONFIGURATOR = GUI_TEXT_MENU_GENERATE + "/ImportSettingsConfigurator Script";
public const string GUI_TEXT_MENU_GENERATE_CUITOOL = GUI_TEXT_MENU_BASE + "/Create CUI Tool";
public const string GUI_TEXT_MENU_GENERATE_POSTPROCESS = GUI_TEXT_MENU_GENERATE + "/Postprocess Script";
public const string GUI_TEXT_MENU_GENERATE_FILTER = GUI_TEXT_MENU_GENERATE + "/Filter Script";
public const string GUI_TEXT_MENU_GENERATE_NODE = GUI_TEXT_MENU_GENERATE + "/Custom Node Script";
public const string GUI_TEXT_MENU_DELETE_CACHE = GUI_TEXT_MENU_BASE + "/Clear Build Cache";
public const string GUI_TEXT_MENU_CLEANUP_SAVEDSETTINGS = GUI_TEXT_MENU_BASE + "/Clean Up SavedSettings";
public const string GRAPH_SEARCH_CONDITION = "t:UnityEngine.AssetGraph.DataModel.Version2.ConfigGraph";
public const string SETTING_TEMPLATE_DIR_SEARCH_CONDITION = "SettingTemplate";
public const string UNITY_METAFILE_EXTENSION = ".meta";
public const string DOTSTART_HIDDEN_FILE_HEADSTRING = ".";
public const string MANIFEST_FOOTER = ".manifest";
public const char UNITY_FOLDER_SEPARATOR = '/';// Mac/Windows/Linux can use '/' in Unity.
public const string BASE64_IDENTIFIER = "B64|";
public const char KEYWORD_WILDCARD = '*';
public const int GRAPHEXECPRIORITY_DEFAULT = 0;
public class UserSettings {
private static readonly string PREFKEY_AB_BUILD_CACHE_DIR = "AssetBundles.GraphTool.Cache.AssetBundle";
private static readonly string PREFKEY_AB_BUILD_GRAPH_GUID = "AssetBundles.GraphTool.GraphGuid";
private static readonly string PREFKEY_BATCHBUILD_LASTSELECTEDCOLLECTION = "AssetBundles.GraphTool.LastSelectedCollection";
private static readonly string PREFKEY_BATCHBUILD__USECOLLECTIONSTATE = "AssetBundles.GraphTool.UseCollection";
public static string AssetBundleBuildCacheDir {
get {
var cacheDir = EditorUserSettings.GetConfigValue (PREFKEY_AB_BUILD_CACHE_DIR);
if (string.IsNullOrEmpty (cacheDir)) {
return System.IO.Path.Combine(AssetGraph.AssetGraphBasePath.CachePath, "AssetBundles");
}
return cacheDir;
}
set {
EditorUserSettings.SetConfigValue (PREFKEY_AB_BUILD_CACHE_DIR, value);
}
}
public static string DefaultAssetBundleBuildGraphGuid {
get {
return EditorUserSettings.GetConfigValue (PREFKEY_AB_BUILD_GRAPH_GUID);
}
set {
EditorUserSettings.SetConfigValue (PREFKEY_AB_BUILD_GRAPH_GUID, value);
}
}
public static string BatchBuildLastSelectedCollection {
get {
return EditorUserSettings.GetConfigValue (PREFKEY_BATCHBUILD_LASTSELECTEDCOLLECTION);
}
set {
EditorUserSettings.SetConfigValue (PREFKEY_BATCHBUILD_LASTSELECTEDCOLLECTION, value);
}
}
public static bool BatchBuildUseCollectionState {
get {
return EditorUserSettings.GetConfigValue (PREFKEY_BATCHBUILD__USECOLLECTIONSTATE) == "True";
}
set {
EditorUserSettings.SetConfigValue (PREFKEY_BATCHBUILD__USECOLLECTIONSTATE, value.ToString());
}
}
}
public class Path {
public const string ASSETS_PATH = "Assets/";
/// <summary>
/// Name of the base directory containing the asset graph tool files.
/// Customize this to match your project's setup if you need to change.
/// </summary>
/// <value>The name of the base directory.</value>
public static string ToolDirName { get { return "UnityEngine.AssetGraph"; } }
public static string ScriptTemplatePath { get { return System.IO.Path.Combine(AssetGraphBasePath.BasePath, "Editor/ScriptTemplate"); } }
public static string UserSpacePath { get { return System.IO.Path.Combine(AssetGraphBasePath.BasePath, "Generated/Editor"); } }
public static string CUISpacePath { get { return System.IO.Path.Combine(AssetGraphBasePath.BasePath, "Generated/CUI"); } }
public static string SavedSettingsPath { get { return System.IO.Path.Combine(AssetGraphBasePath.BasePath, "SavedSettings"); } }
public static string BundleBuilderCachePath { get { return UserSettings.AssetBundleBuildCacheDir; } }
public static string DatabasePath { get { return System.IO.Path.Combine(AssetGraphBasePath.TemporalSettingFilePath, "AssetReferenceDB.asset"); } }
public static string EventRecordPath { get { return System.IO.Path.Combine(AssetGraphBasePath.TemporalSettingFilePath, "AssetProcessEventRecord.asset"); } }
public static string BatchBuildConfigPath { get { return System.IO.Path.Combine(SavedSettingsPath, "BatchBuildConfig/BatchBuildConfig.asset"); } }
public static string GUIResourceBasePath { get { return System.IO.Path.Combine(AssetGraphBasePath.BasePath, "Editor/GUI/GraphicResources"); } }
}
public struct BuildAssetBundleOption {
public readonly BuildAssetBundleOptions option;
public readonly string description;
public BuildAssetBundleOption(string desc, BuildAssetBundleOptions opt) {
option = opt;
description = desc;
}
}
public struct BuildPlayerOption {
public readonly BuildOptions option;
public readonly string description;
public BuildPlayerOption(string desc, BuildOptions opt) {
option = opt;
description = desc;
}
}
public static List<BuildAssetBundleOption> BundleOptionSettings = new List<BuildAssetBundleOption> {
new BuildAssetBundleOption("Uncompressed AssetBundle", BuildAssetBundleOptions.UncompressedAssetBundle),
new BuildAssetBundleOption("Disable Write TypeTree", BuildAssetBundleOptions.DisableWriteTypeTree),
new BuildAssetBundleOption("Deterministic AssetBundle", BuildAssetBundleOptions.DeterministicAssetBundle),
new BuildAssetBundleOption("Force Rebuild AssetBundle", BuildAssetBundleOptions.ForceRebuildAssetBundle),
new BuildAssetBundleOption("Ignore TypeTree Changes", BuildAssetBundleOptions.IgnoreTypeTreeChanges),
new BuildAssetBundleOption("Append Hash To AssetBundle Name", BuildAssetBundleOptions.AppendHashToAssetBundleName),
new BuildAssetBundleOption("ChunkBased Compression", BuildAssetBundleOptions.ChunkBasedCompression),
new BuildAssetBundleOption("Strict Mode", BuildAssetBundleOptions.StrictMode)
#if !UNITY_5_5_OR_NEWER
,
// UnityEditor.BuildAssetBundleOptions does no longer have OmitClassVersions available
new BuildAssetBundleOption("Omit Class Versions", BuildAssetBundleOptions.OmitClassVersions)
#endif
};
public static List<BuildPlayerOption> BuildPlayerOptionsSettings = new List<BuildPlayerOption> {
new BuildPlayerOption("Accept External Modification To Player", BuildOptions.AcceptExternalModificationsToPlayer),
new BuildPlayerOption("Allow Debugging", BuildOptions.AllowDebugging),
new BuildPlayerOption("Auto Run Player", BuildOptions.AutoRunPlayer),
new BuildPlayerOption("Build Additional Streamed Scenes", BuildOptions.BuildAdditionalStreamedScenes),
new BuildPlayerOption("Build Scripts Only", BuildOptions.BuildScriptsOnly),
#if UNITY_5_6_OR_NEWER
new BuildPlayerOption("Compress With LZ4", BuildOptions.CompressWithLz4),
#endif
new BuildPlayerOption("Compute CRC", BuildOptions.ComputeCRC),
new BuildPlayerOption("Connect To Host", BuildOptions.ConnectToHost),
new BuildPlayerOption("Connect With Profiler", BuildOptions.ConnectWithProfiler),
new BuildPlayerOption("Development Build", BuildOptions.Development),
new BuildPlayerOption("Enable Headless Mode", BuildOptions.EnableHeadlessMode),
new BuildPlayerOption("Force Enable Assertions", BuildOptions.ForceEnableAssertions),
#if !UNITY_2017_1_OR_NEWER
new BuildPlayerOption("Force Optimize Script Compilation", BuildOptions.ForceOptimizeScriptCompilation),
#endif
#if !UNITY_2018_1_OR_NEWER
new BuildPlayerOption("Use IL2CPP", BuildOptions.Il2CPP),
#endif
new BuildPlayerOption("Install In Build Folder", BuildOptions.InstallInBuildFolder),
new BuildPlayerOption("Show Built Player", BuildOptions.ShowBuiltPlayer),
new BuildPlayerOption("Strict Mode", BuildOptions.StrictMode),
new BuildPlayerOption("Symlink Libraries", BuildOptions.SymlinkLibraries),
new BuildPlayerOption("Uncompressed AssetBundle", BuildOptions.UncompressedAssetBundle)
};
public const float WINDOW_SPAN = 20f;
public const string GROUPING_KEYWORD_DEFAULT = "/Group_*/";
public const string BUNDLECONFIG_BUNDLENAME_TEMPLATE_DEFAULT = "bundle_*";
// by default, AssetBundleGraph's node has only 1 InputPoint. and
// this is only one definition of it's label.
public const string DEFAULT_INPUTPOINT_LABEL = "-";
public const string DEFAULT_OUTPUTPOINT_LABEL = "+";
public const string BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL = "bundles";
public const string BUNDLECONFIG_VARIANTNAME_DEFAULT = "";
public const string DEFAULT_FILTER_KEYWORD = "";
public const string DEFAULT_FILTER_KEYTYPE = "Any";
public const string FILTER_KEYWORD_WILDCARD = "*";
public const string NODE_INPUTPOINT_FIXED_LABEL = "FIXED_INPUTPOINT_ID";
public class GUI {
public const float NODE_BASE_WIDTH = 120f;
public const float NODE_BASE_HEIGHT = 40f;
public const float NODE_WIDTH_MARGIN = 48f;
public const float NODE_TITLE_HEIGHT_MARGIN = 8f;
public const float CONNECTION_ARROW_WIDTH = 12f;
public const float CONNECTION_ARROW_HEIGHT = 15f;
public const float INPUT_POINT_WIDTH = 21f;
public const float INPUT_POINT_HEIGHT = 29f;
public const float OUTPUT_POINT_WIDTH = 10f;
public const float OUTPUT_POINT_HEIGHT = 23f;
public const float FILTER_OUTPUT_SPAN = 32f;
public const float CONNECTION_POINT_MARK_SIZE = 16f;
public const float CONNECTION_CURVE_LENGTH = 20f;
public const float TOOLBAR_HEIGHT = 20f;
public const float TOOLBAR_GRAPHNAMEMENU_WIDTH = 150f;
public const int TOOLBAR_GRAPHNAMEMENU_CHAR_LENGTH = 20;
public static readonly Color COLOR_ENABLED = new Color(0.43f, 0.65f, 1.0f, 1.0f);
public static readonly Color COLOR_CONNECTED = new Color(0.9f, 0.9f, 0.9f, 1.0f);
public static readonly Color COLOR_NOT_CONNECTED = Color.grey;
public static readonly Color COLOR_CAN_CONNECT = Color.white;//new Color(0.60f, 0.60f, 1.0f, 1.0f);
public static readonly Color COLOR_CAN_NOT_CONNECT = new Color(0.33f, 0.33f, 0.33f, 1.0f);
public static string Skin { get { return System.IO.Path.Combine(Path.GUIResourceBasePath, "NodeStyle.guiskin"); } }
public static string ConnectionPoint { get { return System.IO.Path.Combine(Path.GUIResourceBasePath, "ConnectionPoint.png"); } }
public static string InputBG { get { return System.IO.Path.Combine(Path.GUIResourceBasePath, "InputBG.png"); } }
public static string OutputBG { get { return System.IO.Path.Combine(Path.GUIResourceBasePath, "OutputBG.png"); } }
public static string GraphIcon { get { return System.IO.Path.Combine(Path.GUIResourceBasePath, "ConfigGraphIcon.psd"); } }
public static string WindowIcon { get { return System.IO.Path.Combine(Path.GUIResourceBasePath, "AssetGraphWindow.png"); } }
public static string WindowIconPro { get { return System.IO.Path.Combine(Path.GUIResourceBasePath, "d_AssetGraphWindow.png"); } }
}
}
}
| |
//
// TypeSystem.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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 Mono.Cecil.Metadata;
namespace Mono.Cecil
{
public abstract class TypeSystem
{
sealed class CoreTypeSystem : TypeSystem
{
public CoreTypeSystem(ModuleDefinition module)
: base(module)
{
}
internal override TypeReference LookupType(string @namespace, string name)
{
var type = LookupTypeDefinition(@namespace, name) ?? LookupTypeForwarded(@namespace, name);
if (type != null)
return type;
throw new NotSupportedException();
}
TypeReference LookupTypeDefinition(string @namespace, string name)
{
var metadata = module.MetadataSystem;
if (metadata.Types == null)
Initialize(module.Types);
return module.Read(new Row<string, string>(@namespace, name), (row, reader) =>
{
var types = reader.metadata.Types;
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
types[i] = reader.GetTypeDefinition((uint)i + 1);
var type = types[i];
if (type.Name == row.Col2 && type.Namespace == row.Col1)
return type;
}
return null;
});
}
TypeReference LookupTypeForwarded(string @namespace, string name)
{
if (!module.HasExportedTypes)
return null;
var exported_types = module.ExportedTypes;
for (int i = 0; i < exported_types.Count; i++)
{
var exported_type = exported_types[i];
if (exported_type.Name == name && exported_type.Namespace == @namespace)
return exported_type.CreateReference();
}
return null;
}
static void Initialize(object obj)
{
}
}
sealed class CommonTypeSystem : TypeSystem
{
AssemblyNameReference corlib;
public CommonTypeSystem(ModuleDefinition module)
: base(module)
{
}
internal override TypeReference LookupType(string @namespace, string name)
{
return CreateTypeReference(@namespace, name);
}
public AssemblyNameReference GetCorlibReference()
{
if (corlib != null)
return corlib;
const string mscorlib = "mscorlib";
const string systemruntime = "System.Runtime";
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++)
{
var reference = references[i];
if (reference.Name == mscorlib || reference.Name == systemruntime)
return corlib = reference;
}
corlib = new AssemblyNameReference
{
Name = mscorlib,
Version = GetCorlibVersion(),
PublicKeyToken = new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },
};
references.Add(corlib);
return corlib;
}
Version GetCorlibVersion()
{
switch (module.Runtime)
{
case TargetRuntime.Net_1_0:
case TargetRuntime.Net_1_1:
return new Version(1, 0, 0, 0);
case TargetRuntime.Net_2_0:
return new Version(2, 0, 0, 0);
case TargetRuntime.Net_4_0:
return new Version(4, 0, 0, 0);
default:
throw new NotSupportedException();
}
}
TypeReference CreateTypeReference(string @namespace, string name)
{
return new TypeReference(@namespace, name, module, GetCorlibReference());
}
}
readonly ModuleDefinition module;
TypeReference type_object;
TypeReference type_void;
TypeReference type_bool;
TypeReference type_char;
TypeReference type_sbyte;
TypeReference type_byte;
TypeReference type_int16;
TypeReference type_uint16;
TypeReference type_int32;
TypeReference type_uint32;
TypeReference type_int64;
TypeReference type_uint64;
TypeReference type_single;
TypeReference type_double;
TypeReference type_intptr;
TypeReference type_uintptr;
TypeReference type_string;
TypeReference type_typedref;
TypeSystem(ModuleDefinition module)
{
this.module = module;
}
internal static TypeSystem CreateTypeSystem(ModuleDefinition module)
{
if (Mixin.IsCorlib(module))
return new CoreTypeSystem(module);
return new CommonTypeSystem(module);
}
internal abstract TypeReference LookupType(string @namespace, string name);
TypeReference LookupSystemType(ref TypeReference typeRef, string name, ElementType element_type)
{
lock (module.SyncRoot)
{
if (typeRef != null)
return typeRef;
var type = LookupType("System", name);
type.etype = element_type;
return typeRef = type;
}
}
TypeReference LookupSystemValueType(ref TypeReference typeRef, string name, ElementType element_type)
{
lock (module.SyncRoot)
{
if (typeRef != null)
return typeRef;
var type = LookupType("System", name);
type.etype = element_type;
type.IsValueType = true;
return typeRef = type;
}
}
public IMetadataScope Corlib
{
get
{
var common = this as CommonTypeSystem;
if (common == null)
return module;
return common.GetCorlibReference();
}
}
public TypeReference Object
{
get { return type_object ?? (LookupSystemType(ref type_object, "Object", ElementType.Object)); }
}
public TypeReference Void
{
get { return type_void ?? (LookupSystemType(ref type_void, "Void", ElementType.Void)); }
}
public TypeReference Boolean
{
get { return type_bool ?? (LookupSystemValueType(ref type_bool, "Boolean", ElementType.Boolean)); }
}
public TypeReference Char
{
get { return type_char ?? (LookupSystemValueType(ref type_char, "Char", ElementType.Char)); }
}
public TypeReference SByte
{
get { return type_sbyte ?? (LookupSystemValueType(ref type_sbyte, "SByte", ElementType.I1)); }
}
public TypeReference Byte
{
get { return type_byte ?? (LookupSystemValueType(ref type_byte, "Byte", ElementType.U1)); }
}
public TypeReference Int16
{
get { return type_int16 ?? (LookupSystemValueType(ref type_int16, "Int16", ElementType.I2)); }
}
public TypeReference UInt16
{
get { return type_uint16 ?? (LookupSystemValueType(ref type_uint16, "UInt16", ElementType.U2)); }
}
public TypeReference Int32
{
get { return type_int32 ?? (LookupSystemValueType(ref type_int32, "Int32", ElementType.I4)); }
}
public TypeReference UInt32
{
get { return type_uint32 ?? (LookupSystemValueType(ref type_uint32, "UInt32", ElementType.U4)); }
}
public TypeReference Int64
{
get { return type_int64 ?? (LookupSystemValueType(ref type_int64, "Int64", ElementType.I8)); }
}
public TypeReference UInt64
{
get { return type_uint64 ?? (LookupSystemValueType(ref type_uint64, "UInt64", ElementType.U8)); }
}
public TypeReference Single
{
get { return type_single ?? (LookupSystemValueType(ref type_single, "Single", ElementType.R4)); }
}
public TypeReference Double
{
get { return type_double ?? (LookupSystemValueType(ref type_double, "Double", ElementType.R8)); }
}
public TypeReference IntPtr
{
get { return type_intptr ?? (LookupSystemValueType(ref type_intptr, "IntPtr", ElementType.I)); }
}
public TypeReference UIntPtr
{
get { return type_uintptr ?? (LookupSystemValueType(ref type_uintptr, "UIntPtr", ElementType.U)); }
}
public TypeReference String
{
get { return type_string ?? (LookupSystemType(ref type_string, "String", ElementType.String)); }
}
public TypeReference TypedReference
{
get { return type_typedref ?? (LookupSystemValueType(ref type_typedref, "TypedReference", ElementType.TypedByRef)); }
}
}
}
| |
// 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.
namespace Microsoft.Xml
{
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Xml;
using Microsoft.Xml.Schema;
/// <summary>
/// This writer implements XmlOutputMethod.AutoDetect. If the first element is "html", then output will be
/// directed to an Html writer. Otherwise, output will be directed to an Xml writer.
/// </summary>
internal class XmlAutoDetectWriter : XmlRawWriter, IRemovableWriter
{
private XmlRawWriter _wrapped;
private OnRemoveWriter _onRemove;
private XmlWriterSettings _writerSettings;
private XmlEventCache _eventCache; // Cache up events until first StartElement is encountered
private TextWriter _textWriter;
private Stream _strm;
//-----------------------------------------------
// Constructors
//-----------------------------------------------
private XmlAutoDetectWriter(XmlWriterSettings writerSettings)
{
Debug.Assert(writerSettings.OutputMethod == XmlOutputMethod.AutoDetect);
_writerSettings = (XmlWriterSettings)writerSettings.Clone();
_writerSettings.ReadOnly = true;
// Start caching all events
_eventCache = new XmlEventCache(string.Empty, true);
}
public XmlAutoDetectWriter(TextWriter textWriter, XmlWriterSettings writerSettings)
: this(writerSettings)
{
_textWriter = textWriter;
}
public XmlAutoDetectWriter(Stream strm, XmlWriterSettings writerSettings)
: this(writerSettings)
{
_strm = strm;
}
//-----------------------------------------------
// IRemovableWriter interface
//-----------------------------------------------
/// <summary>
/// This writer will raise this event once it has determined whether to replace itself with the Html or Xml writer.
/// </summary>
public OnRemoveWriter OnRemoveWriterEvent
{
get { return _onRemove; }
set { _onRemove = value; }
}
//-----------------------------------------------
// XmlWriter interface
//-----------------------------------------------
public override XmlWriterSettings Settings
{
get { return _writerSettings; }
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
if (_wrapped == null)
{
// This is the first time WriteStartElement has been called, so create the Xml or Html writer
if (ns.Length == 0 && IsHtmlTag(localName))
CreateWrappedWriter(XmlOutputMethod.Html);
else
CreateWrappedWriter(XmlOutputMethod.Xml);
}
_wrapped.WriteStartElement(prefix, localName, ns);
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
Debug.Assert(_wrapped != null);
_wrapped.WriteEndAttribute();
}
public override void WriteCData(string text)
{
if (TextBlockCreatesWriter(text))
_wrapped.WriteCData(text);
else
_eventCache.WriteCData(text);
}
public override void WriteComment(string text)
{
if (_wrapped == null)
_eventCache.WriteComment(text);
else
_wrapped.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
if (_wrapped == null)
_eventCache.WriteProcessingInstruction(name, text);
else
_wrapped.WriteProcessingInstruction(name, text);
}
public override void WriteWhitespace(string ws)
{
if (_wrapped == null)
_eventCache.WriteWhitespace(ws);
else
_wrapped.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
if (TextBlockCreatesWriter(text))
_wrapped.WriteString(text);
else
_eventCache.WriteString(text);
}
public override void WriteChars(char[] buffer, int index, int count)
{
WriteString(new string(buffer, index, count));
}
public override void WriteRaw(char[] buffer, int index, int count)
{
WriteRaw(new string(buffer, index, count));
}
public override void WriteRaw(string data)
{
if (TextBlockCreatesWriter(data))
_wrapped.WriteRaw(data);
else
_eventCache.WriteRaw(data);
}
public override void WriteEntityRef(string name)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteCharEntity(ch);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteBase64(buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteBinHex(buffer, index, count);
}
public override void Close()
{
// Flush any cached events to an Xml writer
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.Close();
}
public override void Flush()
{
// Flush any cached events to an Xml writer
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.Flush();
}
public override void WriteValue(object value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(string value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(bool value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(DateTimeOffset value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(double value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(float value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(decimal value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(int value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(long value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
//-----------------------------------------------
// XmlRawWriter interface
//-----------------------------------------------
internal override IXmlNamespaceResolver NamespaceResolver
{
get
{
return this.resolver;
}
set
{
this.resolver = value;
if (_wrapped == null)
_eventCache.NamespaceResolver = value;
else
_wrapped.NamespaceResolver = value;
}
}
internal override void WriteXmlDeclaration(XmlStandalone standalone)
{
// Forces xml writer to be created
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteXmlDeclaration(standalone);
}
internal override void WriteXmlDeclaration(string xmldecl)
{
// Forces xml writer to be created
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteXmlDeclaration(xmldecl);
}
internal override void StartElementContent()
{
Debug.Assert(_wrapped != null);
_wrapped.StartElementContent();
}
internal override void WriteEndElement(string prefix, string localName, string ns)
{
Debug.Assert(_wrapped != null);
_wrapped.WriteEndElement(prefix, localName, ns);
}
internal override void WriteFullEndElement(string prefix, string localName, string ns)
{
Debug.Assert(_wrapped != null);
_wrapped.WriteFullEndElement(prefix, localName, ns);
}
internal override void WriteNamespaceDeclaration(string prefix, string ns)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteNamespaceDeclaration(prefix, ns);
}
internal override bool SupportsNamespaceDeclarationInChunks
{
get
{
return _wrapped.SupportsNamespaceDeclarationInChunks;
}
}
internal override void WriteStartNamespaceDeclaration(string prefix)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteStartNamespaceDeclaration(prefix);
}
internal override void WriteEndNamespaceDeclaration()
{
_wrapped.WriteEndNamespaceDeclaration();
}
//-----------------------------------------------
// Helper methods
//-----------------------------------------------
/// <summary>
/// Return true if "tagName" == "html" (case-insensitive).
/// </summary>
private static bool IsHtmlTag(string tagName)
{
if (tagName.Length != 4)
return false;
if (tagName[0] != 'H' && tagName[0] != 'h')
return false;
if (tagName[1] != 'T' && tagName[1] != 't')
return false;
if (tagName[2] != 'M' && tagName[2] != 'm')
return false;
if (tagName[3] != 'L' && tagName[3] != 'l')
return false;
return true;
}
/// <summary>
/// If a wrapped writer has not yet been created, create one.
/// </summary>
private void EnsureWrappedWriter(XmlOutputMethod outMethod)
{
if (_wrapped == null)
CreateWrappedWriter(outMethod);
}
/// <summary>
/// If the specified text consist only of whitespace, then cache the whitespace, as it is not enough to
/// force the creation of a wrapped writer. Otherwise, create a wrapped writer if one has not yet been
/// created and return true.
/// </summary>
private bool TextBlockCreatesWriter(string textBlock)
{
if (_wrapped == null)
{
// Whitespace-only text blocks aren't enough to determine Xml vs. Html
if (XmlCharType.Instance.IsOnlyWhitespace(textBlock))
{
return false;
}
// Non-whitespace text block selects Xml method
CreateWrappedWriter(XmlOutputMethod.Xml);
}
return true;
}
/// <summary>
/// Create either the Html or Xml writer and send any cached events to it.
/// </summary>
private void CreateWrappedWriter(XmlOutputMethod outMethod)
{
Debug.Assert(_wrapped == null);
// Create either the Xml or Html writer
_writerSettings.ReadOnly = false;
_writerSettings.OutputMethod = outMethod;
// If Indent was not set by the user, then default to True for Html
if (outMethod == XmlOutputMethod.Html && _writerSettings.IndentInternal == TriState.Unknown)
_writerSettings.Indent = true;
_writerSettings.ReadOnly = true;
if (_textWriter != null)
_wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_textWriter, _writerSettings)).RawWriter;
else
_wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_strm, _writerSettings)).RawWriter;
// Send cached events to the new writer
_eventCache.EndEvents();
_eventCache.EventsToWriter(_wrapped);
// Send OnRemoveWriter event
if (_onRemove != null)
(this._onRemove)(_wrapped);
}
}
}
| |
// 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.Collections.Generic;
using System.Linq;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis.Values {
/// <summary>
/// Represents an instance of a class implemented in Python
/// </summary>
internal class InstanceInfo : AnalysisValue, IReferenceableContainer {
private readonly ClassInfo _classInfo;
private Dictionary<string, VariableDef> _instanceAttrs;
public InstanceInfo(ClassInfo classInfo) {
_classInfo = classInfo;
}
public override IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext, GetMemberOptions options = GetMemberOptions.None) {
var res = new Dictionary<string, IAnalysisSet>();
if (_instanceAttrs != null) {
foreach (var kvp in _instanceAttrs) {
var types = kvp.Value.TypesNoCopy;
var key = kvp.Key;
kvp.Value.ClearOldValues();
if (kvp.Value.VariableStillExists) {
MergeTypes(res, key, types);
}
}
}
// check and see if it's defined in a base class instance as well...
if (!options.HasFlag(GetMemberOptions.DeclaredOnly)) {
foreach (var b in _classInfo.Bases) {
foreach (var ns in b) {
if (ns.Push()) {
try {
ClassInfo baseClass = ns as ClassInfo;
if (baseClass != null &&
baseClass.Instance._instanceAttrs != null) {
foreach (var kvp in baseClass.Instance._instanceAttrs) {
kvp.Value.ClearOldValues();
if (kvp.Value.VariableStillExists) {
MergeTypes(res, kvp.Key, kvp.Value.TypesNoCopy);
}
}
}
} finally {
ns.Pop();
}
}
}
}
foreach (var classMem in _classInfo.GetAllMembers(moduleContext)) {
MergeTypes(res, classMem.Key, classMem.Value);
}
}
return res;
}
private static void MergeTypes(Dictionary<string, IAnalysisSet> res, string key, IEnumerable<AnalysisValue> types) {
IAnalysisSet set;
if (!res.TryGetValue(key, out set)) {
res[key] = set = AnalysisSet.Create(types);
} else {
res[key] = set.Union(types);
}
}
public Dictionary<string, VariableDef> InstanceAttributes {
get {
return _instanceAttrs;
}
}
public PythonAnalyzer ProjectState {
get {
return _classInfo.AnalysisUnit.ProjectState;
}
}
public override IEnumerable<OverloadResult> Overloads {
get {
IAnalysisSet callRes;
if (_classInfo.GetAllMembers(ProjectState._defaultContext).TryGetValue("__call__", out callRes)) {
foreach (var overload in callRes.SelectMany(av => av.Overloads)) {
yield return overload.WithNewParameters(
overload.Parameters.Skip(1).ToArray()
);
}
}
foreach (var overload in base.Overloads) {
yield return overload;
}
}
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var res = base.Call(node, unit, args, keywordArgNames);
if (Push()) {
try {
var callRes = GetTypeMember(node, unit, "__call__");
if (callRes.Any()) {
res = res.Union(callRes.Call(node, unit, args, keywordArgNames));
}
} finally {
Pop();
}
}
return res;
}
public override IAnalysisSet GetTypeMember(Node node, AnalysisUnit unit, string name) {
var result = AnalysisSet.Empty;
var classMem = _classInfo.GetMemberNoReferences(node, unit, name);
if (classMem.Count > 0) {
result = classMem.GetDescriptor(node, this, _classInfo, unit);
if (result.Count > 0) {
// TODO: Check if it's a data descriptor...
}
return result;
} else {
// if the class gets a value later we need to be re-analyzed
_classInfo.Scope.CreateEphemeralVariable(node, unit, name, false).AddDependency(unit);
}
return result;
}
public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) {
// __getattribute__ takes precedence over everything.
IAnalysisSet getattrRes = AnalysisSet.Empty;
var getAttribute = _classInfo.GetMemberNoReferences(node, unit.CopyForEval(), "__getattribute__");
if (getAttribute.Count > 0) {
foreach (var getAttrFunc in getAttribute) {
var func = getAttrFunc as BuiltinMethodInfo;
if (func != null && func.Function.DeclaringType.TypeId == BuiltinTypeId.Object) {
continue;
}
// TODO: We should really do a get descriptor / call here
getattrRes = getattrRes.Union(getAttrFunc.Call(node, unit, new[] { SelfSet, ProjectState.ClassInfos[BuiltinTypeId.Str].Instance.SelfSet }, ExpressionEvaluator.EmptyNames));
}
}
// ok, it must be an instance member, or it will become one later
VariableDef def;
if (_instanceAttrs == null) {
_instanceAttrs = new Dictionary<string, VariableDef>();
}
if (!_instanceAttrs.TryGetValue(name, out def)) {
_instanceAttrs[name] = def = new EphemeralVariableDef();
}
def.AddReference(node, unit);
def.AddDependency(unit);
// now check class members
var res = GetTypeMember(node, unit, name);
res = res.Union(def.Types);
// check and see if it's defined in a base class instance as well...
foreach (var b in _classInfo.Bases) {
foreach (var ns in b) {
if (ns.Push()) {
try {
ClassInfo baseClass = ns as ClassInfo;
if (baseClass != null &&
baseClass.Instance._instanceAttrs != null &&
baseClass.Instance._instanceAttrs.TryGetValue(name, out def)) {
res = res.Union(def.GetTypesNoCopy(unit, DeclaringModule));
}
} finally {
ns.Pop();
}
}
}
}
if (res.Count == 0) {
// and if that doesn't exist fall back to __getattr__
var getAttr = _classInfo.GetMemberNoReferences(node, unit, "__getattr__");
if (getAttr.Count > 0) {
foreach (var getAttrFunc in getAttr) {
getattrRes = getattrRes.Union(getAttr.Call(node, unit, new[] { SelfSet, _classInfo.AnalysisUnit.ProjectState.ClassInfos[BuiltinTypeId.Str].Instance.SelfSet }, ExpressionEvaluator.EmptyNames));
}
}
return getattrRes;
}
return res;
}
public override IAnalysisSet GetDescriptor(Node node, AnalysisValue instance, AnalysisValue context, AnalysisUnit unit) {
if (Push()) {
try {
var getter = GetTypeMember(node, unit, "__get__");
if (getter.Count > 0) {
var get = getter.GetDescriptor(node, this, _classInfo, unit);
return get.Call(node, unit, new[] { instance, context }, ExpressionEvaluator.EmptyNames);
}
} finally {
Pop();
}
}
return SelfSet;
}
public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) {
if (_instanceAttrs == null) {
_instanceAttrs = new Dictionary<string, VariableDef>();
}
VariableDef instMember;
if (!_instanceAttrs.TryGetValue(name, out instMember) || instMember == null) {
_instanceAttrs[name] = instMember = new VariableDef();
}
instMember.AddAssignment(node, unit);
instMember.MakeUnionStrongerIfMoreThan(ProjectState.Limits.InstanceMembers, value);
instMember.AddTypes(unit, value, true, DeclaringModule);
}
public override void DeleteMember(Node node, AnalysisUnit unit, string name) {
if (_instanceAttrs == null) {
_instanceAttrs = new Dictionary<string, VariableDef>();
}
VariableDef instMember;
if (!_instanceAttrs.TryGetValue(name, out instMember) || instMember == null) {
_instanceAttrs[name] = instMember = new VariableDef();
}
instMember.AddReference(node, unit);
_classInfo.GetMember(node, unit, name);
}
public override IAnalysisSet UnaryOperation(Node node, AnalysisUnit unit, PythonOperator operation) {
if (operation == PythonOperator.Not) {
return unit.ProjectState.ClassInfos[BuiltinTypeId.Bool].Instance;
}
string methodName = UnaryOpToString(unit.ProjectState, operation);
if (methodName != null) {
var method = GetTypeMember(node, unit, methodName);
if (method.Count > 0) {
var res = method.Call(
node,
unit,
new[] { this },
ExpressionEvaluator.EmptyNames
);
return res;
}
}
return base.UnaryOperation(node, unit, operation);
}
internal static string UnaryOpToString(PythonAnalyzer state, PythonOperator operation) {
string op = null;
switch (operation) {
case PythonOperator.Not: op = state.LanguageVersion.Is3x() ? "__bool__" : "__nonzero__"; break;
case PythonOperator.Pos: op = "__pos__"; break;
case PythonOperator.Invert: op = "__invert__"; break;
case PythonOperator.Negate: op = "__neg__"; break;
}
return op;
}
public override IAnalysisSet BinaryOperation(Node node, AnalysisUnit unit, PythonOperator operation, IAnalysisSet rhs) {
string op = BinaryOpToString(operation);
if (op != null) {
var invokeMem = GetTypeMember(node, unit, op);
if (invokeMem.Count > 0) {
// call __*__ method
return invokeMem.Call(node, unit, new[] { rhs }, ExpressionEvaluator.EmptyNames);
}
}
return base.BinaryOperation(node, unit, operation, rhs);
}
internal static string BinaryOpToString(PythonOperator operation) {
string op = null;
switch (operation) {
case PythonOperator.Multiply: op = "__mul__"; break;
case PythonOperator.MatMultiply: op = "__matmul__"; break;
case PythonOperator.Add: op = "__add__"; break;
case PythonOperator.Subtract: op = "__sub__"; break;
case PythonOperator.Xor: op = "__xor__"; break;
case PythonOperator.BitwiseAnd: op = "__and__"; break;
case PythonOperator.BitwiseOr: op = "__or__"; break;
case PythonOperator.Divide: op = "__div__"; break;
case PythonOperator.FloorDivide: op = "__floordiv__"; break;
case PythonOperator.LeftShift: op = "__lshift__"; break;
case PythonOperator.Mod: op = "__mod__"; break;
case PythonOperator.Power: op = "__pow__"; break;
case PythonOperator.RightShift: op = "__rshift__"; break;
case PythonOperator.TrueDivide: op = "__truediv__"; break;
}
return op;
}
public override IAnalysisSet ReverseBinaryOperation(Node node, AnalysisUnit unit, PythonOperator operation, IAnalysisSet rhs) {
string op = ReverseBinaryOpToString(operation);
if (op != null) {
var invokeMem = GetTypeMember(node, unit, op);
if (invokeMem.Count > 0) {
// call __r*__ method
return invokeMem.Call(node, unit, new[] { rhs }, ExpressionEvaluator.EmptyNames);
}
}
return base.ReverseBinaryOperation(node, unit, operation, rhs);
}
private static string ReverseBinaryOpToString(PythonOperator operation) {
string op = null;
switch (operation) {
case PythonOperator.Multiply: op = "__rmul__"; break;
case PythonOperator.MatMultiply: op = "__rmatmul__"; break;
case PythonOperator.Add: op = "__radd__"; break;
case PythonOperator.Subtract: op = "__rsub__"; break;
case PythonOperator.Xor: op = "__rxor__"; break;
case PythonOperator.BitwiseAnd: op = "__rand__"; break;
case PythonOperator.BitwiseOr: op = "__ror__"; break;
case PythonOperator.Divide: op = "__rdiv__"; break;
case PythonOperator.FloorDivide: op = "__rfloordiv__"; break;
case PythonOperator.LeftShift: op = "__rlshift__"; break;
case PythonOperator.Mod: op = "__rmod__"; break;
case PythonOperator.Power: op = "__rpow__"; break;
case PythonOperator.RightShift: op = "__rrshift__"; break;
case PythonOperator.TrueDivide: op = "__rtruediv__"; break;
}
return op;
}
public override IAnalysisSet GetEnumeratorTypes(Node node, AnalysisUnit unit) {
if (Push()) {
try {
var iter = GetIterator(node, unit);
if (iter.Any()) {
return iter
.GetMember(node, unit, unit.ProjectState.LanguageVersion.Is3x() ? "__next__" : "next")
.Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames);
}
} finally {
Pop();
}
}
return base.GetEnumeratorTypes(node, unit);
}
public override IAnalysisSet GetAsyncEnumeratorTypes(Node node, AnalysisUnit unit) {
if (unit.ProjectState.LanguageVersion.Is3x() && Push()) {
try {
var iter = GetAsyncIterator(node, unit);
if (iter.Any()) {
return iter
.GetMember(node, unit, "__anext__")
.Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames)
.Await(node, unit);
}
} finally {
Pop();
}
}
return base.GetAsyncEnumeratorTypes(node, unit);
}
public override IPythonProjectEntry DeclaringModule {
get {
return _classInfo.DeclaringModule;
}
}
public override int DeclaringVersion {
get {
return _classInfo.DeclaringVersion;
}
}
public override string Description {
get {
return ClassInfo.ClassDefinition.Name + " instance";
}
}
public override string Documentation {
get {
return ClassInfo.Documentation;
}
}
public override PythonMemberType MemberType {
get {
return PythonMemberType.Instance;
}
}
internal override bool IsOfType(IAnalysisSet klass) {
return klass.Contains(ClassInfo) || klass.Contains(ProjectState.ClassInfos[BuiltinTypeId.Object]);
}
public ClassInfo ClassInfo {
get { return _classInfo; }
}
public override string ToString() {
return ClassInfo.AnalysisUnit.FullName + " instance";
}
internal override bool UnionEquals(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
if (ns.TypeId == BuiltinTypeId.NoneType) {
// II + BII(None) => do not merge
return false;
}
// II + II => BII(object)
// II + BII => BII(object)
var obj = ProjectState.ClassInfos[BuiltinTypeId.Object];
return ns is InstanceInfo ||
(ns is BuiltinInstanceInfo && ns.TypeId != BuiltinTypeId.Type && ns.TypeId != BuiltinTypeId.Function) ||
ns == obj.Instance;
} else if (strength >= MergeStrength.ToBaseClass) {
var ii = ns as InstanceInfo;
if (ii != null) {
return ii.ClassInfo.UnionEquals(ClassInfo, strength);
}
var bii = ns as BuiltinInstanceInfo;
if (bii != null) {
return bii.ClassInfo.UnionEquals(ClassInfo, strength);
}
}
return base.UnionEquals(ns, strength);
}
internal override int UnionHashCode(int strength) {
if (strength >= MergeStrength.ToObject) {
return ProjectState.ClassInfos[BuiltinTypeId.Object].Instance.UnionHashCode(strength);
} else if (strength >= MergeStrength.ToBaseClass) {
return ClassInfo.UnionHashCode(strength);
}
return base.UnionHashCode(strength);
}
internal override AnalysisValue UnionMergeTypes(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
// II + II => BII(object)
// II + BII => BII(object)
return ProjectState.ClassInfos[BuiltinTypeId.Object].Instance;
} else if (strength >= MergeStrength.ToBaseClass) {
var ii = ns as InstanceInfo;
if (ii != null) {
return ii.ClassInfo.UnionMergeTypes(ClassInfo, strength).GetInstanceType().Single();
}
var bii = ns as BuiltinInstanceInfo;
if (bii != null) {
return bii.ClassInfo.UnionMergeTypes(ClassInfo, strength).GetInstanceType().Single();
}
}
return base.UnionMergeTypes(ns, strength);
}
#region IVariableDefContainer Members
public IEnumerable<IReferenceable> GetDefinitions(string name) {
VariableDef def;
if (_instanceAttrs != null && _instanceAttrs.TryGetValue(name, out def)) {
yield return def;
}
foreach (var classDef in _classInfo.GetDefinitions(name)) {
yield return classDef;
}
}
#endregion
}
}
| |
#if !LOCALTEST
using System.Runtime.CompilerServices;
using System.Text;
namespace System {
public static class Console {
static byte[] ascii2ConsoleKey_Map = new byte[128] {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 9 , 0x00, 0x00, 0x00, 13 , 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 27 , 0x00, 0x00, 0x00, 0x00,
32 , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 ,
80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 ,
80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 0x00, 0x00, 0x00, 0x00, 0x00,
};
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void Write(string s);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static int Internal_ReadKey();
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static bool Internal_KeyAvailable();
#region Write Methods
public static void Write(object value) {
if (value != null) {
Write(value.ToString());
}
}
public static void Write(char value) {
Write(value.ToString());
}
public static void Write(string format, params object[] args) {
Write(string.Format(format, args));
}
public static void Write(string format, object obj1) {
Write(format, new object[] { obj1 });
}
public static void Write(string format, object obj1, object obj2) {
Write(format, new object[] { obj1, obj2 });
}
public static void Write(string format, object obj1, object obj2, object obj3) {
Write(format, new object[] { obj1, obj2, obj3 });
}
public static void Write(string format, object obj1, object obj2, object obj3, object obj4) {
Write(format, new object[] { obj1, obj2, obj3, obj4 });
}
#endregion
#region WriteLine Methods
public static void WriteLine(string value) {
Write(value);
Write(Environment.NewLine);
}
public static void WriteLine() {
WriteLine(string.Empty);
}
public static void WriteLine(bool value) {
WriteLine(value.ToString());
}
public static void WriteLine(sbyte value) {
WriteLine(value.ToString());
}
public static void WriteLine(byte value) {
WriteLine(value.ToString());
}
public static void WriteLine(int value) {
WriteLine(value.ToString());
}
public static void WriteLine(uint value) {
WriteLine(value.ToString());
}
public static void WriteLine(long value) {
WriteLine(value.ToString());
}
public static void WriteLine(ulong value) {
WriteLine(value.ToString());
}
public static void WriteLine(char value) {
WriteLine(value.ToString());
}
public static void WriteLine(float value) {
WriteLine(value.ToString());
}
public static void WriteLine(double value) {
WriteLine(value.ToString());
}
public static void WriteLine(object value) {
if (value == null) {
WriteLine();
} else {
WriteLine(value.ToString());
}
}
public static void WriteLine(string format, params object[] args) {
WriteLine(string.Format(format, args));
}
public static void WriteLine(string format, object obj1) {
WriteLine(format, new object[] { obj1 });
}
public static void WriteLine(string format, object obj1, object obj2) {
WriteLine(format, new object[] { obj1, obj2 });
}
public static void WriteLine(string format, object obj1, object obj2, object obj3) {
WriteLine(format, new object[] { obj1, obj2, obj3 });
}
public static void WriteLine(string format, object obj1, object obj2, object obj3, object obj4) {
WriteLine(format, new object[] { obj1, obj2, obj3, obj4 });
}
#endregion
#region ReadKey Methods
public static bool KeyAvailable {
get {
return Internal_KeyAvailable();
}
}
public static ConsoleKeyInfo ReadKey() {
return ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept) {
int key = Internal_ReadKey();
char c = (char)key;
if (!intercept) {
Write(c);
}
ConsoleKey k;
if (key < 128) {
k = (ConsoleKey)ascii2ConsoleKey_Map[key];
} else {
k = ConsoleKey.Unknown;
}
return new ConsoleKeyInfo(c, k, false, false, false);
}
#endregion
public static string ReadLine()
{
StringBuilder builder = new StringBuilder();
while (true)
{
int num = ReadKey().KeyChar;
switch (num)
{
case -1:
if (builder.Length > 0)
{
return builder.ToString();
}
return null;
case 13:
// case 10:
//if ((num == 13) && (Peek() == 10))
//{
// Read();
//}
return builder.ToString();
case 10: continue;
}
builder.Append((char)num);
}
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using System;
using System.Linq;
using System.Collections.Generic;
namespace VerifyNetworkPeeringWithNetworkWatcher
{
public class Program
{
/**
* Azure Network sample for enabling and updating network peering between two virtual networks
*
* Summary ...
*
* - This sample uses Azure Network Watcher's connectivity check to verify connectivity between
* two peered virtual networks.
*
* Details ...
*
* 1. Define two virtual networks network "A" and network "B" with one subnet each
*
* 2. Create two virtual machines, each within a separate network
* - The virtual machines currently must use a special extension to support Network Watcher
* 3. Peer the networks...
* - the peering will initially have default settings:
* - each network's IP address spaces will be accessible from the other network
* - no traffic forwarding will be enabled between the networks
* - no gateway transit between one network and the other will be enabled
*
* 4. Use Network Watcher to check connectivity between the virtual machines in different peering scenarios:
* - both virtual machines accessible to each other (bi-directional)
* - virtual machine A accessible to virtual machine B, but not the other way
*/
public static void RunSample(IAzure azure)
{
Region region = Region.USEast;
string resourceGroupName = SdkContext.RandomResourceName("rg", 15);
string vnetAName = SdkContext.RandomResourceName("net", 15);
string vnetBName = SdkContext.RandomResourceName("net", 15);
string[] vmNames = SdkContext.RandomResourceNames("vm", 15, 2);
string[] vmIPAddresses = new String[] {
/* within subnetA */ "10.0.0.8",
/* within subnetB */ "10.1.0.8"
};
string peeringABName = SdkContext.RandomResourceName("peer", 15);
string rootname = "tirekicker";
string password = SdkContext.RandomResourceName("pWd!", 15);
string networkWatcherName = SdkContext.RandomResourceName("netwch", 20);
try
{
//=============================================================
// Define two virtual networks to peer and put the virtual machines in, at specific IP addresses
List<ICreatable<INetwork>> networkDefinitions = new List<ICreatable<INetwork>>();
networkDefinitions.Add(azure.Networks.Define(vnetAName)
.WithRegion(region)
.WithNewResourceGroup(resourceGroupName)
.WithAddressSpace("10.0.0.0/27")
.WithSubnet("subnetA", "10.0.0.0/27"));
networkDefinitions.Add(azure.Networks.Define(vnetBName)
.WithRegion(region)
.WithNewResourceGroup(resourceGroupName)
.WithAddressSpace("10.1.0.0/27")
.WithSubnet("subnetB", "10.1.0.0/27"));
//=============================================================
// Define a couple of Windows VMs and place them in each of the networks
List<ICreatable<IVirtualMachine>> vmDefinitions = new List<ICreatable<IVirtualMachine>>();
for (int i = 0; i < networkDefinitions.Count; i++)
{
vmDefinitions.Add(azure.VirtualMachines.Define(vmNames[i])
.WithRegion(region)
.WithExistingResourceGroup(resourceGroupName)
.WithNewPrimaryNetwork(networkDefinitions[i])
.WithPrimaryPrivateIPAddressStatic(vmIPAddresses[i])
.WithoutPrimaryPublicIPAddress()
.WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
.WithAdminUsername(rootname)
.WithAdminPassword(password)
// Extension currently needed for network watcher support
.DefineNewExtension("packetCapture")
.WithPublisher("Microsoft.Azure.NetworkWatcher")
.WithType("NetworkWatcherAgentWindows")
.WithVersion("1.4")
.Attach());
}
// Create the VMs in parallel for better performance
Utilities.Log("Creating virtual machines and virtual networks...");
var createdVMs = azure.VirtualMachines.Create(vmDefinitions);
IVirtualMachine vmA = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[0].Key);
IVirtualMachine vmB = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[1].Key);
Utilities.Log("Created the virtual machines and networks.");
//=============================================================
// Peer the two networks using default settings
INetwork networkA = vmA.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
INetwork networkB = vmB.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
Utilities.PrintVirtualNetwork(networkA);
Utilities.PrintVirtualNetwork(networkB);
Utilities.Log(
"Peering the networks using default settings...\n"
+ "- Network access enabled\n"
+ "- Traffic forwarding disabled\n"
+ "- Gateway use (transit) by the remote network disabled");
INetworkPeering peeringAB = networkA.Peerings.Define(peeringABName)
.WithRemoteNetwork(networkB)
.Create();
Utilities.PrintVirtualNetwork(networkA);
Utilities.PrintVirtualNetwork(networkB);
//=============================================================
// Check connectivity between the two VMs/networks using Network Watcher
INetworkWatcher networkWatcher = azure.NetworkWatchers.Define(networkWatcherName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroupName)
.Create();
// Verify bi-directional connectivity between the VMs on port 22 (SSH enabled by default on Linux VMs)
IExecutable<IConnectivityCheck> connectivityAtoB = networkWatcher.CheckConnectivity()
.ToDestinationAddress(vmIPAddresses[1])
.ToDestinationPort(22)
.FromSourceVirtualMachine(vmA);
Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus);
IExecutable<IConnectivityCheck> connectivityBtoA = networkWatcher.CheckConnectivity()
.ToDestinationAddress(vmIPAddresses[0])
.ToDestinationPort(22)
.FromSourceVirtualMachine(vmB);
Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus);
// Change the peering to allow access between A and B
Utilities.Log("Changing the peering to disable access between A and B...");
peeringAB.Update()
.WithoutAccessFromEitherNetwork()
.Apply();
Utilities.PrintVirtualNetwork(networkA);
Utilities.PrintVirtualNetwork(networkB);
// Verify connectivity no longer possible between A and B
Utilities.Log("Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A...");
Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus);
Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + resourceGroupName);
azure.ResourceGroups.BeginDeleteByName(resourceGroupName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
}
| |
namespace SimpleBlogDemo.Helpers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Dropbox.Api;
using Dropbox.Api.Files;
using SimpleBlogDemo.Models;
public static class BlogHelpers
{
private static Dictionary<string, Article> ArticleCache = new Dictionary<string, Article>();
public static async Task<Article> GetArticle(this DropboxClient client, string blogName, ArticleMetadata metadata, bool bypassCache = false)
{
if (metadata == null || string.IsNullOrEmpty(blogName))
{
return null;
}
var key = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", blogName, metadata.Name);
Article article;
if (!bypassCache)
{
lock (ArticleCache)
{
if (ArticleCache.TryGetValue(key, out article))
{
if (article.Metadata.Rev == metadata.Rev)
{
return article;
}
}
}
}
try
{
using (var download = await client.Files.DownloadAsync("/" + metadata.Filename))
{
var content = await download.GetContentAsStringAsync();
var html = content.ParseMarkdown();
article = Article.FromMetadata(download.Response, html);
}
}
catch (ApiException<DownloadError> e)
{
var pathError = e.ErrorResponse.AsPath;
if (pathError != null && pathError.Value.IsNotFile)
{
return null;
}
throw;
}
lock (ArticleCache)
{
ArticleCache[key] = article;
}
return article;
}
public static void FlushCache(this ControllerBase controller, string blogName)
{
var prefix = blogName + ":";
lock (ArticleCache)
{
var keys = from k in ArticleCache.Keys
where k.StartsWith(prefix)
select k;
foreach (var key in keys)
{
ArticleCache.Remove(key);
}
}
}
public static async Task<IEnumerable<ArticleMetadata>> GetArticleList(this DropboxClient client)
{
var list = await client.Files.ListFolderAsync(string.Empty);
var articles = new List<ArticleMetadata>();
foreach (var item in list.Entries)
{
if (!item.IsFile)
{
continue;
}
var fileMetadata = item.AsFile;
var metadata = ArticleMetadata.Parse(item.Name, fileMetadata.Rev);
if (metadata != null)
{
articles.Add(metadata);
}
}
articles.Sort((l, r) => l.Date.CompareTo(r.Date));
return articles;
}
public static Tuple<string, DateTime, string> ParseBlogFileName(this string filename)
{
var elements = filename.Split('.');
if (elements.Length != 3 || elements[2] != "md" || elements[1].Length != 8)
{
return null;
}
var name = elements[0];
ulong dateInteger;
if (!ulong.TryParse(elements[1], out dateInteger))
{
return null;
}
int year = (int)(dateInteger / 10000);
int month = (int)((dateInteger / 100) % 100);
int day = (int)(dateInteger % 100);
if (month < 1 || month > 12 || day < 1 || day > 31)
{
return null;
}
var date = new DateTime(year, month, day);
return Tuple.Create(
elements[0],
date,
string.Format(CultureInfo.InvariantCulture, "{0}-{1:yyyy-MM-dd}", elements[0], date));
}
}
public class Blog
{
public string BlogName { get; private set; }
public IReadOnlyList<ArticleMetadata> BlogArticles { get; private set; }
public DateTime MostRecent
{
get
{
if (this.BlogArticles.Count == 0)
{
return DateTime.MinValue;
}
return this.BlogArticles.Last().Date;
}
}
public static async Task<Blog> FromUserAsync(UserProfile user)
{
if (string.IsNullOrWhiteSpace(user.BlogName) ||
string.IsNullOrWhiteSpace(user.DropboxAccessToken))
{
return null;
}
using (var client = new DropboxClient(user.DropboxAccessToken, new DropboxClientConfig("SimpleBlogDemo")))
{
return new Blog
{
BlogName = user.BlogName,
BlogArticles = new List<ArticleMetadata>(await client.GetArticleList()).AsReadOnly()
};
}
}
}
public class ArticleMetadata
{
public string Name { get; private set; }
public string DisplayName { get; private set; }
public string Rev { get; private set; }
public DateTime Date { get; private set; }
public string Filename
{
get
{
return string.Format(
CultureInfo.InvariantCulture,
"{0}.{1:yyyyMMdd}.md",
this.Name,
this.Date);
}
}
public static ArticleMetadata Parse(string filename, string rev)
{
var parsed = filename.ParseBlogFileName();
if (parsed == null)
{
return null;
}
return new ArticleMetadata
{
Name = parsed.Item1,
Date = parsed.Item2,
DisplayName = parsed.Item3,
Rev = rev
};
}
}
public class Article
{
public Article(string name, ArticleMetadata metadata, HtmlString content)
{
this.Name = name;
this.Metadata = metadata;
this.Content = content;
}
public string Name { get; private set; }
public ArticleMetadata Metadata { get; private set; }
public HtmlString Content { get; private set; }
public static Article FromMetadata(FileMetadata metadata, HtmlString content)
{
var parsed = metadata.Name.ParseBlogFileName();
return new Article(
metadata.Name,
ArticleMetadata.Parse(metadata.Name, metadata.Rev),
content);
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Linq
{
internal class EnumerableRewriter : ExpressionVisitor
{
// We must ensure that if a LabelTarget is rewritten that it is always rewritten to the same new target
// or otherwise expressions using it won't match correctly.
private Dictionary<LabelTarget, LabelTarget> _targetCache;
// Finding equivalent types can be relatively expensive, and hitting with the same types repeatedly is quite likely.
private Dictionary<Type, Type> _equivalentTypeCache;
protected override Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = this.Visit(m.Object);
ReadOnlyCollection<Expression> args = Visit(m.Arguments);
// check for args changed
if (obj != m.Object || args != m.Arguments)
{
MethodInfo mInfo = m.Method;
Type[] typeArgs = (mInfo.IsGenericMethod) ? mInfo.GetGenericArguments() : null;
if ((mInfo.IsStatic || mInfo.DeclaringType.IsAssignableFrom(obj.Type))
&& ArgsMatch(mInfo, args, typeArgs))
{
// current method is still valid
return Expression.Call(obj, mInfo, args);
}
else if (mInfo.DeclaringType == typeof(Queryable))
{
// convert Queryable method to Enumerable method
MethodInfo seqMethod = FindEnumerableMethod(mInfo.Name, args, typeArgs);
args = this.FixupQuotedArgs(seqMethod, args);
return Expression.Call(obj, seqMethod, args);
}
else
{
// rebind to new method
MethodInfo method = FindMethod(mInfo.DeclaringType, mInfo.Name, args, typeArgs);
args = this.FixupQuotedArgs(method, args);
return Expression.Call(obj, method, args);
}
}
return m;
}
private ReadOnlyCollection<Expression> FixupQuotedArgs(MethodInfo mi, ReadOnlyCollection<Expression> argList)
{
ParameterInfo[] pis = mi.GetParameters();
if (pis.Length > 0)
{
List<Expression> newArgs = null;
for (int i = 0, n = pis.Length; i < n; i++)
{
Expression arg = argList[i];
ParameterInfo pi = pis[i];
arg = FixupQuotedExpression(pi.ParameterType, arg);
if (newArgs == null && arg != argList[i])
{
newArgs = new List<Expression>(argList.Count);
for (int j = 0; j < i; j++)
{
newArgs.Add(argList[j]);
}
}
if (newArgs != null)
{
newArgs.Add(arg);
}
}
if (newArgs != null)
argList = newArgs.AsReadOnly();
}
return argList;
}
private Expression FixupQuotedExpression(Type type, Expression expression)
{
Expression expr = expression;
while (true)
{
if (type.IsAssignableFrom(expr.Type))
return expr;
if (expr.NodeType != ExpressionType.Quote)
break;
expr = ((UnaryExpression)expr).Operand;
}
if (!type.IsAssignableFrom(expr.Type) && type.IsArray && expr.NodeType == ExpressionType.NewArrayInit)
{
Type strippedType = StripExpression(expr.Type);
if (type.IsAssignableFrom(strippedType))
{
Type elementType = type.GetElementType();
NewArrayExpression na = (NewArrayExpression)expr;
List<Expression> exprs = new List<Expression>(na.Expressions.Count);
for (int i = 0, n = na.Expressions.Count; i < n; i++)
{
exprs.Add(this.FixupQuotedExpression(elementType, na.Expressions[i]));
}
expression = Expression.NewArrayInit(elementType, exprs);
}
}
return expression;
}
protected override Expression VisitLambda<T>(Expression<T> node)
{
return node;
}
private static Type GetPublicType(Type t)
{
// If we create a constant explicitly typed to be a private nested type,
// such as Lookup<,>.Grouping or a compiler-generated iterator class, then
// we cannot use the expression tree in a context which has only execution
// permissions. We should endeavour to translate constants into
// new constants which have public types.
TypeInfo typeInfo = t.GetTypeInfo();
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition().GetTypeInfo().ImplementedInterfaces.Contains(typeof(IGrouping<,>)))
return typeof(IGrouping<,>).MakeGenericType(t.GetGenericArguments());
if (!typeInfo.IsNestedPrivate)
return t;
foreach (Type iType in typeInfo.ImplementedInterfaces)
{
TypeInfo iTypeInfo = iType.GetTypeInfo();
if (iTypeInfo.IsGenericType && iTypeInfo.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return iType;
}
if (typeof(IEnumerable).IsAssignableFrom(t))
return typeof(IEnumerable);
return t;
}
private Type GetEquivalentType(Type type)
{
Type equiv;
if (_equivalentTypeCache == null)
{
// Pre-loading with the non-generic IQueryable and IEnumerable not only covers this case
// without any reflection-based interspection, but also means the slightly different
// code needed to catch this case can be omitted safely.
_equivalentTypeCache = new Dictionary<Type, Type>
{
{ typeof(IQueryable), typeof(IEnumerable) },
{ typeof(IEnumerable), typeof(IEnumerable) }
};
}
if (!_equivalentTypeCache.TryGetValue(type, out equiv))
{
Type pubType = GetPublicType(type);
TypeInfo info = pubType.GetTypeInfo();
if (info.IsInterface && info.IsGenericType)
{
Type genericType = info.GetGenericTypeDefinition();
if (genericType == typeof(IOrderedEnumerable<>))
equiv = pubType;
else if (genericType == typeof(IOrderedQueryable<>))
equiv = typeof(IOrderedEnumerable<>).MakeGenericType(info.GenericTypeArguments[0]);
else if (genericType == typeof(IEnumerable<>))
equiv = pubType;
else if (genericType == typeof(IQueryable<>))
equiv = typeof(IEnumerable<>).MakeGenericType(info.GenericTypeArguments[0]);
}
if (equiv == null)
{
var interfacesWithInfo = info.ImplementedInterfaces.Select(i => new { Type = i, Info = i.GetTypeInfo() }).ToArray();
var singleTypeGenInterfacesWithGetType = interfacesWithInfo
.Where(i => i.Info.IsGenericType && i.Info.GenericTypeArguments.Length == 1)
.Select(i => new { Type = i.Type, Info = i.Info, GenType = i.Info.GetGenericTypeDefinition() });
Type typeArg = singleTypeGenInterfacesWithGetType.Where(i => i.GenType == typeof(IOrderedQueryable<>) || i.GenType == typeof(IOrderedEnumerable<>)).Select(i => i.Info.GenericTypeArguments[0]).Distinct().SingleOrDefault();
if (typeArg != null)
equiv = typeof(IOrderedEnumerable<>).MakeGenericType(typeArg);
else
{
typeArg = singleTypeGenInterfacesWithGetType.Where(i => i.GenType == typeof(IQueryable<>) || i.GenType == typeof(IEnumerable<>)).Select(i => i.Info.GenericTypeArguments[0]).Distinct().Single();
equiv = typeof(IEnumerable<>).MakeGenericType(typeArg);
}
}
_equivalentTypeCache.Add(type, equiv);
}
return equiv;
}
protected override Expression VisitConstant(ConstantExpression c)
{
EnumerableQuery sq = c.Value as EnumerableQuery;
if (sq != null)
{
if (sq.Enumerable != null)
{
Type t = GetPublicType(sq.Enumerable.GetType());
return Expression.Constant(sq.Enumerable, t);
}
Expression exp = sq.Expression;
if (exp != c)
return Visit(exp);
}
return c;
}
private static volatile ILookup<string, MethodInfo> s_seqMethods;
private static MethodInfo FindEnumerableMethod(string name, ReadOnlyCollection<Expression> args, params Type[] typeArgs)
{
if (s_seqMethods == null)
{
s_seqMethods = typeof(Enumerable).GetStaticMethods().ToLookup(m => m.Name);
}
MethodInfo mi = s_seqMethods[name].FirstOrDefault(m => ArgsMatch(m, args, typeArgs));
Debug.Assert(mi != null, "All static methods with arguments on Queryable have equivalents on Enumerable.");
if (typeArgs != null)
return mi.MakeGenericMethod(typeArgs);
return mi;
}
private static MethodInfo FindMethod(Type type, string name, ReadOnlyCollection<Expression> args, Type[] typeArgs)
{
using (IEnumerator<MethodInfo> en = type.GetStaticMethods().Where(m => m.Name == name).GetEnumerator())
{
if (!en.MoveNext())
throw Error.NoMethodOnType(name, type);
do
{
MethodInfo mi = en.Current;
if (ArgsMatch(mi, args, typeArgs))
return (typeArgs != null) ? mi.MakeGenericMethod(typeArgs) : mi;
} while (en.MoveNext());
}
throw Error.NoMethodOnTypeMatchingArguments(name, type);
}
private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection<Expression> args, Type[] typeArgs)
{
ParameterInfo[] mParams = m.GetParameters();
if (mParams.Length != args.Count)
return false;
if (!m.IsGenericMethod && typeArgs != null && typeArgs.Length > 0)
{
return false;
}
if (!m.IsGenericMethodDefinition && m.IsGenericMethod && m.ContainsGenericParameters)
{
m = m.GetGenericMethodDefinition();
}
if (m.IsGenericMethodDefinition)
{
if (typeArgs == null || typeArgs.Length == 0)
return false;
if (m.GetGenericArguments().Length != typeArgs.Length)
return false;
m = m.MakeGenericMethod(typeArgs);
mParams = m.GetParameters();
}
for (int i = 0, n = args.Count; i < n; i++)
{
Type parameterType = mParams[i].ParameterType;
if (parameterType == null)
return false;
if (parameterType.IsByRef)
parameterType = parameterType.GetElementType();
Expression arg = args[i];
if (!parameterType.IsAssignableFrom(arg.Type))
{
if (arg.NodeType == ExpressionType.Quote)
{
arg = ((UnaryExpression)arg).Operand;
}
if (!parameterType.IsAssignableFrom(arg.Type) &&
!parameterType.IsAssignableFrom(StripExpression(arg.Type)))
{
return false;
}
}
}
return true;
}
private static Type StripExpression(Type type)
{
bool isArray = type.IsArray;
Type tmp = isArray ? type.GetElementType() : type;
Type eType = TypeHelper.FindGenericType(typeof(Expression<>), tmp);
if (eType != null)
tmp = eType.GetGenericArguments()[0];
if (isArray)
{
int rank = type.GetArrayRank();
return (rank == 1) ? tmp.MakeArrayType() : tmp.MakeArrayType(rank);
}
return type;
}
protected override Expression VisitConditional(ConditionalExpression c)
{
Type type = c.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.Visit(c);
Expression test = Visit(c.Test);
Expression ifTrue = Visit(c.IfTrue);
Expression ifFalse = Visit(c.IfFalse);
Type trueType = ifTrue.Type;
Type falseType = ifFalse.Type;
if (trueType.IsAssignableFrom(falseType))
return Expression.Condition(test, ifTrue, ifFalse, trueType);
if (falseType.IsAssignableFrom(trueType))
return Expression.Condition(test, ifTrue, ifFalse, falseType);
TypeInfo info = type.GetTypeInfo();
return Expression.Condition(test, ifTrue, ifFalse, GetEquivalentType(type));
}
protected override Expression VisitBlock(BlockExpression node)
{
Type type = node.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.Visit(node);
ReadOnlyCollection<Expression> nodes = Visit(node.Expressions);
ReadOnlyCollection<ParameterExpression> variables = VisitAndConvert(node.Variables, "EnumerableRewriter.VisitBlock");
if (type == node.Expressions.Last().Type)
return Expression.Block(variables, nodes);
return Expression.Block(GetEquivalentType(type), variables, nodes);
}
protected override Expression VisitGoto(GotoExpression node)
{
Type type = node.Value.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.VisitGoto(node);
LabelTarget target = VisitLabelTarget(node.Target);
Expression value = Visit(node.Value);
return Expression.MakeGoto(node.Kind, target, value, GetEquivalentType(typeof(EnumerableQuery).IsAssignableFrom(type) ? value.Type : type));
}
protected override LabelTarget VisitLabelTarget(LabelTarget node)
{
LabelTarget newTarget;
if (_targetCache == null)
_targetCache = new Dictionary<LabelTarget, LabelTarget>();
else if (_targetCache.TryGetValue(node, out newTarget))
return newTarget;
Type type = node.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
newTarget = base.VisitLabelTarget(node);
else
newTarget = Expression.Label(GetEquivalentType(type), node.Name);
_targetCache.Add(node, newTarget);
return newTarget;
}
}
}
| |
namespace Supa.Platform.Tests
{
using System;
using System.Linq;
using System.Net;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public abstract class ExchangeServiceProviderTestsBase
{
public const string TestFolder = "SupaTestFolder";
public const string FirstConversationSubject = "First conversation";
public const string FirstConversationContent = "Sample content for first conversation";
public const string FirstConversationSecondEmailContent =
"Sample content for second email in first conversation";
public static readonly string TestUser =
Environment.GetEnvironmentVariable("SupaExchangeServiceProviderTestUser");
public static readonly string TestUserPassword =
Environment.GetEnvironmentVariable("SupaExchangeServiceProviderTestPassword");
private const string SecondConversationSubject = "Second conversation";
private const string SecondConversationContent = "Sample content for second conversation";
[TestMethod]
public void ExchangeServiceProviderShouldThrowForNullServiceUrl()
{
Action action = () => this.CreateExchangeServiceProvider(null, CredentialCache.DefaultNetworkCredentials);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("serviceUrl");
}
[TestMethod]
public void ExchangeServiceProviderShouldThrowIfNetworkCredentialIsNull()
{
Action action = () => this.CreateExchangeServiceProvider(new Uri("http://dummyUri"), null);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("credential");
}
#region DeleteMailFolder Scenarios
[TestMethod]
public void DeleteMailFolderShouldThrowIfMailFolderIsNull()
{
Action action = () => this.GetDefaultExchangeServiceProvider().DeleteMailFolder(null);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("mailFolder");
}
[TestMethod]
public void DeleteMailFolderShouldThrowIfFolderDoesNotExist()
{
var nonExistentFolder = new MailFolder { Id = 102, Name = "nonExistentFolder" };
Action action = () => this.GetDefaultExchangeServiceProvider().DeleteMailFolder(nonExistentFolder);
action.ShouldThrow<InvalidOperationException>().And.Message.Should().Be("Folder nonExistentFolder does not exist.");
}
[TestMethod]
public void DeleteMailFolderShouldDeleteFolderIfExist()
{
var exchangeServiceProvider = this.GetDefaultExchangeServiceProvider();
var mailFolder = exchangeServiceProvider.GetMailFolder("dummyFolder12", createIfNotExist: true);
exchangeServiceProvider.DeleteMailFolder(mailFolder);
exchangeServiceProvider.GetMailFolder("dummyFolder12", createIfNotExist: false).Should().BeNull();
}
#endregion
#region GetMailFolder Scenarios
[TestMethod]
public void GetMailFolderShouldThrowIfFolderNameIsNullOrEmpty()
{
Action action = () => this.GetDefaultExchangeServiceProvider().GetMailFolder(null, false);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("folderName");
}
[TestMethod]
public void GetMailFolderShouldCreateFolderIfCreateIfNotExistIsTrue()
{
const string NonExistentFolder = "nonExistentFolderThatWeWillCreate";
var mailFolder = this.GetDefaultExchangeServiceProvider().GetMailFolder(NonExistentFolder, true);
mailFolder.Name.Should().Be(NonExistentFolder);
this.ValidateInboxContainsFolder(NonExistentFolder);
this.GetDefaultExchangeServiceProvider().DeleteMailFolder(mailFolder);
}
// GetMailFolderShouldFindFolderInInbox
// GetMailFolderShouldReturnNullIfFolderNotExistAndCreateIfNotExistIsFalse
#endregion
#region GetConversations Scenarios
// TODO temporarily disabled
//[TestMethod]
public void GetConversationsShouldThrowIfFolderDoesNotExist()
{
Action action = () => this.GetDefaultExchangeServiceProvider().GetEmailThreads("nonExistentFolder");
action.ShouldThrow<InvalidOperationException>();
}
[TestMethod]
public void GetConversationsShouldReturnAllItemsInAFolder()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
items.Count().Should().Be(1);
}
[TestMethod]
public void GetConversationsShouldQueryForNewMailThreadsInAFolder()
{
var itemsCount = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder).Count();
this.CreateMailThreadInTestFolder(SecondConversationSubject, SecondConversationContent, TestUser);
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
itemsCount.Should().Be(1);
items.Count().Should().Be(2);
this.DeleteMailThreadInTestFolder(SecondConversationSubject);
items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
items.Count().Should().Be(1);
}
#endregion
#region MailThread Scenarios
[TestMethod]
public void GetConversationsShouldReturnMailThreadWithIdAsConversationId()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstConversation = items.Single();
firstConversation.Id.Should().NotBeNullOrEmpty();
}
[TestMethod]
public void GetConversationShouldReturnMailThreadWithTopicAsConversationSubject()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstConversation = items.Single();
firstConversation.Topic.Should().Be(FirstConversationSubject);
}
[TestMethod]
public void GetConversationShouldReturnMailThreadWithMailForConversationWithOneEmail()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstConversation = items.Single();
firstConversation.Mails.Should().NotBeNull();
firstConversation.Mails.Count.Should().Be(1);
}
[TestMethod]
public void GetConversationShouldAddNewItemsToMailThread()
{
var firstConversation = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder).Single();
var initialMailCount = firstConversation.Mails.Count;
this.AddMailToMailThread(FirstConversationSubject, FirstConversationSecondEmailContent);
firstConversation = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder).Single();
firstConversation.Mails.Count.Should().Be(initialMailCount + 1);
this.DeleteLastMailFromMailThread(FirstConversationSubject);
}
#endregion
#region Mail Scenarios
[TestMethod]
public void GetConversationShouldReturnMailWithId()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstMail = items.Single().Mails.Single();
firstMail.Id.Should().NotBeNullOrEmpty();
}
[TestMethod]
public void GetConversationShouldReturnMailWithSubject()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstMail = items.Single().Mails.Single();
firstMail.Subject.Should().Be(FirstConversationSubject);
}
[TestMethod]
public void GetConversationShouldReturnMailWithSubjectSameAsConversationTopic()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder).ToList();
var firstMail = items.Single().Mails.Single();
firstMail.Subject.Should().Be(items.Single().Topic);
}
[TestMethod]
public void GetConversationShouldReturnMailWithFromAsTestUser()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstMail = items.Single().Mails.Single();
firstMail.From.Should().Be(TestUser);
}
[TestMethod]
public void GetConversationShouldReturnMailWithRecipientsAsTestUser()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstMail = items.Single().Mails.Single();
firstMail.Recipients.Should().Be(TestUser);
}
[TestMethod]
public void GetConversationShouldReturnMailWithBodyAsMailContent()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstMail = items.Single().Mails.Single();
firstMail.Body.Should().Be(FirstConversationContent);
}
[TestMethod]
public void GetConversationShouldReturnMailWithDateTimeReceivedSet()
{
var items = this.GetDefaultExchangeServiceProvider().GetEmailThreads(TestFolder);
var firstMail = items.Single().Mails.Single();
firstMail.DateTimeReceived.Should().BeCloseTo(DateTime.Now, 20 * 60 * 1000);
}
#endregion
protected abstract IExchangeServiceProvider GetDefaultExchangeServiceProvider();
protected abstract IExchangeServiceProvider CreateExchangeServiceProvider(Uri serviceUrl, NetworkCredential credential);
protected abstract void ValidateInboxContainsFolder(string folderName);
protected abstract void CreateMailThreadInTestFolder(string subject, string body, string recipients);
protected abstract void AddMailToMailThread(string conversationSubject, string body);
protected abstract void DeleteMailThreadInTestFolder(string subject);
protected abstract void DeleteLastMailFromMailThread(string conversationSubject);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct MethodDefinition
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint _treatmentAndRowId;
internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private MethodDefTreatment Treatment
{
get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private MethodDefinitionHandle Handle
{
get { return MethodDefinitionHandle.FromRowId(RowId); }
}
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
public BlobHandle Signature
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetSignature(Handle);
}
return GetProjectedSignature();
}
}
public MethodSignature<TType> DecodeSignature<TType, TGenericContext>(ISignatureTypeProvider<TType, TGenericContext> provider, TGenericContext genericContext)
{
var decoder = new SignatureDecoder<TType, TGenericContext>(provider, _reader, genericContext);
var blobReader = _reader.GetBlobReader(Signature);
return decoder.DecodeMethodSignature(ref blobReader);
}
public int RelativeVirtualAddress
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetRva(Handle);
}
return GetProjectedRelativeVirtualAddress();
}
}
public MethodAttributes Attributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
public MethodImplAttributes ImplAttributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetImplFlags(Handle);
}
return GetProjectedImplFlags();
}
}
public TypeDefinitionHandle GetDeclaringType()
{
return _reader.GetDeclaringType(Handle);
}
public ParameterHandleCollection GetParameters()
{
return new ParameterHandleCollection(_reader, Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return _reader.GenericParamTable.FindGenericParametersForMethod(Handle);
}
public MethodImport GetImport()
{
int implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle);
if (implMapRid == 0)
{
return default(MethodImport);
}
return _reader.ImplMapTable.GetImport(implMapRid);
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(_reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle);
}
#region Projections
private StringHandle GetProjectedName()
{
if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod)
{
return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose);
}
return _reader.MethodDefTable.GetName(Handle);
}
private MethodAttributes GetProjectedFlags()
{
MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle);
MethodDefTreatment treatment = Treatment;
if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private;
}
if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0)
{
flags |= MethodAttributes.Abstract;
}
if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public;
}
return flags | MethodAttributes.HideBySig;
}
private MethodImplAttributes GetProjectedImplFlags()
{
MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle);
switch (Treatment & MethodDefTreatment.KindMask)
{
case MethodDefTreatment.DelegateMethod:
flags |= MethodImplAttributes.Runtime;
break;
case MethodDefTreatment.DisposeMethod:
case MethodDefTreatment.AttributeMethod:
case MethodDefTreatment.InterfaceMethod:
case MethodDefTreatment.HiddenInterfaceImplementation:
case MethodDefTreatment.Other:
flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall;
break;
}
return flags;
}
private BlobHandle GetProjectedSignature()
{
return _reader.MethodDefTable.GetSignature(Handle);
}
private int GetProjectedRelativeVirtualAddress()
{
return 0;
}
#endregion
}
}
| |
/* This is a very early MIDI to BGM converter. There is still a lot unknown. */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MIDI2BGM
{
class Program
{
public static void WriteBytes(byte[] i, BinaryWriter writer)
{
writer.Write(i);
}
public static void WriteDelta(float i, BinaryWriter writer)
{
//Welp, never know(?)
if ((i % 1) != 0) { i = (int)Math.Round((double)i, MidpointRounding.AwayFromZero); }
// Console.WriteLine("delta_rounded: {0}", i);
while (i > 0xFFFFFFF) { WriteDummy(0xFFFFFFF, writer); i -= 0xFFFFFFF; }
//Console.WriteLine("delta_rounded_2: {0}", i);
UInt32 b = ((UInt32)i & 0x7F);
//Console.WriteLine("delta_rounded_3: {0}", b);
int tmp = (int)i;
while (Convert.ToBoolean(tmp >>= 7))
{
b <<= 8;
b |= (uint)((tmp & 0x7F) | 0x80);
}
// Console.WriteLine("delta_rounded_4: {0}", b);
do
{
writer.Write((byte)b);
if ((b & 0x80) == 0)
{
break;
}
b >>= 8;
} while (true);
}
public static void WriteDummy(int i, BinaryWriter writer)
{
if (i == 0)
{
return;
}
WriteDelta(i, writer);
byte[] buffer1 = {0x5d, 0};
WriteBytes(buffer1, writer);
}
static void Main(string[] args)
{
if (args.Length == 1)
{
foreach (string name in args)
{
GetBGM(name);
}
}
else
{
Console.Write("Enter BGM File: ");
string name = Console.ReadLine();
GetBGM(name);
}
}
public static void GetBGM(string nme)
{
#region vars
int t;
byte cmd;
byte trackC;
ushort ppqn;
long ActualPos;
float delta;
int deltaMod = 1;
FileStream midS = File.Open(nme, FileMode.Open, FileAccess.Read);
BinaryReader mid = new BinaryReader(midS);
FileStream bgmS = File.Open(nme + ".bgm", FileMode.Create, FileAccess.Write);
BinaryWriter bgm = new BinaryWriter(bgmS);
byte lKey = 255;
byte lVelocity = 0x40;
byte track = 0;
byte channel = 0;
byte[] command;
byte[] towrite = new byte[0];
byte SubCommand;
long trackLenOffset;
UInt16 temp;
UInt32 temp32;
#endregion
try
{
#region Header
if (mid.ReadUInt32() != 0x6468544D || mid.ReadUInt32() != 0x06000000)
{
Console.WriteLine("BAD HEADER!");
return;
}
temp = mid.ReadUInt16();
temp = (UInt16)((temp & 0xFFU) << 8 | (temp & 0xFF00U) >> 8);
t = (int)temp;
if (t != 1)
{
Console.WriteLine("WARNING: Play type is not what's expected! (Got {0}; Want 1)\nPress enter to try to convert anyway...", t);
Console.ReadLine();
}
temp = mid.ReadUInt16();
temp = (UInt16)((temp & 0xFFU) << 8 | (temp & 0xFF00U) >> 8);
ppqn = temp;
Console.WriteLine("# of Tracks: {0}", ppqn);
if (ppqn > 0xFF)
{
Console.WriteLine("ERROR: This many tracks cannot be stored in a BGM file!");
return;
}
trackC = (byte)ppqn;
temp = mid.ReadUInt16();
temp = (UInt16)((temp & 0xFFU) << 8 | (temp & 0xFF00U) >> 8);
ppqn = temp;
Console.WriteLine("PPQN: {0}", ppqn);
if (ppqn != 48)
{ //KH1 forces PPQN=48, even when you save something else
deltaMod = (ppqn / 48);//Might have an issue there, just setting a flag in case there's a prob'
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Modded PPQN: {0} (calc={2})\nDeltaModDiv: {1}", 48, deltaMod, ppqn / deltaMod);
Console.ResetColor();
ppqn = 48;
}
bgm.Write((UInt32)0x204D4742); //header
Console.Write("Enter Seq ID: ");
UInt16 seqid = UInt16.Parse(Console.ReadLine());
bgm.Write(seqid);
Console.Write("Enter WD ID: ");
UInt16 insid = UInt16.Parse(Console.ReadLine());
bgm.Write(insid);
bgm.Write(trackC);
bgm.Write((byte)5); //unknown, often 5
bgm.Write((byte)0); //unknown
bgm.Write((byte)0); //unknown
Console.Write("Enter in-game volume level [0-255]: ");
t = Int32.Parse(Console.ReadLine());
if (t > 255)
{
t = 255;
}
else
{
if (t < 21)
{
Console.WriteLine("WARNING: {0} is awfully quiet, you might not hear it in-game!", t);
}
}
bgm.Write((byte)t); //volume
bgm.Write((byte)0); //unknown
bgm.Write(ppqn);
bgm.Write((UInt32)0); //fileSize
bgm.Write((UInt32)0);
bgm.Write((UInt32)0);
bgm.Write((UInt32)0); //padding
bgmS.Flush();
Console.Write("Press enter to continue...");
Console.ReadLine();
#endregion
for (; track < trackC; track++)
{
if (mid.ReadUInt32() != 0x6b72544d)
{
Console.WriteLine("Bad track {0} header!", track);
return;
}
temp32 = mid.ReadUInt32();
temp32 = (temp32 & 0x000000FFU) << 24 | (temp32 & 0x0000FF00U) << 8 | (temp32 & 0x00FF0000U) >> 8 | (temp32 & 0xFF000000U) >> 24;
ActualPos = temp32;
Console.WriteLine("Track {0}; Length = {1}", track, ActualPos);
trackLenOffset = bgmS.Position;
bgm.Write((UInt32)0); //len
delta = t = 0;
channel = (byte)((int)track % 16);
for (ActualPos += midS.Position; midS.Position < ActualPos - 1;)
{
do
{
byte tmptbyte;
t = tmptbyte = mid.ReadByte();
delta = ((int)delta << 7) + (tmptbyte & 0x7f);
} while (Convert.ToBoolean(t & 0x80));
delta /= deltaMod;
//Console.WriteLine("delta: {0}", delta);
/*if(track>2){//skip track
midS.Position=tSzT;
bgm.WriteDelta(delta);delta=0;
bgm.WriteBytes([0]);
bgmS.Position=trackLenOffset;
bgm.Write(UInt32(bgmS.Length-4-trackLenOffset));//update len
bgmS.Seek(0,SeekOrigin.End);
Console.WriteLine('end');
break;
}*/
cmd = mid.ReadByte();
//Console.WriteLine("Current command: {0:x2}",cmd);
if (cmd == 0xFF)
{
command = new byte[] { mid.ReadByte(), mid.ReadByte() };
// Console.WriteLine("Current command: {0:x2} {1:x2} {2:x2}", cmd, command[0], command[1]);
switch (command[0])
{
case 0x2F:
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 0 };
WriteBytes(towrite, bgm);
bgmS.Position = trackLenOffset;
bgm.Write((UInt32)(bgmS.Length - 4 - trackLenOffset)); //update len
bgmS.Seek(0, SeekOrigin.End);
Console.WriteLine("end");
break;
case 0x51:
t = (Int32)(((UInt32)(mid.ReadByte()) << 16) + ((UInt32)(mid.ReadByte()) << 8) + mid.ReadByte());
WriteDelta(delta, bgm);
delta = 0;
//Console.WriteLine(' Tempo={0} ({1}; {2})',byte(60000000/t),60000000/t,t);
towrite = new byte[] { 8, (byte)(60000000 / t) };
WriteBytes(towrite, bgm);
break;
case 0x58:
command = new byte[] { mid.ReadByte(), mid.ReadByte(), mid.ReadByte(), mid.ReadByte() };
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 0x0c, command[0], command[1] };
WriteBytes(towrite, bgm);
break;
case 6:
command = mid.ReadBytes(command[1]);
if (command.Length == 9 && command[0] == 108 && command[1] == 111 && command[2] == 111 && command[3] == 112 && command[4] == 83 && command[5] == 116 && command[6] == 97 && command[7] == 114 && command[8] == 116)
{
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 2 };
WriteBytes(towrite, bgm);
}
else
{
if (command.Length == 7 && command[0] == 108 && command[1] == 111 && command[2] == 111 && command[3] == 112 && command[4] == 69 && command[5] == 110 && command[6] == 100)
{
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 3 };
WriteBytes(towrite, bgm);
}
}
break;
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
//Text events, just ignore
case 0x7f:
//Sequencer-specific meta event
midS.Position += command[1];
break;
default:
midS.Position += command[1];
Console.WriteLine("Unknown command1: 0x{0:x2} 0x{1:x2}", cmd, command[0]);
towrite = new byte[0];
break;
}
}
else
{
if ((cmd & 0xB0) == 0xB0)
{
cmd = mid.ReadByte();
SubCommand = mid.ReadByte();
// Console.WriteLine("Current command: {0:x2} {1:x2}", cmd, SubCommand);
switch (cmd)
{
case 7:
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 0x22, SubCommand };
WriteBytes(towrite, bgm);
break;
case 11:
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 0x24, SubCommand };
WriteBytes(towrite, bgm);
break;
case 10:
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 0x26, SubCommand };
WriteBytes(towrite, bgm);
break;
case 64:
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 0x3C, SubCommand };
WriteBytes(towrite, bgm);
break;
default:
Console.WriteLine("Unknown command2: 0xBx 0x{0:x2} (value={1})", cmd, SubCommand);
break;
}
}
else
{
// Console.WriteLine("Current command: {0:x2}", cmd);
if ((cmd & 0xC0) == 0xC0)
{
WriteDelta(delta, bgm);
delta = 0;
towrite = new byte[] { 0x20, mid.ReadByte() };
WriteBytes(towrite, bgm);
}
else
{
if ((cmd & 0x90) == 0x90)
{
command = new byte[] { mid.ReadByte(), mid.ReadByte() };
WriteDelta(delta, bgm);
delta = 0;
if (command[0] == lKey)
{
if (command[1] == lVelocity)
{
towrite = new byte[] { 0x10 };
WriteBytes(towrite, bgm);
}
else
{
lVelocity = command[1];
towrite = new byte[] { 0x13, lVelocity };
WriteBytes(towrite, bgm);
}
}
else
{
if (command[1] == lVelocity)
{
lKey = command[0];
towrite = new byte[] { 0x12, lKey };
WriteBytes(towrite, bgm);
}
else
{
lKey = command[0];
lVelocity = command[1];
towrite = new byte[] { 0x11, lKey, lVelocity };
WriteBytes(towrite, bgm);
}
}
}
else
{
if ((cmd & 0x80) == 0x80)
{
command = new byte[] { mid.ReadByte(), mid.ReadByte() };
WriteDelta(delta, bgm);
delta = 0;
//Console.WriteLine("wtf: {0:x2}, {1:x2}", command[0], lKey);
if (command[0] == lKey)
{
towrite = new byte[] { 0x18 };
WriteBytes(towrite, bgm);
}
else
{
lKey = command[0];
towrite = new byte[] { 0x1A, lKey };
WriteBytes(towrite, bgm);
}
}
else { Console.WriteLine("Unknown command3: 0x{0:x2}", cmd); }
}
}
}
}
/* Console.Write("{0}: [ ", (bgm.BaseStream.Position - towrite.Length).ToString("X"));
int y = 0;
foreach (var item in towrite)
{
if (y > 0) { Console.Write(", "); }
Console.Write(item.ToString("X"));
y++;
}
Console.WriteLine("]");*/
}
if (midS.Position != ActualPos)
{
Console.WriteLine("Got a bad auto-offset! (pos={0}) Attempting to fix...", midS.Position);
midS.Position = ActualPos;
}
}
bgmS.Position = 16;
bgm.Write((UInt32)bgmS.Length);
}
finally
{
bgm.Close();
mid.Close();
};
Console.ReadLine();
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Events;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer
{
/// <summary>
/// This controller processes the consent UI
/// </summary>
[SecurityHeaders]
[Authorize]
public class ConsentController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IResourceStore _resourceStore;
private readonly IEventService _events;
private readonly ILogger<ConsentController> _logger;
public ConsentController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IResourceStore resourceStore,
IEventService events,
ILogger<ConsentController> logger)
{
_interaction = interaction;
_clientStore = clientStore;
_resourceStore = resourceStore;
_events = events;
_logger = logger;
}
/// <summary>
/// Shows the consent screen
/// </summary>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Index(string returnUrl)
{
var vm = await BuildViewModelAsync(returnUrl);
if (vm != null)
{
return View("Index", vm);
}
return View("Error");
}
/// <summary>
/// Handles the consent screen postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ConsentInputModel model)
{
var result = await ProcessConsent(model);
if (result.IsRedirect)
{
if (await _clientStore.IsPkceClientAsync(result.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = result.RedirectUri });
}
return Redirect(result.RedirectUri);
}
if (result.HasValidationError)
{
ModelState.AddModelError(string.Empty, result.ValidationError);
}
if (result.ShowView)
{
return View("Index", result.ViewModel);
}
return View("Error");
}
/*****************************************/
/* helper APIs for the ConsentController */
/*****************************************/
private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
{
var result = new ProcessConsentResult();
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model?.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested));
}
// user clicked 'yes' - validate the data
else if (model?.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.ClientId = request.ClientId;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
}
return result;
}
private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
{
return CreateConsentViewModel(model, returnUrl, request, client, resources);
}
else
{
_logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y));
}
}
else
{
_logger.LogError("Invalid client id: {0}", request.ClientId);
}
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ConsentViewModel CreateConsentViewModel(
ConsentInputModel model, string returnUrl,
AuthorizationRequest request,
Client client, Resources resources)
{
var vm = new ConsentViewModel
{
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ReturnUrl = returnUrl,
ClientName = client.ClientName ?? client.ClientId,
ClientUrl = client.ClientUri,
ClientLogoUrl = client.LogoUri,
AllowRememberConsent = client.AllowRememberConsent
};
vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] {
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ritter.Domain;
using Ritter.Infra.Crosscutting;
using Ritter.Infra.Crosscutting.Collections;
using Ritter.Infra.Crosscutting.Specifications;
namespace Ritter.Infra.Data
{
public abstract class EFRepository<TEntity, TKey> : Repository, ISqlRepository<TEntity, TKey>
where TEntity : class
{
public new IEFUnitOfWork UnitOfWork { get; private set; }
protected EFRepository(IEFUnitOfWork unitOfWork)
: base(unitOfWork)
{
UnitOfWork = unitOfWork;
}
public virtual TEntity Find(TKey id)
{
return UnitOfWork
.Set<TEntity>()
.Find(id);
}
public virtual ICollection<TEntity> Find()
{
return UnitOfWork
.Set<TEntity>()
.ToList();
}
public virtual ICollection<TEntity> Find(ISpecification<TEntity> specification)
{
return FindSpecific(specification)
.ToList();
}
public virtual IPagedCollection<TEntity> Find(ISpecification<TEntity> specification, IPagination pagination)
{
Ensure.Argument.NotNull(pagination, nameof(pagination));
return FindSpecific(specification)
.PaginateList(pagination);
}
public virtual IPagedCollection<TEntity> Find(IPagination pagination) => Find(new TrueSpecification<TEntity>(), pagination);
public virtual async Task<TEntity> FindAsync(TKey id, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
return await UnitOfWork
.Set<TEntity>()
.FindAsync(id);
}
public virtual async Task<ICollection<TEntity>> FindAsync(CancellationToken cancellationToken = new CancellationToken())
{
return await UnitOfWork
.Set<TEntity>()
.ToListAsync(cancellationToken);
}
public virtual async Task<ICollection<TEntity>> FindAsync(ISpecification<TEntity> specification, CancellationToken cancellationToken = new CancellationToken())
{
return await FindSpecific(specification)
.ToListAsync(cancellationToken);
}
public virtual async Task<IPagedCollection<TEntity>> FindAsync(IPagination pagination, CancellationToken cancellationToken = new CancellationToken())
=> await FindAsync(new TrueSpecification<TEntity>(), pagination, cancellationToken);
public virtual async Task<IPagedCollection<TEntity>> FindAsync(ISpecification<TEntity> specification, IPagination pagination, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(pagination, nameof(pagination));
return await FindSpecific(specification)
.PaginateListAsync(pagination, cancellationToken);
}
public virtual bool Any()
{
return UnitOfWork
.Set<TEntity>()
.AsNoTracking()
.Any();
}
public virtual bool Any(ISpecification<TEntity> specification) => FindSpecific(specification).Any();
public virtual async Task<bool> AnyAsync(CancellationToken cancellationToken = new CancellationToken())
{
return await UnitOfWork
.Set<TEntity>()
.AsNoTracking()
.AnyAsync(cancellationToken);
}
public virtual async Task<bool> AnyAsync(ISpecification<TEntity> specification, CancellationToken cancellationToken = new CancellationToken())
=> await FindSpecific(specification).AnyAsync(cancellationToken);
public virtual void Add(TEntity entity)
{
Ensure.Argument.NotNull(entity, nameof(entity));
UnitOfWork
.Set<TEntity>()
.Add(entity);
UnitOfWork.SaveChanges();
}
public virtual void Add(IEnumerable<TEntity> entities)
{
Ensure.Argument.NotNull(entities, nameof(entities));
UnitOfWork
.Set<TEntity>()
.AddRange(entities);
UnitOfWork.SaveChanges();
}
public virtual async Task AddAsync(TEntity entity, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(entity, nameof(entity));
await UnitOfWork
.Set<TEntity>()
.AddAsync(entity, cancellationToken);
await UnitOfWork.SaveChangesAsync(cancellationToken);
}
public virtual async Task AddAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(entities, nameof(entities));
await UnitOfWork
.Set<TEntity>()
.AddRangeAsync(entities, cancellationToken);
await UnitOfWork.SaveChangesAsync(cancellationToken);
}
public virtual void Update(TEntity entity)
{
Ensure.Argument.NotNull(entity, nameof(entity));
UnitOfWork
.Set<TEntity>()
.Update(entity);
UnitOfWork.SaveChanges();
}
public virtual void Update(IEnumerable<TEntity> entities)
{
Ensure.Argument.NotNull(entities, nameof(entities));
UnitOfWork
.Set<TEntity>()
.UpdateRange(entities);
UnitOfWork.SaveChanges();
}
public virtual async Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(entity, nameof(entity));
UnitOfWork
.Set<TEntity>()
.Update(entity);
await UnitOfWork.SaveChangesAsync(cancellationToken);
}
public virtual async Task UpdateAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(entities, nameof(entities));
UnitOfWork
.Set<TEntity>()
.UpdateRange(entities);
await UnitOfWork.SaveChangesAsync(cancellationToken);
}
public virtual void Remove(TEntity entity)
{
Ensure.Argument.NotNull(entity, nameof(entity));
UnitOfWork
.Set<TEntity>()
.Remove(entity);
UnitOfWork.SaveChanges();
}
public virtual void Remove(IEnumerable<TEntity> entities)
{
Ensure.Argument.NotNull(entities, nameof(entities));
UnitOfWork
.Set<TEntity>()
.RemoveRange(entities);
UnitOfWork.SaveChanges();
}
public virtual void Remove(ISpecification<TEntity> specification)
{
Ensure.Argument.NotNull(specification, nameof(specification));
var entities = UnitOfWork
.Set<TEntity>()
.Where(specification.SatisfiedBy())
.ToList();
UnitOfWork
.Set<TEntity>()
.RemoveRange(entities);
UnitOfWork.SaveChanges();
}
public virtual async Task RemoveAsync(TEntity entity, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(entity, nameof(entity));
UnitOfWork
.Set<TEntity>()
.Remove(entity);
await UnitOfWork.SaveChangesAsync(cancellationToken);
}
public virtual async Task RemoveAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(entities, nameof(entities));
UnitOfWork
.Set<TEntity>()
.RemoveRange(entities);
await UnitOfWork.SaveChangesAsync(cancellationToken);
}
public virtual async Task RemoveAsync(ISpecification<TEntity> specification, CancellationToken cancellationToken = new CancellationToken())
{
Ensure.Argument.NotNull(specification, nameof(specification));
var entities = UnitOfWork
.Set<TEntity>()
.Where(specification.SatisfiedBy())
.ToList();
UnitOfWork
.Set<TEntity>()
.RemoveRange(entities);
await UnitOfWork.SaveChangesAsync(cancellationToken);
}
private IQueryable<TEntity> FindSpecific(ISpecification<TEntity> specification)
{
Ensure.Argument.NotNull(specification, nameof(specification));
return UnitOfWork.Set<TEntity>()
.Where(specification.SatisfiedBy());
}
}
}
| |
namespace Framework
{
using System;
using System.Globalization;
/// <summary>
/// HashCode Combiner class to create new hashes from objects.
/// </summary>
public sealed class HashCodeUtility
{
/// <summary>
/// Initializes a new instance of the <see cref="HashCodeUtility"/> class.
/// </summary>
public HashCodeUtility()
{
this.CombinedHash = 5381L;
}
/// <summary>
/// Initializes a new instance of the <see cref="HashCodeUtility"/> class.
/// </summary>
/// <param name="initialCombinedHash">
/// The initial combined hash.
/// </param>
public HashCodeUtility(long initialCombinedHash)
{
this.CombinedHash = initialCombinedHash;
}
/// <summary>
/// Gets the combined hash.
/// </summary>
/// <value>
/// The combined hash.
/// </value>
public long CombinedHash
{
get;
private set;
}
/// <summary>
/// Gets the combined hash32.
/// </summary>
/// <value>
/// The combined hash32.
/// </value>
public int CombinedHash32
{
get
{
return this.CombinedHash.GetHashCode();
}
}
/// <summary>
/// Gets the combined hash string.
/// </summary>
/// <value>
/// The combined hash string.
/// </value>
public string CombinedHashString
{
get
{
return this.CombinedHash.ToString("x", CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Performs an implicit conversion from <see cref="HashCodeUtility"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="other">The other.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator string(HashCodeUtility other)
{
return other == null ? string.Empty : other.ToString();
}
/// <summary>
/// Adds the array.
/// </summary>
/// <param name="array">Array to add.</param>
public void AddArray(string[] array)
{
if (array != null)
{
int length = array.Length;
for (int i = 0; i < length; i++)
{
this.AddObject(array[i]);
}
}
}
/// <summary>
/// Adds the case insensitive string.
/// </summary>
/// <param name="value">The value.</param>
public void AddCaseInsensitiveString(string value)
{
if (value != null)
{
this.AddInt(StringComparer.InvariantCultureIgnoreCase.GetHashCode(value));
}
}
/// <summary>
/// Adds the date time.
/// </summary>
/// <param name="date">The date to add.</param>
public void AddDateTime(DateTime date)
{
this.AddInt(date.GetHashCode());
}
/// <summary>
/// Adds the value.
/// </summary>
/// <param name="value">The number to add.</param>
public void AddInt(int value)
{
this.CombinedHash = ((this.CombinedHash << 5) + this.CombinedHash) ^ value;
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="value">The value to add.</param>
public void AddObject(bool value)
{
this.AddInt(value.GetHashCode());
}
/// <summary>
/// Adds the value.
/// </summary>
/// <param name="obj">The value to add.</param>
public void AddObject(byte obj)
{
this.AddInt(obj.GetHashCode());
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="value">
/// The number to add.
/// </param>
public void AddObject(int value)
{
this.AddInt(value);
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="value">
/// The number to add.
/// </param>
public void AddObject(long value)
{
this.AddInt(value.GetHashCode());
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="value">
/// The object to add.
/// </param>
public void AddObject(object value)
{
if (value != null)
{
this.AddInt(value.GetHashCode());
}
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
public void AddObject(string value)
{
if (value != null)
{
this.AddInt(value.GetHashCode());
}
}
/// <summary>
/// Serves as a hash function for a particular type. <see cref="M:System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"></see>.
/// </returns>
public override int GetHashCode()
{
return this.CombinedHash32;
}
/// <summary>
/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>
public override string ToString()
{
return this.CombinedHash32.ToString(CultureInfo.InvariantCulture);
}
}
}
| |
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 StudyServer.Areas.HelpPage.ModelDescriptions;
using StudyServer.Areas.HelpPage.Models;
namespace StudyServer.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class CrefCompletionProvider : AbstractCompletionProvider
{
public static readonly SymbolDisplayFormat CrefFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
public override bool IsCommitCharacter(CompletionItem completionItem, char ch, string textTypedSoFar)
{
if (ch == '{' && completionItem.DisplayText.Contains('{'))
{
return false;
}
if (ch == '(' && completionItem.DisplayText.Contains('('))
{
return false;
}
return CompletionUtilities.IsCommitCharacter(completionItem, ch, textTypedSoFar);
}
public override bool SendEnterThroughToEditor(CompletionItem completionItem, string textTypedSoFar)
{
return CompletionUtilities.SendEnterThroughToEditor(completionItem, textTypedSoFar);
}
public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options);
}
protected override Task<bool> IsExclusiveAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
return SpecializedTasks.True;
}
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, System.Threading.CancellationToken cancellationToken)
{
var tree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (!tree.IsEntirelyWithinCrefSyntax(position, cancellationToken))
{
return null;
}
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (token.Kind() == SyntaxKind.None)
{
return null;
}
var result = SpecializedCollections.EmptyEnumerable<ISymbol>();
// To get a Speculative SemanticModel (which is much faster), we need to
// walk up to the node the DocumentationTrivia is attached to.
var parentNode = token.GetAncestor<DocumentationCommentTriviaSyntax>().ParentTrivia.Token.Parent;
var semanticModel = await document.GetCSharpSemanticModelForNodeAsync(parentNode, cancellationToken).ConfigureAwait(false);
// cref ""|, ""|"", ""a|""
if (token.IsKind(SyntaxKind.DoubleQuoteToken, SyntaxKind.SingleQuoteToken) && token.Parent.IsKind(SyntaxKind.XmlCrefAttribute))
{
result = semanticModel.LookupSymbols(token.SpanStart)
.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);
result = result.Concat(GetOperatorsAndIndexers(token, semanticModel, cancellationToken));
}
else if (IsSignatureContext(token))
{
result = semanticModel.LookupNamespacesAndTypes(token.SpanStart)
.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);
}
else if (token.IsKind(SyntaxKind.DotToken) && token.Parent.IsKind(SyntaxKind.QualifiedCref))
{
// cref "a.|"
var parent = token.Parent as QualifiedCrefSyntax;
var leftType = semanticModel.GetTypeInfo(parent.Container, cancellationToken).Type;
var leftSymbol = semanticModel.GetSymbolInfo(parent.Container, cancellationToken).Symbol;
var container = leftSymbol ?? leftType;
result = semanticModel.LookupSymbols(token.SpanStart, container: (INamespaceOrTypeSymbol)container)
.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);
if (container is INamedTypeSymbol)
{
result = result.Concat(((INamedTypeSymbol)container).InstanceConstructors);
}
}
return await CreateItemsAsync(document.Project.Solution.Workspace, semanticModel,
position, result, token, cancellationToken).ConfigureAwait(false);
}
private bool IsSignatureContext(SyntaxToken token)
{
return token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken, SyntaxKind.RefKeyword, SyntaxKind.OutKeyword)
&& token.Parent.IsKind(SyntaxKind.CrefParameterList, SyntaxKind.CrefBracketedParameterList);
}
// LookupSymbols doesn't return indexers or operators because they can't be referred to by name, so we'll have to try to
// find the innermost type declaration and return its operators and indexers
private IEnumerable<ISymbol> GetOperatorsAndIndexers(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var typeDeclaration = token.GetAncestor<TypeDeclarationSyntax>();
var result = new List<ISymbol>();
if (typeDeclaration != null)
{
var type = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
result.AddRange(type.GetMembers().OfType<IPropertySymbol>().Where(p => p.IsIndexer));
result.AddRange(type.GetAccessibleMembersInThisAndBaseTypes<IMethodSymbol>(type)
.Where(m => m.MethodKind == MethodKind.UserDefinedOperator));
}
return result;
}
private async Task<IEnumerable<CompletionItem>> CreateItemsAsync(
Workspace workspace, SemanticModel semanticModel, int textChangeSpanPosition, IEnumerable<ISymbol> symbols, SyntaxToken token, CancellationToken cancellationToken)
{
var items = new List<CompletionItem>();
foreach (var symbol in symbols)
{
var item = await CreateItemAsync(workspace, semanticModel, textChangeSpanPosition, symbol, token, cancellationToken).ConfigureAwait(false);
items.Add(item);
}
return items;
}
private async Task<CompletionItem> CreateItemAsync(
Workspace workspace, SemanticModel semanticModel, int textChangeSpanPosition, ISymbol symbol, SyntaxToken token, CancellationToken cancellationToken)
{
int tokenPosition = token.SpanStart;
string symbolText = string.Empty;
if (symbol is INamespaceOrTypeSymbol && token.IsKind(SyntaxKind.DotToken))
{
symbolText = symbol.Name.EscapeIdentifier();
if (symbol.GetArity() > 0)
{
symbolText += "{";
symbolText += string.Join(", ", ((INamedTypeSymbol)symbol).TypeParameters);
symbolText += "}";
}
}
else
{
symbolText = symbol.ToMinimalDisplayString(semanticModel, tokenPosition, CrefFormat);
var parameters = symbol.GetParameters().Select(p =>
{
var displayName = p.Type.ToMinimalDisplayString(semanticModel, tokenPosition);
if (p.RefKind == RefKind.Out)
{
return "out " + displayName;
}
if (p.RefKind == RefKind.Ref)
{
return "ref " + displayName;
}
return displayName;
});
var parameterList = !symbol.IsIndexer() ? string.Format("({0})", string.Join(", ", parameters))
: string.Format("[{0}]", string.Join(", ", parameters));
symbolText += parameterList;
}
var insertionText = symbolText
.Replace('<', '{')
.Replace('>', '}')
.Replace("()", "");
var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return new CrefCompletionItem(
workspace,
completionProvider: this,
displayText: insertionText,
insertionText: insertionText,
textSpan: GetTextChangeSpan(text, textChangeSpanPosition),
descriptionFactory: CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, tokenPosition, symbol),
glyph: symbol.GetGlyph(),
sortText: symbolText);
}
private TextSpan GetTextChangeSpan(SourceText text, int position)
{
return CommonCompletionUtilities.GetTextChangeSpan(
text,
position,
(ch) => CompletionUtilities.IsTextChangeSpanStartCharacter(ch) || ch == '{',
(ch) => CompletionUtilities.IsWordCharacter(ch) || ch == '{' || ch == '}');
}
private string CreateParameters(IEnumerable<ITypeSymbol> arguments, SemanticModel semanticModel, int position)
{
return string.Join(", ", arguments.Select(t => t.ToMinimalDisplayString(semanticModel, position)));
}
public override TextChange GetTextChange(CompletionItem selectedItem, char? ch = null, string textTypedSoFar = null)
{
return new TextChange(selectedItem.FilterSpan, ((CrefCompletionItem)selectedItem).InsertionText);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// Name used for AGGDECLs in the symbol table.
// AggregateSymbol - a symbol representing an aggregate type. These are classes,
// interfaces, and structs. Parent is a namespace or class. Children are methods,
// properties, and member variables, and types (including its own AGGTYPESYMs).
internal class AggregateSymbol : NamespaceOrAggregateSymbol
{
public Type AssociatedSystemType;
public Assembly AssociatedAssembly;
// This InputFile is some infile for the assembly containing this AggregateSymbol.
// It is used for fast access to the filter BitSet and assembly ID.
private InputFile _infile;
// The instance type. Created when first needed.
private AggregateType _atsInst;
private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused.
private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct.
private TypeArray _ifaces; // The explicit base interfaces for a class or interface.
private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces.
private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations.
private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes.
private TypeManager _pTypeManager; // This is so AGGTYPESYMs can instantiate their baseClass and ifacesAll members on demand.
// First UD conversion operator. This chain is for this type only (not base types).
// The hasConversion flag indicates whether this or any base types have UD conversions.
private MethodSymbol _pConvFirst;
// ------------------------------------------------------------------------
//
// Put members that are bits under here in a contiguous section.
//
// ------------------------------------------------------------------------
private AggKindEnum _aggKind;
private bool _isLayoutError; // Whether there is a cycle in the layout for the struct
// Where this came from - fabricated, source, import
// Fabricated AGGs have isSource == true but hasParseTree == false.
// N.B.: in incremental builds, it is quite possible for
// isSource==TRUE and hasParseTree==FALSE. Be
// sure you use the correct variable for what you are trying to do!
private bool _isSource; // This class is defined in source, although the
// source might not be being read during this compile.
// Predefined
private bool _isPredefined; // A special predefined type.
private PredefinedType _iPredef; // index of the predefined type, if isPredefined.
// Flags
private bool _isAbstract; // Can it be instantiated?
private bool _isSealed; // Can it be derived from?
// Attribute
private bool _isUnmanagedStruct; // Set if the struct is known to be un-managed (for unsafe code). Set in FUNCBREC.
private bool _isManagedStruct; // Set if the struct is known to be managed (for unsafe code). Set during import.
// Constructors
private bool _hasPubNoArgCtor; // Whether it has a public instance constructor taking no args
// private struct members should not be checked for assignment or references
private bool _hasExternReference;
// User defined operators
private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate).
private bool _isAnonymousType; // true if the class is an anonymous type
// When this is unset we don't know if we have conversions. When this
// is set it indicates if this type or any base type has user defined
// conversion operators
private bool? _hasConversion;
// ----------------------------------------------------------------------------
// AggregateSymbol
// ----------------------------------------------------------------------------
public AggregateSymbol GetBaseAgg()
{
return _pBaseClass?.getAggregate();
}
public AggregateType getThisType()
{
if (_atsInst == null)
{
Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested());
AggregateType pOuterType = isNested() ? GetOuterAgg().getThisType() : null;
_atsInst = _pTypeManager.GetAggregate(this, pOuterType, GetTypeVars());
}
//Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count);
return _atsInst;
}
public void InitFromInfile(InputFile infile)
{
_infile = infile;
_isSource = infile.isSource;
}
public bool FindBaseAgg(AggregateSymbol agg)
{
for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg())
{
if (aggT == agg)
return true;
}
return false;
}
public NamespaceOrAggregateSymbol Parent
{
get { return parent.AsNamespaceOrAggregateSymbol(); }
}
private new AggregateDeclaration DeclFirst()
{
return (AggregateDeclaration)base.DeclFirst();
}
public AggregateDeclaration DeclOnly()
{
//Debug.Assert(DeclFirst() != null && DeclFirst().DeclNext() == null);
return DeclFirst();
}
public bool InAlias(KAID aid)
{
Debug.Assert(_infile != null);
//Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID());
Debug.Assert(0 <= aid);
if (aid < KAID.kaidMinModule)
return _infile.InAlias(aid);
return (aid == GetModuleID());
}
private KAID GetModuleID()
{
return 0;
}
public KAID GetAssemblyID()
{
Debug.Assert(_infile != null);
//Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID());
return _infile.GetAssemblyID();
}
public bool IsUnresolved()
{
return _infile != null && _infile.GetAssemblyID() == KAID.kaidUnresolved;
}
public bool isNested()
{
return parent != null && parent.IsAggregateSymbol();
}
public AggregateSymbol GetOuterAgg()
{
return parent != null && parent.IsAggregateSymbol() ? parent.AsAggregateSymbol() : null;
}
public bool isPredefAgg(PredefinedType pt)
{
return _isPredefined && (PredefinedType)_iPredef == pt;
}
// ----------------------------------------------------------------------------
// The following are the Accessor functions for AggregateSymbol.
// ----------------------------------------------------------------------------
public AggKindEnum AggKind()
{
return (AggKindEnum)_aggKind;
}
public void SetAggKind(AggKindEnum aggKind)
{
// NOTE: When importing can demote types:
// - enums with no underlying type go to struct
// - delegates which are abstract or have no .ctor/Invoke method goto class
_aggKind = aggKind;
//An interface is always abstract
if (aggKind == AggKindEnum.Interface)
{
SetAbstract(true);
}
}
public bool IsClass()
{
return AggKind() == AggKindEnum.Class;
}
public bool IsDelegate()
{
return AggKind() == AggKindEnum.Delegate;
}
public bool IsInterface()
{
return AggKind() == AggKindEnum.Interface;
}
public bool IsStruct()
{
return AggKind() == AggKindEnum.Struct;
}
public bool IsEnum()
{
return AggKind() == AggKindEnum.Enum;
}
public bool IsValueType()
{
return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum;
}
public bool IsRefType()
{
return AggKind() == AggKindEnum.Class ||
AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate;
}
public bool IsStatic()
{
return (_isAbstract && _isSealed);
}
public bool IsAnonymousType()
{
return _isAnonymousType;
}
public void SetAnonymousType(bool isAnonymousType)
{
_isAnonymousType = isAnonymousType;
}
public bool IsAbstract()
{
return _isAbstract;
}
public void SetAbstract(bool @abstract)
{
_isAbstract = @abstract;
}
public bool IsPredefined()
{
return _isPredefined;
}
public void SetPredefined(bool predefined)
{
_isPredefined = predefined;
}
public PredefinedType GetPredefType()
{
return (PredefinedType)_iPredef;
}
public void SetPredefType(PredefinedType predef)
{
_iPredef = predef;
}
public bool IsLayoutError()
{
return _isLayoutError == true;
}
public void SetLayoutError(bool layoutError)
{
_isLayoutError = layoutError;
}
public bool IsSealed()
{
return _isSealed == true;
}
public void SetSealed(bool @sealed)
{
_isSealed = @sealed;
}
////////////////////////////////////////////////////////////////////////////////
public bool HasConversion(SymbolLoader pLoader)
{
pLoader.RuntimeBinderSymbolTable.AddConversionsForType(AssociatedSystemType);
if (!_hasConversion.HasValue)
{
// ok, we tried defining all the conversions, and we didn't get anything
// for this type. However, we will still think this type has conversions
// if it's base type has conversions.
_hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion(pLoader);
}
return _hasConversion.Value;
}
////////////////////////////////////////////////////////////////////////////////
public void SetHasConversion()
{
_hasConversion = true;
}
////////////////////////////////////////////////////////////////////////////////
private bool IsUnmanagedStruct()
{
return _isUnmanagedStruct;
}
public void SetUnmanagedStruct(bool unmanagedStruct)
{
_isUnmanagedStruct = unmanagedStruct;
}
public bool IsManagedStruct()
{
return _isManagedStruct == true;
}
public void SetManagedStruct(bool managedStruct)
{
_isManagedStruct = managedStruct;
}
public bool IsKnownManagedStructStatus()
{
Debug.Assert(IsStruct());
Debug.Assert(!IsManagedStruct() || !IsUnmanagedStruct());
return IsManagedStruct() || IsUnmanagedStruct();
}
public bool HasPubNoArgCtor()
{
return _hasPubNoArgCtor == true;
}
public void SetHasPubNoArgCtor(bool hasPubNoArgCtor)
{
_hasPubNoArgCtor = hasPubNoArgCtor;
}
public bool HasExternReference()
{
return _hasExternReference == true;
}
public void SetHasExternReference(bool hasExternReference)
{
_hasExternReference = hasExternReference;
}
public bool IsSkipUDOps()
{
return _isSkipUDOps == true;
}
public void SetSkipUDOps(bool skipUDOps)
{
_isSkipUDOps = skipUDOps;
}
public bool IsSource()
{
return _isSource == true;
}
public TypeArray GetTypeVars()
{
return _typeVarsThis;
}
public void SetTypeVars(TypeArray typeVars)
{
if (typeVars == null)
{
_typeVarsThis = null;
_typeVarsAll = null;
}
else
{
TypeArray outerTypeVars;
if (GetOuterAgg() != null)
{
Debug.Assert(GetOuterAgg().GetTypeVars() != null);
Debug.Assert(GetOuterAgg().GetTypeVarsAll() != null);
outerTypeVars = GetOuterAgg().GetTypeVarsAll();
}
else
{
outerTypeVars = BSYMMGR.EmptyTypeArray();
}
_typeVarsThis = typeVars;
_typeVarsAll = _pTypeManager.ConcatenateTypeArrays(outerTypeVars, typeVars);
}
}
public TypeArray GetTypeVarsAll()
{
return _typeVarsAll;
}
public AggregateType GetBaseClass()
{
return _pBaseClass;
}
public void SetBaseClass(AggregateType baseClass)
{
_pBaseClass = baseClass;
}
public AggregateType GetUnderlyingType()
{
return _pUnderlyingType;
}
public void SetUnderlyingType(AggregateType underlyingType)
{
_pUnderlyingType = underlyingType;
}
public TypeArray GetIfaces()
{
return _ifaces;
}
public void SetIfaces(TypeArray ifaces)
{
_ifaces = ifaces;
}
public TypeArray GetIfacesAll()
{
return _ifacesAll;
}
public void SetIfacesAll(TypeArray ifacesAll)
{
_ifacesAll = ifacesAll;
}
public TypeManager GetTypeManager()
{
return _pTypeManager;
}
public void SetTypeManager(TypeManager typeManager)
{
_pTypeManager = typeManager;
}
public MethodSymbol GetFirstUDConversion()
{
return _pConvFirst;
}
public void SetFirstUDConversion(MethodSymbol conv)
{
_pConvFirst = conv;
}
public bool InternalsVisibleTo(Assembly assembly)
{
return _pTypeManager.InternalsVisibleTo(AssociatedAssembly, assembly);
}
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
using crypt = System.Security.Cryptography;
namespace SourceCode.Clay.Tests
{
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public static class Sha256Tests
{
private static readonly crypt.SHA256 s_sha256 = crypt.SHA256.Create();
[Trait("Type", "Unit")]
[Fact]
public static void When_check_default()
{
var expected = default(Sha256);
var actual = Sha256.Parse(Sha256TestVectors.Zero);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_check_empty()
{
var expected = Sha256.Parse(Sha256TestVectors.Empty);
// Empty Array singleton
Sha256 actual = s_sha256.HashData(Array.Empty<byte>());
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty Array
actual = s_sha256.HashData(new byte[0]);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty default ArraySegment
actual = s_sha256.HashData(default(ArraySegment<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty new ArraySegment
actual = s_sha256.HashData(new ArraySegment<byte>(new byte[0], 0, 0));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty default Span
actual = s_sha256.HashData(default(Span<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty new Span
actual = s_sha256.HashData(new Span<byte>(new byte[0], 0, 0));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty default ReadOnlySpan
actual = s_sha256.HashData(default(ReadOnlySpan<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty new ReadOnlySpan
actual = s_sha256.HashData(new ReadOnlySpan<byte>(new byte[0], 0, 0));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty String
actual = s_sha256.HashData(string.Empty);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_null_sha256()
{
var expected = default(Sha256);
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(null));
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(new Span<byte>()));
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(new Span<byte>(new byte[0])));
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(new Span<byte>(new byte[1] { 0 })));
Assert.True(default == expected);
Assert.False(default != expected);
Assert.True(expected.Equals((object)expected));
Assert.Equal(new KeyValuePair<string, string>("", Sha256TestVectors.Zero), expected.Split(0, false));
Assert.Equal(new KeyValuePair<string, string>("", Sha256TestVectors.Zero), expected.Split(0, true));
Assert.Equal(new KeyValuePair<string, string>("00", Sha256TestVectors.Zero.Left(Sha256.HexLength - 2)), expected.Split(2, false));
Assert.Equal(new KeyValuePair<string, string>("00", Sha256TestVectors.Zero.Left(Sha256.HexLength - 2).ToUpperInvariant()), expected.Split(2, true));
Assert.Equal(new KeyValuePair<string, string>(Sha256TestVectors.Zero, ""), expected.Split(Sha256.HexLength, false));
Assert.Equal(new KeyValuePair<string, string>(Sha256TestVectors.Zero, ""), expected.Split(Sha256.HexLength, true));
// Null string
Assert.Throws<ArgumentNullException>(() => s_sha256.HashData((string)null));
// Null bytes
Assert.Throws<ArgumentNullException>(() => s_sha256.HashData((byte[])null));
Assert.Throws<ArgumentNullException>(() => s_sha256.HashData(null, 0, 0));
// Stream
Assert.Throws<ArgumentNullException>(() => s_sha256.HashData((Stream)null));
// Roundtrip string
var actual = Sha256.Parse(expected.ToString());
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip formatted
actual = Sha256.Parse(expected.ToString("D"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha256.Parse(expected.ToString("S"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// With hex specifier
actual = Sha256.Parse("0x" + expected.ToString("D"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha256.Parse("0x" + expected.ToString("S"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha256_from_Bytes()
{
Sha256 expected = s_sha256.HashData("abc");
byte[] buffer = new byte[Sha256.ByteLength + 10];
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(new byte[Sha256.ByteLength - 1])); // Too short
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(new byte[Sha256.ByteLength].AsSpan().Slice(1))); // Bad offset
// Construct Byte[]
expected.CopyTo(buffer.AsSpan());
var actual = new Sha256(buffer);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Byte[] with offset 0
expected.CopyTo(buffer.AsSpan());
actual = new Sha256(buffer);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Byte[] with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
actual = new Sha256(buffer.AsSpan().Slice(5));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha256_from_ArraySegment()
{
Sha256 expected = s_sha256.HashData("abc");
byte[] buffer = new byte[Sha256.ByteLength + 10];
// Construct Byte[] with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
var actual = new Sha256(buffer.AsSpan().Slice(5));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Segment
expected.CopyTo(buffer.AsSpan());
var seg = new ArraySegment<byte>(buffer);
actual = new Sha256(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Segment with offset 0
expected.CopyTo(buffer.AsSpan());
seg = new ArraySegment<byte>(buffer, 0, Sha256.ByteLength);
actual = new Sha256(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Segment with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
seg = new ArraySegment<byte>(buffer, 5, Sha256.ByteLength);
actual = new Sha256(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha256_from_Memory()
{
Sha256 expected = s_sha256.HashData("abc");
byte[] buffer = new byte[Sha256.ByteLength + 10];
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(Memory<byte>.Empty.Span)); // Empty
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha256(new Memory<byte>(new byte[Sha256.ByteLength - 1]).Span)); // Too short
// Construct Memory
expected.CopyTo(buffer.AsSpan());
var mem = new Memory<byte>(buffer);
var actual = new Sha256(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Memory with offset 0
expected.CopyTo(buffer.AsSpan());
mem = new Memory<byte>(buffer, 0, Sha256.ByteLength);
actual = new Sha256(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Memory with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
mem = new Memory<byte>(buffer, 5, Sha256.ByteLength);
actual = new Sha256(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha256_from_ReadOnlyMemory()
{
Sha256 expected = s_sha256.HashData("abc");
byte[] buffer = new byte[Sha256.ByteLength + 10];
// Construct ReadOnlyMemory
expected.CopyTo(buffer.AsSpan());
var mem = new ReadOnlyMemory<byte>(buffer);
var actual = new Sha256(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlyMemory with offset 0
expected.CopyTo(buffer.AsSpan());
mem = new ReadOnlyMemory<byte>(buffer, 0, Sha256.ByteLength);
actual = new Sha256(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlyMemory with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
mem = new ReadOnlyMemory<byte>(buffer, 5, Sha256.ByteLength);
actual = new Sha256(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha256_from_Stream()
{
byte[] buffer = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
// Construct MemoryStream
var mem = new MemoryStream(buffer);
Sha256 expected = s_sha256.HashData(buffer);
Sha256 actual = s_sha256.HashData(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct MemoryStream with offset 0
mem = new MemoryStream(buffer, 0, buffer.Length);
expected = s_sha256.HashData(buffer, 0, buffer.Length);
actual = s_sha256.HashData(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct MemoryStream with offset N
mem = new MemoryStream(buffer, 5, buffer.Length - 5);
expected = s_sha256.HashData(buffer, 5, buffer.Length - 5);
actual = s_sha256.HashData(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha256_from_Span()
{
Sha256 expected = s_sha256.HashData("abc");
byte[] buffer = new byte[Sha256.ByteLength + 10];
// Construct Span
expected.CopyTo(buffer.AsSpan());
var span = new Span<byte>(buffer);
var actual = new Sha256(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Span with offset 0
expected.CopyTo(buffer.AsSpan());
span = new Span<byte>(buffer, 0, Sha256.ByteLength);
actual = new Sha256(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Span with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
span = new Span<byte>(buffer, 5, Sha256.ByteLength);
actual = new Sha256(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_copyto_with_null_buffer()
{
// Arrange
byte[] buffer = null;
var sha256 = new Sha256();
// Action
ArgumentException actual = Assert.Throws<ArgumentException>(() => sha256.CopyTo(buffer.AsSpan()));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha256_from_ReadOnlySpan()
{
Sha256 expected = s_sha256.HashData("abc");
byte[] buffer = new byte[Sha256.ByteLength + 10];
// Construct ReadOnlySpan
expected.CopyTo(buffer.AsSpan());
var span = new ReadOnlySpan<byte>(buffer);
var actual = new Sha256(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlySpan with offset 0
expected.CopyTo(buffer.AsSpan());
span = new ReadOnlySpan<byte>(buffer, 0, Sha256.ByteLength);
actual = new Sha256(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlySpan with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
span = new ReadOnlySpan<byte>(buffer, 5, Sha256.ByteLength);
actual = new Sha256(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Theory]
[ClassData(typeof(Sha256TestVectors))] // http://www.di-mgt.com.au/sha_testvectors.html
public static void When_create_test_vectors(string input, string expected)
{
var sha256 = Sha256.Parse(expected);
{
// String
string actual = s_sha256.HashData(input).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(Sha256.HexLength, Encoding.UTF8.GetByteCount(actual));
// Bytes
byte[] bytes = Encoding.UTF8.GetBytes(input);
actual = s_sha256.HashData(bytes).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = s_sha256.HashData(bytes, 0, bytes.Length).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Object
Assert.True(expected.Equals((object)actual));
// Roundtrip string
actual = sha256.ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip formatted
actual = Sha256.Parse(sha256.ToString("D")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha256.Parse(sha256.ToString("S")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// With hex specifier
actual = Sha256.Parse("0x" + sha256.ToString("D")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha256.Parse("0x" + sha256.ToString("S")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Get Byte[]
byte[] buffer = new byte[Sha256.ByteLength];
sha256.CopyTo(buffer.AsSpan());
// Roundtrip Byte[]
actual = new Sha256(buffer).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip Segment
actual = new Sha256(new ArraySegment<byte>(buffer)).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha256_from_empty_ArraySegment()
{
Sha256 expected = s_sha256.HashData(Array.Empty<byte>());
// Empty segment
Sha256 actual = s_sha256.HashData(default(ArraySegment<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_bytes()
{
byte[] buffer = new byte[Sha256.ByteLength];
byte[] tinyBuffer = new byte[Sha256.ByteLength - 1];
for (int i = 1; i < 200; i++)
{
string str = new string(char.MinValue, i);
byte[] byt = Encoding.UTF8.GetBytes(str);
Sha256 sha = s_sha256.HashData(byt);
Assert.NotEqual(default, sha);
Assert.Equal(Sha256.HexLength, Encoding.UTF8.GetByteCount(sha.ToString()));
bool copied = sha.TryCopyTo(buffer);
Assert.True(copied);
var shb = new Sha256(buffer);
Assert.Equal(sha, shb);
copied = sha.TryCopyTo(tinyBuffer);
Assert.False(copied);
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_empty_string()
{
const string expected = Sha256TestVectors.Empty; // http://www.di-mgt.com.au/sha_testvectors.html
var sha256 = Sha256.Parse(expected);
{
const string input = "";
// String
string actual = s_sha256.HashData(input).ToString();
Assert.Equal(expected, actual);
Assert.Equal(Sha256.HexLength, Encoding.UTF8.GetByteCount(actual));
// Empty array
actual = s_sha256.HashData(Array.Empty<byte>()).ToString();
Assert.Equal(expected, actual);
actual = s_sha256.HashData(Array.Empty<byte>(), 0, 0).ToString();
Assert.Equal(expected, actual);
// Empty segment
actual = s_sha256.HashData(new ArraySegment<byte>(Array.Empty<byte>())).ToString();
Assert.Equal(expected, actual);
// Bytes
byte[] bytes = Encoding.UTF8.GetBytes(input);
actual = s_sha256.HashData(bytes).ToString();
Assert.Equal(expected, actual);
// Object
Assert.True(expected.Equals((object)actual));
// Roundtrip string
actual = sha256.ToString();
Assert.Equal(expected, actual);
// Roundtrip formatted
actual = Sha256.Parse(sha256.ToString("D")).ToString();
Assert.Equal(expected, actual);
actual = Sha256.Parse(sha256.ToString("S")).ToString();
Assert.Equal(expected, actual);
// With hex specifier
actual = Sha256.Parse("0x" + sha256.ToString("D")).ToString();
Assert.Equal(expected, actual);
actual = Sha256.Parse("0x" + sha256.ToString("S")).ToString();
Assert.Equal(expected, actual);
// Get Byte[]
byte[] buffer = new byte[Sha256.ByteLength];
sha256.CopyTo(buffer.AsSpan());
// Roundtrip Byte[]
actual = new Sha256(buffer).ToString();
Assert.Equal(expected, actual);
// Roundtrip Segment
actual = new Sha256(new ArraySegment<byte>(buffer)).ToString();
Assert.Equal(expected, actual);
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_narrow_string()
{
for (int i = 1; i < 200; i++)
{
string str = new string(char.MinValue, i);
Sha256 sha256 = s_sha256.HashData(str);
Assert.NotEqual(default, sha256);
Assert.Equal(Sha256.HexLength, Encoding.UTF8.GetByteCount(sha256.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_wide_string_1()
{
for (int i = 1; i < 200; i++)
{
string str = new string(char.MaxValue, i);
Sha256 sha256 = s_sha256.HashData(str);
Assert.NotEqual(default, sha256);
Assert.Equal(Sha256.HexLength, Encoding.UTF8.GetByteCount(sha256.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_wide_string_2()
{
string str = string.Empty;
for (int i = 1; i < 200; i++)
{
str += TestConstants.SurrogatePair;
Sha256 sha256 = s_sha256.HashData(str);
Assert.NotEqual(default, sha256);
Assert.Equal(Sha256.HexLength, Encoding.UTF8.GetByteCount(sha256.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_format_sha256()
{
// http://www.di-mgt.com.au/sha_testvectors.html
const string expected_N = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
var sha256 = Sha256.Parse(expected_N);
// ("N")
{
string actual = sha256.ToString(); // Default format
Assert.Equal(expected_N, actual);
actual = sha256.ToString("N");
Assert.Equal(expected_N.ToUpperInvariant(), actual);
actual = sha256.ToString("n");
Assert.Equal(expected_N, actual);
}
// ("D")
{
const string expected_D = "cdc76e5c-9914fb92-81a1c7e2-84d73e67-f1809a48-a497200e-046d39cc-c7112cd0";
string actual = sha256.ToString("D");
Assert.Equal(expected_D.ToUpperInvariant(), actual);
actual = sha256.ToString("d");
Assert.Equal(expected_D, actual);
}
// ("S")
{
const string expected_S = "cdc76e5c 9914fb92 81a1c7e2 84d73e67 f1809a48 a497200e 046d39cc c7112cd0";
string actual = sha256.ToString("S");
Assert.Equal(expected_S.ToUpperInvariant(), actual);
actual = sha256.ToString("s");
Assert.Equal(expected_S, actual);
}
// (null)
{
Assert.Throws<FormatException>(() => sha256.ToString(null));
}
// ("")
{
Assert.Throws<FormatException>(() => sha256.ToString(""));
}
// (" ")
{
Assert.Throws<FormatException>(() => sha256.ToString(" "));
}
// ("x")
{
Assert.Throws<FormatException>(() => sha256.ToString("x"));
}
// ("ss")
{
Assert.Throws<FormatException>(() => sha256.ToString("nn"));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_parse_sha256()
{
// http://www.di-mgt.com.au/sha_testvectors.html
const string expected_N = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
var sha256 = Sha256.Parse(expected_N);
Assert.True(Sha256.TryParse(expected_N, out _));
Assert.True(Sha256.TryParse(expected_N.AsSpan(), out _));
Assert.True(Sha256.TryParse("0x" + expected_N, out _));
Assert.True(Sha256.TryParse("0X" + expected_N, out _));
Assert.False(Sha256.TryParse(expected_N.Substring(10), out _));
Assert.False(Sha256.TryParse("0x" + expected_N.Substring(10), out _));
Assert.False(Sha256.TryParse("0X" + expected_N.Substring(10), out _));
Assert.False(Sha256.TryParse("0x" + expected_N.Substring(Sha256.HexLength - 2), out _));
Assert.False(Sha256.TryParse("0X" + expected_N.Substring(Sha256.HexLength - 2), out _));
Assert.False(Sha256.TryParse(expected_N.Replace('8', 'G'), out _));
Assert.False(Sha256.TryParse(expected_N.Replace('8', 'G').AsSpan(), out _));
Assert.Throws<FormatException>(() => Sha256.Parse(expected_N.Replace('8', 'G').AsSpan()));
Assert.False(Sha256.TryParse($"0x{new string('1', Sha256.HexLength - 2)}", out _));
Assert.False(Sha256.TryParse($"0x{new string('1', Sha256.HexLength - 1)}", out _));
Assert.True(Sha256.TryParse($"0x{new string('1', Sha256.HexLength)}", out _));
// "N"
{
var actual = Sha256.Parse(sha256.ToString()); // Default format
Assert.Equal(sha256, actual);
actual = Sha256.Parse(sha256.ToString("N"));
Assert.Equal(sha256, actual);
actual = Sha256.Parse("0x" + sha256.ToString("N"));
Assert.Equal(sha256, actual);
Assert.Throws<FormatException>(() => Sha256.Parse(sha256.ToString("N") + "a"));
}
// "D"
{
var actual = Sha256.Parse(sha256.ToString("D"));
Assert.Equal(sha256, actual);
actual = Sha256.Parse("0x" + sha256.ToString("D"));
Assert.Equal(sha256, actual);
Assert.Throws<FormatException>(() => Sha256.Parse(sha256.ToString("D") + "a"));
}
// "S"
{
var actual = Sha256.Parse(sha256.ToString("S"));
Assert.Equal(sha256, actual);
actual = Sha256.Parse("0x" + sha256.ToString("S"));
Assert.Equal(sha256, actual);
Assert.Throws<FormatException>(() => Sha256.Parse(sha256.ToString("S") + "a"));
}
// null
{
Assert.Throws<ArgumentNullException>(() => Sha256.Parse(null));
}
// Empty
{
Assert.Throws<FormatException>(() => Sha256.Parse(""));
}
// Whitespace
{
Assert.Throws<FormatException>(() => Sha256.Parse(" "));
Assert.Throws<FormatException>(() => Sha256.Parse("\t"));
}
// "0x"
{
Assert.Throws<FormatException>(() => Sha256.Parse("0x"));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_lexographic_compare_sha256()
{
byte[] byt1 = new byte[32] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
var sha256 = new Sha256(byt1);
string str1 = sha256.ToString();
Assert.Equal("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", str1);
for (int n = 0; n < 20; n++)
{
for (int i = n + 1; i <= byte.MaxValue; i++)
{
// Bump blit[n]
byt1[n] = (byte)i;
var sha2 = new Sha256(byt1);
Assert.True(sha2 > sha256);
}
byt1[n] = (byte)n;
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_compare_sha256()
{
Sha256 sha256 = s_sha256.HashData("abc"); // ba7816bf-8f01cfea-414140de-5dae2223-b00361a3-96177a9c-b410ff61-f20015ad
Assert.True(default(Sha256) < sha256);
Assert.True(sha256 > default(Sha256));
Sha256 sha2 = sha256; // ba7816bf-8f01cfea-414140de-5dae2223-b00361a3-96177a9c-b410ff61-f20015ad
Assert.True(sha2 <= sha256);
Assert.True(sha2 >= sha256);
Assert.False(sha2 < sha256);
Assert.False(sha2 > sha256);
Sha256 sha3 = s_sha256.HashData("def"); // cb8379ac-2098aa16-5029e393-8a51da0b-cecfc008-fd6795f4-01178647-f96c5b34
Assert.True(sha256.CompareTo(sha2) == 0);
Assert.True(sha256.CompareTo(sha3) != 0);
var span = new Span<byte>(new byte[Sha256.ByteLength]);
sha256.CopyTo(span);
span[Sha256.ByteLength - 1]++;
var sha4 = new Sha256(span); // ba7816bf-8f01cfea-414140de-5dae2223-b00361a3-96177a9c-b410ff61-f20015ae
Assert.True(sha4 >= sha256);
Assert.True(sha4 > sha256);
Assert.False(sha4 < sha256);
Assert.False(sha4 <= sha256);
Assert.True(sha256.CompareTo(sha4) < 0);
Sha256[] list = new[] { sha4, sha256, sha2, sha3 };
Sha256Comparer comparer = Sha256Comparer.Default;
Array.Sort(list, comparer.Compare);
Assert.True(list[0] == list[1]);
Assert.True(list[2] > list[1]);
Assert.True(list[2] < list[3]);
}
[Trait("Type", "Unit")]
[Fact]
public static void When_parse_sha256_whitespace()
{
const string whitespace = " \n \t \r ";
Sha256 expected = s_sha256.HashData("abc"); // ba7816bf-8f01cfea-414140de-5dae2223-b00361a3-96177a9c-b410ff61-f20015ad
string str = expected.ToString();
// Leading whitespace
var actual = Sha256.Parse(whitespace + str);
Assert.Equal(expected, actual);
// Trailing whitespace
actual = Sha256.Parse(str + whitespace);
Assert.Equal(expected, actual);
// Both
actual = Sha256.Parse(whitespace + str + whitespace);
Assert.Equal(expected, actual);
// Fail
Assert.False(Sha256.TryParse("1" + str, out _));
Assert.False(Sha256.TryParse(str + "1", out _));
Assert.False(Sha256.TryParse("1" + whitespace + str, out _));
Assert.False(Sha256.TryParse(str + whitespace + "1", out _));
Assert.False(Sha256.TryParse("1" + whitespace + str + whitespace, out _));
Assert.False(Sha256.TryParse(whitespace + str + whitespace + "1", out _));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_sha256_equality()
{
var sha0 = default(Sha256);
Sha256 sha1 = s_sha256.HashData("abc");
Sha256 sha2 = s_sha256.HashData("abc");
Sha256 sha3 = s_sha256.HashData("def");
Assert.True(sha1 == sha2);
Assert.False(sha1 != sha2);
Assert.True(sha1.Equals((object)sha2));
Assert.False(sha1.Equals(new object()));
Assert.Equal(sha1, sha2);
Assert.Equal(sha1.GetHashCode(), sha2.GetHashCode());
Assert.Equal(sha1.ToString(), sha2.ToString());
Assert.NotEqual(sha0, sha1);
Assert.NotEqual(sha0.GetHashCode(), sha1.GetHashCode());
Assert.NotEqual(sha0.ToString(), sha1.ToString());
Assert.NotEqual(sha3, sha1);
Assert.NotEqual(sha3.GetHashCode(), sha1.GetHashCode());
Assert.NotEqual(sha3.ToString(), sha1.ToString());
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\CapsuleComponent.h:16
namespace UnrealEngine
{
[ManageType("ManageCapsuleComponent")]
public partial class ManageCapsuleComponent : UCapsuleComponent, IManageWrapper
{
public ManageCapsuleComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_UpdateBodySetup(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnComponentCollisionSettingsChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PutAllRigidBodiesToSleep(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetAllMassScale(IntPtr self, float inMassScale);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetAllUseCCD(IntPtr self, bool inUseCCD);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetAngularDamping(IntPtr self, float inDamping);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetEnableGravity(IntPtr self, bool bGravityEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetLinearDamping(IntPtr self, float inDamping);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetNotifyRigidBodyCollision(IntPtr self, bool bNewNotifyRigidBodyCollision);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetSimulatePhysics(IntPtr self, bool bSimulate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_UnWeldChildren(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_UnWeldFromParent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_UpdatePhysicsToRBChannels(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_WakeAllRigidBodies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnAttachmentChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnHiddenInGameChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnVisibilityChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PropagateLightingScenarioChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_UpdateBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCapsuleComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Update the body setup parameters based on shape information
/// </summary>
public override void UpdateBodySetup()
=> E__Supper__UCapsuleComponent_UpdateBodySetup(this);
/// <summary>
/// Called when the BodyInstance ResponseToChannels, CollisionEnabled or bNotifyRigidBodyCollision changes, in case subclasses want to use that information.
/// </summary>
protected override void OnComponentCollisionSettingsChanged()
=> E__Supper__UCapsuleComponent_OnComponentCollisionSettingsChanged(this);
/// <summary>
/// Force all bodies in this component to sleep.
/// </summary>
public override void PutAllRigidBodiesToSleep()
=> E__Supper__UCapsuleComponent_PutAllRigidBodiesToSleep(this);
/// <summary>
/// Change the mass scale used fo all bodies in this component
/// </summary>
public override void SetAllMassScale(float inMassScale)
=> E__Supper__UCapsuleComponent_SetAllMassScale(this, inMassScale);
/// <summary>
/// Set whether all bodies in this component should use Continuous Collision Detection
/// </summary>
public override void SetAllUseCCD(bool inUseCCD)
=> E__Supper__UCapsuleComponent_SetAllUseCCD(this, inUseCCD);
/// <summary>
/// Sets the angular damping of this component.
/// </summary>
public override void SetAngularDamping(float inDamping)
=> E__Supper__UCapsuleComponent_SetAngularDamping(this, inDamping);
/// <summary>
/// Enables/disables whether this component is affected by gravity. This applies only to components with bSimulatePhysics set to true.
/// </summary>
public override void SetEnableGravity(bool bGravityEnabled)
=> E__Supper__UCapsuleComponent_SetEnableGravity(this, bGravityEnabled);
/// <summary>
/// Sets the linear damping of this component.
/// </summary>
public override void SetLinearDamping(float inDamping)
=> E__Supper__UCapsuleComponent_SetLinearDamping(this, inDamping);
/// <summary>
/// Changes the value of bNotifyRigidBodyCollision
/// </summary>
public override void SetNotifyRigidBodyCollision(bool bNewNotifyRigidBodyCollision)
=> E__Supper__UCapsuleComponent_SetNotifyRigidBodyCollision(this, bNewNotifyRigidBodyCollision);
/// <summary>
/// Sets whether or not a single body should use physics simulation, or should be 'fixed' (kinematic).
/// <para>Note that if this component is currently attached to something, beginning simulation will detach it. </para>
/// </summary>
/// <param name="bSimulate">New simulation state for single body</param>
public override void SetSimulatePhysics(bool bSimulate)
=> E__Supper__UCapsuleComponent_SetSimulatePhysics(this, bSimulate);
/// <summary>
/// Unwelds the children of this component. Attachment is maintained
/// </summary>
public override void UnWeldChildren()
=> E__Supper__UCapsuleComponent_UnWeldChildren(this);
/// <summary>
/// UnWelds this component from its parent component. Attachment is maintained (DetachFromParent automatically unwelds)
/// </summary>
public override void UnWeldFromParent()
=> E__Supper__UCapsuleComponent_UnWeldFromParent(this);
/// <summary>
/// Internal function that updates physics objects to match the component collision settings.
/// </summary>
protected override void UpdatePhysicsToRBChannels()
=> E__Supper__UCapsuleComponent_UpdatePhysicsToRBChannels(this);
/// <summary>
/// Ensure simulation is running for all bodies in this component.
/// </summary>
public override void WakeAllRigidBodies()
=> E__Supper__UCapsuleComponent_WakeAllRigidBodies(this);
/// <summary>
/// DEPRECATED - Use DetachFromComponent() instead
/// </summary>
public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify)
=> E__Supper__UCapsuleComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify);
/// <summary>
/// Called when AttachParent changes, to allow the scene to update its attachment state.
/// </summary>
public override void OnAttachmentChanged()
=> E__Supper__UCapsuleComponent_OnAttachmentChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the hidden in game value of the component.
/// </summary>
protected override void OnHiddenInGameChanged()
=> E__Supper__UCapsuleComponent_OnHiddenInGameChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the visibility of the component.
/// </summary>
protected override void OnVisibilityChanged()
=> E__Supper__UCapsuleComponent_OnVisibilityChanged(this);
/// <summary>
/// Updates any visuals after the lighting has changed
/// </summary>
public override void PropagateLightingScenarioChange()
=> E__Supper__UCapsuleComponent_PropagateLightingScenarioChange(this);
/// <summary>
/// Update the Bounds of the component.
/// </summary>
public override void UpdateBounds()
=> E__Supper__UCapsuleComponent_UpdateBounds(this);
/// <summary>
/// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true.
/// </summary>
/// <param name="bTriggerNotifiers">if true, send zone/volume change events</param>
public override void UpdatePhysicsVolume(bool bTriggerNotifiers)
=> E__Supper__UCapsuleComponent_UpdatePhysicsVolume(this, bTriggerNotifiers);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__UCapsuleComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__UCapsuleComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__UCapsuleComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__UCapsuleComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__UCapsuleComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__UCapsuleComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__UCapsuleComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__UCapsuleComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__UCapsuleComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__UCapsuleComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__UCapsuleComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__UCapsuleComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__UCapsuleComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__UCapsuleComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__UCapsuleComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__UCapsuleComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__UCapsuleComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__UCapsuleComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__UCapsuleComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__UCapsuleComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__UCapsuleComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__UCapsuleComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__UCapsuleComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__UCapsuleComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__UCapsuleComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UCapsuleComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UCapsuleComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UCapsuleComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UCapsuleComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UCapsuleComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UCapsuleComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UCapsuleComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UCapsuleComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UCapsuleComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UCapsuleComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UCapsuleComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UCapsuleComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UCapsuleComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UCapsuleComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UCapsuleComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageCapsuleComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageCapsuleComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageCapsuleComponent>(PtrDesc);
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.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.
* - Neither the name of the openmetaverse.org 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;
namespace OpenMetaverse.Imaging
{
public class ManagedImage
{
[Flags]
public enum ImageChannels
{
Gray = 1,
Color = 2,
Alpha = 4,
Bump = 8
};
public enum ImageResizeAlgorithm
{
NearestNeighbor
}
/// <summary>
/// Image width
/// </summary>
public int Width;
/// <summary>
/// Image height
/// </summary>
public int Height;
/// <summary>
/// Image channel flags
/// </summary>
public ImageChannels Channels;
/// <summary>
/// Red channel data
/// </summary>
public byte[] Red;
/// <summary>
/// Green channel data
/// </summary>
public byte[] Green;
/// <summary>
/// Blue channel data
/// </summary>
public byte[] Blue;
/// <summary>
/// Alpha channel data
/// </summary>
public byte[] Alpha;
/// <summary>
/// Bump channel data
/// </summary>
public byte[] Bump;
/// <summary>
/// Create a new blank image
/// </summary>
/// <param name="width">width</param>
/// <param name="height">height</param>
/// <param name="channels">channel flags</param>
public ManagedImage(int width, int height, ImageChannels channels)
{
Width = width;
Height = height;
Channels = channels;
int n = width * height;
if ((channels & ImageChannels.Gray) != 0)
{
Red = new byte[n];
}
else if ((channels & ImageChannels.Color) != 0)
{
Red = new byte[n];
Green = new byte[n];
Blue = new byte[n];
}
if ((channels & ImageChannels.Alpha) != 0)
Alpha = new byte[n];
if ((channels & ImageChannels.Bump) != 0)
Bump = new byte[n];
}
#if !NO_UNSAFE
/// <summary>
///
/// </summary>
/// <param name="bitmap"></param>
public ManagedImage(System.Drawing.Bitmap bitmap)
{
Width = bitmap.Width;
Height = bitmap.Height;
int pixelCount = Width * Height;
if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
Channels = ImageChannels.Alpha | ImageChannels.Color;
Red = new byte[pixelCount];
Green = new byte[pixelCount];
Blue = new byte[pixelCount];
Alpha = new byte[pixelCount];
System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
unsafe
{
byte* pixel = (byte*)bd.Scan0;
for (int i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGRA and we need to turn that in to RGBA
Blue[i] = *(pixel++);
Green[i] = *(pixel++);
Red[i] = *(pixel++);
Alpha[i] = *(pixel++);
}
}
bitmap.UnlockBits(bd);
}
else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppGrayScale)
{
Channels = ImageChannels.Gray;
Red = new byte[pixelCount];
throw new NotImplementedException("16bpp grayscale image support is incomplete");
}
else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
{
Channels = ImageChannels.Color;
Red = new byte[pixelCount];
Green = new byte[pixelCount];
Blue = new byte[pixelCount];
System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
unsafe
{
byte* pixel = (byte*)bd.Scan0;
for (int i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGR and we need to turn that in to RGB
Blue[i] = *(pixel++);
Green[i] = *(pixel++);
Red[i] = *(pixel++);
}
}
bitmap.UnlockBits(bd);
}
else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb)
{
Channels = ImageChannels.Color;
Red = new byte[pixelCount];
Green = new byte[pixelCount];
Blue = new byte[pixelCount];
System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
unsafe
{
byte* pixel = (byte*)bd.Scan0;
for (int i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGR and we need to turn that in to RGB
Blue[i] = *(pixel++);
Green[i] = *(pixel++);
Red[i] = *(pixel++);
pixel++; // Skip over the empty byte where the Alpha info would normally be
}
}
bitmap.UnlockBits(bd);
}
else
{
throw new NotSupportedException("Unrecognized pixel format: " + bitmap.PixelFormat.ToString());
}
}
#endif
/// <summary>
/// Convert the channels in the image. Channels are created or destroyed as required.
/// </summary>
/// <param name="channels">new channel flags</param>
public void ConvertChannels(ImageChannels channels)
{
if (Channels == channels)
return;
int n = Width * Height;
ImageChannels add = Channels ^ channels & channels;
ImageChannels del = Channels ^ channels & Channels;
if ((add & ImageChannels.Color) != 0)
{
Red = new byte[n];
Green = new byte[n];
Blue = new byte[n];
}
else if ((del & ImageChannels.Color) != 0)
{
Red = null;
Green = null;
Blue = null;
}
if ((add & ImageChannels.Alpha) != 0)
{
Alpha = new byte[n];
FillArray(Alpha, 255);
}
else if ((del & ImageChannels.Alpha) != 0)
Alpha = null;
if ((add & ImageChannels.Bump) != 0)
Bump = new byte[n];
else if ((del & ImageChannels.Bump) != 0)
Bump = null;
Channels = channels;
}
/// <summary>
/// Resize or stretch the image using nearest neighbor (ugly) resampling
/// </summary>
/// <param name="width">new width</param>
/// <param name="height">new height</param>
public void ResizeNearestNeighbor(int width, int height)
{
if (width == Width && height == Height)
return;
byte[]
red = null,
green = null,
blue = null,
alpha = null,
bump = null;
int n = width * height;
int di = 0, si;
if (Red != null) red = new byte[n];
if (Green != null) green = new byte[n];
if (Blue != null) blue = new byte[n];
if (Alpha != null) alpha = new byte[n];
if (Bump != null) bump = new byte[n];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
si = (y * Height / height) * Width + (x * Width / width);
if (Red != null) red[di] = Red[si];
if (Green != null) green[di] = Green[si];
if (Blue != null) blue[di] = Blue[si];
if (Alpha != null) alpha[di] = Alpha[si];
if (Bump != null) bump[di] = Bump[si];
di++;
}
}
Width = width;
Height = height;
Red = red;
Green = green;
Blue = blue;
Alpha = alpha;
Bump = bump;
}
/// <summary>
/// Create a byte array containing 32-bit RGBA data with a bottom-left
/// origin, suitable for feeding directly into OpenGL
/// </summary>
/// <returns>A byte array containing raw texture data</returns>
public byte[] ExportRaw()
{
byte[] raw = new byte[Width * Height * 4];
if ((Channels & ImageChannels.Alpha) != 0)
{
if ((Channels & ImageChannels.Color) != 0)
{
// RGBA
for (int h = 0; h < Height; h++)
{
for (int w = 0; w < Width; w++)
{
int pos = (Height - 1 - h) * Width + w;
int srcPos = h * Width + w;
raw[pos * 4 + 0] = Red[srcPos];
raw[pos * 4 + 1] = Green[srcPos];
raw[pos * 4 + 2] = Blue[srcPos];
raw[pos * 4 + 3] = Alpha[srcPos];
}
}
}
else
{
// Alpha only
for (int h = 0; h < Height; h++)
{
for (int w = 0; w < Width; w++)
{
int pos = (Height - 1 - h) * Width + w;
int srcPos = h * Width + w;
raw[pos * 4 + 0] = Alpha[srcPos];
raw[pos * 4 + 1] = Alpha[srcPos];
raw[pos * 4 + 2] = Alpha[srcPos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
}
}
else
{
// RGB
for (int h = 0; h < Height; h++)
{
for (int w = 0; w < Width; w++)
{
int pos = (Height - 1 - h) * Width + w;
int srcPos = h * Width + w;
raw[pos * 4 + 0] = Red[srcPos];
raw[pos * 4 + 1] = Green[srcPos];
raw[pos * 4 + 2] = Blue[srcPos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
}
return raw;
}
/// <summary>
/// Create a byte array containing 32-bit RGBA data with a bottom-left
/// origin, suitable for feeding directly into OpenGL
/// </summary>
/// <returns>A byte array containing raw texture data</returns>
public System.Drawing.Bitmap ExportBitmap()
{
byte[] raw = new byte[Width * Height * 4];
if ((Channels & ImageChannels.Alpha) != 0)
{
if ((Channels & ImageChannels.Color) != 0)
{
// RGBA
for (int pos = 0; pos < Height * Width; pos++)
{
raw[pos * 4 + 0] = Blue[pos];
raw[pos * 4 + 1] = Green[pos];
raw[pos * 4 + 2] = Red[pos];
raw[pos * 4 + 3] = Alpha[pos];
}
}
else
{
// Alpha only
for (int pos = 0; pos < Height * Width; pos++)
{
raw[pos * 4 + 0] = Alpha[pos];
raw[pos * 4 + 1] = Alpha[pos];
raw[pos * 4 + 2] = Alpha[pos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
}
else
{
// RGB
for (int pos = 0; pos < Height * Width; pos++)
{
raw[pos * 4 + 0] = Blue[pos];
raw[pos * 4 + 1] = Green[pos];
raw[pos * 4 + 2] = Red[pos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
System.Drawing.Bitmap b = new System.Drawing.Bitmap(
Width,
Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Drawing.Imaging.BitmapData bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Runtime.InteropServices.Marshal.Copy(raw, 0, bd.Scan0, Width * Height * 4);
b.UnlockBits(bd);
return b;
}
public byte[] ExportTGA()
{
byte[] tga = new byte[Width * Height * ((Channels & ImageChannels.Alpha) == 0 ? 3 : 4) + 32];
int di = 0;
tga[di++] = 0; // idlength
tga[di++] = 0; // colormaptype = 0: no colormap
tga[di++] = 2; // image type = 2: uncompressed RGB
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // x origin = two bytes
tga[di++] = 0; // x origin = two bytes
tga[di++] = 0; // y origin = two bytes
tga[di++] = 0; // y origin = two bytes
tga[di++] = (byte)(Width & 0xFF); // width - low byte
tga[di++] = (byte)(Width >> 8); // width - hi byte
tga[di++] = (byte)(Height & 0xFF); // height - low byte
tga[di++] = (byte)(Height >> 8); // height - hi byte
tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 24 : 32); // 24/32 bits per pixel
tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 32 : 40); // image descriptor byte
int n = Width * Height;
if ((Channels & ImageChannels.Alpha) != 0)
{
if ((Channels & ImageChannels.Color) != 0)
{
// RGBA
for (int i = 0; i < n; i++)
{
tga[di++] = Blue[i];
tga[di++] = Green[i];
tga[di++] = Red[i];
tga[di++] = Alpha[i];
}
}
else
{
// Alpha only
for (int i = 0; i < n; i++)
{
tga[di++] = Alpha[i];
tga[di++] = Alpha[i];
tga[di++] = Alpha[i];
tga[di++] = Byte.MaxValue;
}
}
}
else
{
// RGB
for (int i = 0; i < n; i++)
{
tga[di++] = Blue[i];
tga[di++] = Green[i];
tga[di++] = Red[i];
}
}
return tga;
}
private static void FillArray(byte[] array, byte value)
{
if (array != null)
{
for (int i = 0; i < array.Length; i++)
array[i] = value;
}
}
public void Clear()
{
FillArray(Red, 0);
FillArray(Green, 0);
FillArray(Blue, 0);
FillArray(Alpha, 0);
FillArray(Bump, 0);
}
public ManagedImage Clone()
{
ManagedImage image = new ManagedImage(Width, Height, Channels);
if (Red != null) image.Red = (byte[])Red.Clone();
if (Green != null) image.Green = (byte[])Green.Clone();
if (Blue != null) image.Blue = (byte[])Blue.Clone();
if (Alpha != null) image.Alpha = (byte[])Alpha.Clone();
if (Bump != null) image.Bump = (byte[])Bump.Clone();
return image;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.