text string |
|---|
/* 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:
*
* * 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.
*
* 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.Generic;
using System.IO;
using XenAdmin.Network;
using XenAdmin.Core;
using XenAPI;
using XenAdmin.Actions;
using XenAdmin;
using System.Linq;
using System.Globalization;
using System.Xml;
namespace XenServerHealthCheck
{
public class XenServerHealthCheckBugTool
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static readonly List<string> reportExcluded =
new List<string>
{
"blobs",
"vncterm",
"xapi-debug"
};
private static readonly Dictionary<string, int> reportWithVerbosity =
new Dictionary<string, int>
{
{"host-crashdump-logs", 2},
{"system-logs", 2},
{"tapdisk-logs", 2},
{"xapi", 2},
{"xcp-rrdd-plugins", 2},
{"xenserver-install", 2},
{"xenserver-logs", 2}
};
public readonly string outputFile;
public XenServerHealthCheckBugTool()
{
string name = string.Format("{0}{1}.zip", Messages.BUGTOOL_FILE_PREFIX, DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture));
string folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if (Directory.Exists(folder))
Directory.Delete(folder);
Directory.CreateDirectory(folder);
if (!name.EndsWith(".zip"))
name = string.Concat(name, ".zip");
outputFile = string.Format(@"{0}\{1}", folder, name);
}
public void RunBugtool(IXenConnection connection, Session session)
{
if (connection == null || session == null)
return;
// Fetch the common capabilities of all hosts.
Dictionary<Host, List<string>> hostCapabilities = new Dictionary<Host, List<string>>();
foreach (Host host in connection.Cache.Hosts)
{
GetSystemStatusCapabilities action = new GetSystemStatusCapabilities(host);
action.RunExternal(session);
if (!action.Succeeded)
return;
List<string> keys = new List<string>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(action.Result);
foreach (XmlNode node in doc.GetElementsByTagName("capability"))
{
foreach (XmlAttribute a in node.Attributes)
{
if (a.Name == "key")
keys.Add(a.Value);
}
}
hostCapabilities[host] = keys;
}
List<string> combination = null;
foreach (List<string> capabilities in hostCapabilities.Values)
{
if (capabilities == null)
continue;
if (combination == null)
{
combination = capabilities;
continue;
}
combination = Helpers.ListsCommonItems<string>(combination, capabilities);
}
if (combination == null || combination.Count <= 0)
return;
// The list of the reports which are required in Health Check Report.
List<string> reportIncluded = combination.Except(reportExcluded).ToList();
// Verbosity works for xen-bugtool since Dundee.
if (Helpers.DundeeOrGreater(connection))
{
List<string> verbReport = new List<string>(reportWithVerbosity.Keys);
int idx = -1;
for (int x = 0; x < verbReport.Count; x++)
{
idx = reportIncluded.IndexOf(verbReport[x]);
if (idx >= 0)
{
reportIncluded[idx] = reportIncluded[idx] + ":" + reportWithVerbosity[verbReport[x]].ToString();
}
}
}
// Ensure downloaded filenames are unique even for hosts with the same hostname: append a counter to the timestring
string filepath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if (Directory.Exists(filepath))
Directory.Delete(filepath);
Directory.CreateDirectory(filepath);
string timestring = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
// Collect all master/slave information to output as a separate text file with the report
List<string> mastersInfo = new List<string>();
int i = 0;
Pool p = Helpers.GetPool(connection);
foreach (Host host in connection.Cache.Hosts)
{
// master/slave information
if (p == null)
{
mastersInfo.Add(string.Format("Server '{0}' is a stand alone server",
host.Name()));
}
else
{
mastersInfo.Add(string.Format("Server '{0}' is a {1} of pool '{2}'",
host.Name(),
p.master.opaque_ref == host.opaque_ref ? "master" : "slave",
p.Name()));
}
HostWithStatus hostWithStatus = new HostWithStatus(host, 0);
SingleHostStatusAction statAction = new SingleHostStatusAction(hostWithStatus, reportIncluded, filepath, timestring + "-" + ++i);
statAction.RunExternal(session);
}
// output the slave/master info
string mastersDestination = string.Format("{0}\\{1}-Masters.txt", filepath, timestring);
WriteExtraInfoToFile(mastersInfo, mastersDestination);
// output the XenCenter metadata
var metadata = XenAdminConfigManager.Provider.GetXenCenterMetadata(false);
string metadataDestination = string.Format("{0}\\{1}-Metadata.json", filepath, timestring);
WriteExtraInfoToFile(new List<string> {metadata}, metadataDestination);
// Finish the collection of logs with bugtool.
// Start to zip the files.
ZipStatusReportAction zipAction = new ZipStatusReportAction(filepath, outputFile);
zipAction.RunExternal(session);
log.InfoFormat("Server Status Report is collected: {0}", outputFile);
}
private void WriteExtraInfoToFile(List<string> info, string fileName)
{
if (File.Exists(fileName))
File.Delete(fileName);
StreamWriter sw = null;
try
{
sw = new StreamWriter(fileName);
foreach (string s in info)
sw.WriteLine(s);
sw.Flush();
}
catch (Exception e)
{
log.ErrorFormat("Exception while writing {0} file: {1}", fileName, e);
}
finally
{
if (sw != null)
sw.Close();
}
}
}
}
|
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
public partial class LineSymbolDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LineSymbolDialog));
this.lblSymbologyType = new System.Windows.Forms.Label();
this.lblPredefinedSymbol = new System.Windows.Forms.Label();
this.lblSymbolPreview = new System.Windows.Forms.Label();
this.btnSymbolDetails = new System.Windows.Forms.Button();
this.cmbCategories = new System.Windows.Forms.ComboBox();
this.predefinedLineSymbolControl1 = new DotSpatial.Symbology.Forms.PredefinedLineSymbolControl();
this.symbolPreview1 = new DotSpatial.Symbology.Forms.SymbolPreview();
this.dialogButtons1 = new DotSpatial.Symbology.Forms.DialogButtons();
this.SuspendLayout();
//
// lblSymbologyType
//
resources.ApplyResources(this.lblSymbologyType, "lblSymbologyType");
this.lblSymbologyType.Name = "lblSymbologyType";
//
// lblPredefinedSymbol
//
resources.ApplyResources(this.lblPredefinedSymbol, "lblPredefinedSymbol");
this.lblPredefinedSymbol.Name = "lblPredefinedSymbol";
//
// lblSymbolPreview
//
resources.ApplyResources(this.lblSymbolPreview, "lblSymbolPreview");
this.lblSymbolPreview.Name = "lblSymbolPreview";
//
// btnSymbolDetails
//
resources.ApplyResources(this.btnSymbolDetails, "btnSymbolDetails");
this.btnSymbolDetails.Name = "btnSymbolDetails";
this.btnSymbolDetails.UseVisualStyleBackColor = true;
this.btnSymbolDetails.Click += new System.EventHandler(this.BtnSymbolDetailsClick);
//
// cmbCategories
//
resources.ApplyResources(this.cmbCategories, "cmbCategories");
this.cmbCategories.FormattingEnabled = true;
this.cmbCategories.Name = "cmbCategories";
this.cmbCategories.SelectedIndexChanged += new System.EventHandler(this.CmbCategoriesSelectedIndexChanged);
//
// predefinedLineSymbolControl1
//
resources.ApplyResources(this.predefinedLineSymbolControl1, "predefinedLineSymbolControl1");
this.predefinedLineSymbolControl1.BackColor = System.Drawing.Color.White;
this.predefinedLineSymbolControl1.CategoryFilter = String.Empty;
this.predefinedLineSymbolControl1.CellMargin = 8;
this.predefinedLineSymbolControl1.CellSize = new System.Drawing.Size(62, 62);
this.predefinedLineSymbolControl1.ControlRectangle = new System.Drawing.Rectangle(0, 0, 272, 253);
this.predefinedLineSymbolControl1.DefaultCategoryFilter = "All";
this.predefinedLineSymbolControl1.DynamicColumns = true;
this.predefinedLineSymbolControl1.IsInitialized = false;
this.predefinedLineSymbolControl1.IsSelected = true;
this.predefinedLineSymbolControl1.Name = "predefinedLineSymbolControl1";
this.predefinedLineSymbolControl1.SelectedIndex = -1;
this.predefinedLineSymbolControl1.SelectionBackColor = System.Drawing.Color.LightGray;
this.predefinedLineSymbolControl1.SelectionForeColor = System.Drawing.Color.White;
this.predefinedLineSymbolControl1.ShowSymbolNames = true;
this.predefinedLineSymbolControl1.TextFont = new System.Drawing.Font("Arial", 8F);
this.predefinedLineSymbolControl1.VerticalScrollEnabled = true;
//
// symbolPreview1
//
resources.ApplyResources(this.symbolPreview1, "symbolPreview1");
this.symbolPreview1.BackColor = System.Drawing.Color.White;
this.symbolPreview1.Name = "symbolPreview1";
//
// dialogButtons1
//
resources.ApplyResources(this.dialogButtons1, "dialogButtons1");
this.dialogButtons1.Name = "dialogButtons1";
//
// LineSymbolDialog
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.dialogButtons1);
this.Controls.Add(this.predefinedLineSymbolControl1);
this.Controls.Add(this.cmbCategories);
this.Controls.Add(this.symbolPreview1);
this.Controls.Add(this.btnSymbolDetails);
this.Controls.Add(this.lblSymbolPreview);
this.Controls.Add(this.lblPredefinedSymbol);
this.Controls.Add(this.lblSymbologyType);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "LineSymbolDialog";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button btnSymbolDetails;
private ComboBox cmbCategories;
private DialogButtons dialogButtons1;
private Label lblPredefinedSymbol;
private Label lblSymbolPreview;
private Label lblSymbologyType;
private PredefinedLineSymbolControl predefinedLineSymbolControl1;
private SymbolPreview symbolPreview1;
}
} |
// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2014, SIL International. All Rights Reserved.
// <copyright from='2008' to='2014' company='SIL International'>
// Copyright (c) 2014, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (http://sil.mit-license.org/)
// </copyright>
#endregion
//
// This class originated in FieldWorks (under the GNU Lesser General Public License), but we
// have decided to make it avaialble in SIL.ScriptureUtils as part of Palaso so it will be more
// readily available to other projects.
// ---------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace SIL.Scripture
{
/// <summary>
/// Manipulate information for standard chatper/verse schemes
/// </summary>
public class VersificationTable
{
private readonly ScrVers scrVers;
private List<int[]> bookList;
private Dictionary<string, string> toStandard;
private Dictionary<string, string> fromStandard;
private static string baseDir;
private static VersificationTable[] versifications = null;
// Names of the versificaiton files. These are in "\My Paratext Projects"
private static string[] versificationFiles = new string[] { "",
"org.vrs", "lxx.vrs", "vul.vrs", "eng.vrs", "rsc.vrs", "rso.vrs", "oth.vrs",
"oth2.vrs", "oth3.vrs", "oth4.vrs", "oth5.vrs", "oth6.vrs", "oth7.vrs", "oth8.vrs",
"oth9.vrs", "oth10.vrs", "oth11.vrs", "oth12.vrs", "oth13.vrs", "oth14.vrs",
"oth15.vrs", "oth16.vrs", "oth17.vrs", "oth18.vrs", "oth19.vrs", "oth20.vrs",
"oth21.vrs", "oth22.vrs", "oth23.vrs", "oth24.vrs" };
/// ------------------------------------------------------------------------------------
/// <summary>
/// This method should be called once before an application accesses anything that
/// requires versification info.
/// TODO: Paratext needs to call this with ScrTextCollection.SettingsDirectory.
/// </summary>
/// <param name="vrsFolder">Path to the folder containing the .vrs files</param>
/// ------------------------------------------------------------------------------------
public static void Initialize(string vrsFolder)
{
baseDir = vrsFolder;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Get the versification table for this versification
/// </summary>
/// <param name="vers"></param>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public static VersificationTable Get(ScrVers vers)
{
Debug.Assert(vers != ScrVers.Unknown);
if (versifications == null)
versifications = new VersificationTable[versificationFiles.GetUpperBound(0)];
// Read versification table if not already read
if (versifications[(int)vers] == null)
{
versifications[(int)vers] = new VersificationTable(vers);
ReadVersificationFile(FileName(vers), versifications[(int)vers]);
}
return versifications[(int)vers];
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Read versification file and "add" its entries.
/// At the moment we only do this once. Eventually we will call this twice.
/// Once for the standard versification, once for custom entries in versification.vrs
/// file for this project.
/// </summary>
/// <param name="fileName"></param>
/// <param name="versification"></param>
/// ------------------------------------------------------------------------------------
private static void ReadVersificationFile(string fileName, VersificationTable versification)
{
using (TextReader reader = new StreamReader(fileName))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
line = line.Trim();
if (line == "" || line[0] == '#')
continue;
if (line.Contains("="))
ParseMappingLine(fileName, versification, line);
else
ParseChapterVerseLine(fileName, versification, line);
}
}
}
// Parse lines mapping from this versification to standard versification
// GEN 1:10 = GEN 2:11
// GEN 1:10-13 = GEN 2:11-14
private static void ParseChapterVerseLine(string fileName, VersificationTable versification, string line)
{
string[] parts = line.Split(' ');
int bookNum = BCVRef.BookToNumber(parts[0]);
if (bookNum == -1)
return; // Deuterocanonical books not supported
if (bookNum == 0)
throw new Exception("Invalid [" + parts[0] + "] " + fileName);
while (versification.bookList.Count < bookNum)
versification.bookList.Add(new int[1] { 1 });
List<int> verses = new List<int>();
for (int i = 1; i <= parts.GetUpperBound(0); ++i)
{
string[] pieces = parts[i].Split(':');
int verseCount;
if (pieces.GetUpperBound(0) != 1 ||
!int.TryParse(pieces[1], out verseCount) || verseCount <= 0)
{
throw new Exception("Invalid [" + line + "] " + fileName);
}
verses.Add(verseCount);
}
versification.bookList[bookNum - 1] = verses.ToArray();
}
// Parse lines giving number of verses for each chapter like
// GEN 1:10 2:23 ...
private static void ParseMappingLine(string fileName, VersificationTable versification, string line)
{
try
{
string[] parts = line.Split('=');
string[] leftPieces = parts[0].Trim().Split('-');
string[] rightPieces = parts[1].Trim().Split('-');
BCVRef left = new BCVRef(leftPieces[0]);
int leftLimit = leftPieces.GetUpperBound(0) == 0 ? 0 : int.Parse(leftPieces[1]);
BCVRef right = new BCVRef(rightPieces[0]);
while (true)
{
versification.toStandard[left.ToString()] = right.ToString();
versification.fromStandard[right.ToString()] = left.ToString();
if (left.Verse >= leftLimit)
break;
left.Verse = left.Verse + 1;
right.Verse = right.Verse + 1;
}
}
catch
{
// ENHANCE: Make it so the TE version of Localizer can have its own resources for stuff
// like this.
throw new Exception("Invalid [" + line + "] " + fileName);
}
}
/// <summary>
/// Gets the name of this requested versification file.
/// </summary>
/// <param name="vers">Versification scheme</param>
public static string GetFileNameForVersification(ScrVers vers)
{
return versificationFiles[(int)vers];
}
// Get path of this versification file.
// Fall back to eng.vrs if not present.
private static string FileName(ScrVers vers)
{
if (baseDir == null)
throw new InvalidOperationException("VersificationTable.Initialize must be called first");
string fileName = Path.Combine(baseDir, GetFileNameForVersification(vers));
if (!File.Exists(fileName))
fileName = Path.Combine(baseDir, GetFileNameForVersification(ScrVers.English));
return fileName;
}
// Create empty versification table
private VersificationTable(ScrVers vers)
{
this.scrVers = vers;
bookList = new List<int[]>();
toStandard = new Dictionary<string, string>();
fromStandard = new Dictionary<string, string>();
}
public int LastBook()
{
return bookList.Count;
}
/// <summary>
/// Last chapter number in this book.
/// </summary>
/// <param name="bookNum"></param>
/// <returns></returns>
public int LastChapter(int bookNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
return chapters.GetUpperBound(0) + 1;
}
/// <summary>
/// Last verse number in this book/chapter.
/// </summary>
/// <param name="bookNum"></param>
/// <param name="chapterNum"></param>
/// <returns></returns>
public int LastVerse(int bookNum, int chapterNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
// Chapter "0" is the intro material. Pretend that it has 1 verse.
if (chapterNum - 1 > chapters.GetUpperBound(0) || chapterNum < 1)
return 1;
return chapters[chapterNum - 1];
}
/// <summary>
/// Change the passed VerseRef to be this versification.
/// </summary>
/// <param name="vref"></param>
public void ChangeVersification(IVerseReference vref)
{
if (vref.Versification == scrVers)
return;
// Map from existing to standard versification
string verse = vref.ToString();
string verse2;
Get(vref.Versification).toStandard.TryGetValue(verse, out verse2);
if (verse2 == null)
verse2 = verse;
// Map from standard versification to this versification
string verse3;
fromStandard.TryGetValue(verse2, out verse3);
if (verse3 == null)
verse3 = verse2;
// If verse has changed, parse new value
if (verse != verse3)
vref.Parse(verse3);
vref.Versification = scrVers;
}
}
}
|
using System;
using System.Collections.Generic;
using Foundation.ObjectHydrator.Interfaces;
namespace Foundation.ObjectHydrator.Generators
{
public class UnitedKingdomCityGenerator : IGenerator<string>
{
private readonly Random _random;
private IList<string> _citynames = new List<string>();
public UnitedKingdomCityGenerator()
{
_random = RandomSingleton.Instance.Random;
LoadCityNames();
}
private void LoadCityNames()
{
_citynames = new List<string>()
{
"Aberaeron",
"Aberdare",
"Aberdeen",
"Aberfeldy",
"Abergavenny",
"Abergele",
"Abertillery",
"Aberystwyth",
"Abingdon",
"Accrington",
"Adlington",
"Airdrie",
"Alcester",
"Aldeburgh",
"Aldershot",
"Aldridge",
"Alford",
"Alfreton",
"Alloa",
"Alnwick",
"Alsager",
"Alston",
"Amesbury",
"Amlwch",
"Ammanford",
"Ampthill",
"Andover",
"Annan",
"Antrim",
"Appleby in Westmorland",
"Arbroath",
"Armagh",
"Arundel",
"Ashbourne",
"Ashburton",
"Ashby de la Zouch",
"Ashford",
"Ashington",
"Ashton in Makerfield",
"Atherstone",
"Auchtermuchty",
"Axminster",
"Aylesbury",
"Aylsham",
"Ayr",
"Bacup",
"Bakewell",
"Bala",
"Ballater",
"Ballycastle",
"Ballyclare",
"Ballymena",
"Ballymoney",
"Ballynahinch",
"Banbridge",
"Banbury",
"Banchory",
"Banff",
"Bangor",
"Barmouth",
"Barnard Castle",
"Barnet",
"Barnoldswick",
"Barnsley",
"Barnstaple",
"Barrhead",
"Barrow in Furness",
"Barry",
"Barton upon Humber",
"Basildon",
"Basingstoke",
"Bath",
"Bathgate",
"Batley",
"Battle",
"Bawtry",
"Beaconsfield",
"Bearsden",
"Beaumaris",
"Bebington",
"Beccles",
"Bedale",
"Bedford",
"Bedlington",
"Bedworth",
"Beeston",
"Bellshill",
"Belper",
"Berkhamsted",
"Berwick upon Tweed",
"Betws y Coed",
"Beverley",
"Bewdley",
"Bexhill on Sea",
"Bicester",
"Biddulph",
"Bideford",
"Biggar",
"Biggleswade",
"Billericay",
"Bilston",
"Bingham",
"Birkenhead",
"Birmingham",
"Bishop Auckland",
"Blackburn",
"Blackheath",
"Blackpool",
"Blaenau Ffestiniog",
"Blandford Forum",
"Bletchley",
"Bloxwich",
"Blyth",
"Bodmin",
"Bognor Regis",
"Bollington",
"Bolsover",
"Bolton",
"Bootle",
"Borehamwood",
"Boston",
"Bourne",
"Bournemouth",
"Brackley",
"Bracknell",
"Bradford",
"Bradford on Avon",
"Brading",
"Bradley Stoke",
"Bradninch",
"Braintree",
"Brechin",
"Brecon",
"Brentwood",
"Bridge of Allan",
"Bridgend",
"Bridgnorth",
"Bridgwater",
"Bridlington",
"Bridport",
"Brigg",
"Brighouse",
"Brightlingsea",
"Brighton",
"Bristol",
"Brixham",
"Broadstairs",
"Bromsgrove",
"Bromyard",
"Brynmawr",
"Buckfastleigh",
"Buckie",
"Buckingham",
"Buckley",
"Bude",
"Budleigh Salterton",
"Builth Wells",
"Bungay",
"Buntingford",
"Burford",
"Burgess Hill",
"Burnham on Crouch",
"Burnham on Sea",
"Burnley",
"Burntisland",
"Burntwood",
"Burry Port",
"Burton Latimer",
"Bury",
"Bushmills",
"Buxton",
"Caernarfon",
"Caerphilly",
"Caistor",
"Caldicot",
"Callander",
"Calne",
"Camberley",
"Camborne",
"Cambridge",
"Camelford",
"Campbeltown",
"Cannock",
"Canterbury",
"Cardiff",
"Cardigan",
"Carlisle",
"Carluke",
"Carmarthen",
"Carnforth",
"Carnoustie",
"Carrickfergus",
"Carterton",
"Castle Douglas",
"Castlederg",
"Castleford",
"Castlewellan",
"Chard",
"Charlbury",
"Chatham",
"Chatteris",
"Chelmsford",
"Cheltenham",
"Chepstow",
"Chesham",
"Cheshunt",
"Chester",
"Chester le Street",
"Chesterfield",
"Chichester",
"Chippenham",
"Chipping Campden",
"Chipping Norton",
"Chipping Sodbury",
"Chorley",
"Christchurch",
"Church Stretton",
"Cinderford",
"Cirencester",
"Clacton on Sea",
"Cleckheaton",
"Cleethorpes",
"Clevedon",
"Clitheroe",
"Clogher",
"Clydebank",
"Coalisland",
"Coalville",
"Coatbridge",
"Cockermouth",
"Coggeshall",
"Colchester",
"Coldstream",
"Coleraine",
"Coleshill",
"Colne",
"Colwyn Bay",
"Comber",
"Congleton",
"Conwy",
"Cookstown",
"Corbridge",
"Corby",
"Coventry",
"Cowbridge",
"Cowdenbeath",
"Cowes",
"Craigavon",
"Cramlington",
"Crawley",
"Crayford",
"Crediton",
"Crewe",
"Crewkerne",
"Criccieth",
"Crickhowell",
"Crieff",
"Cromarty",
"Cromer",
"Crowborough",
"Crowthorne",
"Crumlin",
"Cuckfield",
"Cullen",
"Cullompton",
"Cumbernauld",
"Cupar",
"Cwmbran",
"Dalbeattie",
"Dalkeith",
"Darlington",
"Dartford",
"Dartmouth",
"Darwen",
"Daventry",
"Dawlish",
"Deal",
"Denbigh",
"Denton",
"Derby",
"Dereham",
"Devizes",
"Dewsbury",
"Didcot",
"Dingwall",
"Dinnington",
"Diss",
"Dolgellau",
"Donaghadee",
"Doncaster",
"Dorchester",
"Dorking",
"Dornoch",
"Dover",
"Downham Market",
"Downpatrick",
"Driffield",
"Dronfield",
"Droylsden",
"Dudley",
"Dufftown",
"Dukinfield",
"Dumbarton",
"Dumfries",
"Dunbar",
"Dunblane",
"Dundee",
"Dunfermline",
"Dungannon",
"Dunoon",
"Duns",
"Dunstable",
"Durham",
"Dursley",
"Easingwold",
"East Grinstead",
"East Kilbride",
"Eastbourne",
"Eastleigh",
"Eastwood",
"Ebbw Vale",
"Edenbridge",
"Edinburgh",
"Egham",
"Elgin",
"Ellesmere",
"Ellesmere Port",
"Ely",
"Enniskillen",
"Epping",
"Epsom",
"Erith",
"Esher",
"Evesham",
"Exeter",
"Exmouth",
"Eye",
"Eyemouth",
"Failsworth",
"Fairford",
"Fakenham",
"Falkirk",
"Falkland",
"Falmouth",
"Fareham",
"Faringdon",
"Farnborough",
"Farnham",
"Farnworth",
"Faversham",
"Felixstowe",
"Ferndown",
"Filey",
"Fintona",
"Fishguard",
"Fivemiletown",
"Fleet",
"Fleetwood",
"Flint",
"Flitwick",
"Folkestone",
"Fordingbridge",
"Forfar",
"Forres",
"Fort William",
"Fowey",
"Framlingham",
"Fraserburgh",
"Frodsham",
"Frome",
"Gainsborough",
"Galashiels",
"Gateshead",
"Gillingham",
"Glasgow",
"Glastonbury",
"Glossop",
"Gloucester",
"Godalming",
"Godmanchester",
"Goole",
"Gorseinon",
"Gosport",
"Gourock",
"Grange over Sands",
"Grangemouth",
"Grantham",
"Grantown on Spey",
"Gravesend",
"Grays",
"Great Yarmouth",
"Greenock",
"Grimsby",
"Guildford",
"Haddington",
"Hadleigh",
"Hailsham",
"Halesowen",
"Halesworth",
"Halifax",
"Halstead",
"Haltwhistle",
"Hamilton",
"Harlow",
"Harpenden",
"Harrogate",
"Hartlepool",
"Harwich",
"Haslemere",
"Hastings",
"Hatfield",
"Havant",
"Haverfordwest",
"Haverhill",
"Hawarden",
"Hawick",
"Hay on Wye",
"Hayle",
"Haywards Heath",
"Heanor",
"Heathfield",
"Hebden Bridge",
"Helensburgh",
"Helston",
"Hemel Hempstead",
"Henley on Thames",
"Hereford",
"Herne Bay",
"Hertford",
"Hessle",
"Heswall",
"Hexham",
"High Wycombe",
"Higham Ferrers",
"Highworth",
"Hinckley",
"Hitchin",
"Hoddesdon",
"Holmfirth",
"Holsworthy",
"Holyhead",
"Holywell",
"Honiton",
"Horley",
"Horncastle",
"Hornsea",
"Horsham",
"Horwich",
"Houghton le Spring",
"Hove",
"Howden",
"Hoylake",
"Hucknall",
"Huddersfield",
"Hungerford",
"Hunstanton",
"Huntingdon",
"Huntly",
"Hyde",
"Hythe",
"Ilford",
"Ilfracombe",
"Ilkeston",
"Ilkley",
"Ilminster",
"Innerleithen",
"Inveraray",
"Inverkeithing",
"Inverness",
"Inverurie",
"Ipswich",
"Irthlingborough",
"Irvine",
"Ivybridge",
"Jarrow",
"Jedburgh",
"Johnstone",
"Keighley",
"Keith",
"Kelso",
"Kempston",
"Kendal",
"Kenilworth",
"Kesgrave",
"Keswick",
"Kettering",
"Keynsham",
"Kidderminster",
"Kilbarchan",
"Kilkeel",
"Killyleagh",
"Kilmarnock",
"Kilwinning",
"Kinghorn",
"Kingsbridge",
"Kington",
"Kingussie",
"Kinross",
"Kintore",
"Kirkby",
"Kirkby Lonsdale",
"Kirkcaldy",
"Kirkcudbright",
"Kirkham",
"Kirkwall",
"Kirriemuir",
"Knaresborough",
"Knighton",
"Knutsford",
"Ladybank",
"Lampeter",
"Lanark",
"Lancaster",
"Langholm",
"Largs",
"Larne",
"Laugharne",
"Launceston",
"Laurencekirk",
"Leamington Spa",
"Leatherhead",
"Ledbury",
"Leeds",
"Leek",
"Leicester",
"Leighton Buzzard",
"Leiston",
"Leominster",
"Lerwick",
"Letchworth",
"Leven",
"Lewes",
"Leyland",
"Lichfield",
"Limavady",
"Lincoln",
"Linlithgow",
"Lisburn",
"Liskeard",
"Lisnaskea",
"Littlehampton",
"Liverpool",
"Llandeilo",
"Llandovery",
"Llandrindod Wells",
"Llandudno",
"Llanelli",
"Llanfyllin",
"Llangollen",
"Llanidloes",
"Llanrwst",
"Llantrisant",
"Llantwit Major",
"Llanwrtyd Wells",
"Loanhead",
"Lochgilphead",
"Lockerbie",
"Londonderry",
"Long Eaton",
"Longridge",
"Looe",
"Lossiemouth",
"Lostwithiel",
"Loughborough",
"Loughton",
"Louth",
"Lowestoft",
"Ludlow",
"Lurgan",
"Luton",
"Lutterworth",
"Lydd",
"Lydney",
"Lyme Regis",
"Lymington",
"Lynton",
"Mablethorpe",
"Macclesfield",
"Machynlleth",
"Maesteg",
"Magherafelt",
"Maidenhead",
"Maidstone",
"Maldon",
"Malmesbury",
"Malton",
"Malvern",
"Manchester",
"Manningtree",
"Mansfield",
"March",
"Margate",
"Market Deeping",
"Market Drayton",
"Market Harborough",
"Market Rasen",
"Market Weighton",
"Markethill",
"Markinch",
"Marlborough",
"Marlow",
"Maryport",
"Matlock",
"Maybole",
"Melksham",
"Melrose",
"Melton Mowbray",
"Merthyr Tydfil",
"Mexborough",
"Middleham",
"Middlesbrough",
"Middlewich",
"Midhurst",
"Midsomer Norton",
"Milford Haven",
"Milngavie",
"Milton Keynes",
"Minehead",
"Moffat",
"Mold",
"Monifieth",
"Monmouth",
"Montgomery",
"Montrose",
"Morecambe",
"Moreton in Marsh",
"Moretonhampstead",
"Morley",
"Morpeth",
"Motherwell",
"Musselburgh",
"Nailsea",
"Nailsworth",
"Nairn",
"Nantwich",
"Narberth",
"Neath",
"Needham Market",
"Neston",
"New Mills",
"New Milton",
"Newbury",
"Newcastle",
"Newcastle Emlyn",
"Newcastle upon Tyne",
"Newent",
"Newhaven",
"Newmarket",
"Newport",
"Newport Pagnell",
"Newport on Tay",
"Newquay",
"Newry",
"Newton Abbot",
"Newton Aycliffe",
"Newton Stewart",
"Newton le Willows",
"Newtown",
"Newtownabbey",
"Newtownards",
"Normanton",
"North Berwick",
"North Walsham",
"Northallerton",
"Northampton",
"Northwich",
"Norwich",
"Nottingham",
"Nuneaton",
"Oakham",
"Oban",
"Okehampton",
"Oldbury",
"Oldham",
"Oldmeldrum",
"Olney",
"Omagh",
"Ormskirk",
"Orpington",
"Ossett",
"Oswestry",
"Otley",
"Oundle",
"Oxford",
"Padstow",
"Paignton",
"Painswick",
"Paisley",
"Peebles",
"Pembroke",
"Penarth",
"Penicuik",
"Penistone",
"Penmaenmawr",
"Penrith",
"Penryn",
"Penzance",
"Pershore",
"Perth",
"Peterborough",
"Peterhead",
"Peterlee",
"Petersfield",
"Petworth",
"Pickering",
"Pitlochry",
"Pittenweem",
"Plymouth",
"Pocklington",
"Polegate",
"Pontefract",
"Pontypridd",
"Poole",
"Port Talbot",
"Portadown",
"Portaferry",
"Porth",
"Porthcawl",
"Porthmadog",
"Portishead",
"Portrush",
"Portsmouth",
"Portstewart",
"Potters Bar",
"Potton",
"Poulton le Fylde",
"Prescot",
"Prestatyn",
"Presteigne",
"Preston",
"Prestwick",
"Princes Risborough",
"Prudhoe",
"Pudsey",
"Pwllheli",
"Ramsgate",
"Randalstown",
"Rayleigh",
"Reading",
"Redcar",
"Redditch",
"Redhill",
"Redruth",
"Reigate",
"Retford",
"Rhayader",
"Rhuddlan",
"Rhyl",
"Richmond",
"Rickmansworth",
"Ringwood",
"Ripley",
"Ripon",
"Rochdale",
"Rochester",
"Rochford",
"Romford",
"Romsey",
"Ross on Wye",
"Rostrevor",
"Rothbury",
"Rotherham",
"Rothesay",
"Rowley Regis",
"Royston",
"Rugby",
"Rugeley",
"Runcorn",
"Rushden",
"Rutherglen",
"Ruthin",
"Ryde",
"Rye",
"Saffron Walden",
"Saintfield",
"Salcombe",
"Sale",
"Salford",
"Salisbury",
"Saltash",
"Saltcoats",
"Sandbach",
"Sandhurst",
"Sandown",
"Sandwich",
"Sandy",
"Sawbridgeworth",
"Saxmundham",
"Scarborough",
"Scunthorpe",
"Seaford",
"Seaton",
"Sedgefield",
"Selby",
"Selkirk",
"Selsey",
"Settle",
"Sevenoaks",
"Shaftesbury",
"Shanklin",
"Sheerness",
"Sheffield",
"Shepshed",
"Shepton Mallet",
"Sherborne",
"Sheringham",
"Shildon",
"Shipston on Stour",
"Shoreham by Sea",
"Shrewsbury",
"Sidmouth",
"Sittingbourne",
"Skegness",
"Skelmersdale",
"Skipton",
"Sleaford",
"Slough",
"Smethwick",
"Soham",
"Solihull",
"Somerton",
"South Molton",
"South Shields",
"South Woodham Ferrers",
"Southam",
"Southampton",
"Southborough",
"Southend on Sea",
"Southport",
"Southsea",
"Southwell",
"Southwold",
"Spalding",
"Spennymoor",
"Spilsby",
"Stafford",
"Staines",
"Stamford",
"Stanley",
"Staveley",
"Stevenage",
"Stirling",
"Stockport",
"Stockton on Tees",
"Stoke on Trent",
"Stone",
"Stowmarket",
"Strabane",
"Stranraer",
"Stratford upon Avon",
"Strood",
"Stroud",
"Sudbury",
"Sunderland",
"Sutton Coldfield",
"Sutton in Ashfield",
"Swadlincote",
"Swanage",
"Swanley",
"Swansea",
"Swindon",
"Tadcaster",
"Tadley",
"Tain",
"Talgarth",
"Tamworth",
"Taunton",
"Tavistock",
"Teignmouth",
"Telford",
"Tenby",
"Tenterden",
"Tetbury",
"Tewkesbury",
"Thame",
"Thatcham",
"Thaxted",
"Thetford",
"Thirsk",
"Thornbury",
"Thrapston",
"Thurso",
"Tilbury",
"Tillicoultry",
"Tipton",
"Tiverton",
"Tobermory",
"Todmorden",
"Tonbridge",
"Torpoint",
"Torquay",
"Totnes",
"Totton",
"Towcester",
"Tredegar",
"Tregaron",
"Tring",
"Troon",
"Trowbridge",
"Truro",
"Tunbridge Wells",
"Tywyn",
"Uckfield",
"Ulverston",
"Uppingham",
"Usk",
"Uttoxeter",
"Ventnor",
"Verwood",
"Wadebridge",
"Wadhurst",
"Wakefield",
"Wallasey",
"Wallingford",
"Walsall",
"Waltham Abbey",
"Waltham Cross",
"Walton on Thames",
"Walton on the Naze",
"Wantage",
"Ware",
"Wareham",
"Warminster",
"Warrenpoint",
"Warrington",
"Warwick",
"Washington",
"Watford",
"Wednesbury",
"Wednesfield",
"Wellingborough",
"Wellington",
"Wells",
"Wells next the Sea",
"Welshpool",
"Welwyn Garden City",
"Wem",
"Wendover",
"West Bromwich",
"Westbury",
"Westerham",
"Westhoughton",
"Weston super Mare",
"Wetherby",
"Weybridge",
"Weymouth",
"Whaley Bridge",
"Whitby",
"Whitchurch",
"Whitehaven",
"Whitley Bay",
"Whitnash",
"Whitstable",
"Whitworth",
"Wick",
"Wickford",
"Widnes",
"Wigan",
"Wigston",
"Wigtown",
"Willenhall",
"Wincanton",
"Winchester",
"Windermere",
"Winsford",
"Winslow",
"Wisbech",
"Witham",
"Withernsea",
"Witney",
"Woburn",
"Woking",
"Wokingham",
"Wolverhampton",
"Wombwell",
"Woodbridge",
"Woodstock",
"Wootton Bassett",
"Worcester",
"Workington",
"Worksop",
"Worthing",
"Wotton under Edge",
"Wrexham",
"Wymondham",
"Yarm",
"Yarmouth",
"Yate",
"Yateley",
"Yeadon",
"Yeovil",
"York"
};
}
public string Generate()
{
return _citynames[_random.Next(0, _citynames.Count)];
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
namespace UnitTestGrains
{
public class TimerGrain : Grain, ITimerGrain
{
private bool deactivating;
int counter = 0;
Dictionary<string, IDisposable> allTimers;
IDisposable defaultTimer;
private static readonly TimeSpan period = TimeSpan.FromMilliseconds(100);
string DefaultTimerName = "DEFAULT TIMER";
ISchedulingContext context;
private Logger logger;
public override Task OnActivateAsync()
{
ThrowIfDeactivating();
logger = this.GetLogger("TimerGrain_" + base.Data.Address.ToString());
context = RuntimeContext.Current.ActivationContext;
defaultTimer = this.RegisterTimer(Tick, DefaultTimerName, period, period);
allTimers = new Dictionary<string, IDisposable>();
return Task.CompletedTask;
}
public Task StopDefaultTimer()
{
ThrowIfDeactivating();
defaultTimer.Dispose();
return Task.CompletedTask;
}
private Task Tick(object data)
{
counter++;
logger.Info(data.ToString() + " Tick # " + counter + " RuntimeContext = " + RuntimeContext.Current.ActivationContext.ToString());
// make sure we run in the right activation context.
if(!Equals(context, RuntimeContext.Current.ActivationContext))
logger.Error((int)ErrorCode.Runtime_Error_100146, "grain not running in the right activation context");
string name = (string)data;
IDisposable timer = null;
if (name == DefaultTimerName)
{
timer = defaultTimer;
}
else
{
timer = allTimers[(string)data];
}
if(timer == null)
logger.Error((int)ErrorCode.Runtime_Error_100146, "Timer is null");
if (timer != null && counter > 10000)
{
// do not let orphan timers ticking for long periods
timer.Dispose();
}
return Task.CompletedTask;
}
public Task<TimeSpan> GetTimerPeriod()
{
return Task.FromResult(period);
}
public Task<int> GetCounter()
{
ThrowIfDeactivating();
return Task.FromResult(counter);
}
public Task SetCounter(int value)
{
ThrowIfDeactivating();
lock (this)
{
counter = value;
}
return Task.CompletedTask;
}
public Task StartTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = this.RegisterTimer(Tick, timerName, TimeSpan.Zero, period);
allTimers.Add(timerName, timer);
return Task.CompletedTask;
}
public Task StopTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = allTimers[timerName];
timer.Dispose();
return Task.CompletedTask;
}
public Task LongWait(TimeSpan time)
{
ThrowIfDeactivating();
Thread.Sleep(time);
return Task.CompletedTask;
}
public Task Deactivate()
{
deactivating = true;
DeactivateOnIdle();
return Task.CompletedTask;
}
private void ThrowIfDeactivating()
{
if (deactivating) throw new InvalidOperationException("This activation is deactivating");
}
}
public class TimerCallGrain : Grain, ITimerCallGrain
{
private int tickCount;
private Exception tickException;
private IDisposable timer;
private string timerName;
private ISchedulingContext context;
private TaskScheduler activationTaskScheduler;
private Logger logger;
public Task<int> GetTickCount() { return Task.FromResult(tickCount); }
public Task<Exception> GetException() { return Task.FromResult(tickException); }
public override Task OnActivateAsync()
{
logger = this.GetLogger("TimerCallGrain_" + base.Data.Address);
context = RuntimeContext.Current.ActivationContext;
activationTaskScheduler = TaskScheduler.Current;
return Task.CompletedTask;
}
public Task StartTimer(string name, TimeSpan delay)
{
logger.Info("StartTimer Name={0} Delay={1}", name, delay);
this.timerName = name;
this.timer = base.RegisterTimer(TimerTick, name, delay, Constants.INFINITE_TIMESPAN); // One shot timer
return Task.CompletedTask;
}
public Task StopTimer(string name)
{
logger.Info("StopTimer Name={0}", name);
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
timer.Dispose();
return Task.CompletedTask;
}
private async Task TimerTick(object data)
{
try
{
await ProcessTimerTick(data);
}
catch (Exception exc)
{
this.tickException = exc;
throw;
}
}
private async Task ProcessTimerTick(object data)
{
string step = "TimerTick";
LogStatus(step);
// make sure we run in the right activation context.
CheckRuntimeContext(step);
string name = (string)data;
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
ISimpleGrain grain = GrainFactory.GetGrain<ISimpleGrain>(0, SimpleGrain.SimpleGrainNamePrefix);
LogStatus("Before grain call #1");
await grain.SetA(tickCount);
step = "After grain call #1";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before Delay");
await Task.Delay(TimeSpan.FromSeconds(1));
step = "After Delay";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #2");
await grain.SetB(tickCount);
step = "After grain call #2";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #3");
int res = await grain.GetAxB();
step = "After grain call #3 - Result = " + res;
LogStatus(step);
CheckRuntimeContext(step);
tickCount++;
}
private void CheckRuntimeContext(string what)
{
if (RuntimeContext.Current.ActivationContext == null
|| !RuntimeContext.Current.ActivationContext.Equals(context))
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected activation context: Expected={1} Actual={2}",
what, context, RuntimeContext.Current.ActivationContext));
}
if (TaskScheduler.Current.Equals(activationTaskScheduler) && TaskScheduler.Current is ActivationTaskScheduler)
{
// Everything is as expected
}
else
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected TaskScheduler.Current context: Expected={1} Actual={2}",
what, activationTaskScheduler, TaskScheduler.Current));
}
}
private void LogStatus(string what)
{
logger.Info("{0} Tick # {1} - {2} - RuntimeContext.Current={3} TaskScheduler.Current={4} CurrentWorkerThread={5}",
timerName, tickCount, what, RuntimeContext.Current, TaskScheduler.Current,
WorkerPoolThread.CurrentWorkerThread);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using FluentAssertions;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Csdl;
using Microsoft.OData.Edm.Library;
using Microsoft.OData.Edm.Library.Values;
using Microsoft.OData.Edm.Validation;
using Microsoft.OData.Edm.Values;
using Xunit;
using Vipr.Reader.OData.v4;
using Vipr.Core.CodeModel;
using Vipr.Core.CodeModel.Vocabularies.Capabilities;
namespace ODataReader.v4UnitTests
{
public class Given_An_ODataVocabularyParser
{
public Given_An_ODataVocabularyParser()
{
}
[Xunit.Fact]
public void Boolean_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> booleanConstantPredicate = o => new EdmBooleanConstant((bool) o);
ConstantValueShouldRoundtrip(true, booleanConstantPredicate);
ConstantValueShouldRoundtrip(false, booleanConstantPredicate);
}
[Fact]
public void String_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> stringPredicate = o => new EdmStringConstant((string) o);
ConstantValueShouldRoundtrip("♪♪ unicode test string ♪♪", stringPredicate);
}
[Fact]
public void Guid_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> guidConstantPredicate = o => new EdmGuidConstant((Guid) o);
ConstantValueShouldRoundtrip(Guid.NewGuid(), guidConstantPredicate);
}
[Fact]
public void Binary_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> binaryConstantPredicate = o => new EdmBinaryConstant((byte[]) o);
ConstantValueShouldRoundtrip(new byte[] {1, 3, 3, 7}, binaryConstantPredicate);
}
[Fact]
public void Date_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> dateConstantPredicate = o => new EdmDateConstant((Date) o);
ConstantValueShouldRoundtrip(Date.Now, dateConstantPredicate);
}
[Fact]
public void DateOffset_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> dateTimeOffsetConstantPredicate =
o => new EdmDateTimeOffsetConstant((DateTimeOffset) o);
ConstantValueShouldRoundtrip(DateTimeOffset.Now, dateTimeOffsetConstantPredicate);
ConstantValueShouldRoundtrip(DateTimeOffset.UtcNow, dateTimeOffsetConstantPredicate);
}
[Fact]
public void Decimal_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> decimalConstantValuePredicate = o => new EdmDecimalConstant((decimal) o);
ConstantValueShouldRoundtrip((decimal) 1.234, decimalConstantValuePredicate);
}
[Fact]
public void Floating_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> floatingConstantValuePredicate = o => new EdmFloatingConstant((double) o);
ConstantValueShouldRoundtrip(1.234d, floatingConstantValuePredicate);
}
[Fact]
public void Integer_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> integerConstantValuePredicate = o => new EdmIntegerConstant((long) o);
ConstantValueShouldRoundtrip(123400L, integerConstantValuePredicate);
}
[Fact]
public void Duration_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> durationConstantValuePredicate = o => new EdmDurationConstant((TimeSpan) o);
ConstantValueShouldRoundtrip(new TimeSpan(1, 2, 3, 4), durationConstantValuePredicate);
}
[Fact]
public void TimeOfDay_contant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> timeOfDayConstantValuePredicate = o => new EdmTimeOfDayConstant((TimeOfDay) o);
ConstantValueShouldRoundtrip(TimeOfDay.Now, timeOfDayConstantValuePredicate);
}
private void ConstantValueShouldRoundtrip(object originalValue, Func<object, IEdmValue> valuePredicate)
{
// Map our original value to an IEdmValue with the supplied predicate
var iEdmValue = valuePredicate(originalValue);
var result = ODataVocabularyReader.MapToClr(iEdmValue);
result.Should()
.Be(originalValue, "because a given clr value should roundtrip through its appropriate edm value ");
}
[Fact]
public void Validly_annotated_Edm_will_correctly_parse_insert_restrictions()
{
var annotations = GetAnnotationsFromOneNoteSampleEntitySet("sections");
annotations.Should().HaveCount(4, "because sections have four annotations");
annotations.Should().Contain(x => x.Name == "InsertRestrictions");
var insertRestrictions = annotations.First(x => x.Name == "InsertRestrictions");
insertRestrictions.Namespace.Should().Be("Org.OData.Capabilities.V1");
insertRestrictions.Value.Should().BeOfType<InsertRestrictionsType>();
var insertValue = insertRestrictions.Value as InsertRestrictionsType;
insertValue.Insertable.Should().BeFalse();
insertValue.NonInsertableNavigationProperties.Should().HaveCount(2);
insertValue.NonInsertableNavigationProperties.Should().Contain("parentNotebook");
insertValue.NonInsertableNavigationProperties.Should().Contain("parentSectionGroup");
}
[Fact]
public void Validly_annotated_edm_will_correctly_parse_update_restrictions()
{
var annotations = GetAnnotationsFromOneNoteSampleEntitySet("sections");
annotations.Should().Contain(x => x.Name == "UpdateRestrictions");
var update = annotations.First(x => x.Name == "UpdateRestrictions");
update.Namespace.Should().Be("Org.OData.Capabilities.V1");
update.Value.Should().BeOfType<UpdateRestrictionsType>();
var updateValue = update.Value as UpdateRestrictionsType;
updateValue.Updatable.Should().BeFalse();
updateValue.NonUpdatableNavigationProperties.Should().HaveCount(3);
updateValue.NonUpdatableNavigationProperties.Should().Contain("pages");
updateValue.NonUpdatableNavigationProperties.Should().Contain("parentNotebook");
updateValue.NonUpdatableNavigationProperties.Should().Contain("parentSectionGroup");
}
[Fact]
public void Validly_annotated_edm_will_correctly_parse_delete_restrictions()
{
var annotations = GetAnnotationsFromOneNoteSampleEntitySet("sections");
annotations.Should().Contain(x => x.Name == "DeleteRestrictions");
var delete = annotations.First(x => x.Name == "DeleteRestrictions");
delete.Namespace.Should().Be("Org.OData.Capabilities.V1");
delete.Value.Should().BeOfType<DeleteRestrictionsType>();
var deleteValue = delete.Value as DeleteRestrictionsType;
deleteValue.Deletable.Should().BeFalse();
deleteValue.NonDeletableNavigationProperties.Should().HaveCount(3);
deleteValue.NonDeletableNavigationProperties.Should().Contain("pages");
deleteValue.NonDeletableNavigationProperties.Should().Contain("parentNotebook");
deleteValue.NonDeletableNavigationProperties.Should().Contain("parentSectionGroup");
}
[Fact]
public void Validly_annotated_edm_will_correctly_parse_annotations_with_primitive_values()
{
var annotations = GetAnnotationsFromOneNoteSampleEntityContainer();
annotations.Should().HaveCount(3);
annotations.Should().Contain(x => x.Name == "BatchSupported");
annotations.Should().Contain(x => x.Name == "AsynchronousRequestsSupported");
annotations.Should().Contain(x => x.Name == "BatchContinueOnErrorSupported");
// In this case, all of the value and namespaces for these annotaion are the same
// We'll loop over them for brevity.
foreach (var annotation in annotations)
{
annotation.Namespace.Should().Be("Org.OData.Capabilities.V1");
annotation.Value.Should().BeOfType<bool>();
((bool) annotation.Value).Should().BeFalse();
}
}
private List<OdcmVocabularyAnnotation> GetAnnotationsFromOneNoteSampleEntitySet(string entitySet)
{
IEdmModel model = SampleParsedEdmModel;
IEdmEntitySet sampleEntitySet = model.FindEntityContainer("OneNoteApi").FindEntitySet(entitySet);
return ODataVocabularyReader.GetOdcmAnnotations(model, sampleEntitySet).ToList();
}
private List<OdcmVocabularyAnnotation> GetAnnotationsFromOneNoteSampleEntityContainer()
{
IEdmModel model = SampleParsedEdmModel;
var sampleContainer = model.FindEntityContainer("OneNoteApi");
return ODataVocabularyReader.GetOdcmAnnotations(model, sampleContainer).ToList();
}
#region Helper methods
private static readonly IEdmModel SampleParsedEdmModel = GetSampleParsedEdmModel();
private static IEdmModel GetSampleParsedEdmModel()
{
IEdmModel edmModel;
IEnumerable<EdmError> errors;
if (!EdmxReader.TryParse(XmlReader.Create(new StringReader(ODataReader.v4UnitTests.Properties.Resources.OneNoteExampleEdmx)), out edmModel, out errors))
{
throw new InvalidOperationException("Failed to parse Edm model");
}
return edmModel;
}
}
#endregion
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Common.Core;
using Microsoft.Common.Core.Logging;
using Microsoft.R.Common.Core.Output;
using static System.FormattableString;
namespace Microsoft.R.Host.Client.BrokerServices {
public class WebServer {
private static ConcurrentDictionary<int, WebServer> Servers { get; } = new ConcurrentDictionary<int, WebServer>();
private static object _serverLock = new object();
private readonly IRemoteUriWebService _remoteUriService;
private readonly string _baseAddress;
private readonly IActionLog _log;
private readonly IConsole _console;
private readonly string _name;
private HttpListener _listener;
public string LocalHost { get; }
public int LocalPort { get; private set; }
public string RemoteHost { get; }
public int RemotePort { get; }
private WebServer(string remoteHostIp, int remotePort, string baseAddress, string name, IActionLog log, IConsole console) {
_name = name.ToUpperInvariant();
_baseAddress = baseAddress;
_log = log;
_console = console;
LocalHost = IPAddress.Loopback.ToString();
RemoteHost = remoteHostIp;
RemotePort = remotePort;
_remoteUriService = new RemoteUriWebService(baseAddress, log, console);
}
public void Initialize(CancellationToken ct) {
Random r = new Random();
// if remote port is between 10000 and 32000, select a port in the same range.
// R Help uses ports in that range.
int localPortMin = (RemotePort >= 10000 && RemotePort <= 32000) ? 10000 : 49152;
int localPortMax = (RemotePort >= 10000 && RemotePort <= 32000) ? 32000 : 65535;
_console.WriteErrorLine(Resources.Info_RemoteWebServerStarting.FormatInvariant(_name));
while (true) {
ct.ThrowIfCancellationRequested();
_listener = new HttpListener();
LocalPort = r.Next(localPortMin, localPortMax);
_listener.Prefixes.Add(Invariant($"http://{LocalHost}:{LocalPort}/"));
try {
_listener.Start();
} catch (HttpListenerException) {
_listener.Close();
continue;
} catch (ObjectDisposedException) {
// Socket got closed
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name));
_console.WriteErrorLine(Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name));
throw new OperationCanceledException();
}
break;
}
try {
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.General, Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort));
_console.WriteErrorLine(Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort));
_console.WriteErrorLine(Resources.Info_RemoteWebServerDetails.FormatInvariant(Environment.MachineName, LocalHost, LocalPort, _name, _baseAddress));
} catch {
}
}
private void Stop() {
try {
if (_listener.IsListening) {
_listener.Stop();
}
_listener.Close();
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.General, Resources.Info_RemoteWebServerStopped.FormatInvariant(_name));
_console.WriteErrorLine(Resources.Info_RemoteWebServerStopped.FormatInvariant(_name));
} catch (Exception ex) when (!ex.IsCriticalException()) {
}
}
public static void Stop(int port) {
if (Servers.TryRemove(port, out WebServer server)) {
server.Stop();
}
}
public static void StopAll() {
var ports = Servers.Keys.AsArray();
foreach (var port in ports) {
Stop(port);
}
}
private async Task DoWorkAsync(CancellationToken ct = default(CancellationToken)) {
try {
while (_listener.IsListening) {
if (ct.IsCancellationRequested) {
_listener.Stop();
break;
}
HttpListenerContext context = await _listener.GetContextAsync();
string localUrl = $"{LocalHost}:{LocalPort}";
string remoteUrl = $"{RemoteHost}:{RemotePort}";
_remoteUriService.GetResponseAsync(context, localUrl, remoteUrl, ct).DoNotWait();
}
} catch(Exception ex) {
if (Servers.ContainsKey(RemotePort)) {
// Log only if we expect this web server to be running and it fails.
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_RemoteWebServerFailed.FormatInvariant(_name, ex.Message));
_console.WriteErrorLine(Resources.Error_RemoteWebServerFailed.FormatInvariant(_name, ex.Message));
}
} finally {
Stop(RemotePort);
}
}
public static Task<string> CreateWebServerAndHandleUrlAsync(string remoteUrl, string baseAddress, string name, IActionLog log, IConsole console, CancellationToken ct = default(CancellationToken)) {
var remoteUri = new Uri(remoteUrl);
var localUri = new UriBuilder(remoteUri);
WebServer server;
lock (_serverLock) {
if (!Servers.TryGetValue(remoteUri.Port, out server)) {
server = new WebServer(remoteUri.Host, remoteUri.Port, baseAddress, name, log, console);
server.Initialize(ct);
Servers.TryAdd(remoteUri.Port, server);
}
}
server.DoWorkAsync(ct).DoNotWait();
localUri.Host = server.LocalHost;
localUri.Port = server.LocalPort;
return Task.FromResult(localUri.Uri.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCL.Net;
namespace Conv.NET
{
[Serializable]
public class FullyConnectedLayer : Layer
{
#region Fields
private double dropoutParameter;
// Host
private float[] weightsHost;
private float[] biasesHost;
// Device
[NonSerialized]
private Mem dropoutMaskGPU;
[NonSerialized]
private Mem weightsGPU;
[NonSerialized]
private Mem biasesGPU;
[NonSerialized]
private Mem weightsGradientsGPU;
[NonSerialized]
private Mem biasesGradientsGPU;
[NonSerialized]
private Mem weightsSpeedGPU;
[NonSerialized]
private Mem biasesSpeedGPU;
// Global and local work-group sizes (for OpenCL kernels) - will be set in SetWorkGroupSizes();
private IntPtr[] forwardGlobalWorkSizePtr;
private IntPtr[] forwardLocalWorkSizePtr;
private IntPtr[] backwardGlobalWorkSizePtr;
private IntPtr[] backwardLocalWorkSizePtr;
private IntPtr[] updateGlobalWorkSizePtr;
private IntPtr[] updateLocalWorkSizePtr;
private IntPtr[] constrainNormGlobalWorkSizePtr;
private IntPtr[] constrainNormLocalWorkSizePtr;
#endregion
#region Properties
public override Mem WeightsGPU
{
get { return weightsGPU; }
}
public override double DropoutParameter
{
set { this.dropoutParameter = value; }
}
#endregion
#region Setup methods
/// <summary>
/// Constructor of fully connected layer type. Specify number of units as argument.
/// </summary>
/// <param name="nUnits"></param>
public FullyConnectedLayer(int nUnits)
{
this.type = "FullyConnected";
this.nOutputUnits = nUnits;
}
public override void SetupOutput()
{
this.outputDepth = nOutputUnits;
this.outputHeight = 1;
this.outputWidth = 1;
this.outputNeurons = new Neurons(this.nOutputUnits);
#if OPENCL_ENABLED
this.dropoutMaskGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)(sizeof(bool) * nOutputUnits * inputNeurons.MiniBatchSize),
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "InitializeParameters(): Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(dropoutMaskGPU, nOutputUnits * inputNeurons.MiniBatchSize, typeof(bool));
#endif
}
public override void InitializeParameters(string Option)
{
base.InitializeParameters(Option); // makes sure this method is only call AFTER "SetupOutput()"
if (Option == "random") // sample new parameters
{
// WEIGHTS are initialized as normally distributed numbers with mean 0 and std equals to sqrt(2/nInputUnits)
// BIASES are initialized to a small positive number, e.g. 0.001
this.weightsHost = new float[nOutputUnits * nInputUnits];
this.biasesHost = new float[nOutputUnits];
double weightsStdDev = Math.Sqrt(2.0 / (10 * nInputUnits));
double uniformRand1;
double uniformRand2;
double tmp;
for (int iRow = 0; iRow < nOutputUnits; iRow++)
{
for (int iCol = 0; iCol < nInputUnits; iCol++)
{
uniformRand1 = Global.rng.NextDouble();
uniformRand2 = Global.rng.NextDouble();
// Use a Box-Muller transform to get a random normal(0,1)
tmp = Math.Sqrt(-2.0 * Math.Log(uniformRand1)) * Math.Sin(2.0 * Math.PI * uniformRand2);
tmp = weightsStdDev * tmp; // rescale
weightsHost[iRow * nInputUnits + iCol] = (float)tmp;
}
biasesHost[iRow] = 0.00f;
}
}
// else Option must be ''load'' => do not sample parameters, just load them from host to device
int weightBufferSize = sizeof(float) * (outputNeurons.NumberOfUnits * inputNeurons.NumberOfUnits);
int biasesBufferSize = sizeof(float) * outputNeurons.NumberOfUnits;
this.weightsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite | MemFlags.CopyHostPtr,
(IntPtr)weightBufferSize,
weightsHost,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
this.biasesGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite | MemFlags.CopyHostPtr,
(IntPtr)biasesBufferSize,
biasesHost,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
// Also create weightsGradients and biasesGradients buffers and initialize them to zero
this.weightsGradientsGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)weightBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(weightsGradientsGPU, (nInputUnits * nOutputUnits), typeof(float));
this.biasesGradientsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)biasesBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(biasesGradientsGPU, nOutputUnits, typeof(float));
// Also create weightsSpeed and biasesSpeed buffers and initialize them to zero
this.weightsSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)weightBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(weightsSpeedGPU, (nInputUnits * nOutputUnits), typeof(float));
this.biasesSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)biasesBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(biasesSpeedGPU, nOutputUnits, typeof(float));
}
public override void SetWorkGroups()
{
// Work group sizes will be set as follows:
// global work size = smallest multiple of OPTIMAL_GROUP_SIZE larger than
// the total number of processes needed (for efficiency).
// local work size = as close as possible to OPTIMAL_GROUP_SIZE (making sure
// that global worksize is a multiple of this)
// OPTIMAL_GROUP_SIZE is a small multiple of BASE_GROUP_SIZE, which in turn is a
// constant multiple of 2, platform-dependent, e.g. 32 (Nvidia
// WARP) or 64 (AMD WAVEFRONT).
int miniBatchSize = outputNeurons.MiniBatchSize;
// FeedForward (2D) ________________________________________________________________________________
// Local
int optimalToBaseRatio = OpenCLSpace.OPTIMAL_GROUP_SIZE / OpenCLSpace.BASE_GROUP_SIZE;
this.forwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio };
// Global
int smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
int smallestMultiple1 = (int)(optimalToBaseRatio * Math.Ceiling((double)(miniBatchSize) / (double)optimalToBaseRatio));
this.forwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// BackPropagate (2D) _________________________________________________________________________________
// Local
this.backwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio };
// Global
smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE)); // input this time!
this.backwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// UpdateSpeeds and UpdateParameters (2D) ________________________________________________________________
// Local
this.updateLocalWorkSizePtr = new IntPtr[] { (IntPtr)optimalToBaseRatio, (IntPtr)OpenCLSpace.BASE_GROUP_SIZE }; // product is OPTIMAL_WORK_SIZE
// Global
smallestMultiple0 = (int)(optimalToBaseRatio * Math.Ceiling((double)(nOutputUnits) / (double)optimalToBaseRatio));
smallestMultiple1 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
this.updateGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// Max norm constrain
this.constrainNormLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE };
int smallestMultipleAux = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
this.constrainNormGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultipleAux };
}
public override void CopyBuffersToHost()
{
OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
weightsHost, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer weightsGPU");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
biasesHost, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer biasesGPU");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Speeds are not saved.
}
#endregion
#region Methods
public override void FeedForward()
{
#if TIMING_LAYERS
Utils.FCForwardTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCForward, 0, outputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 1, inputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 2, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 3, biasesGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 7, (IntPtr)sizeof(float), (float)dropoutParameter);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 8, (IntPtr)sizeof(ulong), (ulong)Guid.NewGuid().GetHashCode()); // this should be quite a good random seed
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 9, dropoutMaskGPU);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCForward,
2,
null,
forwardGlobalWorkSizePtr,
forwardLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
// TODO: add dropout CPU
// Generate dropout mask
if (dropoutParameter < 1)
{
for (int iUnit = 0; iUnit < nOutputUnits * inputNeurons.MiniBatchSize; ++iUnit)
dropoutMask[iUnit] = Global.RandomDouble() < dropoutParameter;
}
for (int m = 0; m < inputNeurons.MiniBatchSize; m++)
{
double[] unbiasedOutput = Utils.MultiplyMatrixByVector(weights, inputNeurons.GetHost()[m]);
this.outputNeurons.SetHost(m, unbiasedOutput.Zip(biases, (x, y) => x + y).ToArray());
}
#endif
#if TIMING_LAYERS
Utils.FCForwardTimer.Stop();
#endif
}
public override void BackPropagate()
{
#if TIMING_LAYERS
Utils.FCBackpropTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 0, inputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 1, outputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 2, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 3, dropoutMaskGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCBackward,
2,
null,
backwardGlobalWorkSizePtr,
backwardLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
for (int m = 0; m < inputNeurons.MiniBatchSize; m++)
{
inputNeurons.DeltaHost[m] = Utils.MultiplyMatrixTranspByVector(weights, outputNeurons.DeltaHost[m]);
}
#endif
#if TIMING_LAYERS
Utils.FCBackpropTimer.Stop();
#endif
}
public override void UpdateSpeeds(double learningRate, double momentumCoefficient, double weightDecayCoefficient)
{
#if TIMING_LAYERS
Utils.FCUpdateSpeedsTimer.Start();
#endif
#if DEBUGGING_STEPBYSTEP_FC
float[,] weightsBeforeUpdate = new float[output.NumberOfUnits, input.NumberOfUnits];
/* ------------------------- DEBUGGING --------------------------------------------- */
#if OPENCL_ENABLED
// Display weights before update
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)),
weightsBeforeUpdate, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsBeforeUpdate");
#else
weightsBeforeUpdate = weights;
#endif
Console.WriteLine("\nWeights BEFORE update:");
for (int i = 0; i < weightsBeforeUpdate.GetLength(0); i++)
{
for (int j = 0; j < weightsBeforeUpdate.GetLength(1); j++)
Console.Write("{0} ", weightsBeforeUpdate[i, j]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
// Display biases before update
float[] biasesBeforeUpdate = new float[output.NumberOfUnits];
#if OPENCL_ENABLED
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * sizeof(float)),
biasesBeforeUpdate, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer biasesBeforeUpdate");
#else
biasesBeforeUpdate = biases;
#endif
Console.WriteLine("\nBiases BEFORE update:");
for (int i = 0; i < biasesBeforeUpdate.Length; i++)
{
Console.Write("{0} ", biasesBeforeUpdate[i]);
}
Console.WriteLine();
Console.ReadKey();
// Display weight update speed before update
float[,] tmpWeightsUpdateSpeed = new float[output.NumberOfUnits, input.NumberOfUnits];
#if OPENCL_ENABLED
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsUpdateSpeedGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)),
tmpWeightsUpdateSpeed, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsUpdateSpeed");
#else
tmpWeightsUpdateSpeed = weightsUpdateSpeed;
#endif
Console.WriteLine("\nWeight update speed BEFORE update:");
for (int i = 0; i < tmpWeightsUpdateSpeed.GetLength(0); i++)
{
for (int j = 0; j < tmpWeightsUpdateSpeed.GetLength(1); j++)
Console.Write("{0} ", tmpWeightsUpdateSpeed[i, j]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
// Display input activations before update
/*
float[] inputActivations = new float[input.NumberOfUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
input.ActivationsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(input.NumberOfUnits * sizeof(float)),
inputActivations, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer inputActivations");
Console.WriteLine("\nInput activations BEFORE update:");
for (int j = 0; j < inputActivations.Length; j++)
{
Console.Write("{0} ", inputActivations[j]);
}
Console.WriteLine();
Console.ReadKey();
// Display output delta before update
float[] outputDelta = new float[output.NumberOfUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
output.DeltaGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * sizeof(float)),
outputDelta, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer outputDelta");
Console.WriteLine("\nOutput delta BEFORE update:");
for (int i = 0; i < outputDelta.Length; i++)
{
Console.Write("{0}", outputDelta[i]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
*/
/*------------------------- END DEBUGGING --------------------------------------------- */
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 0, weightsSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 1, biasesSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 2, weightsGradientsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 3, biasesGradientsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 4, inputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 5, outputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 6, dropoutMaskGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 7, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 8, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 9, (IntPtr)sizeof(float), (float)momentumCoefficient);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 10, (IntPtr)sizeof(float), (float)learningRate);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 11, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 12, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 13, (IntPtr)sizeof(float), (float)weightDecayCoefficient);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCUpdateSpeeds,
2,
null,
updateGlobalWorkSizePtr,
updateLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
int miniBatchSize = inputNeurons.MiniBatchSize;
for (int m = 0; m < miniBatchSize; m++)
{
for (int i = 0; i < nOutputUnits; i++)
{
// weights speed
for (int j = 0; j < nInputUnits; j++)
{
if (m == 0)
weightsUpdateSpeed[i, j] *= momentumCoefficient;
weightsUpdateSpeed[i, j] -= learningRate/miniBatchSize * inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i];
#if GRADIENT_CHECK
weightsGradients[i, j] = inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i];
#endif
}
// update biases
if (m == 0)
biasesUpdateSpeed[i] *= momentumCoefficient;
biasesUpdateSpeed[i] -= learningRate/miniBatchSize * outputNeurons.DeltaHost[m][i];
#if GRADIENT_CHECK
biasesGradients[i] = outputNeurons.DeltaHost[m][i];
#endif
}
} // end loop over mini-batch
#endif
#if TIMING_LAYERS
Utils.FCUpdateSpeedsTimer.Stop();
#endif
}
public override void UpdateParameters(double weightMaxNorm)
{
#if TIMING_LAYERS
Utils.FCUpdateParametersTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 0, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 1, biasesGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 2, weightsSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 3, biasesSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCUpdateParameters,
2,
null,
updateGlobalWorkSizePtr,
updateLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
// Now constrain norm of each weight vector
if (!double.IsInfinity(weightMaxNorm))
{
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 0, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 1, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 2, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 3, (IntPtr)sizeof(float), (float)weightMaxNorm);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel(OpenCLSpace.Queue,
OpenCLSpace.FCConstrainWeightNorm,
1,
null,
constrainNormGlobalWorkSizePtr,
constrainNormLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
}
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
for (int i = 0; i < nOutputUnits; i++)
{
// weights update
for (int j = 0; j < nInputUnits; j++)
{
weights[i, j] += weightsUpdateSpeed[i, j];
}
// update biases
biases[i] += biasesUpdateSpeed[i];
}
#endif
#if TIMING_LAYERS
Utils.FCUpdateParametersTimer.Stop();
#endif
}
#endregion
#region Gradient check
public override double[] GetParameters()
{
int nParameters = nInputUnits * nOutputUnits + nOutputUnits;
double[] parameters = new double[nParameters];
// Copy weights and biases buffers to host
float[] tmpWeights = new float[nInputUnits * nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeights, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
float[] tmpBiases = new float[nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiases, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Convert to double and write into parameters array
for (int i = 0; i < nInputUnits*nOutputUnits; ++i)
{
parameters[i] = (double)tmpWeights[i];
}
for (int i = 0; i < nOutputUnits; ++i)
{
parameters[nInputUnits * nOutputUnits + i] = (double)tmpBiases[i];
}
return parameters;
}
public override double[] GetParameterGradients()
{
int nParameters = nInputUnits * nOutputUnits + nOutputUnits;
double[] parameterGradients = new double[nParameters];
// Copy weights and biases gradients buffers to host
float[] tmpWeightsGrad = new float[nInputUnits * nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGradientsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeightsGrad, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
float[] tmpBiasesGrad = new float[nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGradientsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiasesGrad, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Convert to double and write into parameterGradients
//Console.WriteLine("Weight gradients:\n");
for (int i = 0; i < nInputUnits * nOutputUnits; ++i)
{
parameterGradients[i] = (double)tmpWeightsGrad[i];
//Console.Write(" {0}", tmpWeightsGrad[i]);
}
//Console.ReadKey();
for (int i = 0; i < nOutputUnits; ++i)
{
parameterGradients[nInputUnits * nOutputUnits + i] = (double)tmpBiasesGrad[i];
}
return parameterGradients;
}
public override void SetParameters(double[] NewParameters)
{
// Convert to float and write into tmp arrays
float[] tmpWeights = new float[nInputUnits * nOutputUnits];
float[] tmpBiases = new float[nOutputUnits];
for (int i = 0; i < nInputUnits * nOutputUnits; ++i)
{
tmpWeights[i] = (float)NewParameters[i];
}
for (int i = 0; i < nOutputUnits; ++i)
{
tmpBiases[i] = (float)NewParameters[nInputUnits * nOutputUnits + i];
}
// Write arrays into buffers on device
OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue,
weightsGPU,
OpenCL.Net.Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeights,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue,
biasesGPU,
OpenCL.Net.Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiases,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using NHibernate.Driver;
using NHibernate.Test.SecondLevelCacheTests;
using NUnit.Framework;
namespace NHibernate.Test.QueryTest
{
[TestFixture]
public class MultipleMixedQueriesFixture : TestCase
{
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override IList Mappings
{
get { return new[] { "SecondLevelCacheTest.Item.hbm.xml" }; }
}
protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory)
{
return factory.ConnectionProvider.Driver.SupportsMultipleQueries;
}
protected override void OnTearDown()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
session.Delete("from System.Object");
session.Flush();
transaction.Commit();
}
}
[Test]
public void NH_1085_WillIgnoreParametersIfDoesNotAppearInQuery()
{
using (var s = Sfi.OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids)").AddEntity(typeof (Item)))
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids2)").AddEntity(typeof (Item)))
.SetParameterList("ids", new[] {50})
.SetParameterList("ids2", new[] {50});
multiQuery.List();
}
}
[Test]
public void NH_1085_WillGiveReasonableErrorIfBadParameterName()
{
using (var s = Sfi.OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids)").AddEntity(typeof(Item)))
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids2)").AddEntity(typeof(Item)));
var e = Assert.Throws<QueryException>(() => multiQuery.List());
Assert.That(e.Message, Is.EqualTo("Not all named parameters have been set: ['ids'] [select * from ITEM where Id in (:ids)]"));
}
}
[Test]
public void CanGetMultiQueryFromSecondLevelCache()
{
CreateItems();
//set the query in the cache
DoMutiQueryAndAssert();
var cacheHashtable = MultipleQueriesFixture.GetHashTableUsedAsQueryCache(Sfi);
var cachedListEntry = (IList)new ArrayList(cacheHashtable.Values)[0];
var cachedQuery = (IList)cachedListEntry[1];
var firstQueryResults = (IList)cachedQuery[0];
firstQueryResults.Clear();
firstQueryResults.Add(3);
firstQueryResults.Add(4);
var secondQueryResults = (IList)cachedQuery[1];
secondQueryResults[0] = 2L;
using (var s = Sfi.OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id > ?").AddEntity(typeof(Item))
.SetInt32(0, 50)
.SetFirstResult(10))
.Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(2, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(2L, count);
}
}
[Test]
public void CanSpecifyParameterOnMultiQueryWhenItIsNotUsedInAllQueries()
{
using (var s = OpenSession())
{
s.CreateMultiQuery()
.Add("from Item")
.Add(s.CreateSQLQuery("select * from ITEM where Id > :id").AddEntity(typeof(Item)))
.SetParameter("id", 5)
.List();
}
}
[Test]
public void CanSpecifyParameterOnMultiQueryWhenItIsNotUsedInAllQueries_MoreThanOneParameter()
{
using (var s = OpenSession())
{
s.CreateMultiQuery()
.Add("from Item")
.Add(s.CreateSQLQuery("select * from ITEM where Id = :id or Id = :id2").AddEntity(typeof(Item)))
.Add("from Item i where i.Id = :id2")
.SetParameter("id", 5)
.SetInt32("id2", 5)
.List();
}
}
[Test]
public void TwoMultiQueriesWithDifferentPagingGetDifferentResultsWhenUsingCachedQueries()
{
CreateItems();
using (var s = OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateQuery("from Item i where i.Id > ?")
.SetInt32(0, 50)
.SetFirstResult(10))
.Add(s.CreateSQLQuery("select count(*) as count from ITEM where Id > ?").AddScalar("count", NHibernateUtil.Int64)
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(89, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
using (var s = OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id > ?").AddEntity(typeof(Item))
.SetInt32(0, 50)
.SetFirstResult(20))
.Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(79, items.Count,
"Should have gotten different result here, because the paging is different");
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
}
[Test]
public void CanUseSecondLevelCacheWithPositionalParameters()
{
var cacheHashtable = MultipleQueriesFixture.GetHashTableUsedAsQueryCache(Sfi);
cacheHashtable.Clear();
CreateItems();
DoMutiQueryAndAssert();
Assert.AreEqual(1, cacheHashtable.Count);
}
private void DoMutiQueryAndAssert()
{
using (var s = OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id > ?").AddEntity(typeof(Item))
.SetInt32(0, 50)
.SetFirstResult(10))
.Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(89, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
}
private void CreateItems()
{
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
for (var i = 0; i < 150; i++)
{
var item = new Item();
item.Id = i;
s.Save(item);
}
t.Commit();
}
}
[Test]
public void CanUseWithParameterizedQueriesAndLimit()
{
using (var s = OpenSession())
{
for (var i = 0; i < 150; i++)
{
var item = new Item();
item.Id = i;
s.Save(item);
}
s.Flush();
}
using (var s = OpenSession())
{
var getItems = s.CreateSQLQuery("select * from ITEM where Id > :id").AddEntity(typeof(Item)).SetFirstResult(10);
var countItems = s.CreateQuery("select count(*) from Item i where i.Id > :id");
var results = s.CreateMultiQuery()
.Add(getItems)
.Add(countItems)
.SetInt32("id", 50)
.List();
var items = (IList)results[0];
Assert.AreEqual(89, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
}
[Test]
public void CanUseSetParameterList()
{
using (var s = OpenSession())
{
var item = new Item();
item.Id = 1;
s.Save(item);
s.Flush();
}
using (var s = OpenSession())
{
var results = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:items)").AddEntity(typeof(Item)))
.Add("select count(*) from Item i where i.id in (:items)")
.SetParameterList("items", new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 })
.List();
var items = (IList)results[0];
var fromDb = (Item)items[0];
Assert.AreEqual(1, fromDb.Id);
var counts = (IList)results[1];
var count = (long)counts[0];
Assert.AreEqual(1L, count);
}
}
[Test]
public void CanExecuteMultiplyQueriesInSingleRoundTrip()
{
using (var s = OpenSession())
{
var item = new Item();
item.Id = 1;
s.Save(item);
s.Flush();
}
using (var s = OpenSession())
{
var getItems = s.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item));
var countItems = s.CreateQuery("select count(*) from Item");
var results = s.CreateMultiQuery()
.Add(getItems)
.Add(countItems)
.List();
var items = (IList)results[0];
var fromDb = (Item)items[0];
Assert.AreEqual(1, fromDb.Id);
var counts = (IList)results[1];
var count = (long)counts[0];
Assert.AreEqual(1L, count);
}
}
[Test]
public void CanAddIQueryWithKeyAndRetrieveResultsWithKey()
{
CreateItems();
using (var session = OpenSession())
{
var multiQuery = session.CreateMultiQuery();
var firstQuery = session.CreateSQLQuery("select * from ITEM where Id < :id").AddEntity(typeof(Item))
.SetInt32("id", 50);
var secondQuery = session.CreateQuery("from Item");
multiQuery.Add("first", firstQuery).Add("second", secondQuery);
var secondResult = (IList)multiQuery.GetResult("second");
var firstResult = (IList)multiQuery.GetResult("first");
Assert.Greater(secondResult.Count, firstResult.Count);
}
}
[Test]
public void CanNotAddQueryWithKeyThatAlreadyExists()
{
using (var session = OpenSession())
{
var multiQuery = session.CreateMultiQuery();
var firstQuery = session.CreateSQLQuery("select * from ITEM where Id < :id").AddEntity(typeof(Item))
.SetInt32("id", 50);
try
{
IQuery secondQuery = session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item));
multiQuery.Add("first", firstQuery).Add("second", secondQuery);
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
Assert.Fail("This should've thrown an InvalidOperationException");
}
}
}
[Test]
public void CanNotRetrieveQueryResultWithUnknownKey()
{
using (var session = OpenSession())
{
var multiQuery = session.CreateMultiQuery();
multiQuery.Add("firstQuery", session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item)));
try
{
multiQuery.GetResult("unknownKey");
Assert.Fail("This should've thrown an InvalidOperationException");
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
Assert.Fail("This should've thrown an InvalidOperationException");
}
}
}
[Test]
public void ExecutingQueryThroughMultiQueryTransformsResults()
{
CreateItems();
using (var session = OpenSession())
{
var transformer = new ResultTransformerStub();
var query = session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item))
.SetResultTransformer(transformer);
session.CreateMultiQuery()
.Add(query)
.List();
Assert.IsTrue(transformer.WasTransformTupleCalled, "Transform Tuple was not called");
Assert.IsTrue(transformer.WasTransformListCalled, "Transform List was not called");
}
}
[Test]
public void ExecutingQueryThroughMultiQueryTransformsResults_When_setting_on_multi_query_directly()
{
CreateItems();
using (var session = OpenSession())
{
var transformer = new ResultTransformerStub();
IQuery query = session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item));
session.CreateMultiQuery()
.Add(query)
.SetResultTransformer(transformer)
.List();
Assert.IsTrue(transformer.WasTransformTupleCalled, "Transform Tuple was not called");
Assert.IsTrue(transformer.WasTransformListCalled, "Transform List was not called");
}
}
[Test]
public void CanGetResultsInAGenericList()
{
using (var s = OpenSession())
{
var getItems = s.CreateQuery("from Item");
var countItems = s.CreateSQLQuery("select count(*) as count from ITEM").AddScalar("count", NHibernateUtil.Int64);
var results = s.CreateMultiQuery()
.Add(getItems)
.Add<long>(countItems)
.List();
Assert.That(results[0], Is.InstanceOf<List<object>>());
Assert.That(results[1], Is.InstanceOf<List<long>>());
}
}
}
}
|
//
// System.Web.UI.HtmlControls.HtmlSelect.cs
//
// Author:
// Dick Porter <dick@ximian.com>
//
// Copyright (C) 2005-2010 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.Web.UI.WebControls;
using System.Web.Util;
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Security.Permissions;
namespace System.Web.UI.HtmlControls
{
// CAS
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
// attributes
[DefaultEvent ("ServerChange")]
[ValidationProperty ("Value")]
[ControlBuilder (typeof (HtmlSelectBuilder))]
[SupportsEventValidation]
public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler, IParserAccessor
{
static readonly object EventServerChange = new object ();
DataSourceView _boundDataSourceView;
bool requiresDataBinding;
bool _initialized;
object datasource;
ListItemCollection items;
public HtmlSelect () : base ("select")
{
}
[DefaultValue ("")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual string DataMember {
get {
string member = Attributes["datamember"];
if (member == null) {
return (String.Empty);
}
return (member);
}
set {
if (value == null) {
Attributes.Remove ("datamember");
} else {
Attributes["datamember"] = value;
}
}
}
[DefaultValue (null)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual object DataSource {
get {
return (datasource);
}
set {
if ((value != null) &&
!(value is IEnumerable) &&
!(value is IListSource)) {
throw new ArgumentException ();
}
datasource = value;
}
}
[DefaultValue ("")]
public virtual string DataSourceID {
get {
return ViewState.GetString ("DataSourceID", "");
}
set {
if (DataSourceID == value)
return;
ViewState ["DataSourceID"] = value;
if (_boundDataSourceView != null)
_boundDataSourceView.DataSourceViewChanged -= OnDataSourceViewChanged;
_boundDataSourceView = null;
OnDataPropertyChanged ();
}
}
[DefaultValue ("")]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual string DataTextField {
get {
string text = Attributes["datatextfield"];
if (text == null) {
return (String.Empty);
}
return (text);
}
set {
if (value == null) {
Attributes.Remove ("datatextfield");
} else {
Attributes["datatextfield"] = value;
}
}
}
[DefaultValue ("")]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual string DataValueField {
get {
string value = Attributes["datavaluefield"];
if (value == null) {
return (String.Empty);
}
return (value);
}
set {
if (value == null) {
Attributes.Remove ("datavaluefield");
} else {
Attributes["datavaluefield"] = value;
}
}
}
public override string InnerHtml {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
public override string InnerText {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
protected bool IsBoundUsingDataSourceID {
get {
return (DataSourceID.Length != 0);
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
public ListItemCollection Items {
get {
if (items == null) {
items = new ListItemCollection ();
if (IsTrackingViewState)
((IStateManager) items).TrackViewState ();
}
return (items);
}
}
[DefaultValue ("")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Behavior")]
public bool Multiple {
get {
string multi = Attributes["multiple"];
if (multi == null) {
return (false);
}
return (true);
}
set {
if (value == false) {
Attributes.Remove ("multiple");
} else {
Attributes["multiple"] = "multiple";
}
}
}
[DefaultValue ("")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Behavior")]
public string Name {
get {
return (UniqueID);
}
set {
/* Do nothing */
}
}
protected bool RequiresDataBinding {
get { return requiresDataBinding; }
set { requiresDataBinding = value; }
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
public virtual int SelectedIndex {
get {
/* Make sure Items has been initialised */
ListItemCollection listitems = Items;
for (int i = 0; i < listitems.Count; i++) {
if (listitems[i].Selected) {
return (i);
}
}
/* There is always a selected item in
* non-multiple mode, if the size is
* <= 1
*/
if (!Multiple && Size <= 1) {
/* Select the first item */
if (listitems.Count > 0) {
/* And make it stick
* if there is
* anything in the
* list
*/
listitems[0].Selected = true;
}
return (0);
}
return (-1);
}
set {
ClearSelection ();
if (value == -1 || items == null) {
return;
}
if (value < 0 || value >= items.Count) {
throw new ArgumentOutOfRangeException ("value");
}
items[value].Selected = true;
}
}
/* "internal infrastructure" according to the docs,
* but has some documentation in 2.0
*/
protected virtual int[] SelectedIndices {
get {
ArrayList selected = new ArrayList ();
int count = Items.Count;
for (int i = 0; i < count; i++) {
if (Items [i].Selected) {
selected.Add (i);
}
}
return ((int[])selected.ToArray (typeof (int)));
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public int Size {
get {
string size = Attributes["size"];
if (size == null) {
return (-1);
}
return (Int32.Parse (size, Helpers.InvariantCulture));
}
set {
if (value == -1) {
Attributes.Remove ("size");
} else {
Attributes["size"] = value.ToString ();
}
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public string Value {
get {
int sel = SelectedIndex;
if (sel >= 0 && sel < Items.Count) {
return (Items[sel].Value);
}
return (String.Empty);
}
set {
int sel = Items.IndexOf (value);
if (sel >= 0) {
SelectedIndex = sel;
}
}
}
[WebSysDescription("")]
[WebCategory("Action")]
public event EventHandler ServerChange {
add {
Events.AddHandler (EventServerChange, value);
}
remove {
Events.RemoveHandler (EventServerChange, value);
}
}
protected override void AddParsedSubObject (object obj)
{
if (!(obj is ListItem)) {
throw new HttpException ("HtmlSelect can only contain ListItem");
}
Items.Add ((ListItem)obj);
base.AddParsedSubObject (obj);
}
/* "internal infrastructure" according to the docs,
* but has some documentation in 2.0
*/
protected virtual void ClearSelection ()
{
if (items == null) {
return;
}
int count = items.Count;
for (int i = 0; i < count; i++) {
items[i].Selected = false;
}
}
protected override ControlCollection CreateControlCollection ()
{
return (base.CreateControlCollection ());
}
protected void EnsureDataBound ()
{
if (IsBoundUsingDataSourceID && RequiresDataBinding)
DataBind ();
}
protected virtual IEnumerable GetData ()
{
if (DataSource != null && IsBoundUsingDataSourceID)
throw new HttpException ("Control bound using both DataSourceID and DataSource properties.");
if (DataSource != null)
return DataSourceResolver.ResolveDataSource (DataSource, DataMember);
if (!IsBoundUsingDataSourceID)
return null;
IEnumerable result = null;
DataSourceView boundDataSourceView = ConnectToDataSource ();
boundDataSourceView.Select (DataSourceSelectArguments.Empty, delegate (IEnumerable data) { result = data; });
return result;
}
protected override void LoadViewState (object savedState)
{
object first = null;
object second = null;
Pair pair = savedState as Pair;
if (pair != null) {
first = pair.First;
second = pair.Second;
}
base.LoadViewState (first);
if (second != null) {
IStateManager manager = Items as IStateManager;
manager.LoadViewState (second);
}
}
protected override void OnDataBinding (EventArgs e)
{
base.OnDataBinding (e);
/* Make sure Items has been initialised */
ListItemCollection listitems = Items;
listitems.Clear ();
IEnumerable list = GetData ();
if (list == null)
return;
foreach (object container in list) {
string text = null;
string value = null;
if (DataTextField == String.Empty &&
DataValueField == String.Empty) {
text = container.ToString ();
value = text;
} else {
if (DataTextField != String.Empty) {
text = DataBinder.Eval (container, DataTextField).ToString ();
}
if (DataValueField != String.Empty) {
value = DataBinder.Eval (container, DataValueField).ToString ();
} else {
value = text;
}
if (text == null &&
value != null) {
text = value;
}
}
if (text == null) {
text = String.Empty;
}
if (value == null) {
value = String.Empty;
}
ListItem item = new ListItem (text, value);
listitems.Add (item);
}
RequiresDataBinding = false;
IsDataBound = true;
}
protected virtual void OnDataPropertyChanged ()
{
if (_initialized)
RequiresDataBinding = true;
}
protected virtual void OnDataSourceViewChanged (object sender,
EventArgs e)
{
RequiresDataBinding = true;
}
protected internal override void OnInit (EventArgs e)
{
base.OnInit (e);
Page.PreLoad += new EventHandler (OnPagePreLoad);
}
protected virtual void OnPagePreLoad (object sender, EventArgs e)
{
Initialize ();
}
protected internal override void OnLoad (EventArgs e)
{
if (!_initialized)
Initialize ();
base.OnLoad (e);
}
void Initialize ()
{
_initialized = true;
if (!IsDataBound)
RequiresDataBinding = true;
if (IsBoundUsingDataSourceID)
ConnectToDataSource ();
}
bool IsDataBound{
get {
return ViewState.GetBool ("_DataBound", false);
}
set {
ViewState ["_DataBound"] = value;
}
}
DataSourceView ConnectToDataSource ()
{
if (_boundDataSourceView != null)
return _boundDataSourceView;
/* verify that the data source exists and is an IDataSource */
object ctrl = null;
Page page = Page;
if (page != null)
ctrl = page.FindControl (DataSourceID);
if (ctrl == null || !(ctrl is IDataSource)) {
string format;
if (ctrl == null)
format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. A control with ID '{1}' could not be found.";
else
format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. '{1}' is not an IDataSource.";
throw new HttpException (String.Format (format, ID, DataSourceID));
}
_boundDataSourceView = ((IDataSource)ctrl).GetView (String.Empty);
_boundDataSourceView.DataSourceViewChanged += OnDataSourceViewChanged;
return _boundDataSourceView;
}
protected internal override void OnPreRender (EventArgs e)
{
EnsureDataBound ();
base.OnPreRender (e);
Page page = Page;
if (page != null && !Disabled) {
page.RegisterRequiresPostBack (this);
page.RegisterEnabledControl (this);
}
}
protected virtual void OnServerChange (EventArgs e)
{
EventHandler handler = (EventHandler)Events[EventServerChange];
if (handler != null) {
handler (this, e);
}
}
protected override void RenderAttributes (HtmlTextWriter w)
{
Page page = Page;
if (page != null)
page.ClientScript.RegisterForEventValidation (UniqueID);
/* If there is no "name" attribute,
* LoadPostData doesn't work...
*/
w.WriteAttribute ("name", Name);
Attributes.Remove ("name");
/* Don't render the databinding attributes */
Attributes.Remove ("datamember");
Attributes.Remove ("datatextfield");
Attributes.Remove ("datavaluefield");
base.RenderAttributes (w);
}
protected internal override void RenderChildren (HtmlTextWriter w)
{
base.RenderChildren (w);
if (items == null)
return;
w.WriteLine ();
bool done_sel = false;
int count = items.Count;
for (int i = 0; i < count; i++) {
ListItem item = items[i];
w.Indent++;
/* Write the <option> elements this
* way so that the output HTML matches
* the ms version (can't make
* HtmlTextWriterTag.Option an inline
* element, cos that breaks other
* stuff.)
*/
w.WriteBeginTag ("option");
if (item.Selected && !done_sel) {
w.WriteAttribute ("selected", "selected");
if (!Multiple) {
done_sel = true;
}
}
w.WriteAttribute ("value", item.Value, true);
if (item.HasAttributes) {
AttributeCollection attrs = item.Attributes;
foreach (string key in attrs.Keys)
w.WriteAttribute (key, HttpUtility.HtmlAttributeEncode (attrs [key]));
}
w.Write (HtmlTextWriter.TagRightChar);
w.Write (HttpUtility.HtmlEncode(item.Text));
w.WriteEndTag ("option");
w.WriteLine ();
w.Indent--;
}
}
protected override object SaveViewState ()
{
object first = null;
object second = null;
first = base.SaveViewState ();
IStateManager manager = items as IStateManager;
if (manager != null) {
second = manager.SaveViewState ();
}
if (first == null && second == null)
return (null);
return new Pair (first, second);
}
/* "internal infrastructure" according to the docs,
* but has some documentation in 2.0
*/
protected virtual void Select (int[] selectedIndices)
{
if (items == null) {
return;
}
ClearSelection ();
int count = items.Count;
foreach (int i in selectedIndices) {
if (i >= 0 && i < count) {
items[i].Selected = true;
}
}
}
protected override void TrackViewState ()
{
base.TrackViewState ();
IStateManager manager = items as IStateManager;
if (manager != null) {
manager.TrackViewState ();
}
}
protected virtual void RaisePostDataChangedEvent ()
{
OnServerChange (EventArgs.Empty);
}
protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
{
/* postCollection contains the values that are
* selected
*/
string[] values = postCollection.GetValues (postDataKey);
bool changed = false;
if (values != null) {
if (Multiple) {
/* We have a set of
* selections. We can't just
* set the new list, because
* we need to know if the set
* has changed from last time
*/
int value_len = values.Length;
int[] old_sel = SelectedIndices;
int[] new_sel = new int[value_len];
int old_sel_len = old_sel.Length;
for (int i = 0; i < value_len; i++) {
new_sel[i] = Items.IndexOf (values[i]);
if (old_sel_len != value_len ||
old_sel[i] != new_sel[i]) {
changed = true;
}
}
if (changed) {
Select (new_sel);
}
} else {
/* Just take the first one */
int sel = Items.IndexOf (values[0]);
if (sel != SelectedIndex) {
SelectedIndex = sel;
changed = true;
}
}
}
if (changed)
ValidateEvent (postDataKey, String.Empty);
return (changed);
}
bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
{
return LoadPostData (postDataKey, postCollection);
}
void IPostBackDataHandler.RaisePostDataChangedEvent ()
{
RaisePostDataChangedEvent ();
}
}
}
|
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IBApi
{
public class EClientErrors
{
public static readonly CodeMsgPair AlreadyConnected = new CodeMsgPair(501, "Already Connected.");
public static readonly CodeMsgPair CONNECT_FAIL = new CodeMsgPair(502, "Couldn't connect to TWS. Confirm that \"Enable ActiveX and Socket Clients\" is enabled on the TWS \"Configure->API\" menu.");
public static readonly CodeMsgPair UPDATE_TWS = new CodeMsgPair(503, "The TWS is out of date and must be upgraded.");
public static readonly CodeMsgPair NOT_CONNECTED = new CodeMsgPair(504, "Not connected");
public static readonly CodeMsgPair UNKNOWN_ID = new CodeMsgPair(505, "Fatal Error: Unknown message id.");
public static readonly CodeMsgPair FAIL_SEND_REQMKT = new CodeMsgPair(510, "Request Market Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANMKT = new CodeMsgPair(511, "Cancel Market Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_ORDER = new CodeMsgPair(512, "Order Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_ACCT = new CodeMsgPair(513, "Account Update Request Sending Error -");
public static readonly CodeMsgPair FAIL_SEND_EXEC = new CodeMsgPair(514, "Request For Executions Sending Error -");
public static readonly CodeMsgPair FAIL_SEND_CORDER = new CodeMsgPair(515, "Cancel Order Sending Error -");
public static readonly CodeMsgPair FAIL_SEND_OORDER = new CodeMsgPair(516, "Request Open Order Sending Error -");
public static readonly CodeMsgPair UNKNOWN_CONTRACT = new CodeMsgPair(517, "Unknown contract. Verify the contract details supplied.");
public static readonly CodeMsgPair FAIL_SEND_REQCONTRACT = new CodeMsgPair(518, "Request Contract Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQMKTDEPTH = new CodeMsgPair(519, "Request Market Depth Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANMKTDEPTH = new CodeMsgPair(520, "Cancel Market Depth Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_SERVER_LOG_LEVEL = new CodeMsgPair(521, "Set Server Log Level Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_FA_REQUEST = new CodeMsgPair(522, "FA Information Request Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_FA_REPLACE = new CodeMsgPair(523, "FA Information Replace Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQSCANNER = new CodeMsgPair(524, "Request Scanner Subscription Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANSCANNER = new CodeMsgPair(525, "Cancel Scanner Subscription Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQSCANNERPARAMETERS = new CodeMsgPair(526, "Request Scanner Parameter Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQHISTDATA = new CodeMsgPair(527, "Request Historical Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANHISTDATA = new CodeMsgPair(528, "Request Historical Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQRTBARS = new CodeMsgPair(529, "Request Real-time Bar Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANRTBARS = new CodeMsgPair(530, "Cancel Real-time Bar Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQCURRTIME = new CodeMsgPair(531, "Request Current Time Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQFUNDDATA = new CodeMsgPair(532, "Request Fundamental Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANFUNDDATA = new CodeMsgPair(533, "Cancel Fundamental Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQCALCIMPLIEDVOLAT = new CodeMsgPair(534, "Request Calculate Implied Volatility Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQCALCOPTIONPRICE = new CodeMsgPair(535, "Request Calculate Option Price Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANCALCIMPLIEDVOLAT = new CodeMsgPair(536, "Cancel Calculate Implied Volatility Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANCALCOPTIONPRICE = new CodeMsgPair(537, "Cancel Calculate Option Price Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQGLOBALCANCEL = new CodeMsgPair(538, "Request Global Cancel Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQMARKETDATATYPE = new CodeMsgPair(539, "Request Market Data Type Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQPOSITIONS = new CodeMsgPair(540, "Request Positions Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANPOSITIONS = new CodeMsgPair(541, "Cancel Positions Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_REQACCOUNTDATA = new CodeMsgPair(542, "Request Account Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_CANACCOUNTDATA = new CodeMsgPair(543, "Cancel Account Data Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_VERIFYREQUEST = new CodeMsgPair(544, "Verify Request Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_VERIFYMESSAGE = new CodeMsgPair(545, "Verify Message Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_QUERYDISPLAYGROUPS = new CodeMsgPair(546, "Query Display Groups Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_SUBSCRIBETOGROUPEVENTS = new CodeMsgPair(547, "Subscribe To Group Events Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_UPDATEDISPLAYGROUP = new CodeMsgPair(548, "Update Display Group Sending Error - ");
public static readonly CodeMsgPair FAIL_SEND_UNSUBSCRIBEFROMGROUPEVENTS = new CodeMsgPair(549, "Unsubscribe From Group Events Sending Error - ");
public static readonly CodeMsgPair FAIL_GENERIC = new CodeMsgPair(-1, "Specific error message needs to be given for these requests! ");
}
public class CodeMsgPair
{
private int code;
private string message;
public CodeMsgPair(int code, string message)
{
this.code = code;
this.message = message;
}
public int Code
{
get { return code; }
}
public string Message
{
get { return message; }
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace GSoft.Dynamite.Collections
{
/// <summary>
/// A list that supports synchronized reading and writing.
/// </summary>
/// <typeparam name="T">The type of object contained in the list.</typeparam>
[Serializable]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is actually a list.")]
public class ConcurrentList<T> : IList<T>, IList
{
#region Fields
private readonly List<T> _underlyingList = new List<T>();
[NonSerialized]
private volatile ReaderWriterLockSlim _lock;
#endregion
#region Properties
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get
{
this.Lock.EnterReadLock();
try
{
return this._underlyingList.Count;
}
finally
{
this.Lock.ExitReadLock();
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly
{
get
{
this.Lock.EnterReadLock();
try
{
return ((IList)this._underlyingList).IsReadOnly;
}
finally
{
this.Lock.ExitReadLock();
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.IList"/> has a fixed size; otherwise, false.</returns>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Not part of IList of T.")]
bool IList.IsFixedSize
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Not part of IList of T.")]
bool ICollection.IsSynchronized
{
get { return true; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Not part of IList of T.")]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// Gets the lock used for synchronization.
/// </summary>
private ReaderWriterLockSlim Lock
{
get
{
if (this._lock == null)
{
lock (this)
{
if (this._lock == null)
{
this._lock = new ReaderWriterLockSlim();
}
}
}
return this._lock;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index to add the item at.</param>
/// <returns>
/// The element at the specified index.
/// </returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">
/// The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
/// </exception>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (T)value;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index to add the item at.</param>
/// <returns>
/// The element at the specified index.
/// </returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
public T this[int index]
{
get
{
this.Lock.EnterReadLock();
try
{
return this._underlyingList[index];
}
finally
{
this.Lock.ExitReadLock();
}
}
set
{
this.Lock.EnterWriteLock();
try
{
this._underlyingList[index] = value;
}
finally
{
this.Lock.ExitWriteLock();
}
}
}
#endregion
#region Methods
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
public int IndexOf(T item)
{
this.Lock.EnterReadLock();
try
{
return this._underlyingList.IndexOf(item);
}
finally
{
this.Lock.ExitReadLock();
}
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
/// </exception>
public void Insert(int index, T item)
{
this.Lock.EnterWriteLock();
try
{
this._underlyingList.Insert(index, item);
}
finally
{
this.Lock.ExitWriteLock();
}
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
/// </exception>
public void RemoveAt(int index)
{
this.Lock.EnterWriteLock();
try
{
this._underlyingList.RemoveAt(index);
}
finally
{
this.Lock.ExitWriteLock();
}
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public void Add(T item)
{
this.Lock.EnterWriteLock();
try
{
this._underlyingList.Add(item);
}
finally
{
this.Lock.ExitWriteLock();
}
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public void Clear()
{
this.Lock.EnterWriteLock();
try
{
this._underlyingList.Clear();
}
finally
{
this.Lock.ExitWriteLock();
}
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
public bool Contains(T item)
{
this.Lock.EnterReadLock();
try
{
return this._underlyingList.Contains(item);
}
finally
{
this.Lock.ExitReadLock();
}
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(T[] array, int arrayIndex)
{
((IList)this).CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public bool Remove(T item)
{
this.Lock.EnterWriteLock();
try
{
return this._underlyingList.Remove(item);
}
finally
{
this.Lock.ExitWriteLock();
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public virtual IEnumerator<T> GetEnumerator()
{
this.Lock.EnterReadLock();
return new ReadLockedEnumerator<T>(this.Lock, this._underlyingList.GetEnumerator());
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.IList"/>.
/// </summary>
/// <param name="value">The object to add to the <see cref="T:System.Collections.IList"/>.</param>
/// <returns>
/// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection,
/// </returns>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IList"/> is read-only.-or- The <see cref="T:System.Collections.IList"/> has a fixed size. </exception>
int IList.Add(object value)
{
this.Lock.EnterWriteLock();
try
{
return ((IList)this._underlyingList).Add(value);
}
finally
{
this.Lock.ExitWriteLock();
}
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value.
/// </summary>
/// <param name="value">The object to locate in the <see cref="T:System.Collections.IList"/>.</param>
/// <returns>
/// true if the <see cref="T:System.Object"/> is found in the <see cref="T:System.Collections.IList"/>; otherwise, false.
/// </returns>
bool IList.Contains(object value)
{
return this.Contains((T)value);
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.IList"/>.
/// </summary>
/// <param name="value">The object to locate in the <see cref="T:System.Collections.IList"/>.</param>
/// <returns>
/// The index of <paramref name="value"/> if found in the list; otherwise, -1.
/// </returns>
int IList.IndexOf(object value)
{
return this.IndexOf((T)value);
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.IList"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param>
/// <param name="value">The object to insert into the <see cref="T:System.Collections.IList"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.IList"/>. </exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IList"/> is read-only.-or- The <see cref="T:System.Collections.IList"/> has a fixed size. </exception>
/// <exception cref="T:System.NullReferenceException">
/// <paramref name="value"/> is null reference in the <see cref="T:System.Collections.IList"/>.</exception>
void IList.Insert(int index, object value)
{
this.Insert(index, (T)value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.IList"/>.
/// </summary>
/// <param name="value">The object to remove from the <see cref="T:System.Collections.IList"/>.</param>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IList"/> is read-only.-or- The <see cref="T:System.Collections.IList"/> has a fixed size. </exception>
void IList.Remove(object value)
{
this.Remove((T)value);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="array"/> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than zero. </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="array"/> is multidimensional.-or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>. </exception>
/// <exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>. </exception>
void ICollection.CopyTo(Array array, int index)
{
this.Lock.EnterReadLock();
try
{
((IList)this._underlyingList).CopyTo(array, index);
}
finally
{
this.Lock.ExitReadLock();
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Nested classes
/// <summary>
/// An enumerator that releases a read lock when Disposing.
/// </summary>
/// <typeparam name="TItem">The type of the item.</typeparam>
private class ReadLockedEnumerator<TItem> : IEnumerator<TItem>
{
private readonly ReaderWriterLockSlim _syncRoot;
private readonly IEnumerator<TItem> _underlyingEnumerator;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentList<T>.ReadLockedEnumerator<TItem>"/> class.
/// </summary>
/// <param name="syncRoot">The sync root.</param>
/// <param name="underlyingEnumerator">The underlying enumerator.</param>
public ReadLockedEnumerator(ReaderWriterLockSlim syncRoot, IEnumerator<TItem> underlyingEnumerator)
{
this._syncRoot = syncRoot;
this._underlyingEnumerator = underlyingEnumerator;
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
public TItem Current
{
get { return this._underlyingEnumerator.Current; }
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this._syncRoot.ExitReadLock();
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public bool MoveNext()
{
return this._underlyingEnumerator.MoveNext();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public void Reset()
{
this._underlyingEnumerator.Reset();
}
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Mindscape.Raygun4Net.Messages;
using System.Threading;
using System.Reflection;
using Mindscape.Raygun4Net.Builders;
namespace Mindscape.Raygun4Net
{
public class RaygunClient : RaygunClientBase
{
private readonly string _apiKey;
private readonly List<Type> _wrapperExceptions = new List<Type>();
/// <summary>
/// Initializes a new instance of the <see cref="RaygunClient" /> class.
/// </summary>
/// <param name="apiKey">The API key.</param>
public RaygunClient(string apiKey)
{
_apiKey = apiKey;
_wrapperExceptions.Add(typeof(TargetInvocationException));
}
/// <summary>
/// Initializes a new instance of the <see cref="RaygunClient" /> class.
/// Uses the ApiKey specified in the config file.
/// </summary>
public RaygunClient()
: this(RaygunSettings.Settings.ApiKey)
{
}
protected bool ValidateApiKey()
{
if (string.IsNullOrEmpty(_apiKey))
{
System.Diagnostics.Debug.WriteLine("ApiKey has not been provided, exception will not be logged");
return false;
}
return true;
}
/// <summary>
/// Gets or sets the username/password credentials which are used to authenticate with the system default Proxy server, if one is set
/// and requires credentials.
/// </summary>
public ICredentials ProxyCredentials { get; set; }
/// <summary>
/// Gets or sets an IWebProxy instance which can be used to override the default system proxy server settings
/// </summary>
public IWebProxy WebProxy { get; set; }
/// <summary>
/// Adds a list of outer exceptions that will be stripped, leaving only the valuable inner exception.
/// This can be used when a wrapper exception, e.g. TargetInvocationException or HttpUnhandledException,
/// contains the actual exception as the InnerException. The message and stack trace of the inner exception will then
/// be used by Raygun for grouping and display. The above two do not need to be added manually,
/// but if you have other wrapper exceptions that you want stripped you can pass them in here.
/// </summary>
/// <param name="wrapperExceptions">Exception types that you want removed and replaced with their inner exception.</param>
public void AddWrapperExceptions(params Type[] wrapperExceptions)
{
foreach (Type wrapper in wrapperExceptions)
{
if (!_wrapperExceptions.Contains(wrapper))
{
_wrapperExceptions.Add(wrapper);
}
}
}
/// <summary>
/// Specifies types of wrapper exceptions that Raygun should send rather than stripping out and sending the inner exception.
/// This can be used to remove the default wrapper exceptions (TargetInvocationException and HttpUnhandledException).
/// </summary>
/// <param name="wrapperExceptions">Exception types that should no longer be stripped away.</param>
public void RemoveWrapperExceptions(params Type[] wrapperExceptions)
{
foreach (Type wrapper in wrapperExceptions)
{
_wrapperExceptions.Remove(wrapper);
}
}
/// <summary>
/// Transmits an exception to Raygun.io synchronously, using the version number of the originating assembly.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
public override void Send(Exception exception)
{
Send(exception, null, (IDictionary)null, null);
}
/// <summary>
/// Transmits an exception to Raygun.io synchronously specifying a list of string tags associated
/// with the message for identification. This uses the version number of the originating assembly.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
/// <param name="tags">A list of strings associated with the message.</param>
public void Send(Exception exception, IList<string> tags)
{
Send(exception, tags, (IDictionary)null, null);
}
/// <summary>
/// Transmits an exception to Raygun.io synchronously specifying a list of string tags associated
/// with the message for identification, as well as sending a key-value collection of custom data.
/// This uses the version number of the originating assembly.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
/// <param name="tags">A list of strings associated with the message.</param>
/// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param>
public void Send(Exception exception, IList<string> tags, IDictionary userCustomData)
{
Send(exception, tags, userCustomData, null);
}
/// <summary>
/// Transmits an exception to Raygun.io synchronously specifying a list of string tags associated
/// with the message for identification, as well as sending a key-value collection of custom data.
/// This uses the version number of the originating assembly.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
/// <param name="tags">A list of strings associated with the message.</param>
/// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param>
/// <param name="userInfo">Information about the user including the identity string.</param>
public void Send(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfo)
{
if (CanSend(exception))
{
StripAndSend(exception, tags, userCustomData, userInfo, null);
FlagAsSent(exception);
}
}
/// <summary>
/// Asynchronously transmits a message to Raygun.io.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
public void SendInBackground(Exception exception)
{
SendInBackground(exception, null, (IDictionary)null, null);
}
/// <summary>
/// Asynchronously transmits an exception to Raygun.io.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
/// <param name="tags">A list of strings associated with the message.</param>
public void SendInBackground(Exception exception, IList<string> tags)
{
SendInBackground(exception, tags, (IDictionary)null, null);
}
/// <summary>
/// Asynchronously transmits an exception to Raygun.io.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
/// <param name="tags">A list of strings associated with the message.</param>
/// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param>
public void SendInBackground(Exception exception, IList<string> tags, IDictionary userCustomData)
{
SendInBackground(exception, tags, userCustomData, null);
}
/// <summary>
/// Asynchronously transmits an exception to Raygun.io.
/// </summary>
/// <param name="exception">The exception to deliver.</param>
/// <param name="tags">A list of strings associated with the message.</param>
/// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param>
/// <param name="userInfo">Information about the user including the identity string.</param>
public void SendInBackground(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfo)
{
DateTime? currentTime = DateTime.UtcNow;
if (CanSend(exception))
{
ThreadPool.QueueUserWorkItem(c =>
{
try
{
StripAndSend(exception, tags, userCustomData, userInfo, currentTime);
}
catch (Exception)
{
// This will swallow any unhandled exceptions unless we explicitly want to throw on error.
// Otherwise this can bring the whole process down.
if (RaygunSettings.Settings.ThrowOnError)
{
throw;
}
}
});
FlagAsSent(exception);
}
}
/// <summary>
/// Asynchronously transmits a message to Raygun.io.
/// </summary>
/// <param name="raygunMessage">The RaygunMessage to send. This needs its OccurredOn property
/// set to a valid DateTime and as much of the Details property as is available.</param>
public void SendInBackground(RaygunMessage raygunMessage)
{
ThreadPool.QueueUserWorkItem(c => Send(raygunMessage));
}
protected RaygunMessage BuildMessage(Exception exception, IList<string> tags, IDictionary userCustomData)
{
return BuildMessage(exception, tags, userCustomData, null, null);
}
protected RaygunMessage BuildMessage(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfoMessage)
{
return BuildMessage(exception, tags, userCustomData, userInfoMessage, null);
}
protected RaygunMessage BuildMessage(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfoMessage, DateTime? currentTime)
{
var message = RaygunMessageBuilder.New
.SetEnvironmentDetails()
.SetTimeStamp(currentTime)
.SetMachineName(Environment.MachineName)
.SetExceptionDetails(exception)
.SetClientDetails()
.SetVersion(ApplicationVersion)
.SetTags(tags)
.SetUserCustomData(userCustomData)
.SetUser(userInfoMessage ?? UserInfo ?? (!String.IsNullOrEmpty(User) ? new RaygunIdentifierMessage(User) : null))
.Build();
return message;
}
private void StripAndSend(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfo, DateTime? currentTime)
{
foreach (Exception e in StripWrapperExceptions(exception))
{
Send(BuildMessage(e, tags, userCustomData, userInfo, currentTime));
}
}
protected IEnumerable<Exception> StripWrapperExceptions(Exception exception)
{
if (exception != null && _wrapperExceptions.Any(wrapperException => exception.GetType() == wrapperException && exception.InnerException != null))
{
AggregateException aggregate = exception as AggregateException;
if (aggregate != null)
{
foreach (Exception e in aggregate.InnerExceptions)
{
foreach (Exception ex in StripWrapperExceptions(e))
{
yield return ex;
}
}
}
else
{
foreach (Exception e in StripWrapperExceptions(exception.InnerException))
{
yield return e;
}
}
}
else
{
yield return exception;
}
}
/// <summary>
/// Posts a RaygunMessage to the Raygun.io api endpoint.
/// </summary>
/// <param name="raygunMessage">The RaygunMessage to send. This needs its OccurredOn property
/// set to a valid DateTime and as much of the Details property as is available.</param>
public override void Send(RaygunMessage raygunMessage)
{
if (ValidateApiKey())
{
bool canSend = OnSendingMessage(raygunMessage);
if (canSend)
{
using (var client = CreateWebClient())
{
try
{
var message = SimpleJson.SerializeObject(raygunMessage);
client.UploadString(RaygunSettings.Settings.ApiEndpoint, message);
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(string.Format("Error Logging Exception to Raygun.io {0}", ex.Message));
if (RaygunSettings.Settings.ThrowOnError)
{
throw;
}
}
}
}
}
}
protected WebClient CreateWebClient()
{
var client = new WebClient();
client.Headers.Add("X-ApiKey", _apiKey);
client.Headers.Add("content-type", "application/json; charset=utf-8");
client.Encoding = System.Text.Encoding.UTF8;
if (WebProxy != null)
{
client.Proxy = WebProxy;
}
else if (WebRequest.DefaultWebProxy != null)
{
Uri proxyUri = WebRequest.DefaultWebProxy.GetProxy(new Uri(RaygunSettings.Settings.ApiEndpoint.ToString()));
if (proxyUri != null && proxyUri.AbsoluteUri != RaygunSettings.Settings.ApiEndpoint.ToString())
{
client.Proxy = new WebProxy(proxyUri, false);
if (ProxyCredentials == null)
{
client.UseDefaultCredentials = true;
client.Proxy.Credentials = CredentialCache.DefaultCredentials;
}
else
{
client.UseDefaultCredentials = false;
client.Proxy.Credentials = ProxyCredentials;
}
}
}
return client;
}
}
}
|
/*
* 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;
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// 1-D rained system
// m (v2 - v1) = lambda
// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
// x2 = x1 + h * v2
// 1-D mass-damper-spring system
// m (v2 - v1) + h * d * v2 + h * k *
// C = norm(p2 - p1) - L
// u = (p2 - p1) / norm(p2 - p1)
// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// J = [-u -cross(r1, u) u cross(r2, u)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
/// <summary>
/// A distance joint rains two points on two bodies
/// to remain at a fixed distance from each other. You can view
/// this as a massless, rigid rod.
/// </summary>
public class DistanceJoint : Joint
{
#region Properties/Fields
/// <summary>
/// The local anchor point relative to bodyA's origin.
/// </summary>
public Vector2 localAnchorA;
/// <summary>
/// The local anchor point relative to bodyB's origin.
/// </summary>
public Vector2 localAnchorB;
public override sealed Vector2 worldAnchorA
{
get { return bodyA.getWorldPoint( localAnchorA ); }
set { Debug.Assert( false, "You can't set the world anchor on this joint type." ); }
}
public override sealed Vector2 worldAnchorB
{
get { return bodyB.getWorldPoint( localAnchorB ); }
set { Debug.Assert( false, "You can't set the world anchor on this joint type." ); }
}
/// <summary>
/// The natural length between the anchor points.
/// Manipulating the length can lead to non-physical behavior when the frequency is zero.
/// </summary>
public float length;
/// <summary>
/// The mass-spring-damper frequency in Hertz. A value of 0
/// disables softness.
/// </summary>
public float frequency;
/// <summary>
/// The damping ratio. 0 = no damping, 1 = critical damping.
/// </summary>
public float dampingRatio;
// Solver shared
float _bias;
float _gamma;
float _impulse;
// Solver temp
int _indexA;
int _indexB;
Vector2 _u;
Vector2 _rA;
Vector2 _rB;
Vector2 _localCenterA;
Vector2 _localCenterB;
float _invMassA;
float _invMassB;
float _invIA;
float _invIB;
float _mass;
#endregion
internal DistanceJoint()
{
jointType = JointType.Distance;
}
/// <summary>
/// This requires defining an
/// anchor point on both bodies and the non-zero length of the
/// distance joint. If you don't supply a length, the local anchor points
/// is used so that the initial configuration can violate the constraint
/// slightly. This helps when saving and loading a game.
/// Warning Do not use a zero or short length.
/// </summary>
/// <param name="bodyA">The first body</param>
/// <param name="bodyB">The second body</param>
/// <param name="anchorA">The first body anchor</param>
/// <param name="anchorB">The second body anchor</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public DistanceJoint( Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, bool useWorldCoordinates = false ) : base( bodyA, bodyB )
{
jointType = JointType.Distance;
if( useWorldCoordinates )
{
localAnchorA = bodyA.getLocalPoint( ref anchorA );
localAnchorB = bodyB.getLocalPoint( ref anchorB );
length = ( anchorB - anchorA ).Length();
}
else
{
localAnchorA = anchorA;
localAnchorB = anchorB;
length = ( base.bodyB.getWorldPoint( ref anchorB ) - base.bodyA.getWorldPoint( ref anchorA ) ).Length();
}
}
/// <summary>
/// Get the reaction force given the inverse time step. Unit is N.
/// </summary>
/// <param name="invDt"></param>
/// <returns></returns>
public override Vector2 getReactionForce( float invDt )
{
Vector2 F = ( invDt * _impulse ) * _u;
return F;
}
/// <summary>
/// Get the reaction torque given the inverse time step.
/// Unit is N*m. This is always zero for a distance joint.
/// </summary>
/// <param name="invDt"></param>
/// <returns></returns>
public override float getReactionTorque( float invDt )
{
return 0.0f;
}
internal override void initVelocityConstraints( ref SolverData data )
{
_indexA = bodyA.islandIndex;
_indexB = bodyB.islandIndex;
_localCenterA = bodyA._sweep.localCenter;
_localCenterB = bodyB._sweep.localCenter;
_invMassA = bodyA._invMass;
_invMassB = bodyB._invMass;
_invIA = bodyA._invI;
_invIB = bodyB._invI;
Vector2 cA = data.positions[_indexA].c;
float aA = data.positions[_indexA].a;
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
Vector2 cB = data.positions[_indexB].c;
float aB = data.positions[_indexB].a;
Vector2 vB = data.velocities[_indexB].v;
float wB = data.velocities[_indexB].w;
Rot qA = new Rot( aA ), qB = new Rot( aB );
_rA = MathUtils.mul( qA, localAnchorA - _localCenterA );
_rB = MathUtils.mul( qB, localAnchorB - _localCenterB );
_u = cB + _rB - cA - _rA;
// Handle singularity.
float length = _u.Length();
if( length > Settings.linearSlop )
{
_u *= 1.0f / length;
}
else
{
_u = Vector2.Zero;
}
float crAu = MathUtils.cross( _rA, _u );
float crBu = MathUtils.cross( _rB, _u );
float invMass = _invMassA + _invIA * crAu * crAu + _invMassB + _invIB * crBu * crBu;
// Compute the effective mass matrix.
_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
if( frequency > 0.0f )
{
float C = length - this.length;
// Frequency
float omega = 2.0f * Settings.pi * frequency;
// Damping coefficient
float d = 2.0f * _mass * dampingRatio * omega;
// Spring stiffness
float k = _mass * omega * omega;
// magic formulas
float h = data.step.dt;
_gamma = h * ( d + h * k );
_gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f;
_bias = C * h * k * _gamma;
invMass += _gamma;
_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
}
else
{
_gamma = 0.0f;
_bias = 0.0f;
}
if( Settings.enableWarmstarting )
{
// Scale the impulse to support a variable time step.
_impulse *= data.step.dtRatio;
Vector2 P = _impulse * _u;
vA -= _invMassA * P;
wA -= _invIA * MathUtils.cross( _rA, P );
vB += _invMassB * P;
wB += _invIB * MathUtils.cross( _rB, P );
}
else
{
_impulse = 0.0f;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override void solveVelocityConstraints( ref SolverData data )
{
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
Vector2 vB = data.velocities[_indexB].v;
float wB = data.velocities[_indexB].w;
// Cdot = dot(u, v + cross(w, r))
Vector2 vpA = vA + MathUtils.cross( wA, _rA );
Vector2 vpB = vB + MathUtils.cross( wB, _rB );
float Cdot = Vector2.Dot( _u, vpB - vpA );
float impulse = -_mass * ( Cdot + _bias + _gamma * _impulse );
_impulse += impulse;
Vector2 P = impulse * _u;
vA -= _invMassA * P;
wA -= _invIA * MathUtils.cross( _rA, P );
vB += _invMassB * P;
wB += _invIB * MathUtils.cross( _rB, P );
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override bool solvePositionConstraints( ref SolverData data )
{
if( frequency > 0.0f )
{
// There is no position correction for soft distance constraints.
return true;
}
var cA = data.positions[_indexA].c;
var aA = data.positions[_indexA].a;
var cB = data.positions[_indexB].c;
var aB = data.positions[_indexB].a;
Rot qA = new Rot( aA ), qB = new Rot( aB );
var rA = MathUtils.mul( qA, localAnchorA - _localCenterA );
var rB = MathUtils.mul( qB, localAnchorB - _localCenterB );
var u = cB + rB - cA - rA;
var length = u.Length();
Nez.Vector2Ext.normalize( ref u );
var C = length - this.length;
C = MathUtils.clamp( C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection );
var impulse = -_mass * C;
var P = impulse * u;
cA -= _invMassA * P;
aA -= _invIA * MathUtils.cross( rA, P );
cB += _invMassB * P;
aB += _invIB * MathUtils.cross( rB, P );
data.positions[_indexA].c = cA;
data.positions[_indexA].a = aA;
data.positions[_indexB].c = cB;
data.positions[_indexB].a = aB;
return Math.Abs( C ) < Settings.linearSlop;
}
}
} |
using System;
using Ionic.Zlib;
using UnityEngine;
namespace VoiceChat
{
public static class VoiceChatUtils
{
static void ToShortArray(this float[] input, short[] output)
{
if (output.Length < input.Length)
{
throw new System.ArgumentException("in: " + input.Length + ", out: " + output.Length);
}
for (int i = 0; i < input.Length; ++i)
{
output[i] = (short)Mathf.Clamp((int)(input[i] * 32767.0f), short.MinValue, short.MaxValue);
}
}
static void ToFloatArray(this short[] input, float[] output, int length)
{
if (output.Length < length || input.Length < length)
{
throw new System.ArgumentException();
}
for (int i = 0; i < length; ++i)
{
output[i] = input[i] / (float)short.MaxValue;
}
}
static byte[] ZlibCompress(byte[] input, int length)
{
using (var ms = new System.IO.MemoryStream())
{
using (var compressor = new Ionic.Zlib.ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression))
{
compressor.Write(input, 0, length);
}
return ms.ToArray();
}
}
static byte[] ZlibDecompress(byte[] input, int length)
{
using (var ms = new System.IO.MemoryStream())
{
using (var compressor = new Ionic.Zlib.ZlibStream(ms, CompressionMode.Decompress, CompressionLevel.BestCompression))
{
compressor.Write(input, 0, length);
}
return ms.ToArray();
}
}
static byte[] ALawCompress(float[] input)
{
byte[] output = VoiceChatBytePool.Instance.Get();
for (int i = 0; i < input.Length; ++i)
{
int scaled = (int)(input[i] * 32767.0f);
short clamped = (short)Mathf.Clamp(scaled, short.MinValue, short.MaxValue);
output[i] = NAudio.Codecs.ALawEncoder.LinearToALawSample(clamped);
}
return output;
}
static float[] ALawDecompress(byte[] input, int length)
{
float[] output = VoiceChatFloatPool.Instance.Get();
for (int i = 0; i < length; ++i)
{
short alaw = NAudio.Codecs.ALawDecoder.ALawToLinearSample(input[i]);
output[i] = alaw / (float)short.MaxValue;
}
return output;
}
static NSpeex.SpeexEncoder speexEnc = new NSpeex.SpeexEncoder(NSpeex.BandMode.Narrow);
static byte[] SpeexCompress(float[] input, out int length)
{
short[] shortBuffer = VoiceChatShortPool.Instance.Get();
byte[] encoded = VoiceChatBytePool.Instance.Get();
input.ToShortArray(shortBuffer);
length = speexEnc.Encode(shortBuffer, 0, input.Length, encoded, 0, encoded.Length);
VoiceChatShortPool.Instance.Return(shortBuffer);
return encoded;
}
static float[] SpeexDecompress(NSpeex.SpeexDecoder speexDec, byte[] data, int dataLength)
{
float[] decoded = VoiceChatFloatPool.Instance.Get();
short[] shortBuffer = VoiceChatShortPool.Instance.Get();
speexDec.Decode(data, 0, dataLength, shortBuffer, 0, false);
shortBuffer.ToFloatArray(decoded, shortBuffer.Length);
VoiceChatShortPool.Instance.Return(shortBuffer);
return decoded;
}
public static VoiceChatPacket Compress(float[] sample)
{
VoiceChatPacket packet = new VoiceChatPacket();
packet.Compression = VoiceChatSettings.Instance.Compression;
switch (packet.Compression)
{
/*
case VoiceChatCompression.Raw:
{
short[] buffer = VoiceChatShortPool.Instance.Get();
packet.Length = sample.Length * 2;
sample.ToShortArray(shortBuffer);
Buffer.BlockCopy(shortBuffer, 0, byteBuffer, 0, packet.Length);
}
break;
case VoiceChatCompression.RawZlib:
{
packet.Length = sample.Length * 2;
sample.ToShortArray(shortBuffer);
Buffer.BlockCopy(shortBuffer, 0, byteBuffer, 0, packet.Length);
packet.Data = ZlibCompress(byteBuffer, packet.Length);
packet.Length = packet.Data.Length;
}
break;
*/
case VoiceChatCompression.Alaw:
{
packet.Length = sample.Length;
packet.Data = ALawCompress(sample);
}
break;
case VoiceChatCompression.AlawZlib:
{
byte[] alaw = ALawCompress(sample);
packet.Data = ZlibCompress(alaw, sample.Length);
packet.Length = packet.Data.Length;
VoiceChatBytePool.Instance.Return(alaw);
}
break;
case VoiceChatCompression.Speex:
{
packet.Data = SpeexCompress(sample, out packet.Length);
}
break;
}
return packet;
}
public static int Decompress(VoiceChatPacket packet, out float[] data)
{
return Decompress(null, packet, out data);
}
public static int Decompress(NSpeex.SpeexDecoder speexDecoder, VoiceChatPacket packet, out float[] data)
{
switch (packet.Compression)
{
/*
case VoiceChatCompression.Raw:
{
short[9 buffer
Buffer.BlockCopy(packet.Data, 0, shortBuffer, 0, packet.Length);
shortBuffer.ToFloatArray(data, packet.Length / 2);
return packet.Length / 2;
}
case VoiceChatCompression.RawZlib:
{
byte[] unzipedData = ZlibDecompress(packet.Data, packet.Length);
Buffer.BlockCopy(unzipedData, 0, shortBuffer, 0, unzipedData.Length);
shortBuffer.ToFloatArray(data, unzipedData.Length / 2);
return unzipedData.Length / 2;
}
*/
case VoiceChatCompression.Speex:
{
data = SpeexDecompress(speexDecoder, packet.Data, packet.Length);
return data.Length;
}
case VoiceChatCompression.Alaw:
{
data = ALawDecompress(packet.Data, packet.Length);
return packet.Length;
}
case VoiceChatCompression.AlawZlib:
{
byte[] alaw = ZlibDecompress(packet.Data, packet.Length);
data = ALawDecompress(alaw, alaw.Length);
return alaw.Length;
}
}
data = new float[0];
return 0;
}
public static int ClosestPowerOfTwo(int value)
{
int i = 1;
while (i < value)
{
i <<= 1;
}
return i;
}
}
} |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace TheBigCatProject.Server.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "TheBigCatProject.Server.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} |
/// <summary>
/// This class handles user ID, session ID, time stamp, and sends a user message, optionally including system specs, when the game starts
/// </summary>
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System;
using System.Net;
#if !UNITY_WEBPLAYER && !UNITY_NACL && !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO && !UNITY_PS3
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
#endif
public class GA_GenericInfo
{
#region public values
/// <summary>
/// The ID of the user/player. A unique ID will be determined the first time the player plays. If an ID has already been created for a player this ID will be used.
/// </summary>
public string UserID
{
get {
if ((_userID == null || _userID == string.Empty) && !GA.SettingsGA.CustomUserID)
{
_userID = GetUserUUID();
}
return _userID;
}
}
/// <summary>
/// The ID of the current session. A unique ID will be determined when the game starts. This ID will be used for the remainder of the play session.
/// </summary>
public string SessionID
{
get {
if (_sessionID == null)
{
_sessionID = GetSessionUUID();
}
return _sessionID;
}
}
/// <summary>
/// The current UTC date/time in seconds
/// </summary>
/*public string TimeStamp
{
get {
return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
}
}*/
#endregion
#region private values
private string _userID = string.Empty;
private string _sessionID;
private bool _settingUserID;
#endregion
#region public methods
/// <summary>
/// Gets generic system information at the beginning of a play session
/// </summary>
/// <param name="inclSpecs">
/// Determines if all the system specs should be included <see cref="System.Bool"/>
/// </param>
/// <returns>
/// The message to submit to the GA server is a dictionary of all the relevant parameters (containing user ID, session ID, system information, language information, date/time, build version) <see cref="Dictionary<System.String, System.Object>"/>
/// </returns>
public List<Hashtable> GetGenericInfo(string message)
{
List<Hashtable> systemspecs = new List<Hashtable>();
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "unity_sdk " + GA_Settings.VERSION, message));
/*
* Apple does not allow tracking of device specific data:
* "You may not use analytics software in your application to collect and send device data to a third party"
* - iOS Developer Program License Agreement: http://www.scribd.com/doc/41213383/iOS-Developer-Program-License-Agreement
*/
#if !UNITY_IPHONE
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:"+SystemInfo.operatingSystem, message));
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "processor_type:"+SystemInfo.processorType, message));
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_name:"+SystemInfo.graphicsDeviceName, message));
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_version:"+SystemInfo.graphicsDeviceVersion, message));
// Unity provides lots of additional system info which might be worth tracking for some games:
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "process_count:"+SystemInfo.processorCount.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sys_mem_size:"+SystemInfo.systemMemorySize.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_mem_size:"+SystemInfo.graphicsMemorySize.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor:"+SystemInfo.graphicsDeviceVendor, message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_id:"+SystemInfo.graphicsDeviceID.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor_id:"+SystemInfo.graphicsDeviceVendorID.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_shader_level:"+SystemInfo.graphicsShaderLevel.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_pixel_fillrate:"+SystemInfo.graphicsPixelFillrate.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_shadows:"+SystemInfo.supportsShadows.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_render_textures:"+SystemInfo.supportsRenderTextures.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_image_effects:"+SystemInfo.supportsImageEffects.ToString(), message));
#else
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:iOS", message));
#endif
return systemspecs;
}
/// <summary>
/// Gets a universally unique ID to represent the user. User ID should be device specific to allow tracking across different games on the same device:
/// -- Android uses deviceUniqueIdentifier.
/// -- iOS/PC/Mac uses the first MAC addresses available.
/// -- Webplayer uses deviceUniqueIdentifier.
/// Note: The unique user ID is based on the ODIN specifications. See http://code.google.com/p/odinmobile/ for more information on ODIN.
/// </summary>
/// <returns>
/// The generated UUID <see cref="System.String"/>
/// </returns>
public static string GetUserUUID()
{
#if UNITY_IPHONE && !UNITY_EDITOR
string uid = GA.SettingsGA.GetUniqueIDiOS();
if (uid == null)
{
return "";
}
else if (uid != "OLD")
{
if (uid.StartsWith("VENDOR-"))
return uid.Remove(0, 7);
else
return uid;
}
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
string uid = GA.SettingsGA.GetAdvertisingIDAndroid();
if (!string.IsNullOrEmpty(uid))
{
return uid;
}
#endif
#if UNITY_WEBPLAYER || UNITY_NACL || UNITY_WP8 || UNITY_METRO || UNITY_PS3
return SystemInfo.deviceUniqueIdentifier;
#elif !UNITY_FLASH
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
string mac = "";
foreach (NetworkInterface adapter in nics)
{
PhysicalAddress address = adapter.GetPhysicalAddress();
if (address.ToString() != "" && mac == "")
{
mac = GA_Submit.CreateSha1Hash(address.ToString());
}
}
return mac;
}
catch
{
return SystemInfo.deviceUniqueIdentifier;
}
#else
return GetSessionUUID();
#endif
}
/// <summary>
/// Gets a universally unique ID to represent the session.
/// </summary>
/// <returns>
/// The generated UUID <see cref="System.String"/>
/// </returns>
public static string GetSessionUUID()
{
#if !UNITY_FLASH
return Guid.NewGuid().ToString();
#else
string returnValue = "";
for (int i = 0; i < 12; i++)
{
returnValue += UnityEngine.Random.Range(0, 10).ToString();
}
return returnValue;
#endif
}
/// <summary>
/// Sets the session ID. If newSessionID is null then a random UUID will be generated, otherwise newSessionID will be used as the session ID.
/// </summary>
/// <param name="newSessionID">New session I.</param>
public void SetSessionUUID(string newSessionID)
{
if (newSessionID == null)
{
_sessionID = GetSessionUUID();
}
else
{
_sessionID = newSessionID;
}
}
/// <summary>
/// Do not call this method (instead use GA_static_api.Settings.SetCustomUserID)! Only the GA class should call this method.
/// </summary>
/// <param name="customID">
/// The custom user ID - this should be unique for each user
/// </param>
public void SetCustomUserID(string customID)
{
_userID = customID;
}
#endregion
#region private methods
/// <summary>
/// Adds detailed system specifications regarding the users/players device to the parameters.
/// </summary>
/// <param name="parameters">
/// The parameters which will be sent to the server <see cref="Dictionary<System.String, System.Object>"/>
/// </param>
private Hashtable AddSystemSpecs(GA_Error.SeverityType severity, string type, string message)
{
string addmessage = "";
if (message != "")
addmessage = ": " + message;
Hashtable parameters = new Hashtable()
{
{ GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Severity], severity.ToString() },
{ GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Message], type + addmessage },
{ GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Level], GA.SettingsGA.CustomArea.Equals(string.Empty)?Application.loadedLevelName:GA.SettingsGA.CustomArea }
};
return parameters;
}
/// <summary>
/// Gets the users system type
/// </summary>
/// <returns>
/// String determining the system the user is currently running <see cref="System.String"/>
/// </returns>
public static string GetSystem()
{
#if UNITY_STANDALONE_OSX
return "MAC";
#elif UNITY_STANDALONE_WIN
return "PC";
#elif UNITY_WEBPLAYER
return "WEBPLAYER";
#elif UNITY_WII
return "WII";
#elif UNITY_IPHONE
return "IPHONE";
#elif UNITY_ANDROID
return "ANDROID";
#elif UNITY_PS3
return "PS3";
#elif UNITY_XBOX360
return "XBOX";
#elif UNITY_FLASH
return "FLASH";
#elif UNITY_STANDALONE_LINUX
return "LINUX";
#elif UNITY_NACL
return "NACL";
#elif UNITY_DASHBOARD_WIDGET
return "DASHBOARD_WIDGET";
#elif UNITY_METRO
return "WINDOWS_STORE_APP";
#elif UNITY_WP8
return "WINDOWS_PHONE_8";
#elif UNITY_BLACKBERRY
return "BLACKBERRY";
#else
return "UNKNOWN";
#endif
}
#endregion
} |
using OfficeDevPnP.MSGraphAPIDemo.Components;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using OfficeDevPnP.MSGraphAPIDemo.Models;
using System.Threading;
namespace OfficeDevPnP.MSGraphAPIDemo.Controllers
{
public class FilesController : Controller
{
// GET: Files
public ActionResult Index()
{
return View();
}
public ActionResult PlayWithFiles()
{
var drive = FilesHelper.GetUserPersonalDrive();
var root = FilesHelper.GetUserPersonalDriveRoot();
var childrenItems = FilesHelper.ListFolderChildren(drive.Id, root.Id);
var newFileOnRoot = UploadSampleFile(drive, root, Server.MapPath("~/AppIcon.png"));
// Collect information about children items in the root folder
StringBuilder sb = new StringBuilder();
String oneFolderId = null;
foreach (var item in childrenItems)
{
if (item.Folder != null)
{
sb.AppendFormat("Found folder {0} with {1} child items.\n", item.Name, item.Folder.ChildCount);
if (item.Name == "One Folder")
{
oneFolderId = item.Id;
}
}
else
{
sb.AppendFormat("Found file {0}.\n", item.Name);
}
}
var filesLog = sb.ToString();
// Create a new folder in the root folder
var newFolder = FilesHelper.CreateFolder(drive.Id, root.Id,
new Models.DriveItem
{
Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}",
Folder = new Models.Folder { },
});
var newFile = UploadSampleFile(drive, newFolder, Server.MapPath("~/AppIcon.png"));
UpdateSampleFile(drive, newFile, Server.MapPath("~/SP2016-MinRoles.jpg"));
// Create another folder in the root folder
var anotherFolder = FilesHelper.CreateFolder(drive.Id, root.Id,
new Models.DriveItem
{
Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}",
Folder = new Models.Folder { },
});
var movedItem = FilesHelper.MoveDriveItem(drive.Id, newFile.Id, "moved.jpg", anotherFolder.Name);
var movedFolder = FilesHelper.MoveDriveItem(drive.Id, anotherFolder.Id, "Moved Folder", newFolder.Name);
var searchResult = FilesHelper.Search("PnPLogo", drive.Id, root.Id);
if (searchResult != null && searchResult.Count > 0)
{
var firstFileResult = searchResult.FirstOrDefault(i => i.File != null);
try
{
var thumbnails = FilesHelper.GetFileThumbnails(drive.Id, firstFileResult.Id);
var thumbnailMedium = FilesHelper.GetFileThumbnail(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium);
var thumbnailImage = FilesHelper.GetFileThumbnailImage(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium);
}
catch (Exception)
{
// Something wrong while getting the thumbnail,
// We will have to handle it properly ...
}
}
if (newFileOnRoot != null)
{
var permission = FilesHelper.GetDriveItemPermission(newFileOnRoot.Id, "0");
FilesHelper.DeleteFile(drive.Id, newFileOnRoot.Id);
}
try
{
var sharingPermission = FilesHelper.CreateSharingLink(newFolder.Id,
SharingLinkType.View, SharingLinkScope.Anonymous);
}
catch (Exception)
{
// Something wrong while getting the sharing link,
// We will have to handle it properly ...
}
if (!String.IsNullOrEmpty(oneFolderId))
{
var newFolderChildren = FilesHelper.ListFolderChildren(drive.Id, newFolder.Id);
var file = newFolderChildren.FirstOrDefault(f => f.Name == "moved.jpg");
if (file != null)
{
String jpegContentType = "image/jpeg";
Stream fileContent = FilesHelper.GetFileContent(drive.Id, file.Id, jpegContentType);
return (base.File(fileContent, jpegContentType, file.Name));
}
}
return View("Index");
}
private Models.DriveItem UploadSampleFile(Models.Drive drive, Models.DriveItem newFolder, String filePath)
{
Models.DriveItem result = null;
Stream memPhoto = getFileContent(filePath);
try
{
if (memPhoto.Length > 0)
{
String contentType = "image/png";
result = FilesHelper.UploadFile(drive.Id, newFolder.Id,
new Models.DriveItem
{
File = new Models.File { },
Name = "PnPLogo.png",
ConflictBehavior = "rename",
},
memPhoto,
contentType);
}
}
catch (Exception ex)
{
// Handle the exception
}
return (result);
}
private void UpdateSampleFile(Drive drive, DriveItem newFile, String filePath)
{
FilesHelper.RenameFile(drive.Id, newFile.Id, "SP2016-MinRoles.jpg");
Stream memPhoto = getFileContent(filePath);
try
{
if (memPhoto.Length > 0)
{
String contentType = "image/jpeg";
FilesHelper.UpdateFileContent(
drive.Id,
newFile.Id,
memPhoto,
contentType);
}
}
catch (Exception ex)
{
// Handle the exception
}
}
private static Stream getFileContent(String filePath)
{
MemoryStream memPhoto = new MemoryStream();
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Byte[] newPhoto = new Byte[fs.Length];
fs.Read(newPhoto, 0, (Int32)(fs.Length - 1));
memPhoto.Write(newPhoto, 0, newPhoto.Length);
memPhoto.Position = 0;
}
return memPhoto;
}
}
} |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaWriter
{
private readonly JsonWriter _writer;
private readonly JsonSchemaResolver _resolver;
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
_writer = writer;
_resolver = resolver;
}
private void ReferenceOrWriteSchema(JsonSchema schema)
{
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.ReferencePropertyName);
_writer.WriteValue(schema.Id);
_writer.WriteEndObject();
}
else
{
WriteSchema(schema);
}
}
public void WriteSchema(JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(schema, "schema");
if (!_resolver.LoadedSchemas.Contains(schema))
_resolver.LoadedSchemas.Add(schema);
_writer.WriteStartObject();
WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.OptionalPropertyName, schema.Optional);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
if (schema.Type != null)
WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
if (!schema.AllowAdditionalProperties)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
_writer.WriteValue(schema.AllowAdditionalProperties);
}
else
{
if (schema.AdditionalProperties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
ReferenceOrWriteSchema(schema.AdditionalProperties);
}
}
if (schema.Properties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.PropertiesPropertyName);
_writer.WriteStartObject();
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties)
{
_writer.WritePropertyName(property.Key);
ReferenceOrWriteSchema(property.Value);
}
_writer.WriteEndObject();
}
WriteItems(schema);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumDecimalsPropertyName, schema.MaximumDecimals);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
if (schema.Enum != null)
{
_writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
_writer.WriteStartArray();
foreach (JToken token in schema.Enum)
{
token.WriteTo(_writer);
}
_writer.WriteEndArray();
}
if (schema.Default != null)
{
_writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
schema.Default.WriteTo(_writer);
}
if (schema.Options != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionsPropertyName);
_writer.WriteStartArray();
foreach (KeyValuePair<JToken, string> option in schema.Options)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
option.Key.WriteTo(_writer);
if (option.Value != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
_writer.WriteValue(option.Value);
}
_writer.WriteEndObject();
}
_writer.WriteEndArray();
}
if (schema.Disallow != null)
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
if (schema.Extends != null)
{
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
ReferenceOrWriteSchema(schema.Extends);
}
_writer.WriteEndObject();
}
private void WriteItems(JsonSchema schema)
{
if (CollectionUtils.IsNullOrEmpty(schema.Items))
return;
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
if (schema.Items.Count == 1)
{
ReferenceOrWriteSchema(schema.Items[0]);
return;
}
_writer.WriteStartArray();
foreach (JsonSchema itemSchema in schema.Items)
{
ReferenceOrWriteSchema(itemSchema);
}
_writer.WriteEndArray();
}
private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type)
{
IList<JsonSchemaType> types;
if (System.Enum.IsDefined(typeof(JsonSchemaType), type))
types = new List<JsonSchemaType> { type };
else
types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList();
if (types.Count == 0)
return;
writer.WritePropertyName(propertyName);
if (types.Count == 1)
{
writer.WriteValue(JsonSchemaBuilder.MapType(types[0]));
return;
}
writer.WriteStartArray();
foreach (JsonSchemaType jsonSchemaType in types)
{
writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType));
}
writer.WriteEndArray();
}
private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value)
{
if (value != null)
{
writer.WritePropertyName(propertyName);
writer.WriteValue(value);
}
}
}
}
|
namespace StockSharp.Algo.Export
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Ecng.Common;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// Ýêñïîðò â xml.
/// </summary>
public class XmlExporter : BaseExporter
{
private const string _timeFormat = "yyyy-MM-dd HH:mm:ss.fff zzz";
/// <summary>
/// Ñîçäàòü <see cref="XmlExporter"/>.
/// </summary>
/// <param name="security">Èíñòðóìåíò.</param>
/// <param name="arg">Ïàðàìåòð äàííûõ.</param>
/// <param name="isCancelled">Îáðàáîò÷èê, âîçâðàùàþùèé ïðèçíàê ïðåðûâàíèÿ ýêñïîðòà.</param>
/// <param name="fileName">Ïóòü ê ôàéëó.</param>
public XmlExporter(Security security, object arg, Func<int, bool> isCancelled, string fileName)
: base(security, arg, isCancelled, fileName)
{
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="ExecutionMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<ExecutionMessage> messages)
{
switch ((ExecutionTypes)Arg)
{
case ExecutionTypes.Tick:
{
Do(messages, "trades", (writer, trade) =>
{
writer.WriteStartElement("trade");
writer.WriteAttribute("id", trade.TradeId == null ? trade.TradeStringId : trade.TradeId.To<string>());
writer.WriteAttribute("serverTime", trade.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", trade.LocalTime.ToString(_timeFormat));
writer.WriteAttribute("price", trade.TradePrice);
writer.WriteAttribute("volume", trade.Volume);
if (trade.OriginSide != null)
writer.WriteAttribute("originSide", trade.OriginSide.Value);
if (trade.OpenInterest != null)
writer.WriteAttribute("openInterest", trade.OpenInterest.Value);
if (trade.IsUpTick != null)
writer.WriteAttribute("isUpTick", trade.IsUpTick.Value);
writer.WriteEndElement();
});
break;
}
case ExecutionTypes.OrderLog:
{
Do(messages, "orderLog", (writer, item) =>
{
writer.WriteStartElement("item");
writer.WriteAttribute("id", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>());
writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat));
writer.WriteAttribute("price", item.Price);
writer.WriteAttribute("volume", item.Volume);
writer.WriteAttribute("side", item.Side);
writer.WriteAttribute("state", item.OrderState);
writer.WriteAttribute("timeInForce", item.TimeInForce);
writer.WriteAttribute("isSystem", item.IsSystem);
if (item.TradePrice != null)
{
writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>());
writer.WriteAttribute("tradePrice", item.TradePrice);
if (item.OpenInterest != null)
writer.WriteAttribute("openInterest", item.OpenInterest.Value);
}
writer.WriteEndElement();
});
break;
}
case ExecutionTypes.Order:
case ExecutionTypes.Trade:
{
Do(messages, "executions", (writer, item) =>
{
writer.WriteStartElement("item");
writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat));
writer.WriteAttribute("portfolio", item.PortfolioName);
writer.WriteAttribute("transactionId", item.TransactionId);
writer.WriteAttribute("id", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>());
writer.WriteAttribute("price", item.Price);
writer.WriteAttribute("volume", item.Volume);
writer.WriteAttribute("balance", item.Balance);
writer.WriteAttribute("side", item.Side);
writer.WriteAttribute("type", item.OrderType);
writer.WriteAttribute("state", item.OrderState);
writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>());
writer.WriteAttribute("tradePrice", item.TradePrice);
writer.WriteEndElement();
});
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="QuoteChangeMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<QuoteChangeMessage> messages)
{
Do(messages, "depths", (writer, depth) =>
{
writer.WriteStartElement("depth");
writer.WriteAttribute("serverTime", depth.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", depth.LocalTime.ToString(_timeFormat));
foreach (var quote in depth.Bids.Concat(depth.Asks).OrderByDescending(q => q.Price))
{
writer.WriteStartElement("quote");
writer.WriteAttribute("price", quote.Price);
writer.WriteAttribute("volume", quote.Volume);
writer.WriteAttribute("side", quote.Side);
writer.WriteEndElement();
}
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="Level1ChangeMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<Level1ChangeMessage> messages)
{
Do(messages, "messages", (writer, message) =>
{
writer.WriteStartElement("message");
writer.WriteAttribute("serverTime", message.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", message.LocalTime.ToString(_timeFormat));
foreach (var pair in message.Changes)
writer.WriteAttribute(pair.Key.ToString(), pair.Value is DateTime ? ((DateTime)pair.Value).ToString(_timeFormat) : pair.Value);
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="CandleMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<CandleMessage> messages)
{
Do(messages, "candles", (writer, candle) =>
{
writer.WriteStartElement("candle");
writer.WriteAttribute("openTime", candle.OpenTime.ToString(_timeFormat));
writer.WriteAttribute("closeTime", candle.CloseTime.ToString(_timeFormat));
writer.WriteAttribute("O", candle.OpenPrice);
writer.WriteAttribute("H", candle.HighPrice);
writer.WriteAttribute("L", candle.LowPrice);
writer.WriteAttribute("C", candle.ClosePrice);
writer.WriteAttribute("V", candle.TotalVolume);
if (candle.OpenInterest != null)
writer.WriteAttribute("openInterest", candle.OpenInterest.Value);
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="NewsMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<NewsMessage> messages)
{
Do(messages, "news", (writer, n) =>
{
writer.WriteStartElement("item");
if (!n.Id.IsEmpty())
writer.WriteAttribute("id", n.Id);
writer.WriteAttribute("serverTime", n.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", n.LocalTime.ToString(_timeFormat));
if (n.SecurityId != null)
writer.WriteAttribute("securityCode", n.SecurityId.Value.SecurityCode);
if (!n.BoardCode.IsEmpty())
writer.WriteAttribute("boardCode", n.BoardCode);
writer.WriteAttribute("headline", n.Headline);
if (!n.Source.IsEmpty())
writer.WriteAttribute("source", n.Source);
if (n.Url != null)
writer.WriteAttribute("board", n.Url);
if (!n.Story.IsEmpty())
writer.WriteCData(n.Story);
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="SecurityMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<SecurityMessage> messages)
{
Do(messages, "securities", (writer, security) =>
{
writer.WriteStartElement("security");
writer.WriteAttribute("code", security.SecurityId.SecurityCode);
writer.WriteAttribute("board", security.SecurityId.BoardCode);
if (!security.Name.IsEmpty())
writer.WriteAttribute("name", security.Name);
if (!security.ShortName.IsEmpty())
writer.WriteAttribute("shortName", security.ShortName);
if (security.PriceStep != null)
writer.WriteAttribute("priceStep", security.PriceStep.Value);
if (security.VolumeStep != null)
writer.WriteAttribute("volumeStep", security.VolumeStep.Value);
if (security.Multiplier != null)
writer.WriteAttribute("multiplier", security.Multiplier.Value);
if (security.Decimals != null)
writer.WriteAttribute("decimals", security.Decimals.Value);
if (security.Currency != null)
writer.WriteAttribute("currency", security.Currency.Value);
if (security.SecurityType != null)
writer.WriteAttribute("type", security.SecurityType.Value);
if (security.OptionType != null)
writer.WriteAttribute("optionType", security.OptionType.Value);
if (security.Strike != null)
writer.WriteAttribute("strike", security.Strike.Value);
if (!security.BinaryOptionType.IsEmpty())
writer.WriteAttribute("binaryOptionType", security.BinaryOptionType);
if (!security.UnderlyingSecurityCode.IsEmpty())
writer.WriteAttribute("underlyingSecurityCode", security.UnderlyingSecurityCode);
if (security.ExpiryDate != null)
writer.WriteAttribute("expiryDate", security.ExpiryDate.Value.ToString("yyyy-MM-dd"));
if (security.SettlementDate != null)
writer.WriteAttribute("settlementDate", security.SettlementDate.Value.ToString("yyyy-MM-dd"));
if (!security.SecurityId.Bloomberg.IsEmpty())
writer.WriteAttribute("bloomberg", security.SecurityId.Bloomberg);
if (!security.SecurityId.Cusip.IsEmpty())
writer.WriteAttribute("cusip", security.SecurityId.Cusip);
if (!security.SecurityId.IQFeed.IsEmpty())
writer.WriteAttribute("iqfeed", security.SecurityId.IQFeed);
if (security.SecurityId.InteractiveBrokers != null)
writer.WriteAttribute("ib", security.SecurityId.InteractiveBrokers);
if (!security.SecurityId.Isin.IsEmpty())
writer.WriteAttribute("isin", security.SecurityId.Isin);
if (!security.SecurityId.Plaza.IsEmpty())
writer.WriteAttribute("plaza", security.SecurityId.Plaza);
if (!security.SecurityId.Ric.IsEmpty())
writer.WriteAttribute("ric", security.SecurityId.Ric);
if (!security.SecurityId.Sedol.IsEmpty())
writer.WriteAttribute("sedol", security.SecurityId.Sedol);
writer.WriteEndElement();
});
}
private void Do<TValue>(IEnumerable<TValue> values, string rootElem, Action<XmlWriter, TValue> action)
{
using (var writer = XmlWriter.Create(Path, new XmlWriterSettings { Indent = true }))
{
writer.WriteStartElement(rootElem);
foreach (var value in values)
{
if (!CanProcess())
break;
action(writer, value);
}
writer.WriteEndElement();
}
}
}
} |
/*
* 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.
*/
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Cache.Configuration
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
using Apache.Ignite.Core.Cache.Eviction;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cache.Affinity;
using Apache.Ignite.Core.Impl.Cache.Expiry;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Plugin.Cache;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Defines grid cache configuration.
/// </summary>
public class CacheConfiguration : IBinaryRawWriteAwareEx<BinaryWriter>
{
/// <summary> Default size of rebalance thread pool. </summary>
public const int DefaultRebalanceThreadPoolSize = 2;
/// <summary> Default rebalance timeout.</summary>
public static readonly TimeSpan DefaultRebalanceTimeout = TimeSpan.FromMilliseconds(10000);
/// <summary> Time to wait between rebalance messages to avoid overloading CPU. </summary>
public static readonly TimeSpan DefaultRebalanceThrottle = TimeSpan.Zero;
/// <summary> Default number of backups. </summary>
public const int DefaultBackups = 0;
/// <summary> Default caching mode. </summary>
public const CacheMode DefaultCacheMode = CacheMode.Partitioned;
/// <summary> Default atomicity mode. </summary>
public const CacheAtomicityMode DefaultAtomicityMode = CacheAtomicityMode.Atomic;
/// <summary> Default lock timeout. </summary>
public static readonly TimeSpan DefaultLockTimeout = TimeSpan.Zero;
/// <summary> Default cache size to use with eviction policy. </summary>
public const int DefaultCacheSize = 100000;
/// <summary> Default value for 'invalidate' flag that indicates if this is invalidation-based cache. </summary>
public const bool DefaultInvalidate = false;
/// <summary> Default rebalance mode for distributed cache. </summary>
public const CacheRebalanceMode DefaultRebalanceMode = CacheRebalanceMode.Async;
/// <summary> Default rebalance batch size in bytes. </summary>
public const int DefaultRebalanceBatchSize = 512*1024; // 512K
/// <summary> Default value for <see cref="WriteSynchronizationMode"/> property.</summary>
public const CacheWriteSynchronizationMode DefaultWriteSynchronizationMode =
CacheWriteSynchronizationMode.PrimarySync;
/// <summary> Default value for eager ttl flag. </summary>
public const bool DefaultEagerTtl = true;
/// <summary> Default value for 'maxConcurrentAsyncOps'. </summary>
public const int DefaultMaxConcurrentAsyncOperations = 500;
/// <summary> Default value for 'writeBehindEnabled' flag. </summary>
public const bool DefaultWriteBehindEnabled = false;
/// <summary> Default flush size for write-behind cache store. </summary>
public const int DefaultWriteBehindFlushSize = 10240; // 10K
/// <summary> Default flush frequency for write-behind cache store. </summary>
public static readonly TimeSpan DefaultWriteBehindFlushFrequency = TimeSpan.FromMilliseconds(5000);
/// <summary> Default count of flush threads for write-behind cache store. </summary>
public const int DefaultWriteBehindFlushThreadCount = 1;
/// <summary> Default batch size for write-behind cache store. </summary>
public const int DefaultWriteBehindBatchSize = 512;
/// <summary> Default value for load previous value flag. </summary>
public const bool DefaultLoadPreviousValue = false;
/// <summary> Default value for 'readFromBackup' flag. </summary>
public const bool DefaultReadFromBackup = true;
/// <summary> Default timeout after which long query warning will be printed. </summary>
public static readonly TimeSpan DefaultLongQueryWarningTimeout = TimeSpan.FromMilliseconds(3000);
/// <summary> Default value for keep portable in store behavior .</summary>
[Obsolete("Use DefaultKeepBinaryInStore instead.")]
public const bool DefaultKeepVinaryInStore = true;
/// <summary> Default value for <see cref="KeepBinaryInStore"/> property.</summary>
public const bool DefaultKeepBinaryInStore = false;
/// <summary> Default value for 'copyOnRead' flag. </summary>
public const bool DefaultCopyOnRead = true;
/// <summary> Default value for read-through behavior. </summary>
public const bool DefaultReadThrough = false;
/// <summary> Default value for write-through behavior. </summary>
public const bool DefaultWriteThrough = false;
/// <summary> Default value for <see cref="WriteBehindCoalescing"/>. </summary>
public const bool DefaultWriteBehindCoalescing = true;
/// <summary> Default value for <see cref="PartitionLossPolicy"/>. </summary>
public const PartitionLossPolicy DefaultPartitionLossPolicy = PartitionLossPolicy.Ignore;
/// <summary> Default value for <see cref="SqlIndexMaxInlineSize"/>. </summary>
public const int DefaultSqlIndexMaxInlineSize = -1;
/// <summary> Default value for <see cref="StoreConcurrentLoadAllThreshold"/>. </summary>
public const int DefaultStoreConcurrentLoadAllThreshold = 5;
/// <summary> Default value for <see cref="RebalanceOrder"/>. </summary>
public const int DefaultRebalanceOrder = 0;
/// <summary> Default value for <see cref="RebalanceBatchesPrefetchCount"/>. </summary>
public const long DefaultRebalanceBatchesPrefetchCount = 2;
/// <summary> Default value for <see cref="MaxQueryIteratorsCount"/>. </summary>
public const int DefaultMaxQueryIteratorsCount = 1024;
/// <summary> Default value for <see cref="QueryDetailMetricsSize"/>. </summary>
public const int DefaultQueryDetailMetricsSize = 0;
/// <summary> Default value for <see cref="QueryParallelism"/>. </summary>
public const int DefaultQueryParallelism = 1;
/// <summary> Default value for <see cref="EncryptionEnabled"/>. </summary>
public const bool DefaultEncryptionEnabled = false;
/// <summary>
/// Gets or sets the cache name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CacheConfiguration"/> class.
/// </summary>
public CacheConfiguration() : this((string) null)
{
// No-op.
}
/// <summary>
/// Initializes a new instance of the <see cref="CacheConfiguration"/> class.
/// </summary>
/// <param name="name">Cache name.</param>
public CacheConfiguration(string name)
{
Name = name;
Backups = DefaultBackups;
AtomicityMode = DefaultAtomicityMode;
CacheMode = DefaultCacheMode;
CopyOnRead = DefaultCopyOnRead;
WriteSynchronizationMode = DefaultWriteSynchronizationMode;
EagerTtl = DefaultEagerTtl;
Invalidate = DefaultInvalidate;
KeepBinaryInStore = DefaultKeepBinaryInStore;
LoadPreviousValue = DefaultLoadPreviousValue;
LockTimeout = DefaultLockTimeout;
#pragma warning disable 618
LongQueryWarningTimeout = DefaultLongQueryWarningTimeout;
#pragma warning restore 618
MaxConcurrentAsyncOperations = DefaultMaxConcurrentAsyncOperations;
ReadFromBackup = DefaultReadFromBackup;
RebalanceBatchSize = DefaultRebalanceBatchSize;
RebalanceMode = DefaultRebalanceMode;
RebalanceThrottle = DefaultRebalanceThrottle;
RebalanceTimeout = DefaultRebalanceTimeout;
WriteBehindBatchSize = DefaultWriteBehindBatchSize;
WriteBehindEnabled = DefaultWriteBehindEnabled;
WriteBehindFlushFrequency = DefaultWriteBehindFlushFrequency;
WriteBehindFlushSize = DefaultWriteBehindFlushSize;
WriteBehindFlushThreadCount= DefaultWriteBehindFlushThreadCount;
WriteBehindCoalescing = DefaultWriteBehindCoalescing;
PartitionLossPolicy = DefaultPartitionLossPolicy;
SqlIndexMaxInlineSize = DefaultSqlIndexMaxInlineSize;
StoreConcurrentLoadAllThreshold = DefaultStoreConcurrentLoadAllThreshold;
RebalanceOrder = DefaultRebalanceOrder;
RebalanceBatchesPrefetchCount = DefaultRebalanceBatchesPrefetchCount;
MaxQueryIteratorsCount = DefaultMaxQueryIteratorsCount;
QueryParallelism = DefaultQueryParallelism;
EncryptionEnabled = DefaultEncryptionEnabled;
}
/// <summary>
/// Initializes a new instance of the <see cref="CacheConfiguration"/> class
/// and populates <see cref="QueryEntities"/> according to provided query types.
/// This constructor is depricated, please use <see cref="CacheConfiguration(string, QueryEntity[])"/>
/// </summary>
/// <param name="name">Cache name.</param>
/// <param name="queryTypes">
/// Collection of types to be registered as query entities. These types should use
/// <see cref="QuerySqlFieldAttribute"/> to configure query fields and properties.
/// </param>
[Obsolete("This constructor is deprecated, please use CacheConfiguration(string, QueryEntity[]) instead.")]
public CacheConfiguration(string name, params Type[] queryTypes) : this(name)
{
QueryEntities = queryTypes.Select(type => new QueryEntity {ValueType = type}).ToArray();
}
/// <summary>
/// Initializes a new instance of the <see cref="CacheConfiguration"/> class.
/// </summary>
/// <param name="name">Cache name.</param>
/// <param name="queryEntities">Query entities.</param>
public CacheConfiguration(string name, params QueryEntity[] queryEntities) : this(name)
{
QueryEntities = queryEntities;
}
/// <summary>
/// Initializes a new instance of the <see cref="CacheConfiguration"/> class,
/// performing a deep copy of specified cache configuration.
/// </summary>
/// <param name="other">The other configuration to perfrom deep copy from.</param>
public CacheConfiguration(CacheConfiguration other)
{
if (other != null)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
other.Write(BinaryUtils.Marshaller.StartMarshal(stream), ClientSocket.CurrentProtocolVersion);
stream.SynchronizeOutput();
stream.Seek(0, SeekOrigin.Begin);
Read(BinaryUtils.Marshaller.StartUnmarshal(stream), ClientSocket.CurrentProtocolVersion);
}
CopyLocalProperties(other);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="CacheConfiguration"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="srvVer">Server version.</param>
internal CacheConfiguration(BinaryReader reader, ClientProtocolVersion srvVer)
{
Read(reader, srvVer);
}
/// <summary>
/// Reads data into this instance from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="srvVer">Server version.</param>
private void Read(BinaryReader reader, ClientProtocolVersion srvVer)
{
// Make sure system marshaller is used.
Debug.Assert(reader.Marshaller == BinaryUtils.Marshaller);
AtomicityMode = (CacheAtomicityMode) reader.ReadInt();
Backups = reader.ReadInt();
CacheMode = (CacheMode) reader.ReadInt();
CopyOnRead = reader.ReadBoolean();
EagerTtl = reader.ReadBoolean();
Invalidate = reader.ReadBoolean();
KeepBinaryInStore = reader.ReadBoolean();
LoadPreviousValue = reader.ReadBoolean();
LockTimeout = reader.ReadLongAsTimespan();
#pragma warning disable 618
LongQueryWarningTimeout = reader.ReadLongAsTimespan();
#pragma warning restore 618
MaxConcurrentAsyncOperations = reader.ReadInt();
Name = reader.ReadString();
ReadFromBackup = reader.ReadBoolean();
RebalanceBatchSize = reader.ReadInt();
RebalanceDelay = reader.ReadLongAsTimespan();
RebalanceMode = (CacheRebalanceMode) reader.ReadInt();
RebalanceThrottle = reader.ReadLongAsTimespan();
RebalanceTimeout = reader.ReadLongAsTimespan();
SqlEscapeAll = reader.ReadBoolean();
WriteBehindBatchSize = reader.ReadInt();
WriteBehindEnabled = reader.ReadBoolean();
WriteBehindFlushFrequency = reader.ReadLongAsTimespan();
WriteBehindFlushSize = reader.ReadInt();
WriteBehindFlushThreadCount = reader.ReadInt();
WriteBehindCoalescing = reader.ReadBoolean();
WriteSynchronizationMode = (CacheWriteSynchronizationMode) reader.ReadInt();
ReadThrough = reader.ReadBoolean();
WriteThrough = reader.ReadBoolean();
EnableStatistics = reader.ReadBoolean();
DataRegionName = reader.ReadString();
PartitionLossPolicy = (PartitionLossPolicy) reader.ReadInt();
GroupName = reader.ReadString();
CacheStoreFactory = reader.ReadObject<IFactory<ICacheStore>>();
SqlIndexMaxInlineSize = reader.ReadInt();
OnheapCacheEnabled = reader.ReadBoolean();
StoreConcurrentLoadAllThreshold = reader.ReadInt();
RebalanceOrder = reader.ReadInt();
RebalanceBatchesPrefetchCount = reader.ReadLong();
MaxQueryIteratorsCount = reader.ReadInt();
QueryDetailMetricsSize = reader.ReadInt();
QueryParallelism = reader.ReadInt();
SqlSchema = reader.ReadString();
EncryptionEnabled = reader.ReadBoolean();
QueryEntities = reader.ReadCollectionRaw(r => new QueryEntity(r, srvVer));
NearConfiguration = reader.ReadBoolean() ? new NearCacheConfiguration(reader) : null;
EvictionPolicy = EvictionPolicyBase.Read(reader);
AffinityFunction = AffinityFunctionSerializer.Read(reader);
ExpiryPolicyFactory = ExpiryPolicySerializer.ReadPolicyFactory(reader);
KeyConfiguration = reader.ReadCollectionRaw(r => new CacheKeyConfiguration(r));
var count = reader.ReadInt();
if (count > 0)
{
PluginConfigurations = new List<ICachePluginConfiguration>(count);
for (int i = 0; i < count; i++)
{
if (reader.ReadBoolean())
{
// FactoryId-based plugin: skip.
reader.ReadInt(); // Skip factory id.
var size = reader.ReadInt();
reader.Stream.Seek(size, SeekOrigin.Current); // Skip custom data.
}
else
{
// Pure .NET plugin.
PluginConfigurations.Add(reader.ReadObject<ICachePluginConfiguration>());
}
}
}
}
/// <summary>
/// Writes this instance to the specified writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="srvVer">Server version.</param>
void IBinaryRawWriteAwareEx<BinaryWriter>.Write(BinaryWriter writer, ClientProtocolVersion srvVer)
{
Write(writer, srvVer);
}
/// <summary>
/// Writes this instance to the specified writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="srvVer">Server version.</param>
internal void Write(BinaryWriter writer, ClientProtocolVersion srvVer)
{
// Make sure system marshaller is used.
Debug.Assert(writer.Marshaller == BinaryUtils.Marshaller);
writer.WriteInt((int) AtomicityMode);
writer.WriteInt(Backups);
writer.WriteInt((int) CacheMode);
writer.WriteBoolean(CopyOnRead);
writer.WriteBoolean(EagerTtl);
writer.WriteBoolean(Invalidate);
writer.WriteBoolean(KeepBinaryInStore);
writer.WriteBoolean(LoadPreviousValue);
writer.WriteLong((long) LockTimeout.TotalMilliseconds);
#pragma warning disable 618
writer.WriteLong((long) LongQueryWarningTimeout.TotalMilliseconds);
#pragma warning restore 618
writer.WriteInt(MaxConcurrentAsyncOperations);
writer.WriteString(Name);
writer.WriteBoolean(ReadFromBackup);
writer.WriteInt(RebalanceBatchSize);
writer.WriteLong((long) RebalanceDelay.TotalMilliseconds);
writer.WriteInt((int) RebalanceMode);
writer.WriteLong((long) RebalanceThrottle.TotalMilliseconds);
writer.WriteLong((long) RebalanceTimeout.TotalMilliseconds);
writer.WriteBoolean(SqlEscapeAll);
writer.WriteInt(WriteBehindBatchSize);
writer.WriteBoolean(WriteBehindEnabled);
writer.WriteLong((long) WriteBehindFlushFrequency.TotalMilliseconds);
writer.WriteInt(WriteBehindFlushSize);
writer.WriteInt(WriteBehindFlushThreadCount);
writer.WriteBoolean(WriteBehindCoalescing);
writer.WriteInt((int) WriteSynchronizationMode);
writer.WriteBoolean(ReadThrough);
writer.WriteBoolean(WriteThrough);
writer.WriteBoolean(EnableStatistics);
writer.WriteString(DataRegionName);
writer.WriteInt((int) PartitionLossPolicy);
writer.WriteString(GroupName);
writer.WriteObject(CacheStoreFactory);
writer.WriteInt(SqlIndexMaxInlineSize);
writer.WriteBoolean(OnheapCacheEnabled);
writer.WriteInt(StoreConcurrentLoadAllThreshold);
writer.WriteInt(RebalanceOrder);
writer.WriteLong(RebalanceBatchesPrefetchCount);
writer.WriteInt(MaxQueryIteratorsCount);
writer.WriteInt(QueryDetailMetricsSize);
writer.WriteInt(QueryParallelism);
writer.WriteString(SqlSchema);
writer.WriteBoolean(EncryptionEnabled);
writer.WriteCollectionRaw(QueryEntities, srvVer);
if (NearConfiguration != null)
{
writer.WriteBoolean(true);
NearConfiguration.Write(writer);
}
else
writer.WriteBoolean(false);
EvictionPolicyBase.Write(writer, EvictionPolicy);
AffinityFunctionSerializer.Write(writer, AffinityFunction);
ExpiryPolicySerializer.WritePolicyFactory(writer, ExpiryPolicyFactory);
writer.WriteCollectionRaw(KeyConfiguration);
if (PluginConfigurations != null)
{
writer.WriteInt(PluginConfigurations.Count);
foreach (var cachePlugin in PluginConfigurations)
{
if (cachePlugin == null)
throw new InvalidOperationException("Invalid cache configuration: " +
"ICachePluginConfiguration can't be null.");
if (cachePlugin.CachePluginConfigurationClosureFactoryId != null)
{
writer.WriteBoolean(true);
writer.WriteInt(cachePlugin.CachePluginConfigurationClosureFactoryId.Value);
int pos = writer.Stream.Position;
writer.WriteInt(0); // Reserve size.
cachePlugin.WriteBinary(writer);
writer.Stream.WriteInt(pos, writer.Stream.Position - pos - 4); // Write size.
}
else
{
writer.WriteBoolean(false);
writer.WriteObject(cachePlugin);
}
}
}
else
{
writer.WriteInt(0);
}
}
/// <summary>
/// Copies the local properties (properties that are not written in Write method).
/// </summary>
internal void CopyLocalProperties(CacheConfiguration cfg)
{
Debug.Assert(cfg != null);
PluginConfigurations = cfg.PluginConfigurations;
if (QueryEntities != null && cfg.QueryEntities != null)
{
var entities = cfg.QueryEntities.Where(x => x != null).ToDictionary(x => GetQueryEntityKey(x), x => x);
foreach (var entity in QueryEntities.Where(x => x != null))
{
QueryEntity src;
if (entities.TryGetValue(GetQueryEntityKey(entity), out src))
{
entity.CopyLocalProperties(src);
}
}
}
}
/// <summary>
/// Gets the query entity key.
/// </summary>
private static string GetQueryEntityKey(QueryEntity x)
{
return x.KeyTypeName + "^" + x.ValueTypeName;
}
/// <summary>
/// Validates this instance and outputs information to the log, if necessary.
/// </summary>
internal void Validate(ILogger log)
{
Debug.Assert(log != null);
var entities = QueryEntities;
if (entities != null)
{
foreach (var entity in entities)
entity.Validate(log, string.Format("Validating cache configuration '{0}'", Name ?? ""));
}
}
/// <summary>
/// Gets or sets write synchronization mode. This mode controls whether the main
/// caller should wait for update on other nodes to complete or not.
/// </summary>
[DefaultValue(DefaultWriteSynchronizationMode)]
public CacheWriteSynchronizationMode WriteSynchronizationMode { get; set; }
/// <summary>
/// Gets or sets flag indicating whether expired cache entries will be eagerly removed from cache.
/// When set to false, expired entries will be removed on next entry access.
/// </summary>
[DefaultValue(DefaultEagerTtl)]
public bool EagerTtl { get; set; }
/// <summary>
/// Gets or sets flag indicating whether value should be loaded from store if it is not in the cache
/// for the following cache operations:
/// <list type="bullet">
/// <item><term><see cref="ICache{TK,TV}.PutIfAbsent"/></term></item>
/// <item><term><see cref="ICache{TK,TV}.Replace(TK,TV)"/></term></item>
/// <item><term><see cref="ICache{TK,TV}.Remove(TK)"/></term></item>
/// <item><term><see cref="ICache{TK,TV}.GetAndPut"/></term></item>
/// <item><term><see cref="ICache{TK,TV}.GetAndRemove"/></term></item>
/// <item><term><see cref="ICache{TK,TV}.GetAndReplace"/></term></item>
/// <item><term><see cref="ICache{TK,TV}.GetAndPutIfAbsent"/></term></item>
/// </list>
/// </summary>
[DefaultValue(DefaultLoadPreviousValue)]
public bool LoadPreviousValue { get; set; }
/// <summary>
/// Gets or sets the flag indicating whether <see cref="ICacheStore"/> is working with binary objects
/// instead of deserialized objects.
/// </summary>
[DefaultValue(DefaultKeepBinaryInStore)]
public bool KeepBinaryInStore { get; set; }
/// <summary>
/// Gets or sets caching mode to use.
/// </summary>
[DefaultValue(DefaultCacheMode)]
public CacheMode CacheMode { get; set; }
/// <summary>
/// Gets or sets cache atomicity mode.
/// </summary>
[DefaultValue(DefaultAtomicityMode)]
public CacheAtomicityMode AtomicityMode { get; set; }
/// <summary>
/// Gets or sets number of nodes used to back up single partition for
/// <see cref="Configuration.CacheMode.Partitioned"/> cache.
/// </summary>
[DefaultValue(DefaultBackups)]
public int Backups { get; set; }
/// <summary>
/// Gets or sets default lock acquisition timeout.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:00")]
public TimeSpan LockTimeout { get; set; }
/// <summary>
/// Invalidation flag. If true, values will be invalidated (nullified) upon commit in near cache.
/// </summary>
[DefaultValue(DefaultInvalidate)]
public bool Invalidate { get; set; }
/// <summary>
/// Gets or sets cache rebalance mode.
/// </summary>
[DefaultValue(DefaultRebalanceMode)]
public CacheRebalanceMode RebalanceMode { get; set; }
/// <summary>
/// Gets or sets size (in number bytes) to be loaded within a single rebalance message.
/// Rebalancing algorithm will split total data set on every node into multiple batches prior to sending data.
/// </summary>
[DefaultValue(DefaultRebalanceBatchSize)]
public int RebalanceBatchSize { get; set; }
/// <summary>
/// Gets or sets maximum number of allowed concurrent asynchronous operations, 0 for unlimited.
/// </summary>
[DefaultValue(DefaultMaxConcurrentAsyncOperations)]
public int MaxConcurrentAsyncOperations { get; set; }
/// <summary>
/// Flag indicating whether Ignite should use write-behind behaviour for the cache store.
/// </summary>
[DefaultValue(DefaultWriteBehindEnabled)]
public bool WriteBehindEnabled { get; set; }
/// <summary>
/// Maximum size of the write-behind cache. If cache size exceeds this value, all cached items are flushed
/// to the cache store and write cache is cleared.
/// </summary>
[DefaultValue(DefaultWriteBehindFlushSize)]
public int WriteBehindFlushSize { get; set; }
/// <summary>
/// Frequency with which write-behind cache is flushed to the cache store.
/// This value defines the maximum time interval between object insertion/deletion from the cache
/// at the moment when corresponding operation is applied to the cache store.
/// <para/>
/// If this value is 0, then flush is performed according to the flush size.
/// <para/>
/// Note that you cannot set both
/// <see cref="WriteBehindFlushSize"/> and <see cref="WriteBehindFlushFrequency"/> to 0.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:05")]
public TimeSpan WriteBehindFlushFrequency { get; set; }
/// <summary>
/// Number of threads that will perform cache flushing. Cache flushing is performed when cache size exceeds
/// value defined by <see cref="WriteBehindFlushSize"/>, or flush interval defined by
/// <see cref="WriteBehindFlushFrequency"/> is elapsed.
/// </summary>
[DefaultValue(DefaultWriteBehindFlushThreadCount)]
public int WriteBehindFlushThreadCount { get; set; }
/// <summary>
/// Maximum batch size for write-behind cache store operations.
/// Store operations (get or remove) are combined in a batch of this size to be passed to
/// <see cref="ICacheStore{K, V}.WriteAll"/> or <see cref="ICacheStore{K, V}.DeleteAll"/> methods.
/// </summary>
[DefaultValue(DefaultWriteBehindBatchSize)]
public int WriteBehindBatchSize { get; set; }
/// <summary>
/// Gets or sets rebalance timeout.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:10")]
public TimeSpan RebalanceTimeout { get; set; }
/// <summary>
/// Gets or sets delay upon a node joining or leaving topology (or crash)
/// after which rebalancing should be started automatically.
/// Rebalancing should be delayed if you plan to restart nodes
/// after they leave topology, or if you plan to start multiple nodes at once or one after another
/// and don't want to repartition and rebalance until all nodes are started.
/// </summary>
public TimeSpan RebalanceDelay { get; set; }
/// <summary>
/// Time to wait between rebalance messages to avoid overloading of CPU or network.
/// When rebalancing large data sets, the CPU or network can get over-consumed with rebalancing messages,
/// which consecutively may slow down the application performance. This parameter helps tune
/// the amount of time to wait between rebalance messages to make sure that rebalancing process
/// does not have any negative performance impact. Note that application will continue to work
/// properly while rebalancing is still in progress.
/// <para/>
/// Value of 0 means that throttling is disabled.
/// </summary>
public TimeSpan RebalanceThrottle { get; set; }
/// <summary>
/// Gets or sets flag indicating whether data can be read from backup.
/// </summary>
[DefaultValue(DefaultReadFromBackup)]
public bool ReadFromBackup { get; set; }
/// <summary>
/// Gets or sets flag indicating whether copy of the value stored in cache should be created
/// for cache operation implying return value.
/// </summary>
[DefaultValue(DefaultCopyOnRead)]
public bool CopyOnRead { get; set; }
/// <summary>
/// Gets or sets the timeout after which long query warning will be printed.
/// <para />
/// This property is obsolete, use <see cref="IgniteConfiguration.LongQueryWarningTimeout"/> instead.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:03")]
[Obsolete("Use IgniteConfiguration.LongQueryWarningTimeout instead.")]
public TimeSpan LongQueryWarningTimeout { get; set; }
/// <summary>
/// If true all the SQL table and field names will be escaped with double quotes like
/// ({ "tableName"."fieldsName"}). This enforces case sensitivity for field names and
/// also allows having special characters in table and field names.
/// </summary>
public bool SqlEscapeAll { get; set; }
/// <summary>
/// Gets or sets the factory for underlying persistent storage for read-through and write-through operations.
/// <para />
/// See <see cref="ReadThrough"/> and <see cref="WriteThrough"/> properties to enable read-through and
/// write-through behavior so that cache store is invoked on get and/or put operations.
/// <para />
/// If both <see cref="ReadThrough"/> and <see cref="WriteThrough"/> are <code>false</code>, cache store
/// will be invoked only on <see cref="ICache{TK,TV}.LoadCache"/> calls.
/// </summary>
public IFactory<ICacheStore> CacheStoreFactory { get; set; }
/// <summary>
/// Gets or sets a value indicating whether read-through should be enabled for cache operations.
/// <para />
/// When in read-through mode, cache misses that occur due to cache entries not existing
/// as a result of performing a "get" operations will appropriately cause the
/// configured <see cref="ICacheStore"/> (see <see cref="CacheStoreFactory"/>) to be invoked.
/// </summary>
[DefaultValue(DefaultReadThrough)]
public bool ReadThrough { get; set; }
/// <summary>
/// Gets or sets a value indicating whether write-through should be enabled for cache operations.
/// <para />
/// When in "write-through" mode, cache updates that occur as a result of performing "put" operations
/// will appropriately cause the configured
/// <see cref="ICacheStore"/> (see <see cref="CacheStoreFactory"/>) to be invoked.
/// </summary>
[DefaultValue(DefaultWriteThrough)]
public bool WriteThrough { get; set; }
/// <summary>
/// Gets or sets the query entity configuration.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<QueryEntity> QueryEntities { get; set; }
/// <summary>
/// Gets or sets the near cache configuration.
/// </summary>
public NearCacheConfiguration NearConfiguration { get; set; }
/// <summary>
/// Gets or sets the eviction policy.
/// Null value means disabled evictions.
/// </summary>
public IEvictionPolicy EvictionPolicy { get; set; }
/// <summary>
/// Gets or sets the affinity function to provide mapping from keys to nodes.
/// <para />
/// Predefined implementations:
/// <see cref="RendezvousAffinityFunction"/>.
/// </summary>
public IAffinityFunction AffinityFunction { get; set; }
/// <summary>
/// Gets or sets the factory for <see cref="IExpiryPolicy"/> to be used for all cache operations,
/// unless <see cref="ICache{TK,TV}.WithExpiryPolicy"/> is called.
/// <para />
/// Default is null, which means no expiration.
/// </summary>
public IFactory<IExpiryPolicy> ExpiryPolicyFactory { get; set; }
/// <summary>
/// Gets or sets a value indicating whether statistics gathering is enabled on a cache.
/// These statistics can be retrieved via <see cref="ICache{TK,TV}.GetMetrics()"/>.
/// </summary>
public bool EnableStatistics { get; set; }
/// <summary>
/// Gets or sets the plugin configurations.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<ICachePluginConfiguration> PluginConfigurations { get; set; }
/// <summary>
/// Gets or sets the name of the <see cref="MemoryPolicyConfiguration"/> for this cache.
/// See <see cref="IgniteConfiguration.MemoryConfiguration"/>.
/// </summary>
[Obsolete("Use DataRegionName.")]
[XmlIgnore]
public string MemoryPolicyName
{
get { return DataRegionName; }
set { DataRegionName = value; }
}
/// <summary>
/// Gets or sets the name of the data region, see <see cref="DataRegionConfiguration"/>.
/// </summary>
public string DataRegionName { get; set; }
/// <summary>
/// Gets or sets write coalescing flag for write-behind cache store operations.
/// Store operations (get or remove) with the same key are combined or coalesced to single,
/// resulting operation to reduce pressure to underlying cache store.
/// </summary>
[DefaultValue(DefaultWriteBehindCoalescing)]
public bool WriteBehindCoalescing { get; set; }
/// <summary>
/// Gets or sets the partition loss policy. This policy defines how Ignite will react to
/// a situation when all nodes for some partition leave the cluster.
/// </summary>
[DefaultValue(DefaultPartitionLossPolicy)]
public PartitionLossPolicy PartitionLossPolicy { get; set; }
/// <summary>
/// Gets or sets the cache group name. Caches with the same group name share single underlying 'physical'
/// cache (partition set), but are logically isolated.
/// <para />
/// Since underlying cache is shared, the following configuration properties should be the same within group:
/// <see cref="AffinityFunction"/>, <see cref="CacheMode"/>, <see cref="PartitionLossPolicy"/>,
/// <see cref="DataRegionName"/>
/// <para />
/// Grouping caches reduces overall overhead, since internal data structures are shared.
/// </summary>
public string GroupName { get;set; }
/// <summary>
/// Gets or sets maximum inline size in bytes for sql indexes. See also <see cref="QueryIndex.InlineSize"/>.
/// -1 for automatic.
/// </summary>
[DefaultValue(DefaultSqlIndexMaxInlineSize)]
public int SqlIndexMaxInlineSize { get; set; }
/// <summary>
/// Gets or sets the key configuration.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<CacheKeyConfiguration> KeyConfiguration { get; set; }
/// <summary>
/// Gets or sets a value indicating whether on-heap cache is enabled for the off-heap based page memory.
/// </summary>
public bool OnheapCacheEnabled { get; set; }
/// <summary>
/// Gets or sets the threshold to use when multiple keys are being loaded from an underlying cache store
/// (see <see cref="CacheStoreFactory"/>).
///
/// In the situation when several threads load the same or intersecting set of keys
/// and the total number of keys to load is less or equal to this threshold then there will be no
/// second call to the storage in order to load a key from thread A if the same key is already being
/// loaded by thread B.
///
/// The threshold should be controlled wisely. On the one hand if it's set to a big value then the
/// interaction with a storage during the load of missing keys will be minimal.On the other hand the big
/// value may result in significant performance degradation because it is needed to check
/// for every key whether it's being loaded or not.
/// </summary>
[DefaultValue(DefaultStoreConcurrentLoadAllThreshold)]
public int StoreConcurrentLoadAllThreshold { get; set; }
/// <summary>
/// Gets or sets the cache rebalance order. Caches with bigger RebalanceOrder are rebalanced later than caches
/// with smaller RebalanceOrder.
/// <para />
/// Default is 0, which means unordered rebalance. All caches with RebalanceOrder=0 are rebalanced without any
/// delay concurrently.
/// <para />
/// This parameter is applicable only for caches with <see cref="RebalanceMode"/> of
/// <see cref="CacheRebalanceMode.Sync"/> and <see cref="CacheRebalanceMode.Async"/>.
/// </summary>
[DefaultValue(DefaultRebalanceOrder)]
public int RebalanceOrder { get; set; }
/// <summary>
/// Gets or sets the rebalance batches prefetch count.
/// <para />
/// Source node can provide more than one batch at rebalance start to improve performance.
/// Default is <see cref="DefaultRebalanceBatchesPrefetchCount"/>, minimum is 2.
/// </summary>
[DefaultValue(DefaultRebalanceBatchesPrefetchCount)]
public long RebalanceBatchesPrefetchCount { get; set; }
/// <summary>
/// Gets or sets the maximum number of active query iterators.
/// </summary>
[DefaultValue(DefaultMaxQueryIteratorsCount)]
public int MaxQueryIteratorsCount { get; set; }
/// <summary>
/// Gets or sets the size of the query detail metrics to be stored in memory.
/// <para />
/// 0 means disabled metrics.
/// </summary>
[DefaultValue(DefaultQueryDetailMetricsSize)]
public int QueryDetailMetricsSize { get; set; }
/// <summary>
/// Gets or sets the SQL schema.
/// Non-quoted identifiers are not case sensitive. Quoted identifiers are case sensitive.
/// <para />
/// Quoted <see cref="Name"/> is used by default.
/// </summary>
public string SqlSchema { get; set; }
/// <summary>
/// Gets or sets the desired query parallelism within a single node.
/// Query executor may or may not use this hint, depending on estimated query cost.
/// <para />
/// Default is <see cref="DefaultQueryParallelism"/>.
/// </summary>
[DefaultValue(DefaultQueryParallelism)]
public int QueryParallelism { get; set; }
/// <summary>
/// Gets or sets encryption flag.
/// Default is false.
/// </summary>
[DefaultValue(DefaultEncryptionEnabled)]
public bool EncryptionEnabled { get; set; }
}
}
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapSearchModule")]
public class MapSearchModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Scene m_scene = null; // only need one for communication with GridService
List<Scene> m_scenes = new List<Scene>();
List<UUID> m_Clients;
IWorldMapModule m_WorldMap;
IWorldMapModule WorldMap
{
get
{
if (m_WorldMap == null)
m_WorldMap = m_scene.RequestModuleInterface<IWorldMapModule>();
return m_WorldMap;
}
}
#region ISharedRegionModule Members
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
{
m_scene = scene;
}
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
m_Clients = new List<UUID>();
}
public void RemoveRegion(Scene scene)
{
m_scenes.Remove(scene);
if (m_scene == scene && m_scenes.Count > 0)
m_scene = m_scenes[0];
scene.EventManager.OnNewClient -= OnNewClient;
}
public void PostInitialise()
{
}
public void Close()
{
m_scene = null;
m_scenes.Clear();
}
public string Name
{
get { return "MapSearchModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RegionLoaded(Scene scene)
{
}
#endregion
private void OnNewClient(IClientAPI client)
{
client.OnMapNameRequest += OnMapNameRequestHandler;
}
private void OnMapNameRequestHandler(IClientAPI remoteClient, string mapName, uint flags)
{
lock (m_Clients)
{
if (m_Clients.Contains(remoteClient.AgentId))
return;
m_Clients.Add(remoteClient.AgentId);
}
OnMapNameRequest(remoteClient, mapName, flags);
}
private void OnMapNameRequest(IClientAPI remoteClient, string mapName, uint flags)
{
Util.FireAndForget(x =>
{
try
{
List<MapBlockData> blocks = new List<MapBlockData>();
if (mapName.Length < 3 || (mapName.EndsWith("#") && mapName.Length < 4))
{
// final block, closing the search result
AddFinalBlock(blocks,mapName);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
remoteClient.SendAlertMessage("Use a search string with at least 3 characters");
return;
}
//m_log.DebugFormat("MAP NAME=({0})", mapName);
// Hack to get around the fact that ll V3 now drops the port from the
// map name. See https://jira.secondlife.com/browse/VWR-28570
//
// Caller, use this magic form instead:
// secondlife://http|!!mygrid.com|8002|Region+Name/128/128
// or url encode if possible.
// the hacks we do with this viewer...
//
bool needOriginalName = false;
string mapNameOrig = mapName;
if (mapName.Contains("|"))
{
mapName = mapName.Replace('|', ':');
needOriginalName = true;
}
if (mapName.Contains("+"))
{
mapName = mapName.Replace('+', ' ');
needOriginalName = true;
}
if (mapName.Contains("!"))
{
mapName = mapName.Replace('!', '/');
needOriginalName = true;
}
if (mapName.Contains("."))
needOriginalName = true;
// try to fetch from GridServer
List<GridRegion> regionInfos = m_scene.GridService.GetRegionsByName(m_scene.RegionInfo.ScopeID, mapName, 20);
// if (regionInfos.Count == 0)
// remoteClient.SendAlertMessage("Hyperlink could not be established.");
//m_log.DebugFormat("[MAPSEARCHMODULE]: search {0} returned {1} regions", mapName, regionInfos.Count);
MapBlockData data;
if (regionInfos != null && regionInfos.Count > 0)
{
foreach (GridRegion info in regionInfos)
{
data = new MapBlockData();
data.Agents = 0;
data.Access = info.Access;
MapBlockData block = new MapBlockData();
WorldMap.MapBlockFromGridRegion(block, info, flags);
if (flags == 2 && regionInfos.Count == 1 && needOriginalName)
block.Name = mapNameOrig;
blocks.Add(block);
}
}
// final block, closing the search result
AddFinalBlock(blocks,mapNameOrig);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
// send extra user messages for V3
// because the UI is very confusing
// while we don't fix the hard-coded urls
if (flags == 2)
{
if (regionInfos == null || regionInfos.Count == 0)
remoteClient.SendAgentAlertMessage("No regions found with that name.", true);
// else if (regionInfos.Count == 1)
// remoteClient.SendAgentAlertMessage("Region found!", false);
}
}
finally
{
lock (m_Clients)
m_Clients.Remove(remoteClient.AgentId);
}
});
}
private void AddFinalBlock(List<MapBlockData> blocks,string name)
{
// final block, closing the search result
MapBlockData data = new MapBlockData();
data.Agents = 0;
data.Access = (byte)SimAccess.NonExistent;
data.MapImageId = UUID.Zero;
data.Name = name;
data.RegionFlags = 0;
data.WaterHeight = 0; // not used
data.X = 0;
data.Y = 0;
blocks.Add(data);
}
// private Scene GetClientScene(IClientAPI client)
// {
// foreach (Scene s in m_scenes)
// {
// if (client.Scene.RegionInfo.RegionHandle == s.RegionInfo.RegionHandle)
// return s;
// }
// return m_scene;
// }
}
}
|
using Scharfrichter.Codec;
using Scharfrichter.Codec.Archives;
using Scharfrichter.Codec.Charts;
using Scharfrichter.Codec.Sounds;
using Scharfrichter.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ConvertHelper
{
static public class BemaniToBMS
{
private const string configFileName = "Convert";
private const string databaseFileName = "BeatmaniaDB";
static public void Convert(string[] inArgs, long unitNumerator, long unitDenominator)
{
// configuration
Configuration config = LoadConfig();
Configuration db = LoadDB();
int quantizeMeasure = config["BMS"].GetValue("QuantizeMeasure");
int quantizeNotes = config["BMS"].GetValue("QuantizeNotes");
// splash
Splash.Show("Bemani to BeMusic Script");
Console.WriteLine("Timing: " + unitNumerator.ToString() + "/" + unitDenominator.ToString());
Console.WriteLine("Measure Quantize: " + quantizeMeasure.ToString());
// args
string[] args;
if (inArgs.Length > 0)
args = Subfolder.Parse(inArgs);
else
args = inArgs;
// debug args (if applicable)
if (System.Diagnostics.Debugger.IsAttached && args.Length == 0)
{
Console.WriteLine();
Console.WriteLine("Debugger attached. Input file name:");
args = new string[] { Console.ReadLine() };
}
// show usage if no args provided
if (args.Length == 0)
{
Console.WriteLine();
Console.WriteLine("Usage: BemaniToBMS <input file>");
Console.WriteLine();
Console.WriteLine("Drag and drop with files and folders is fully supported for this application.");
Console.WriteLine();
Console.WriteLine("Supported formats:");
Console.WriteLine("1, 2DX, CS, SD9, SSP");
}
// process files
for (int i = 0; i < args.Length; i++)
{
if (File.Exists(args[i]))
{
Console.WriteLine();
Console.WriteLine("Processing File: " + args[i]);
string filename = args[i];
string IIDXDBName = Path.GetFileNameWithoutExtension(filename);
while (IIDXDBName.StartsWith("0"))
IIDXDBName = IIDXDBName.Substring(1);
byte[] data = File.ReadAllBytes(args[i]);
switch (Path.GetExtension(args[i]).ToUpper())
{
case @".1":
using (MemoryStream source = new MemoryStream(data))
{
Bemani1 archive = Bemani1.Read(source, unitNumerator, unitDenominator);
if (db[IIDXDBName]["TITLE"] != "")
{
for (int j = 0; j < archive.ChartCount; j++)
{
Chart chart = archive.Charts[j];
if (chart != null)
{
chart.Tags["TITLE"] = db[IIDXDBName]["TITLE"];
chart.Tags["ARTIST"] = db[IIDXDBName]["ARTIST"];
chart.Tags["GENRE"] = db[IIDXDBName]["GENRE"];
if (j < 6)
chart.Tags["PLAYLEVEL"] = db[IIDXDBName]["DIFFICULTYSP" + config["IIDX"]["DIFFICULTY" + j.ToString()]];
else if (j < 12)
chart.Tags["PLAYLEVEL"] = db[IIDXDBName]["DIFFICULTYDP" + config["IIDX"]["DIFFICULTY" + j.ToString()]];
}
}
}
ConvertArchive(archive, config, args[i]);
}
break;
case @".2DX":
using (MemoryStream source = new MemoryStream(data))
{
Console.WriteLine("Converting Samples");
Bemani2DX archive = Bemani2DX.Read(source);
ConvertSounds(archive.Sounds, filename, 0.6f);
}
break;
case @".CS":
using (MemoryStream source = new MemoryStream(data))
ConvertChart(BeatmaniaIIDXCSNew.Read(source), config, filename, -1, null);
break;
case @".CS2":
using (MemoryStream source = new MemoryStream(data))
ConvertChart(BeatmaniaIIDXCSOld.Read(source), config, filename, -1, null);
break;
case @".CS5":
using (MemoryStream source = new MemoryStream(data))
ConvertChart(Beatmania5Key.Read(source), config, filename, -1, null);
break;
case @".CS9":
break;
case @".SD9":
using (MemoryStream source = new MemoryStream(data))
{
Sound sound = BemaniSD9.Read(source);
string targetFile = Path.GetFileNameWithoutExtension(filename);
string targetPath = Path.Combine(Path.GetDirectoryName(filename), targetFile) + ".wav";
sound.WriteFile(targetPath, 1.0f);
}
break;
case @".SSP":
using (MemoryStream source = new MemoryStream(data))
ConvertSounds(BemaniSSP.Read(source).Sounds, filename, 1.0f);
break;
}
}
}
// wrap up
Console.WriteLine("BemaniToBMS finished.");
}
static public void ConvertArchive(Archive archive, Configuration config, string filename)
{
for (int j = 0; j < archive.ChartCount; j++)
{
if (archive.Charts[j] != null)
{
Console.WriteLine("Converting Chart " + j.ToString());
ConvertChart(archive.Charts[j], config, filename, j, null);
}
}
}
static public void ConvertChart(Chart chart, Configuration config, string filename, int index, int[] map)
{
if (config == null)
{
config = LoadConfig();
}
int quantizeNotes = config["BMS"].GetValue("QuantizeNotes");
int quantizeMeasure = config["BMS"].GetValue("QuantizeMeasure");
int difficulty = config["IIDX"].GetValue("Difficulty" + index.ToString());
string title = config["BMS"]["Players" + config["IIDX"]["Players" + index.ToString()]] + " " + config["BMS"]["Difficulty" + difficulty.ToString()];
title = title.Trim();
if (quantizeMeasure > 0)
chart.QuantizeMeasureLengths(quantizeMeasure);
using (MemoryStream mem = new MemoryStream())
{
BMS bms = new BMS();
bms.Charts = new Chart[] { chart };
string name = "";
if (chart.Tags.ContainsKey("TITLE"))
name = chart.Tags["TITLE"];
if (name == "")
name = Path.GetFileNameWithoutExtension(Path.GetFileName(filename)); //ex: "1204 [1P Another]"
// write some tags
bms.Charts[0].Tags["TITLE"] = name;
if (chart.Tags.ContainsKey("ARTIST"))
bms.Charts[0].Tags["ARTIST"] = chart.Tags["ARTIST"];
if (chart.Tags.ContainsKey("GENRE"))
bms.Charts[0].Tags["GENRE"] = chart.Tags["GENRE"];
if (difficulty > 0)
bms.Charts[0].Tags["DIFFICULTY"] = difficulty.ToString();
if (bms.Charts[0].Players > 1)
bms.Charts[0].Tags["PLAYER"] = "3";
else
bms.Charts[0].Tags["PLAYER"] = "1";
name = name.Replace(":", "_");
name = name.Replace("/", "_");
name = name.Replace("?", "_");
name = name.Replace("\\", "_");
if (title != null && title.Length > 0)
{
name += " [" + title + "]";
}
string output = Path.Combine(Path.GetDirectoryName(filename), @"@" + name + ".bms");
if (map == null)
bms.GenerateSampleMap();
else
bms.SampleMap = map;
if (quantizeNotes > 0)
bms.Charts[0].QuantizeNoteOffsets(quantizeNotes);
bms.GenerateSampleTags();
bms.Write(mem, true);
File.WriteAllBytes(output, mem.ToArray());
}
}
static public void ConvertSounds(Sound[] sounds, string filename, float volume)
{
string name = Path.GetFileNameWithoutExtension(Path.GetFileName(filename));
string targetPath = Path.Combine(Path.GetDirectoryName(filename), name);
if (!Directory.Exists(targetPath))
Directory.CreateDirectory(targetPath);
int count = sounds.Length;
for (int j = 0; j < count; j++)
{
int sampleIndex = j + 1;
sounds[j].WriteFile(Path.Combine(targetPath, Scharfrichter.Codec.Util.ConvertToBMEString(sampleIndex, 4) + @".wav"), volume);
}
}
static private Configuration LoadConfig()
{
Configuration config = Configuration.ReadFile(configFileName);
config["BMS"].SetDefaultValue("QuantizeMeasure", 16);
config["BMS"].SetDefaultValue("QuantizeNotes", 192);
config["BMS"].SetDefaultString("Difficulty1", "Beginner");
config["BMS"].SetDefaultString("Difficulty2", "Normal");
config["BMS"].SetDefaultString("Difficulty3", "Hyper");
config["BMS"].SetDefaultString("Difficulty4", "Another");
config["BMS"].SetDefaultString("Players1", "1P");
config["BMS"].SetDefaultString("Players2", "2P");
config["BMS"].SetDefaultString("Players3", "DP");
config["IIDX"].SetDefaultString("Difficulty0", "3");
config["IIDX"].SetDefaultString("Difficulty1", "2");
config["IIDX"].SetDefaultString("Difficulty2", "4");
config["IIDX"].SetDefaultString("Difficulty3", "1");
config["IIDX"].SetDefaultString("Difficulty6", "3");
config["IIDX"].SetDefaultString("Difficulty7", "2");
config["IIDX"].SetDefaultString("Difficulty8", "4");
config["IIDX"].SetDefaultString("Difficulty9", "1");
config["IIDX"].SetDefaultString("Players0", "1");
config["IIDX"].SetDefaultString("Players1", "1");
config["IIDX"].SetDefaultString("Players2", "1");
config["IIDX"].SetDefaultString("Players3", "1");
config["IIDX"].SetDefaultString("Players6", "3");
config["IIDX"].SetDefaultString("Players7", "3");
config["IIDX"].SetDefaultString("Players8", "3");
config["IIDX"].SetDefaultString("Players9", "3");
return config;
}
static private Configuration LoadDB()
{
Configuration config = Configuration.ReadFile(databaseFileName);
return config;
}
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using COM = System.Runtime.InteropServices.ComTypes;
// Disable obsolete warnings about VarEnum and COM-marshaling APIs in CoreCLR
#pragma warning disable 618
namespace System.Management.Automation
{
internal static class ComInvoker
{
// DISP HRESULTS - may be returned by IDispatch.Invoke
private const int DISP_E_EXCEPTION = unchecked((int)0x80020009);
// LCID for en-US culture
private const int LCID_DEFAULT = 0x0409;
// The dispatch identifier for a parameter that receives the value of an assignment in a PROPERTYPUT.
// See https://msdn.microsoft.com/library/windows/desktop/ms221242(v=vs.85).aspx for details.
private const int DISPID_PROPERTYPUT = -3;
// Alias of GUID_NULL. It's a GUID set to all zero
private static readonly Guid s_IID_NULL = new Guid();
// Size of the Variant struct
private static readonly int s_variantSize = Marshal.SizeOf<Variant>();
/// <summary>
/// Make a by-Ref VARIANT value based on the passed-in VARIANT argument.
/// </summary>
/// <param name="srcVariantPtr">The source Variant pointer.</param>
/// <param name="destVariantPtr">The destination Variant pointer.</param>
private static unsafe void MakeByRefVariant(IntPtr srcVariantPtr, IntPtr destVariantPtr)
{
var srcVariant = (Variant*)srcVariantPtr;
var destVariant = (Variant*)destVariantPtr;
switch ((VarEnum)srcVariant->_typeUnion._vt)
{
case VarEnum.VT_EMPTY:
case VarEnum.VT_NULL:
// These cannot combine with VT_BYREF. Should try passing as a variant reference
// We follow the code in ComBinder to handle 'VT_EMPTY' and 'VT_NULL'
destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant);
destVariant->_typeUnion._vt = (ushort)VarEnum.VT_VARIANT | (ushort)VarEnum.VT_BYREF;
return;
case VarEnum.VT_RECORD:
// Representation of record is the same with or without byref
destVariant->_typeUnion._unionTypes._record._record = srcVariant->_typeUnion._unionTypes._record._record;
destVariant->_typeUnion._unionTypes._record._recordInfo = srcVariant->_typeUnion._unionTypes._record._recordInfo;
break;
case VarEnum.VT_VARIANT:
destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant);
break;
case VarEnum.VT_DECIMAL:
destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_decimal));
break;
default:
// All the other cases start at the same offset (it's a Union) so using &_i4 should work.
// This is the same code as in CLR implementation. It could be &_i1, &_i2 and etc. CLR implementation just prefer using &_i4.
destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_typeUnion._unionTypes._i4));
break;
}
destVariant->_typeUnion._vt = (ushort)(srcVariant->_typeUnion._vt | (ushort)VarEnum.VT_BYREF);
}
/// <summary>
/// Alloc memory for a VARIANT array with the specified length.
/// Also initialize the VARIANT elements to be the type 'VT_EMPTY'.
/// </summary>
/// <param name="length">Array length.</param>
/// <returns>Pointer to the array.</returns>
private static unsafe IntPtr NewVariantArray(int length)
{
IntPtr variantArray = Marshal.AllocCoTaskMem(s_variantSize * length);
for (int i = 0; i < length; i++)
{
IntPtr currentVarPtr = variantArray + s_variantSize * i;
var currentVar = (Variant*)currentVarPtr;
currentVar->_typeUnion._vt = (ushort)VarEnum.VT_EMPTY;
}
return variantArray;
}
/// <summary>
/// Generate the ByRef array indicating whether the corresponding argument is by-reference.
/// </summary>
/// <param name="parameters">Parameters retrieved from metadata.</param>
/// <param name="argumentCount">Count of arguments to pass in IDispatch.Invoke.</param>
/// <param name="isPropertySet">Indicate if we are handling arguments for PropertyPut/PropertyPutRef.</param>
/// <returns></returns>
internal static bool[] GetByRefArray(ParameterInformation[] parameters, int argumentCount, bool isPropertySet)
{
if (parameters.Length == 0)
{
return null;
}
var byRef = new bool[argumentCount];
int argsToProcess = argumentCount;
if (isPropertySet)
{
// If it's PropertySet, then the last value in arguments is the right-hand side value.
// There is no corresponding parameter for that value, so it's for sure not by-ref.
// Hence, set the last item of byRef array to be false.
argsToProcess = argumentCount - 1;
byRef[argsToProcess] = false;
}
Diagnostics.Assert(parameters.Length >= argsToProcess,
"There might be more parameters than argsToProcess due unspecified optional arguments");
for (int i = 0; i < argsToProcess; i++)
{
byRef[i] = parameters[i].isByRef;
}
return byRef;
}
/// <summary>
/// Invoke the COM member.
/// </summary>
/// <param name="target">IDispatch object.</param>
/// <param name="dispId">Dispatch identifier that identifies the member.</param>
/// <param name="args">Arguments passed in.</param>
/// <param name="byRef">Boolean array that indicates by-Ref parameters.</param>
/// <param name="invokeKind">Invocation kind.</param>
/// <returns></returns>
internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind)
{
Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in.");
Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length,
"If 'args' and 'byRef' are not null, then they should be one-on-one mapping.");
int argCount = args != null ? args.Length : 0;
int refCount = byRef != null ? byRef.Count(c => c) : 0;
IntPtr variantArgArray = IntPtr.Zero, dispIdArray = IntPtr.Zero, tmpVariants = IntPtr.Zero;
try
{
// Package arguments
if (argCount > 0)
{
variantArgArray = NewVariantArray(argCount);
int refIndex = 0;
for (int i = 0; i < argCount; i++)
{
// !! The arguments should be in REVERSED order!!
int actualIndex = argCount - i - 1;
IntPtr varArgPtr = variantArgArray + s_variantSize * actualIndex;
// If need to pass by ref, create a by-ref variant
if (byRef != null && byRef[i])
{
// Allocate memory for temporary VARIANTs used in by-ref marshalling
if (tmpVariants == IntPtr.Zero)
{
tmpVariants = NewVariantArray(refCount);
}
// Create a VARIANT that the by-ref VARIANT points to
IntPtr tmpVarPtr = tmpVariants + s_variantSize * refIndex;
Marshal.GetNativeVariantForObject(args[i], tmpVarPtr);
// Create the by-ref VARIANT
MakeByRefVariant(tmpVarPtr, varArgPtr);
refIndex++;
}
else
{
Marshal.GetNativeVariantForObject(args[i], varArgPtr);
}
}
}
var paramArray = new COM.DISPPARAMS[1];
paramArray[0].rgvarg = variantArgArray;
paramArray[0].cArgs = argCount;
if (invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUT || invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUTREF)
{
// For property putters, the first DISPID argument needs to be DISPID_PROPERTYPUT
dispIdArray = Marshal.AllocCoTaskMem(4); // Allocate 4 bytes to hold a 32-bit signed integer
Marshal.WriteInt32(dispIdArray, DISPID_PROPERTYPUT);
paramArray[0].cNamedArgs = 1;
paramArray[0].rgdispidNamedArgs = dispIdArray;
}
else
{
// Otherwise, no named parameters are necessary since powershell parser doesn't support named parameter
paramArray[0].cNamedArgs = 0;
paramArray[0].rgdispidNamedArgs = IntPtr.Zero;
}
// Make the call
EXCEPINFO info = default(EXCEPINFO);
object result = null;
try
{
// 'puArgErr' is set when IDispatch.Invoke fails with error code 'DISP_E_PARAMNOTFOUND' and 'DISP_E_TYPEMISMATCH'.
// Appropriate exceptions will be thrown in such cases, but FullCLR doesn't use 'puArgErr' in the exception handling, so we also ignore it.
uint puArgErrNotUsed = 0;
target.Invoke(dispId, s_IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed);
}
catch (Exception innerException)
{
// When 'IDispatch.Invoke' returns error code, CLR will raise exception based on internal HR-to-Exception mapping.
// Description of the return code can be found at https://msdn.microsoft.com/library/windows/desktop/ms221479(v=vs.85).aspx
// According to CoreCLR team (yzha), the exception needs to be wrapped as an inner exception of TargetInvocationException.
string exceptionMsg = null;
if (innerException.HResult == DISP_E_EXCEPTION)
{
// Invoke was successful but the actual underlying method failed.
// In this case, we use EXCEPINFO to get additional error info.
// Use EXCEPINFO.scode or EXCEPINFO.wCode as HR to construct the correct exception.
int code = info.scode != 0 ? info.scode : info.wCode;
innerException = Marshal.GetExceptionForHR(code, IntPtr.Zero) ?? innerException;
// Get the richer error description if it's available.
if (info.bstrDescription != IntPtr.Zero)
{
exceptionMsg = Marshal.PtrToStringBSTR(info.bstrDescription);
Marshal.FreeBSTR(info.bstrDescription);
}
// Free the BSTRs
if (info.bstrSource != IntPtr.Zero)
{
Marshal.FreeBSTR(info.bstrSource);
}
if (info.bstrHelpFile != IntPtr.Zero)
{
Marshal.FreeBSTR(info.bstrHelpFile);
}
}
var outerException = exceptionMsg == null
? new TargetInvocationException(innerException)
: new TargetInvocationException(exceptionMsg, innerException);
throw outerException;
}
// Now back propagate the by-ref arguments
if (refCount > 0)
{
for (int i = 0; i < argCount; i++)
{
// !! The arguments should be in REVERSED order!!
int actualIndex = argCount - i - 1;
// If need to pass by ref, back propagate
if (byRef != null && byRef[i])
{
args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex);
}
}
}
return result;
}
finally
{
// Free the variant argument array
if (variantArgArray != IntPtr.Zero)
{
for (int i = 0; i < argCount; i++)
{
VariantClear(variantArgArray + s_variantSize * i);
}
Marshal.FreeCoTaskMem(variantArgArray);
}
// Free the dispId array
if (dispIdArray != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(dispIdArray);
}
// Free the temporary variants created when handling by-Ref arguments
if (tmpVariants != IntPtr.Zero)
{
for (int i = 0; i < refCount; i++)
{
VariantClear(tmpVariants + s_variantSize * i);
}
Marshal.FreeCoTaskMem(tmpVariants);
}
}
}
/// <summary>
/// Clear variables of type VARIANTARG (or VARIANT) before the memory containing the VARIANTARG is freed.
/// </summary>
/// <param name="pVariant"></param>
[DllImport("oleaut32.dll")]
internal static extern void VariantClear(IntPtr pVariant);
/// <summary>
/// We have to declare 'bstrSource', 'bstrDescription' and 'bstrHelpFile' as pointers because
/// CLR marshalling layer would try to free those BSTRs by default and that is not correct.
/// Therefore, manually marshalling might be needed to extract 'bstrDescription'.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct EXCEPINFO
{
public short wCode;
public short wReserved;
public IntPtr bstrSource;
public IntPtr bstrDescription;
public IntPtr bstrHelpFile;
public int dwHelpContext;
public IntPtr pvReserved;
public IntPtr pfnDeferredFillIn;
public int scode;
}
/// <summary>
/// VARIANT type used for passing arguments in COM interop.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Variant
{
// Most of the data types in the Variant are carried in _typeUnion
[FieldOffset(0)]
internal TypeUnion _typeUnion;
// Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc.
// Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so
// TypeUnion._vt can still be used to encode the type.
[FieldOffset(0)]
internal Decimal _decimal;
[StructLayout(LayoutKind.Explicit)]
internal struct TypeUnion
{
[FieldOffset(0)]
internal ushort _vt;
[FieldOffset(2)]
internal ushort _wReserved1;
[FieldOffset(4)]
internal ushort _wReserved2;
[FieldOffset(6)]
internal ushort _wReserved3;
[FieldOffset(8)]
internal UnionTypes _unionTypes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Record
{
internal IntPtr _record;
internal IntPtr _recordInfo;
}
[StructLayout(LayoutKind.Explicit)]
internal struct UnionTypes
{
[FieldOffset(0)]
internal sbyte _i1;
[FieldOffset(0)]
internal Int16 _i2;
[FieldOffset(0)]
internal Int32 _i4;
[FieldOffset(0)]
internal Int64 _i8;
[FieldOffset(0)]
internal byte _ui1;
[FieldOffset(0)]
internal UInt16 _ui2;
[FieldOffset(0)]
internal UInt32 _ui4;
[FieldOffset(0)]
internal UInt64 _ui8;
[FieldOffset(0)]
internal Int32 _int;
[FieldOffset(0)]
internal UInt32 _uint;
[FieldOffset(0)]
internal Int16 _bool;
[FieldOffset(0)]
internal Int32 _error;
[FieldOffset(0)]
internal Single _r4;
[FieldOffset(0)]
internal double _r8;
[FieldOffset(0)]
internal Int64 _cy;
[FieldOffset(0)]
internal double _date;
[FieldOffset(0)]
internal IntPtr _bstr;
[FieldOffset(0)]
internal IntPtr _unknown;
[FieldOffset(0)]
internal IntPtr _dispatch;
[FieldOffset(0)]
internal IntPtr _pvarVal;
[FieldOffset(0)]
internal IntPtr _byref;
[FieldOffset(0)]
internal Record _record;
}
}
}
}
|
//-----------------------------------------------------------------------
// Copyright © Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.PowerShell.Commands
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands.ShowCommandExtension;
/// <summary>
/// Show-Command displays a GUI for a cmdlet, or for all cmdlets if no specific cmdlet is specified.
/// </summary>
[Cmdlet(VerbsCommon.Show, "Command", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217448")]
public class ShowCommandCommand : PSCmdlet, IDisposable
{
#region Private Fields
/// <summary>
/// Set to true when ProcessRecord is reached, since it will always open a window
/// </summary>
private bool _hasOpenedWindow;
/// <summary>
/// Determines if the command should be sent to the pipeline as a string instead of run.
/// </summary>
private bool _passThrough;
/// <summary>
/// Uses ShowCommandProxy to invoke WPF GUI object.
/// </summary>
private ShowCommandProxy _showCommandProxy;
/// <summary>
/// Data container for all cmdlets. This is populated when show-command is called with no command name.
/// </summary>
private List<ShowCommandCommandInfo> _commands;
/// <summary>
/// List of modules that have been loaded indexed by module name
/// </summary>
private Dictionary<string, ShowCommandModuleInfo> _importedModules;
/// <summary>
/// Record the EndProcessing error.
/// </summary>
private PSDataCollection<ErrorRecord> _errors = new PSDataCollection<ErrorRecord>();
/// <summary>
/// Field used for the NoCommonParameter parameter.
/// </summary>
private SwitchParameter _noCommonParameter;
/// <summary>
/// Object used for ShowCommand with a command name that holds the view model created for the command
/// </summary>
private object _commandViewModelObj;
#endregion
/// <summary>
/// Finalizes an instance of the ShowCommandCommand class
/// </summary>
~ShowCommandCommand()
{
this.Dispose(false);
}
#region Input Cmdlet Parameter
/// <summary>
/// Gets or sets the command name.
/// </summary>
[Parameter(Position = 0)]
[Alias("CommandName")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the Width.
/// </summary>
[Parameter]
[ValidateRange(300, Int32.MaxValue)]
public double Height { get; set; }
/// <summary>
/// Gets or sets the Width.
/// </summary>
[Parameter]
[ValidateRange(300, Int32.MaxValue)]
public double Width { get; set; }
/// <summary>
/// Gets or sets a value indicating Common Parameters should not be displayed
/// </summary>
[Parameter]
public SwitchParameter NoCommonParameter
{
get { return _noCommonParameter; }
set { _noCommonParameter = value; }
}
/// <summary>
/// Gets or sets a value indicating errors should not cause a message window to be displayed
/// </summary>
[Parameter]
public SwitchParameter ErrorPopup { get; set; }
/// <summary>
/// Gets or sets a value indicating the command should be sent to the pipeline as a string instead of run
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get { return _passThrough; }
set { _passThrough = value; }
} // PassThru
#endregion
#region Public and Protected Methods
/// <summary>
/// Executes a PowerShell script, writing the output objects to the pipeline.
/// </summary>
/// <param name="script">Script to execute</param>
public void RunScript(string script)
{
if (_showCommandProxy == null || string.IsNullOrEmpty(script))
{
return;
}
if (_passThrough)
{
this.WriteObject(script);
return;
}
if (ErrorPopup)
{
this.RunScriptSilentlyAndWithErrorHookup(script);
return;
}
if (_showCommandProxy.HasHostWindow)
{
if (!_showCommandProxy.SetPendingISECommand(script))
{
this.RunScriptSilentlyAndWithErrorHookup(script);
}
return;
}
if (!ConsoleInputWithNativeMethods.AddToConsoleInputBuffer(script, true))
{
this.WriteDebug(FormatAndOut_out_gridview.CannotWriteToConsoleInputBuffer);
this.RunScriptSilentlyAndWithErrorHookup(script);
}
}
/// <summary>
/// Dispose method in IDisposable
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Initialize a proxy instance for show-command.
/// </summary>
protected override void BeginProcessing()
{
_showCommandProxy = new ShowCommandProxy(this);
if (_showCommandProxy.ScreenHeight < this.Height)
{
ErrorRecord error = new ErrorRecord(
new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", _showCommandProxy.ScreenHeight)),
"PARAMETER_DATA_ERROR",
ErrorCategory.InvalidData,
null);
this.ThrowTerminatingError(error);
}
if (_showCommandProxy.ScreenWidth < this.Width)
{
ErrorRecord error = new ErrorRecord(
new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", _showCommandProxy.ScreenWidth)),
"PARAMETER_DATA_ERROR",
ErrorCategory.InvalidData,
null);
this.ThrowTerminatingError(error);
}
}
/// <summary>
/// ProcessRecord with or without CommandName.
/// </summary>
protected override void ProcessRecord()
{
if (Name == null)
{
_hasOpenedWindow = this.CanProcessRecordForAllCommands();
}
else
{
_hasOpenedWindow = this.CanProcessRecordForOneCommand();
}
}
/// <summary>
/// Optionally displays errors in a message
/// </summary>
protected override void EndProcessing()
{
if (!_hasOpenedWindow)
{
return;
}
// We wait untill the window is loaded and then activate it
// to work arround the console window gaining activation somewhere
// in the end of ProcessRecord, which causes the keyboard focus
// (and use oif tab key to focus controls) to go away from the window
_showCommandProxy.WindowLoaded.WaitOne();
_showCommandProxy.ActivateWindow();
this.WaitForWindowClosedOrHelpNeeded();
this.RunScript(_showCommandProxy.GetScript());
if (_errors.Count == 0 || !ErrorPopup)
{
return;
}
StringBuilder errorString = new StringBuilder();
for (int i = 0; i < _errors.Count; i++)
{
if (i != 0)
{
errorString.AppendLine();
}
ErrorRecord error = _errors[i];
errorString.Append(error.Exception.Message);
}
_showCommandProxy.ShowErrorString(errorString.ToString());
}
/// <summary>
/// StopProcessing is called close the window when user press Ctrl+C in the command prompt.
/// </summary>
protected override void StopProcessing()
{
_showCommandProxy.CloseWindow();
}
#endregion
#region Private Methods
/// <summary>
/// Runs the script in a new PowerShell instance and hooks up error stream to potentially display error popup.
/// This method has the inconvenience of not showing to the console user the script being executed.
/// </summary>
/// <param name="script">script to be run</param>
private void RunScriptSilentlyAndWithErrorHookup(string script)
{
// errors are not created here, because there is a field for it used in the final pop up
PSDataCollection<object> output = new PSDataCollection<object>();
output.DataAdded += new EventHandler<DataAddedEventArgs>(this.Output_DataAdded);
_errors.DataAdded += new EventHandler<DataAddedEventArgs>(this.Error_DataAdded);
PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
ps.Streams.Error = _errors;
ps.Commands.AddScript(script);
ps.Invoke(null, output, null);
}
/// <summary>
/// Issues an error when this.commandName was not found
/// </summary>
private void IssueErrorForNoCommand()
{
InvalidOperationException errorException = new InvalidOperationException(
String.Format(
CultureInfo.CurrentUICulture,
FormatAndOut_out_gridview.CommandNotFound,
Name));
this.ThrowTerminatingError(new ErrorRecord(errorException, "NoCommand", ErrorCategory.InvalidOperation, Name));
}
/// <summary>
/// Issues an error when there is more than one command matching this.commandName
/// </summary>
private void IssueErrorForMoreThanOneCommand()
{
InvalidOperationException errorException = new InvalidOperationException(
String.Format(
CultureInfo.CurrentUICulture,
FormatAndOut_out_gridview.MoreThanOneCommand,
Name,
"Show-Command"));
this.ThrowTerminatingError(new ErrorRecord(errorException, "MoreThanOneCommand", ErrorCategory.InvalidOperation, Name));
}
/// <summary>
/// Called from CommandProcessRecord to run the command that will get the CommandInfo and list of modules
/// </summary>
/// <param name="command">command to be retrieved</param>
/// <param name="modules">list of loaded modules</param>
private void GetCommandInfoAndModules(out CommandInfo command, out Dictionary<string, ShowCommandModuleInfo> modules)
{
command = null;
modules = null;
string commandText = _showCommandProxy.GetShowCommandCommand(Name, true);
Collection<PSObject> commandResults = this.InvokeCommand.InvokeScript(commandText);
object[] commandObjects = (object[])commandResults[0].BaseObject;
object[] moduleObjects = (object[])commandResults[1].BaseObject;
if (commandResults == null || moduleObjects == null || commandObjects.Length == 0)
{
this.IssueErrorForNoCommand();
return;
}
if (commandObjects.Length > 1)
{
this.IssueErrorForMoreThanOneCommand();
}
command = ((PSObject)commandObjects[0]).BaseObject as CommandInfo;
if (command == null)
{
this.IssueErrorForNoCommand();
return;
}
if (command.CommandType == CommandTypes.Alias)
{
commandText = _showCommandProxy.GetShowCommandCommand(command.Definition, false);
commandResults = this.InvokeCommand.InvokeScript(commandText);
if (commandResults == null || commandResults.Count != 1)
{
this.IssueErrorForNoCommand();
return;
}
command = (CommandInfo)commandResults[0].BaseObject;
}
modules = _showCommandProxy.GetImportedModulesDictionary(moduleObjects);
}
/// <summary>
/// ProcessRecord when a command name is specified.
/// </summary>
/// <returns>true if there was no exception processing this record</returns>
private bool CanProcessRecordForOneCommand()
{
CommandInfo commandInfo;
this.GetCommandInfoAndModules(out commandInfo, out _importedModules);
Diagnostics.Assert(commandInfo != null, "GetCommandInfoAndModules would throw a terminating error/exception");
try
{
_commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.IndexOf('\\') != -1);
_showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough);
}
catch (TargetInvocationException ti)
{
this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForOneCommand", ErrorCategory.InvalidOperation, Name));
return false;
}
return true;
}
/// <summary>
/// ProcessRecord when a command name is not specified.
/// </summary>
/// <returns>true if there was no exception processing this record</returns>
private bool CanProcessRecordForAllCommands()
{
Collection<PSObject> rawCommands = this.InvokeCommand.InvokeScript(_showCommandProxy.GetShowAllModulesCommand());
_commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject);
_importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject);
try
{
_showCommandProxy.ShowAllModulesWindow(_importedModules, _commands, _noCommonParameter.ToBool(), _passThrough);
}
catch (TargetInvocationException ti)
{
this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForAllCommands", ErrorCategory.InvalidOperation, Name));
return false;
}
return true;
}
/// <summary>
/// Waits untill the window has been closed answering HelpNeeded events
/// </summary>
private void WaitForWindowClosedOrHelpNeeded()
{
do
{
int which = WaitHandle.WaitAny(new WaitHandle[] { _showCommandProxy.WindowClosed, _showCommandProxy.HelpNeeded, _showCommandProxy.ImportModuleNeeded });
if (which == 0)
{
break;
}
if (which == 1)
{
Collection<PSObject> helpResults = this.InvokeCommand.InvokeScript(_showCommandProxy.GetHelpCommand(_showCommandProxy.CommandNeedingHelp));
_showCommandProxy.DisplayHelp(helpResults);
continue;
}
Diagnostics.Assert(which == 2, "which is 0,1 or 2 and 0 and 1 have been eliminated in the ifs above");
string commandToRun = _showCommandProxy.GetImportModuleCommand(_showCommandProxy.ParentModuleNeedingImportModule);
Collection<PSObject> rawCommands;
try
{
rawCommands = this.InvokeCommand.InvokeScript(commandToRun);
}
catch (RuntimeException e)
{
_showCommandProxy.ImportModuleFailed(e);
continue;
}
_commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject);
_importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject);
_showCommandProxy.ImportModuleDone(_importedModules, _commands);
continue;
}
while (true);
}
/// <summary>
/// Writes the output of a script being run into the pipeline
/// </summary>
/// <param name="sender">output collection</param>
/// <param name="e">output event</param>
private void Output_DataAdded(object sender, DataAddedEventArgs e)
{
this.WriteObject(((PSDataCollection<object>)sender)[e.Index]);
}
/// <summary>
/// Writes the errors of a script being run into the pipeline
/// </summary>
/// <param name="sender">error collection</param>
/// <param name="e">error event</param>
private void Error_DataAdded(object sender, DataAddedEventArgs e)
{
this.WriteError(((PSDataCollection<ErrorRecord>)sender)[e.Index]);
}
/// <summary>
/// Implements IDisposable logic
/// </summary>
/// <param name="isDisposing">true if being called from Dispose</param>
private void Dispose(bool isDisposing)
{
if (isDisposing)
{
if (_errors != null)
{
_errors.Dispose();
_errors = null;
}
}
}
#endregion
/// <summary>
/// Wraps interop code for console input buffer
/// </summary>
internal static class ConsoleInputWithNativeMethods
{
/// <summary>
/// Constant used in calls to GetStdHandle
/// </summary>
internal const int STD_INPUT_HANDLE = -10;
/// <summary>
/// Adds a string to the console input buffer
/// </summary>
/// <param name="str">string to add to console input buffer</param>
/// <param name="newLine">true to add Enter after the string</param>
/// <returns>true if it was successful in adding all characters to console input buffer</returns>
internal static bool AddToConsoleInputBuffer(string str, bool newLine)
{
IntPtr handle = ConsoleInputWithNativeMethods.GetStdHandle(ConsoleInputWithNativeMethods.STD_INPUT_HANDLE);
if (handle == IntPtr.Zero)
{
return false;
}
uint strLen = (uint)str.Length;
ConsoleInputWithNativeMethods.INPUT_RECORD[] records = new ConsoleInputWithNativeMethods.INPUT_RECORD[strLen + (newLine ? 1 : 0)];
for (int i = 0; i < strLen; i++)
{
ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref records[i], str[i]);
}
uint written;
if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, records, strLen, out written) || written != strLen)
{
// I do not know of a case where written is not going to be strlen. Maybe for some character that
// is not supported in the console. The API suggests this can happen,
// so we handle it by returning false
return false;
}
// Enter is written separately, because if this is a command, and one of the characters in the command was not written
// (written != strLen) it is desireable to fail (return false) before typing enter and running the command
if (newLine)
{
ConsoleInputWithNativeMethods.INPUT_RECORD[] enterArray = new ConsoleInputWithNativeMethods.INPUT_RECORD[1];
ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref enterArray[0], (char)13);
written = 0;
if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, enterArray, 1, out written))
{
// I don't think this will happen
return false;
}
Diagnostics.Assert(written == 1, "only Enter is being added and it is a supported character");
}
return true;
}
/// <summary>
/// Gets the console handle
/// </summary>
/// <param name="nStdHandle">which console handle to get</param>
/// <returns>the console handle</returns>
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle);
/// <summary>
/// Writes to the console input buffer
/// </summary>
/// <param name="hConsoleInput">console handle</param>
/// <param name="lpBuffer">inputs to be written</param>
/// <param name="nLength">number of inputs to be written</param>
/// <param name="lpNumberOfEventsWritten">returned number of inputs actually written</param>
/// <returns>0 if the function fails</returns>
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WriteConsoleInput(
IntPtr hConsoleInput,
INPUT_RECORD[] lpBuffer,
uint nLength,
out uint lpNumberOfEventsWritten);
/// <summary>
/// A record to be added to the console buffer
/// </summary>
internal struct INPUT_RECORD
{
/// <summary>
/// The proper event type for a KeyEvent KEY_EVENT_RECORD
/// </summary>
internal const int KEY_EVENT = 0x0001;
/// <summary>
/// input buffer event type
/// </summary>
internal ushort EventType;
/// <summary>
/// The actual event. The original structure is a union of many others, but this is the largest of them
/// And we don't need other kinds of events
/// </summary>
internal KEY_EVENT_RECORD KeyEvent;
/// <summary>
/// Sets the necessary fields of <paramref name="inputRecord"/> for a KeyDown event for the <paramref name="character"/>
/// </summary>
/// <param name="inputRecord">input record to be set</param>
/// <param name="character">character to set the record with</param>
internal static void SetInputRecord(ref INPUT_RECORD inputRecord, char character)
{
inputRecord.EventType = INPUT_RECORD.KEY_EVENT;
inputRecord.KeyEvent.bKeyDown = true;
inputRecord.KeyEvent.UnicodeChar = character;
}
}
/// <summary>
/// Type of INPUT_RECORD which is a key
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct KEY_EVENT_RECORD
{
/// <summary>
/// true for key down and false for key up, but only needed if wVirtualKeyCode is used
/// </summary>
internal bool bKeyDown;
/// <summary>
/// repeat count
/// </summary>
internal ushort wRepeatCount;
/// <summary>
/// virtual key code
/// </summary>
internal ushort wVirtualKeyCode;
/// <summary>
/// virtual key scan code
/// </summary>
internal ushort wVirtualScanCode;
/// <summary>
/// character in input. If this is specified, wVirtualKeyCode, and others don't need to be
/// </summary>
internal char UnicodeChar;
/// <summary>
/// State of keys like Shift and control
/// </summary>
internal uint dwControlKeyState;
}
}
}
}
|
using System;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ContextMenuTests
{
private Mock<IPopupImpl> popupImpl;
private MouseTestHelper _mouse = new MouseTestHelper();
[Fact]
public void ContextRequested_Opens_ContextMenu()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
int openedCount = 0;
sut.MenuOpened += (sender, args) =>
{
openedCount++;
};
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
Assert.Equal(1, openedCount);
}
}
[Fact]
public void ContextMenu_Is_Opened_When_ContextFlyout_Is_Also_Set()
{
// We have this test for backwards compatability with the code that already sets custom ContextMenu.
using (Application())
{
var sut = new ContextMenu();
var flyout = new Flyout();
var target = new Panel
{
ContextMenu = sut,
ContextFlyout = flyout
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
Assert.False(flyout.IsOpen);
}
}
[Fact]
public void KeyUp_Raised_On_Target_Opens_ContextFlyout()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var contextRequestedCount = 0;
target.AddHandler(Control.ContextRequestedEvent, (s, a) => contextRequestedCount++, Interactivity.RoutingStrategies.Tunnel);
var window = PreparedWindow(target);
window.Show();
target.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = Key.Apps, Source = window });
Assert.True(sut.IsOpen);
Assert.Equal(1, contextRequestedCount);
}
}
[Fact]
public void KeyUp_Raised_On_Flyout_Closes_Opened_ContextMenu()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
sut.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = Key.Apps, Source = window });
Assert.False(sut.IsOpen);
}
}
[Fact]
public void Opening_Raises_Single_Opened_Event()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
int openedCount = 0;
sut.MenuOpened += (sender, args) =>
{
openedCount++;
};
sut.Open(target);
Assert.Equal(1, openedCount);
}
}
[Fact]
public void Open_Should_Use_Default_Control()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
bool opened = false;
sut.MenuOpened += (sender, args) =>
{
opened = true;
};
sut.Open();
Assert.True(opened);
}
}
[Fact]
public void Open_Should_Raise_Exception_If_AlreadyDetached()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.ContextMenu = null;
Assert.ThrowsAny<Exception>(()=> sut.Open());
}
}
[Fact]
public void Closing_Raises_Single_Closed_Event()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
sut.Open(target);
int closedCount = 0;
sut.MenuClosed += (sender, args) =>
{
closedCount++;
};
sut.Close();
Assert.Equal(1, closedCount);
}
}
[Fact]
public void Cancel_Light_Dismiss_Closing_Keeps_Flyout_Open()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var window = PreparedWindow();
window.Width = 100;
window.Height = 100;
var button = new Button
{
Height = 10,
Width = 10,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
VerticalAlignment = Layout.VerticalAlignment.Top
};
window.Content = button;
window.ApplyTemplate();
window.Show();
var tracker = 0;
var c = new ContextMenu();
c.ContextMenuClosing += (s, e) =>
{
tracker++;
e.Cancel = true;
};
button.ContextMenu = c;
c.Open(button);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Down(overlay, MouseButton.Left, new Point(90, 90));
_mouse.Up(button, MouseButton.Left, new Point(90, 90));
Assert.Equal(1, tracker);
Assert.True(c.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Never);
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(1));
}
}
[Fact]
public void Light_Dismiss_Closes_Flyout()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var window = PreparedWindow();
window.Width = 100;
window.Height = 100;
var button = new Button
{
Height = 10,
Width = 10,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
VerticalAlignment = Layout.VerticalAlignment.Top
};
window.Content = button;
window.ApplyTemplate();
window.Show();
var c = new ContextMenu();
c.PlacementMode = PlacementMode.Bottom;
c.Open(button);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Down(overlay, MouseButton.Left, new Point(90, 90));
_mouse.Up(button, MouseButton.Left, new Point(90, 90));
Assert.False(c.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Exactly(1));
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(1));
}
}
[Fact]
public void Clicking_On_Control_Toggles_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay);
_mouse.Up(target);
Assert.False(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Once);
popupImpl.Verify(x => x.Hide(), Times.Once);
}
}
[Fact]
public void Right_Clicking_On_Control_Twice_Re_Opens_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay, MouseButton.Right);
_mouse.Up(target, MouseButton.Right);
Assert.True(sut.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Once);
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(2));
}
}
[Fact]
public void Context_Menu_Can_Be_Shared_Between_Controls_Even_After_A_Control_Is_Removed_From_Visual_Tree()
{
using (Application())
{
var sut = new ContextMenu();
var target1 = new Panel
{
ContextMenu = sut
};
var target2 = new Panel
{
ContextMenu = sut
};
var sp = new StackPanel { Children = { target1, target2 } };
var window = new Window { Content = sp };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
_mouse.Click(target1, MouseButton.Right);
Assert.True(sut.IsOpen);
sp.Children.Remove(target1);
Assert.False(sut.IsOpen);
_mouse.Click(target2, MouseButton.Right);
Assert.True(sut.IsOpen);
}
}
[Fact]
public void Cancelling_Opening_Does_Not_Show_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
bool eventCalled = false;
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
new Window { Content = target };
sut.ContextMenuOpening += (c, e) => { eventCalled = true; e.Cancel = true; };
_mouse.Click(target, MouseButton.Right);
Assert.True(eventCalled);
Assert.False(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Never);
}
}
[Fact]
public void Can_Set_Clear_ContextMenu_Property()
{
using (Application())
{
var target = new ContextMenu();
var control = new Panel();
control.ContextMenu = target;
control.ContextMenu = null;
}
}
[Fact]
public void Context_Menu_In_Resources_Can_Be_Shared()
{
using (Application())
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Resources>
<ContextMenu x:Key='contextMenu'>
<MenuItem>Foo</MenuItem>
</ContextMenu>
</Window.Resources>
<StackPanel>
<TextBlock Name='target1' ContextMenu='{StaticResource contextMenu}'/>
<TextBlock Name='target2' ContextMenu='{StaticResource contextMenu}'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target1 = window.Find<TextBlock>("target1");
var target2 = window.Find<TextBlock>("target2");
var mouse = new MouseTestHelper();
Assert.NotNull(target1.ContextMenu);
Assert.NotNull(target2.ContextMenu);
Assert.Same(target1.ContextMenu, target2.ContextMenu);
window.Show();
var menu = target1.ContextMenu;
mouse.Click(target1, MouseButton.Right);
Assert.True(menu.IsOpen);
mouse.Click(target2, MouseButton.Right);
Assert.True(menu.IsOpen);
}
}
[Fact]
public void Context_Menu_Can_Be_Set_In_Style()
{
using (Application())
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='TextBlock'>
<Setter Property='ContextMenu'>
<ContextMenu>
<MenuItem>Foo</MenuItem>
</ContextMenu>
</Setter>
</Style>
</Window.Styles>
<StackPanel>
<TextBlock Name='target1'/>
<TextBlock Name='target2'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target1 = window.Find<TextBlock>("target1");
var target2 = window.Find<TextBlock>("target2");
var mouse = new MouseTestHelper();
Assert.NotNull(target1.ContextMenu);
Assert.NotNull(target2.ContextMenu);
Assert.Same(target1.ContextMenu, target2.ContextMenu);
window.Show();
var menu = target1.ContextMenu;
mouse.Click(target1, MouseButton.Right);
Assert.True(menu.IsOpen);
mouse.Click(target2, MouseButton.Right);
Assert.True(menu.IsOpen);
}
}
[Fact]
public void Cancelling_Closing_Leaves_ContextMenuOpen()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
bool eventCalled = false;
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
sut.ContextMenuClosing += (c, e) => { eventCalled = true; e.Cancel = true; };
window.Show();
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay, MouseButton.Right);
_mouse.Up(target, MouseButton.Right);
Assert.True(eventCalled);
Assert.True(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Once());
popupImpl.Verify(x => x.Hide(), Times.Never);
}
}
private Window PreparedWindow(object content = null)
{
var renderer = new Mock<IRenderer>();
var platform = AvaloniaLocator.Current.GetService<IWindowingPlatform>();
var windowImpl = Mock.Get(platform.CreateWindow());
windowImpl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object);
var w = new Window(windowImpl.Object) { Content = content };
w.ApplyTemplate();
w.Presenter.ApplyTemplate();
return w;
}
private IDisposable Application()
{
var screen = new PixelRect(new PixelPoint(), new PixelSize(100, 100));
var screenImpl = new Mock<IScreenImpl>();
screenImpl.Setup(x => x.ScreenCount).Returns(1);
screenImpl.Setup(X => X.AllScreens).Returns( new[] { new Screen(1, screen, screen, true) });
var windowImpl = MockWindowingPlatform.CreateWindowMock();
popupImpl = MockWindowingPlatform.CreatePopupMock(windowImpl.Object);
popupImpl.SetupGet(x => x.RenderScaling).Returns(1);
windowImpl.Setup(x => x.CreatePopup()).Returns(popupImpl.Object);
windowImpl.Setup(x => x.Screen).Returns(screenImpl.Object);
var services = TestServices.StyledWindow.With(
inputManager: new InputManager(),
windowImpl: windowImpl.Object,
windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object, x => popupImpl.Object));
return UnitTestApplication.Start(services);
}
}
}
|
namespace AngleSharp.Dom
{
using AngleSharp.Attributes;
using System;
/// <summary>
/// The Range interface represents a fragment of a document that can
/// contain nodes and parts of text nodes in a given document.
/// </summary>
[DomName("Range")]
public interface IRange
{
/// <summary>
/// Gets the node that starts the container.
/// </summary>
[DomName("startContainer")]
INode Head { get; }
/// <summary>
/// Gets the offset of the StartContainer in the document.
/// </summary>
[DomName("startOffset")]
Int32 Start { get; }
/// <summary>
/// Gets the node that ends the container.
/// </summary>
[DomName("endContainer")]
INode Tail { get; }
/// <summary>
/// Gets the offset of the EndContainer in the document.
/// </summary>
[DomName("endOffset")]
Int32 End { get; }
/// <summary>
/// Gets a value that indicates if the representation is collapsed.
/// </summary>
[DomName("collapsed")]
Boolean IsCollapsed { get; }
/// <summary>
/// Gets the common ancestor node of the contained range.
/// </summary>
[DomName("commonAncestorContainer")]
INode CommonAncestor { get; }
/// <summary>
/// Selects the start of the given range by using the given reference
/// node and a relative offset.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
/// <param name="offset">
/// The offset relative to the reference node.
/// </param>
[DomName("setStart")]
void StartWith(INode refNode, Int32 offset);
/// <summary>
/// Selects the end of the given range by using the given reference
/// node and a relative offset.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
/// <param name="offset">
/// The offset relative to the reference node.
/// </param>
[DomName("setEnd")]
void EndWith(INode refNode, Int32 offset);
/// <summary>
/// Selects the start of the given range by using an inclusive
/// reference node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setStartBefore")]
void StartBefore(INode refNode);
/// <summary>
/// Selects the end of the given range by using an inclusive reference
/// node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setEndBefore")]
void EndBefore(INode refNode);
/// <summary>
/// Selects the start of the given range by using an exclusive
/// reference node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setStartAfter")]
void StartAfter(INode refNode);
/// <summary>
/// Selects the end of the given range by using an exclusive reference
/// node.
/// </summary>
/// <param name="refNode">The referenced node.</param>
[DomName("setEndAfter")]
void EndAfter(INode refNode);
/// <summary>
/// Collapses the range to a single level.
/// </summary>
/// <param name="toStart">
/// Determines if only the first level should be selected.
/// </param>
[DomName("collapse")]
void Collapse(Boolean toStart);
/// <summary>
/// Selects the contained node.
/// </summary>
/// <param name="refNode">The node to use.</param>
[DomName("selectNode")]
void Select(INode refNode);
/// <summary>
/// Selects the contained nodes by taking a reference node as origin.
/// </summary>
/// <param name="refNode">The reference node.</param>
[DomName("selectNodeContents")]
void SelectContent(INode refNode);
/// <summary>
/// Clears the contained nodes.
/// </summary>
[DomName("deleteContents")]
void ClearContent();
/// <summary>
/// Clears the node representation and returns a document fragment with
/// the originally contained nodes.
/// </summary>
/// <returns>The document fragment containing the nodes.</returns>
[DomName("extractContents")]
IDocumentFragment ExtractContent();
/// <summary>
/// Creates a document fragement of the contained nodes.
/// </summary>
/// <returns>The created document fragment.</returns>
[DomName("cloneContents")]
IDocumentFragment CopyContent();
/// <summary>
/// Inserts a node into the range.
/// </summary>
/// <param name="node">The node to include.</param>
[DomName("insertNode")]
void Insert(INode node);
/// <summary>
/// Includes the given node with its siblings in the range.
/// </summary>
/// <param name="newParent">The range to surround.</param>
[DomName("surroundContents")]
void Surround(INode newParent);
/// <summary>
/// Creates a copy of this range.
/// </summary>
/// <returns>The copy representing the same range.</returns>
[DomName("cloneRange")]
IRange Clone();
/// <summary>
/// Detaches the range from the DOM tree.
/// </summary>
[DomName("detach")]
void Detach();
/// <summary>
/// Checks if the given node is within this range by using a offset.
/// </summary>
/// <param name="node">The node to check for.</param>
/// <param name="offset">The offset to use.</param>
/// <returns>
/// True if the point is within the range, otherwise false.
/// </returns>
[DomName("isPointInRange")]
Boolean Contains(INode node, Int32 offset);
/// <summary>
/// Compares the boundary points of the range.
/// </summary>
/// <param name="how">
/// Determines how these points should be compared.
/// </param>
/// <param name="sourceRange">
/// The range of the other boundary points.
/// </param>
/// <returns>A relative position.</returns>
[DomName("compareBoundaryPoints")]
RangePosition CompareBoundaryTo(RangeType how, IRange sourceRange);
/// <summary>
/// Compares the node to the given offset and returns the relative
/// position.
/// </summary>
/// <param name="node">The node to use.</param>
/// <param name="offset">The offset to use.</param>
/// <returns>The relative position in the range.</returns>
[DomName("comparePoint")]
RangePosition CompareTo(INode node, Int32 offset);
/// <summary>
/// Checks if the given node is contained in this range.
/// </summary>
/// <param name="node">The node to check for.</param>
/// <returns>
/// True if the node is within the range, otherwise false.
/// </returns>
[DomName("intersectsNode")]
Boolean Intersects(INode node);
}
}
|
// 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export, Shared]
internal partial class AnalyzerConfigDocumentAsSolutionItemHandler : IDisposable
{
private static readonly string LocalRegistryPath = $@"Roslyn\Internal\{nameof(AnalyzerConfigDocumentAsSolutionItemHandler)}\";
private static readonly Option<bool> NeverShowAgain = new Option<bool>(nameof(AnalyzerConfigDocumentAsSolutionItemHandler), nameof(NeverShowAgain),
defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeverShowAgain)));
private readonly VisualStudioWorkspace _workspace;
private readonly IThreadingContext _threadingContext;
private DTE? _dte;
private bool _infoBarShownForCurrentSolution;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerConfigDocumentAsSolutionItemHandler(
VisualStudioWorkspace workspace,
IThreadingContext threadingContext)
{
_workspace = workspace;
_threadingContext = threadingContext;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
}
public void Initialize(IServiceProvider serviceProvider)
=> _dte = (DTE)serviceProvider.GetService(typeof(DTE));
void IDisposable.Dispose()
=> _workspace.WorkspaceChanged -= OnWorkspaceChanged;
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
_infoBarShownForCurrentSolution = false;
return;
// Check if a new analyzer config document was added
case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:
break;
default:
return;
}
// Bail out if we have a null DTE instance or we have already shown the info bar for current solution.
if (_dte == null ||
_infoBarShownForCurrentSolution)
{
return;
}
// Check if added analyzer config document is at the root of the current solution.
var analyzerConfigDocumentFilePath = e.NewSolution.GetAnalyzerConfigDocument(e.DocumentId)?.FilePath;
var analyzerConfigDirectory = PathUtilities.GetDirectoryName(analyzerConfigDocumentFilePath);
var solutionDirectory = PathUtilities.GetDirectoryName(e.NewSolution.FilePath);
if (analyzerConfigDocumentFilePath == null ||
analyzerConfigDirectory == null ||
analyzerConfigDirectory != solutionDirectory)
{
return;
}
// Check if user has explicitly disabled the suggestion to add newly added analyzer config document as solution item.
if (_workspace.Options.GetOption(NeverShowAgain))
{
return;
}
// Kick off a task to show info bar to make it a solution item.
Task.Run(async () =>
{
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();
var solution = (Solution2)_dte.Solution;
if (VisualStudioAddSolutionItemService.TryGetExistingSolutionItemsFolder(solution, analyzerConfigDocumentFilePath, out _, out var hasExistingSolutionItem) &&
hasExistingSolutionItem)
{
return;
}
if (!_infoBarShownForCurrentSolution)
{
_infoBarShownForCurrentSolution = true;
var infoBarService = _workspace.Services.GetRequiredService<IInfoBarService>();
infoBarService.ShowInfoBarInGlobalView(
ServicesVSResources.A_new_editorconfig_file_was_detected_at_the_root_of_your_solution_Would_you_like_to_make_it_a_solution_item,
GetInfoBarUIItems().ToArray());
}
});
return;
// Local functions
IEnumerable<InfoBarUI> GetInfoBarUIItems()
{
// Yes - add editorconfig solution item.
yield return new InfoBarUI(
title: ServicesVSResources.Yes,
kind: InfoBarUI.UIKind.Button,
action: AddEditorconfigSolutionItem,
closeAfterAction: true);
// No - do not add editorconfig solution item.
yield return new InfoBarUI(
title: ServicesVSResources.No,
kind: InfoBarUI.UIKind.Button,
action: () => { },
closeAfterAction: true);
// Don't show the InfoBar again link
yield return new InfoBarUI(title: ServicesVSResources.Never_show_this_again,
kind: InfoBarUI.UIKind.Button,
action: () => _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options.WithChangedOption(NeverShowAgain, true))),
closeAfterAction: true);
}
void AddEditorconfigSolutionItem()
{
var addSolutionItemService = _workspace.Services.GetRequiredService<IAddSolutionItemService>();
addSolutionItemService.AddSolutionItemAsync(analyzerConfigDocumentFilePath, CancellationToken.None).Wait();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using u8 = System.Byte;
using u16 = System.UInt16;
using s32 = System.Int32;
using u32 = System.UInt32;
using gps_time_t = System.UInt64;
namespace MissionPlanner.Utilities
{
public class rtcm3 : ICorrections
{
const byte RTCM3PREAMB = 0xD3;
int step = 0;
byte[] buffer = new u8[1024 * 4];
u32 payloadlen = 0;
int msglencount = 0;
rtcmpreamble pre;
public int Read(byte data)
{
switch (step)
{
default:
case 0:
if (data == RTCM3PREAMB)
{
step = 1;
buffer[0] = data;
}
break;
case 1:
buffer[1] = data;
step++;
break;
case 2:
buffer[2] = data;
step++;
pre = new rtcmpreamble();
pre.Read(buffer);
payloadlen = pre.length;
msglencount = 0;
// reset on oversize packet
if (payloadlen > buffer.Length)
step = 0;
break;
case 3:
if (msglencount < (payloadlen))
{
buffer[msglencount + 3] = data;
msglencount++;
}
else
{
step++;
goto case 4;
}
break;
case 4:
buffer[payloadlen + 3] = data;
step++;
break;
case 5:
buffer[payloadlen + 3 + 1] = data;
step++;
break;
case 6:
buffer[payloadlen + 3 + 2] = data;
payloadlen = payloadlen + 3;
u32 crc = crc24.crc24q(buffer, payloadlen, 0);
u32 crcpacket = getbitu(buffer, payloadlen * 8, 24);
if (crc == crcpacket)
{
rtcmheader head = new rtcmheader();
head.Read(buffer);
step = 0;
return head.messageno;
}
step = 0;
break;
}
return -1;
}
static uint getbitu(u8[] buff, u32 pos, u32 len)
{
uint bits = 0;
u32 i;
for (i = pos; i < pos + len; i++)
bits = (uint)((bits << 1) + ((buff[i / 8] >> (int)(7 - i % 8)) & 1u));
return bits;
}
static void setbitu(u8[] buff, u32 pos, u32 len, u32 data)
{
u32 mask = 1u << (int)(len - 1);
if (len <= 0 || 32 < len) return;
for (u32 i = pos; i < pos + len; i++, mask >>= 1)
{
if ((data & mask) > 0)
buff[i / 8] |= (byte)(1u << (int)(7 - i % 8));
else
buff[i / 8] &= (byte)(~(1u << (int)(7 - i % 8)));
}
}
public class rtcmpreamble
{
public u8 preamble = RTCM3PREAMB;
public u8 resv1;
public u16 length;
public void Read(byte[] buffer)
{
uint i = 0;
preamble = (byte)getbitu(buffer, i, 8); i += 8;
resv1 = (byte)getbitu(buffer, i, 6); i += 6;
length = (u16)getbitu(buffer, i, 10); i += 10;
}
public byte[] Write(byte[] buffer)
{
uint i = 0;
setbitu(buffer, i, 8, RTCM3PREAMB); i += 8;
setbitu(buffer, i, 6, resv1); i += 6;
setbitu(buffer, i, 10, length); i += 10;
return buffer;
}
}
public class rtcmheader
{
public u16 messageno;
public u16 refstationid;
public u32 epoch;
public u8 sync;
public u8 nsat;
public u8 smoothind;
public u8 smoothint;
public void Read(byte[] buffer)
{
u32 i = 24;
messageno = (u16)getbitu(buffer, i, 12); i += 12; /* message no */
refstationid = (u16)getbitu(buffer, i, 12); i += 12; /* ref station id */
epoch = (u32)getbitu(buffer, i, 30); i += 30; /* gps epoch time */
sync = (u8)getbitu(buffer, i, 1); i += 1; /* synchronous gnss flag */
nsat = (u8)getbitu(buffer, i, 5); i += 5; /* no of satellites */
smoothind = (u8)getbitu(buffer, i, 1); i += 1; /* smoothing indicator */
smoothint = (u8)getbitu(buffer, i, 3); i += 3; /* smoothing interval */
}
public byte[] Write(byte[] buffer)
{
u32 i = 24;
setbitu(buffer, i, 12, messageno); i += 12; /* message no */
setbitu(buffer, i, 12, refstationid); i += 12; /* ref station id */
setbitu(buffer, i, 30, epoch); i += 30; /* gps epoch time */
setbitu(buffer, i, 1, sync); i += 1; /* synchronous gnss flag */
setbitu(buffer, i, 5, nsat); i += 5; /* no of satellites */
setbitu(buffer, i, 1, smoothind); i += 1; /* smoothing indicator */
setbitu(buffer, i, 3, smoothint); i += 3; /* smoothing interval */
return buffer;
}
}
public class crc24
{
static u32[] crc24qtab = new u32[] {
0x000000, 0x864CFB, 0x8AD50D, 0x0C99F6, 0x93E6E1, 0x15AA1A, 0x1933EC, 0x9F7F17,
0xA18139, 0x27CDC2, 0x2B5434, 0xAD18CF, 0x3267D8, 0xB42B23, 0xB8B2D5, 0x3EFE2E,
0xC54E89, 0x430272, 0x4F9B84, 0xC9D77F, 0x56A868, 0xD0E493, 0xDC7D65, 0x5A319E,
0x64CFB0, 0xE2834B, 0xEE1ABD, 0x685646, 0xF72951, 0x7165AA, 0x7DFC5C, 0xFBB0A7,
0x0CD1E9, 0x8A9D12, 0x8604E4, 0x00481F, 0x9F3708, 0x197BF3, 0x15E205, 0x93AEFE,
0xAD50D0, 0x2B1C2B, 0x2785DD, 0xA1C926, 0x3EB631, 0xB8FACA, 0xB4633C, 0x322FC7,
0xC99F60, 0x4FD39B, 0x434A6D, 0xC50696, 0x5A7981, 0xDC357A, 0xD0AC8C, 0x56E077,
0x681E59, 0xEE52A2, 0xE2CB54, 0x6487AF, 0xFBF8B8, 0x7DB443, 0x712DB5, 0xF7614E,
0x19A3D2, 0x9FEF29, 0x9376DF, 0x153A24, 0x8A4533, 0x0C09C8, 0x00903E, 0x86DCC5,
0xB822EB, 0x3E6E10, 0x32F7E6, 0xB4BB1D, 0x2BC40A, 0xAD88F1, 0xA11107, 0x275DFC,
0xDCED5B, 0x5AA1A0, 0x563856, 0xD074AD, 0x4F0BBA, 0xC94741, 0xC5DEB7, 0x43924C,
0x7D6C62, 0xFB2099, 0xF7B96F, 0x71F594, 0xEE8A83, 0x68C678, 0x645F8E, 0xE21375,
0x15723B, 0x933EC0, 0x9FA736, 0x19EBCD, 0x8694DA, 0x00D821, 0x0C41D7, 0x8A0D2C,
0xB4F302, 0x32BFF9, 0x3E260F, 0xB86AF4, 0x2715E3, 0xA15918, 0xADC0EE, 0x2B8C15,
0xD03CB2, 0x567049, 0x5AE9BF, 0xDCA544, 0x43DA53, 0xC596A8, 0xC90F5E, 0x4F43A5,
0x71BD8B, 0xF7F170, 0xFB6886, 0x7D247D, 0xE25B6A, 0x641791, 0x688E67, 0xEEC29C,
0x3347A4, 0xB50B5F, 0xB992A9, 0x3FDE52, 0xA0A145, 0x26EDBE, 0x2A7448, 0xAC38B3,
0x92C69D, 0x148A66, 0x181390, 0x9E5F6B, 0x01207C, 0x876C87, 0x8BF571, 0x0DB98A,
0xF6092D, 0x7045D6, 0x7CDC20, 0xFA90DB, 0x65EFCC, 0xE3A337, 0xEF3AC1, 0x69763A,
0x578814, 0xD1C4EF, 0xDD5D19, 0x5B11E2, 0xC46EF5, 0x42220E, 0x4EBBF8, 0xC8F703,
0x3F964D, 0xB9DAB6, 0xB54340, 0x330FBB, 0xAC70AC, 0x2A3C57, 0x26A5A1, 0xA0E95A,
0x9E1774, 0x185B8F, 0x14C279, 0x928E82, 0x0DF195, 0x8BBD6E, 0x872498, 0x016863,
0xFAD8C4, 0x7C943F, 0x700DC9, 0xF64132, 0x693E25, 0xEF72DE, 0xE3EB28, 0x65A7D3,
0x5B59FD, 0xDD1506, 0xD18CF0, 0x57C00B, 0xC8BF1C, 0x4EF3E7, 0x426A11, 0xC426EA,
0x2AE476, 0xACA88D, 0xA0317B, 0x267D80, 0xB90297, 0x3F4E6C, 0x33D79A, 0xB59B61,
0x8B654F, 0x0D29B4, 0x01B042, 0x87FCB9, 0x1883AE, 0x9ECF55, 0x9256A3, 0x141A58,
0xEFAAFF, 0x69E604, 0x657FF2, 0xE33309, 0x7C4C1E, 0xFA00E5, 0xF69913, 0x70D5E8,
0x4E2BC6, 0xC8673D, 0xC4FECB, 0x42B230, 0xDDCD27, 0x5B81DC, 0x57182A, 0xD154D1,
0x26359F, 0xA07964, 0xACE092, 0x2AAC69, 0xB5D37E, 0x339F85, 0x3F0673, 0xB94A88,
0x87B4A6, 0x01F85D, 0x0D61AB, 0x8B2D50, 0x145247, 0x921EBC, 0x9E874A, 0x18CBB1,
0xE37B16, 0x6537ED, 0x69AE1B, 0xEFE2E0, 0x709DF7, 0xF6D10C, 0xFA48FA, 0x7C0401,
0x42FA2F, 0xC4B6D4, 0xC82F22, 0x4E63D9, 0xD11CCE, 0x575035, 0x5BC9C3, 0xDD8538
};
/** Calculate Qualcomm 24-bit Cyclical Redundancy Check (CRC-24Q).
*
* The CRC polynomial used is:
* \f[
* x^{24} + x^{23} + x^{18} + x^{17} + x^{14} + x^{11} + x^{10} +
* x^7 + x^6 + x^5 + x^4 + x^3 + x+1
* \f]
* Mask 0x1864CFB, not reversed, not XOR'd
*
* \param buf Array of data to calculate CRC for
* \param len Length of data array
* \param crc Initial CRC value
*
* \return CRC-24Q value
*/
public static u32 crc24q(u8[] buf, u32 len, u32 crc)
{
for (u32 i = 0; i < len; i++)
crc = ((crc << 8) & 0xFFFFFF) ^ crc24qtab[(crc >> 16) ^ buf[i]];
return crc;
}
}
public s32 length
{
get { return (s32)(payloadlen + 2 + 1); }
}
public u8[] packet
{
get { return buffer; }
}
}
} |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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 Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Commands.Sql.Properties;
using Microsoft.Azure.Commands.Sql.Replication.Model;
using Microsoft.Azure.Commands.Sql.Database.Services;
using Microsoft.Rest.Azure;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Sql.Replication.Cmdlet
{
/// <summary>
/// Cmdlet to create a new Azure SQL Database Copy
/// </summary>
[Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "SqlDatabaseCopy", ConfirmImpact = ConfirmImpact.Low, SupportsShouldProcess = true, DefaultParameterSetName = DtuDatabaseParameterSet), OutputType(typeof(AzureSqlDatabaseCopyModel))]
public class NewAzureSqlDatabaseCopy : AzureSqlDatabaseCopyCmdletBase
{
private const string DtuDatabaseParameterSet = "DtuBasedDatabase";
private const string VcoreDatabaseParameterSet = "VcoreBasedDatabase";
/// <summary>
/// Gets or sets the name of the database to be copied.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 2,
HelpMessage = "The name of the Azure SQL Database to be copied.")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the name of the service objective to assign to the Azure SQL Database copy
/// </summary>
[Parameter(ParameterSetName = DtuDatabaseParameterSet, Mandatory = false,
HelpMessage = "The name of the service objective to assign to the Azure SQL Database copy.")]
[ValidateNotNullOrEmpty]
public string ServiceObjectiveName { get; set; }
/// <summary>
/// Gets or sets the name of the Elastic Pool to put the database copy in
/// </summary>
[Parameter(ParameterSetName = DtuDatabaseParameterSet, Mandatory = false,
HelpMessage = "The name of the Elastic Pool to put the database copy in.")]
[ValidateNotNullOrEmpty]
public string ElasticPoolName { get; set; }
/// <summary>
/// Gets or sets the tags associated with the Azure SQL Database Copy
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The tags to associate with the Azure SQL Database Copy")]
[Alias("Tag")]
public Hashtable Tags { get; set; }
/// <summary>
/// Gets or sets the name of the resource group of the copy.
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the resource group of the copy.")]
[ValidateNotNullOrEmpty]
public string CopyResourceGroupName { get; set; }
/// <summary>
/// Gets or sets the name of the Azure SQL Server of the copy.
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the Azure SQL Server of the copy.")]
[ValidateNotNullOrEmpty]
public string CopyServerName { get; set; }
/// <summary>
/// Gets or sets the name of the source database copy.
/// </summary>
[Parameter(Mandatory = true,
HelpMessage = "The name of the Azure SQL Database copy.")]
[ValidateNotNullOrEmpty]
public string CopyDatabaseName { get; set; }
/// <summary>
/// Gets or sets whether or not to run this cmdlet in the background as a job
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
/// <summary>
/// Gets or sets the compute generation of the database copy
/// </summary>
[Parameter(ParameterSetName = VcoreDatabaseParameterSet, Mandatory = true,
HelpMessage = "The compute generation to assign to the new copy.")]
[Alias("Family")]
[PSArgumentCompleter("Gen4", "Gen5")]
[ValidateNotNullOrEmpty]
public string ComputeGeneration { get; set; }
/// <summary>
/// Gets or sets the Vcore numbers of the database copy
/// </summary>
[Parameter(ParameterSetName = VcoreDatabaseParameterSet, Mandatory = true,
HelpMessage = "The Vcore numbers of the Azure Sql Database copy.")]
[Alias("Capacity")]
[ValidateNotNullOrEmpty]
public int VCore { get; set; }
/// <summary>
/// Gets or sets the license type for the Azure Sql database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The license type for the Azure Sql database.")]
[PSArgumentCompleter(
Management.Sql.Models.DatabaseLicenseType.LicenseIncluded,
Management.Sql.Models.DatabaseLicenseType.BasePrice)]
public string LicenseType { get; set; }
/// <summary>
/// Overriding to add warning message
/// </summary>
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
}
/// <summary>
/// Get the entities from the service
/// </summary>
/// <returns>The list of entities</returns>
protected override IEnumerable<AzureSqlDatabaseCopyModel> GetEntity()
{
string copyResourceGroupName = string.IsNullOrWhiteSpace(this.CopyResourceGroupName) ? this.ResourceGroupName : this.CopyResourceGroupName;
string copyServerName = string.IsNullOrWhiteSpace(this.CopyServerName) ? this.ServerName : this.CopyServerName;
// We try to get the database. Since this is a create copy, we don't want the copy database to exist
try
{
ModelAdapter.GetDatabase(copyResourceGroupName, copyServerName, this.CopyDatabaseName);
}
catch (CloudException ex)
{
if (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// This is what we want. We looked and there is no database with this name.
return null;
}
// Unexpected exception encountered
throw;
}
// The database already exists
throw new PSArgumentException(
string.Format(Resources.DatabaseNameExists, this.CopyDatabaseName, copyServerName),
"CopyDatabaseName");
}
/// <summary>
/// Create the model from user input
/// </summary>
/// <param name="model">Model retrieved from service</param>
/// <returns>The model that was passed in</returns>
protected override IEnumerable<AzureSqlDatabaseCopyModel> ApplyUserInputToModel(IEnumerable<AzureSqlDatabaseCopyModel> model)
{
string copyResourceGroup = string.IsNullOrWhiteSpace(CopyResourceGroupName) ? ResourceGroupName : CopyResourceGroupName;
string copyServer = string.IsNullOrWhiteSpace(CopyServerName) ? ServerName : CopyServerName;
string location = ModelAdapter.GetServerLocation(ResourceGroupName, ServerName);
string copyLocation = copyServer.Equals(ServerName) ? location : ModelAdapter.GetServerLocation(copyResourceGroup, copyServer);
Database.Model.AzureSqlDatabaseModel sourceDb = ModelAdapter.GetDatabase(ResourceGroupName, ServerName, DatabaseName);
List<Model.AzureSqlDatabaseCopyModel> newEntity = new List<AzureSqlDatabaseCopyModel>();
AzureSqlDatabaseCopyModel copyModel = new AzureSqlDatabaseCopyModel()
{
Location = location,
ResourceGroupName = ResourceGroupName,
ServerName = ServerName,
DatabaseName = DatabaseName,
CopyResourceGroupName = copyResourceGroup,
CopyServerName = copyServer,
CopyDatabaseName = CopyDatabaseName,
CopyLocation = copyLocation,
ServiceObjectiveName = ServiceObjectiveName,
ElasticPoolName = ElasticPoolName,
Tags = TagsConversionHelper.CreateTagDictionary(Tags, validate: true),
LicenseType = LicenseType // note: default license type is LicenseIncluded
};
if(ParameterSetName == DtuDatabaseParameterSet)
{
if (!string.IsNullOrWhiteSpace(ServiceObjectiveName))
{
copyModel.SkuName = ServiceObjectiveName;
}
else if(string.IsNullOrWhiteSpace(ElasticPoolName))
{
copyModel.SkuName = sourceDb.CurrentServiceObjectiveName;
copyModel.Edition = sourceDb.Edition;
copyModel.Capacity = sourceDb.Capacity;
copyModel.Family = sourceDb.Family;
}
}
else
{
copyModel.SkuName = AzureSqlDatabaseAdapter.GetDatabaseSkuName(sourceDb.Edition);
copyModel.Edition = sourceDb.Edition;
copyModel.Capacity = VCore;
copyModel.Family = ComputeGeneration;
}
newEntity.Add(copyModel);
return newEntity;
}
/// <summary>
/// Create the new database copy
/// </summary>
/// <param name="entity">The output of apply user input to model</param>
/// <returns>The input entity</returns>
protected override IEnumerable<AzureSqlDatabaseCopyModel> PersistChanges(IEnumerable<AzureSqlDatabaseCopyModel> entity)
{
return new List<AzureSqlDatabaseCopyModel>()
{
ModelAdapter.CopyDatabaseWithNewSdk(entity.First().CopyResourceGroupName, entity.First().CopyServerName, entity.First())
};
}
}
}
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project.Automation {
[ComVisible(true)]
public class OAProject : EnvDTE.Project, EnvDTE.ISupportVSProperties {
#region fields
private ProjectNode project;
EnvDTE.ConfigurationManager configurationManager;
#endregion
#region properties
public object Project {
get { return this.project; }
}
internal ProjectNode ProjectNode {
get { return this.project; }
}
#endregion
#region ctor
internal OAProject(ProjectNode project) {
this.project = project;
}
#endregion
#region EnvDTE.Project
/// <summary>
/// Gets or sets the name of the object.
/// </summary>
public virtual string Name {
get {
return project.Caption;
}
set {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
project.SetEditLabel(value);
});
}
}
}
public void Dispose() {
configurationManager = null;
}
/// <summary>
/// Microsoft Internal Use Only. Gets the file name of the project.
/// </summary>
public virtual string FileName {
get {
return project.ProjectFile;
}
}
/// <summary>
/// Microsoft Internal Use Only. Specfies if the project is dirty.
/// </summary>
public virtual bool IsDirty {
get {
int dirty;
ErrorHandler.ThrowOnFailure(project.IsDirty(out dirty));
return dirty != 0;
}
set {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
project.isDirty = value;
});
}
}
}
internal void CheckProjectIsValid() {
if (this.project == null || this.project.Site == null || this.project.IsClosed) {
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the Projects collection containing the Project object supporting this property.
/// </summary>
public virtual EnvDTE.Projects Collection {
get { return null; }
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE {
get {
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
/// <summary>
/// Gets a GUID string indicating the kind or type of the object.
/// </summary>
public virtual string Kind {
get { return project.ProjectGuid.ToString("B"); }
}
/// <summary>
/// Gets a ProjectItems collection for the Project object.
/// </summary>
public virtual EnvDTE.ProjectItems ProjectItems {
get {
return new OAProjectItems(this, project);
}
}
/// <summary>
/// Gets a collection of all properties that pertain to the Project object.
/// </summary>
public virtual EnvDTE.Properties Properties {
get {
return new OAProperties(this.project.NodeProperties);
}
}
/// <summary>
/// Returns the name of project as a relative path from the directory containing the solution file to the project file
/// </summary>
/// <value>Unique name if project is in a valid state. Otherwise null</value>
public virtual string UniqueName {
get {
if (this.project == null || this.project.IsClosed) {
return null;
} else {
// Get Solution service
IVsSolution solution = this.project.GetService(typeof(IVsSolution)) as IVsSolution;
Utilities.CheckNotNull(solution);
// Ask solution for unique name of project
string uniqueName;
ErrorHandler.ThrowOnFailure(
solution.GetUniqueNameOfProject(
project.GetOuterInterface<IVsHierarchy>(),
out uniqueName
)
);
return uniqueName;
}
}
}
/// <summary>
/// Gets an interface or object that can be accessed by name at run time.
/// </summary>
public virtual object Object {
get { return this.project.Object; }
}
/// <summary>
/// Gets the requested Extender object if it is available for this object.
/// </summary>
/// <param name="name">The name of the extender object.</param>
/// <returns>An Extender object. </returns>
public virtual object get_Extender(string name) {
Utilities.ArgumentNotNull("name", name);
return DTE.ObjectExtenders.GetExtender(project.NodeProperties.ExtenderCATID.ToUpper(), name, project.NodeProperties);
}
/// <summary>
/// Gets a list of available Extenders for the object.
/// </summary>
public virtual object ExtenderNames {
get { return DTE.ObjectExtenders.GetExtenderNames(project.NodeProperties.ExtenderCATID.ToUpper(), project.NodeProperties); }
}
/// <summary>
/// Gets the Extender category ID (CATID) for the object.
/// </summary>
public virtual string ExtenderCATID {
get { return project.NodeProperties.ExtenderCATID; }
}
/// <summary>
/// Gets the full path and name of the Project object's file.
/// </summary>
public virtual string FullName {
get {
string filename;
uint format;
ErrorHandler.ThrowOnFailure(project.GetCurFile(out filename, out format));
return filename;
}
}
/// <summary>
/// Gets or sets a value indicatingwhether the object has not been modified since last being saved or opened.
/// </summary>
public virtual bool Saved {
get {
return !this.IsDirty;
}
set {
IsDirty = !value;
}
}
/// <summary>
/// Gets the ConfigurationManager object for this Project .
/// </summary>
public virtual EnvDTE.ConfigurationManager ConfigurationManager {
get {
return ProjectNode.Site.GetUIThread().Invoke(() => {
if (this.configurationManager == null) {
IVsExtensibility3 extensibility = this.project.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3;
Utilities.CheckNotNull(extensibility);
object configurationManagerAsObject;
ErrorHandler.ThrowOnFailure(extensibility.GetConfigMgr(
this.project.GetOuterInterface<IVsHierarchy>(),
VSConstants.VSITEMID_ROOT,
out configurationManagerAsObject
));
Utilities.CheckNotNull(configurationManagerAsObject);
this.configurationManager = (ConfigurationManager)configurationManagerAsObject;
}
return this.configurationManager;
});
}
}
/// <summary>
/// Gets the Globals object containing add-in values that may be saved in the solution (.sln) file, the project file, or in the user's profile data.
/// </summary>
public virtual EnvDTE.Globals Globals {
get { return null; }
}
/// <summary>
/// Gets a ProjectItem object for the nested project in the host project.
/// </summary>
public virtual EnvDTE.ProjectItem ParentProjectItem {
get { return null; }
}
/// <summary>
/// Gets the CodeModel object for the project.
/// </summary>
public virtual EnvDTE.CodeModel CodeModel {
get { return null; }
}
/// <summary>
/// Saves the project.
/// </summary>
/// <param name="fileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten</param>
/// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception>
/// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception>
public virtual void SaveAs(string fileName) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.DoSave(true, fileName);
});
}
/// <summary>
/// Saves the project
/// </summary>
/// <param name="fileName">The file name of the project</param>
/// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception>
/// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception>
public virtual void Save(string fileName) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.DoSave(false, fileName);
});
}
/// <summary>
/// Removes the project from the current solution.
/// </summary>
public virtual void Delete() {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.project.Remove(false);
});
}
}
#endregion
#region ISupportVSProperties methods
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public virtual void NotifyPropertiesDelete() {
}
#endregion
#region private methods
/// <summary>
/// Saves or Save Asthe project.
/// </summary>
/// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param>
/// <param name="fileName">The name of the project file.</param>
private void DoSave(bool isCalledFromSaveAs, string fileName) {
Utilities.ArgumentNotNull("fileName", fileName);
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
// If an empty file name is passed in for Save then make the file name the project name.
if (!isCalledFromSaveAs && string.IsNullOrEmpty(fileName)) {
// Use the solution service to save the project file. Note that we have to use the service
// so that all the shell's elements are aware that we are inside a save operation and
// all the file change listenters registered by the shell are suspended.
// Get the cookie of the project file from the RTD.
IVsRunningDocumentTable rdt = this.project.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
Utilities.CheckNotNull(rdt);
IVsHierarchy hier;
uint itemid;
IntPtr unkData;
uint cookie;
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.project.Url, out hier,
out itemid, out unkData, out cookie));
if (IntPtr.Zero != unkData) {
Marshal.Release(unkData);
}
// Verify that we have a cookie.
if (0 == cookie) {
// This should never happen because if the project is open, then it must be in the RDT.
throw new InvalidOperationException();
}
// Get the IVsHierarchy for the project.
IVsHierarchy prjHierarchy = project.GetOuterInterface<IVsHierarchy>();
// Now get the soulution.
IVsSolution solution = this.project.Site.GetService(typeof(SVsSolution)) as IVsSolution;
// Verify that we have both solution and hierarchy.
Utilities.CheckNotNull(prjHierarchy);
Utilities.CheckNotNull(solution);
ErrorHandler.ThrowOnFailure(solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, prjHierarchy, cookie));
} else {
// We need to make some checks before we can call the save method on the project node.
// This is mainly because it is now us and not the caller like in case of SaveAs or Save that should validate the file name.
// The IPersistFileFormat.Save method only does a validation that is necessary to be performed. Example: in case of Save As the
// file name itself is not validated only the whole path. (thus a file name like file\file is accepted, since as a path is valid)
// 1. The file name has to be valid.
string fullPath = fileName;
try {
fullPath = CommonUtils.GetAbsoluteFilePath(((ProjectNode)Project).ProjectFolder, fileName);
}
// We want to be consistent in the error message and exception we throw. fileName could be for example #¤&%"¤&"% and that would trigger an ArgumentException on Path.IsRooted.
catch (ArgumentException ex) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, fileName), ex);
}
// It might be redundant but we validate the file and the full path of the file being valid. The SaveAs would also validate the path.
// If we decide that this is performance critical then this should be refactored.
Utilities.ValidateFileName(this.project.Site, fullPath);
if (!isCalledFromSaveAs) {
// 2. The file name has to be the same
if (!CommonUtils.IsSamePath(fullPath, this.project.Url)) {
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 1, 0));
} else {
ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 0, 0));
}
}
}
}
#endregion
}
/// <summary>
/// Specifies an alternate name for a property which cannot be fully captured using
/// .NET attribute names.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class PropertyNameAttribute : Attribute {
public readonly string Name;
public PropertyNameAttribute(string name) {
Name = name;
}
}
}
|
#region BSD License
/*
Copyright (c) 2012, Clarius Consulting
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.
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.
*/
#endregion
namespace Clide.VisualStudio
{
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
internal static class VsServiceProviderExtensions
{
public static VsToolWindow ToolWindow(this IServiceProvider serviceProvider, Guid toolWindowId)
{
return new VsToolWindow(serviceProvider, toolWindowId);
}
public static IVsHierarchy GetSelectedHierarchy(this IVsMonitorSelection monitorSelection, IUIThread uiThread)
{
var hierarchyPtr = IntPtr.Zero;
var selectionContainer = IntPtr.Zero;
return uiThread.Invoke(() =>
{
try
{
// Get the current project hierarchy, project item, and selection container for the current selection
// If the selection spans multiple hierarchies, hierarchyPtr is Zero.
// So fast path is for non-zero result (most common case of single active project/item).
uint itemid;
IVsMultiItemSelect multiItemSelect = null;
ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer));
// There may be no selection at all.
if (itemid == VSConstants.VSITEMID_NIL)
return null;
if (itemid == VSConstants.VSITEMID_ROOT)
{
// The root selection could be the solution itself, so no project is active.
if (hierarchyPtr == IntPtr.Zero)
return null;
else
return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy));
}
// We may have a single item selection, so we can safely pick its owning project/hierarchy.
if (itemid != VSConstants.VSITEMID_SELECTION)
return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy));
// Otherwise, this is a multiple item selection within the same hierarchy,
// we select he hierarchy.
uint numberOfSelectedItems;
int isSingleHierarchyInt;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt));
var isSingleHierarchy = (isSingleHierarchyInt != 0);
if (isSingleHierarchy)
return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy));
return null;
}
finally
{
if (hierarchyPtr != IntPtr.Zero)
{
Marshal.Release(hierarchyPtr);
}
if (selectionContainer != IntPtr.Zero)
{
Marshal.Release(selectionContainer);
}
}
});
}
public static IEnumerable<Tuple<IVsHierarchy, uint>> GetSelection(this IVsMonitorSelection monitorSelection, IUIThread uiThread, IVsHierarchy solution)
{
var hierarchyPtr = IntPtr.Zero;
var selectionContainer = IntPtr.Zero;
return uiThread.Invoke(() =>
{
try
{
// Get the current project hierarchy, project item, and selection container for the current selection
// If the selection spans multiple hierarchies, hierarchyPtr is Zero
uint itemid;
IVsMultiItemSelect multiItemSelect = null;
ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer));
if (itemid == VSConstants.VSITEMID_NIL)
return Enumerable.Empty<Tuple<IVsHierarchy, uint>>();
if (itemid == VSConstants.VSITEMID_ROOT)
{
if (hierarchyPtr == IntPtr.Zero)
return new[] { Tuple.Create(solution, VSConstants.VSITEMID_ROOT) };
else
return new[] { Tuple.Create(
(IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)),
VSConstants.VSITEMID_ROOT) };
}
if (itemid != VSConstants.VSITEMID_SELECTION)
return new[] { Tuple.Create(
(IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)),
itemid) };
// This is a multiple item selection.
uint numberOfSelectedItems;
int isSingleHierarchyInt;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt));
var isSingleHierarchy = (isSingleHierarchyInt != 0);
var vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems];
var flags = (isSingleHierarchy) ? (uint)__VSGSIFLAGS.GSI_fOmitHierPtrs : 0;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(flags, numberOfSelectedItems, vsItemSelections));
return vsItemSelections.Where(sel => sel.pHier != null)
// NOTE: we can return lazy results here, since
// the GetSelectedItems has already returned in the UI thread
// the array of results. We're just delaying the creation of the tuples
// in case they aren't all needed.
.Select(sel => Tuple.Create(sel.pHier, sel.itemid));
}
finally
{
if (hierarchyPtr != IntPtr.Zero)
{
Marshal.Release(hierarchyPtr);
}
if (selectionContainer != IntPtr.Zero)
{
Marshal.Release(selectionContainer);
}
}
});
}
}
}
|
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.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 Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !NET_CF && !SILVERLIGHT
namespace NLog.Targets
{
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
using NLog.Config;
/// <summary>
/// Highlighting rule for Win32 colorful console.
/// </summary>
[NLogConfigurationItem]
public class ConsoleWordHighlightingRule
{
private Regex compiledRegex;
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleWordHighlightingRule" /> class.
/// </summary>
public ConsoleWordHighlightingRule()
{
this.BackgroundColor = ConsoleOutputColor.NoChange;
this.ForegroundColor = ConsoleOutputColor.NoChange;
}
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleWordHighlightingRule" /> class.
/// </summary>
/// <param name="text">The text to be matched..</param>
/// <param name="foregroundColor">Color of the foreground.</param>
/// <param name="backgroundColor">Color of the background.</param>
public ConsoleWordHighlightingRule(string text, ConsoleOutputColor foregroundColor, ConsoleOutputColor backgroundColor)
{
this.Text = text;
this.ForegroundColor = foregroundColor;
this.BackgroundColor = backgroundColor;
}
/// <summary>
/// Gets or sets the regular expression to be matched. You must specify either <c>text</c> or <c>regex</c>.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
public string Regex { get; set; }
/// <summary>
/// Gets or sets the text to be matched. You must specify either <c>text</c> or <c>regex</c>.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
public string Text { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to match whole words only.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
[DefaultValue(false)]
public bool WholeWords { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore case when comparing texts.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
[DefaultValue(false)]
public bool IgnoreCase { get; set; }
/// <summary>
/// Gets the compiled regular expression that matches either Text or Regex property.
/// </summary>
public Regex CompiledRegex
{
get
{
if (this.compiledRegex == null)
{
string regexpression = this.Regex;
if (regexpression == null && this.Text != null)
{
regexpression = System.Text.RegularExpressions.Regex.Escape(this.Text);
if (this.WholeWords)
{
regexpression = "\b" + regexpression + "\b";
}
}
RegexOptions regexOptions = RegexOptions.Compiled;
if (this.IgnoreCase)
{
regexOptions |= RegexOptions.IgnoreCase;
}
this.compiledRegex = new Regex(regexpression, regexOptions);
}
return this.compiledRegex;
}
}
/// <summary>
/// Gets or sets the foreground color.
/// </summary>
/// <docgen category='Formatting Options' order='10' />
[DefaultValue("NoChange")]
public ConsoleOutputColor ForegroundColor { get; set; }
/// <summary>
/// Gets or sets the background color.
/// </summary>
/// <docgen category='Formatting Options' order='10' />
[DefaultValue("NoChange")]
public ConsoleOutputColor BackgroundColor { get; set; }
internal string MatchEvaluator(Match m)
{
StringBuilder result = new StringBuilder();
result.Append('\a');
result.Append((char)((int)this.ForegroundColor + 'A'));
result.Append((char)((int)this.BackgroundColor + 'A'));
result.Append(m.Value);
result.Append('\a');
result.Append('X');
return result.ToString();
}
internal string ReplaceWithEscapeSequences(string message)
{
return this.CompiledRegex.Replace(message, new MatchEvaluator(this.MatchEvaluator));
}
}
}
#endif |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
using System.Security.AccessControl;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class hosts a node class in the child process. It uses shared memory to communicate
/// with the local node provider.
/// Wraps a Node.
/// </summary>
public class LocalNode
{
#region Static Constructors
/// <summary>
/// Hook up an unhandled exception handler, in case our error handling paths are leaky
/// </summary>
static LocalNode()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
}
#endregion
#region Static Methods
/// <summary>
/// Dump any unhandled exceptions to a file so they can be diagnosed
/// </summary>
private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception)e.ExceptionObject;
DumpExceptionToFile(ex);
}
/// <summary>
/// Dump the exception information to a file
/// </summary>
internal static void DumpExceptionToFile(Exception ex)
{
// Lock as multiple threads may throw simultaneously
lock (dumpFileLocker)
{
if (dumpFileName == null)
{
Guid guid = Guid.NewGuid();
string tempPath = Path.GetTempPath();
// For some reason we get Watson buckets because GetTempPath gives us a folder here that doesn't exist.
// Either because %TMP% is misdefined, or because they deleted the temp folder during the build.
if (!Directory.Exists(tempPath))
{
// If this throws, no sense catching it, we can't log it now, and we're here
// because we're a child node with no console to log to, so die
Directory.CreateDirectory(tempPath);
}
dumpFileName = Path.Combine(tempPath, "MSBuild_" + guid.ToString());
using (StreamWriter writer = new StreamWriter(dumpFileName, true /*append*/))
{
writer.WriteLine("UNHANDLED EXCEPTIONS FROM CHILD NODE:");
writer.WriteLine("===================");
}
}
using (StreamWriter writer = new StreamWriter(dumpFileName, true /*append*/))
{
writer.WriteLine(DateTime.Now.ToLongTimeString());
writer.WriteLine(ex.ToString());
writer.WriteLine("===================");
}
}
}
#endregion
#region Constructors
/// <summary>
/// Creates an instance of this class.
/// </summary>
internal LocalNode(int nodeNumberIn)
{
this.nodeNumber = nodeNumberIn;
engineCallback = new LocalNodeCallback(communicationThreadExitEvent, this);
}
#endregion
#region Communication Methods
/// <summary>
/// This method causes the reader and writer threads to start and create the shared memory structures
/// </summary>
void StartCommunicationThreads()
{
// The writer thread should be created before the
// reader thread because some LocalCallDescriptors
// assume the shared memory for the writer thread
// has already been created. The method will both
// instantiate the shared memory for the writer
// thread and also start the writer thread itself.
// We will verifyThrow in the method if the
// sharedMemory was not created correctly.
engineCallback.StartWriterThread(nodeNumber);
// Create the shared memory buffer
this.sharedMemory =
new SharedMemory
(
// Generate the name for the shared memory region
LocalNodeProviderGlobalNames.NodeInputMemoryName(nodeNumber),
SharedMemoryType.ReadOnly,
// Reuse an existing shared memory region as it should have already
// been created by the parent node side
true
);
ErrorUtilities.VerifyThrow(this.sharedMemory.IsUsable,
"Failed to create shared memory for local node input.");
// Start the thread that will be processing the calls from the parent engine
ThreadStart threadState = new ThreadStart(this.SharedMemoryReaderThread);
readerThread = new Thread(threadState);
readerThread.Name = "MSBuild Child<-Parent Reader";
readerThread.Start();
}
/// <summary>
/// This method causes the reader and writer threads to exit and dispose of the shared memory structures
/// </summary>
void StopCommunicationThreads()
{
communicationThreadExitEvent.Set();
// Wait for communication threads to exit
Thread writerThread = engineCallback.GetWriterThread();
// The threads may not exist if the child has timed out before the parent has told the node
// to start up its communication threads. This can happen if the node is started with /nodemode:x
// and no parent is running, or if the parent node has spawned a new process and then crashed
// before establishing communication with the child node.
if(writerThread != null)
{
writerThread.Join();
}
if (readerThread != null)
{
readerThread.Join();
}
// Make sure the exit event is not set
communicationThreadExitEvent.Reset();
}
#endregion
#region Startup Methods
/// <summary>
/// Create global events necessary for handshaking with the parent
/// </summary>
/// <param name="nodeNumber"></param>
/// <returns>True if events created successfully and false otherwise</returns>
private static bool CreateGlobalEvents(int nodeNumber)
{
bool createdNew = false;
if (NativeMethods.IsUserAdministrator())
{
EventWaitHandleSecurity mSec = new EventWaitHandleSecurity();
// Add a rule that grants the access only to admins and systems
mSec.SetSecurityDescriptorSddlForm(NativeMethods.ADMINONLYSDDL);
// Create an initiation event to allow the parent side to prove to the child that we have the same level of privilege as it does.
// this is done by having the parent set this event which means it needs to have administrative permissions to do so.
globalInitiateActivationEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInitiateActivationEventName(nodeNumber), out createdNew, mSec);
}
else
{
// Create an initiation event to allow the parent side to prove to the child that we have the same level of privilege as it does.
// this is done by having the parent set this event which means it has atleast the same permissions as the child process
globalInitiateActivationEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInitiateActivationEventName(nodeNumber), out createdNew);
}
// This process must be the creator of the event to prevent squating by a lower privilaged attacker
if (!createdNew)
{
return false;
}
// Informs the parent process that the child process has been created.
globalNodeActive = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeActiveEventName(nodeNumber));
globalNodeActive.Set();
// Indicate to the parent process, this node is currently is ready to start to recieve requests
globalNodeInUse = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInUseEventName(nodeNumber));
// Used by the parent process to inform the child process to shutdown due to the child process
// not recieving the initialization command.
globalNodeErrorShutdown = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeErrorShutdownEventName(nodeNumber));
// Inform the parent process the node has started its communication threads.
globalNodeActivate = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeActivedEventName(nodeNumber));
return true;
}
/// <summary>
/// This function starts local node when process is launched and shuts it down on time out
/// Called by msbuild.exe.
/// </summary>
public static void StartLocalNodeServer(int nodeNumber)
{
// Create global events necessary for handshaking with the parent
if (!CreateGlobalEvents(nodeNumber))
{
return;
}
LocalNode localNode = new LocalNode(nodeNumber);
WaitHandle[] waitHandles = new WaitHandle[4];
waitHandles[0] = shutdownEvent;
waitHandles[1] = globalNodeErrorShutdown;
waitHandles[2] = inUseEvent;
waitHandles[3] = globalInitiateActivationEvent;
// This is necessary to make build.exe finish promptly. Dont remove.
if (!Engine.debugMode)
{
// Create null streams for the current input/output/error streams
Console.SetOut(new StreamWriter(Stream.Null));
Console.SetError(new StreamWriter(Stream.Null));
Console.SetIn(new StreamReader(Stream.Null));
}
bool continueRunning = true;
while (continueRunning)
{
int eventType = WaitHandle.WaitAny(waitHandles, inactivityTimeout, false);
if (eventType == 0 || eventType == 1 || eventType == WaitHandle.WaitTimeout)
{
continueRunning = false;
localNode.ShutdownNode(eventType != 1 ?
Node.NodeShutdownLevel.PoliteShutdown :
Node.NodeShutdownLevel.ErrorShutdown, true, true);
}
else if (eventType == 2)
{
// reset the event as we do not want it to go into this state again when we are done with this if statement.
inUseEvent.Reset();
// The parent knows at this point the child process has been launched
globalNodeActivate.Reset();
// Set the global inuse event so other parent processes know this node is now initialized
globalNodeInUse.Set();
// Make a copy of the parents handle to protect ourselves in case the parent dies,
// this is to prevent a parent from reserving a node another parent is trying to use.
globalNodeReserveHandle =
new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeReserveEventName(nodeNumber));
WaitHandle[] waitHandlesActive = new WaitHandle[3];
waitHandlesActive[0] = shutdownEvent;
waitHandlesActive[1] = globalNodeErrorShutdown;
waitHandlesActive[2] = notInUseEvent;
eventType = WaitHandle.WaitTimeout;
while (eventType == WaitHandle.WaitTimeout && continueRunning == true)
{
eventType = WaitHandle.WaitAny(waitHandlesActive, parentCheckInterval, false);
if (eventType == 0 || /* nice shutdown due to shutdownEvent */
eventType == 1 || /* error shutdown due to globalNodeErrorShutdown */
eventType == WaitHandle.WaitTimeout && !localNode.IsParentProcessAlive())
{
continueRunning = false;
// If the exit is not triggered by running of shutdown method
if (eventType != 0)
{
localNode.ShutdownNode(Node.NodeShutdownLevel.ErrorShutdown, true, true);
}
}
else if (eventType == 2)
{
// Trigger a collection before the node goes idle to insure that
// the memory is released to the system as soon as possible
GC.Collect();
// Change the current directory to a safe one so that the directory
// last used by the build can be safely deleted. We must have read
// access to the safe directory so use SystemDirectory for this purpose.
Directory.SetCurrentDirectory(Environment.SystemDirectory);
notInUseEvent.Reset();
globalNodeInUse.Reset();
}
}
ErrorUtilities.VerifyThrow(localNode.node == null,
"Expected either node to be null or continueRunning to be false.");
// Stop the communication threads and release the shared memory object so that the next parent can create it
localNode.StopCommunicationThreads();
// Close the local copy of the reservation handle (this allows another parent to reserve
// the node)
globalNodeReserveHandle.Close();
globalNodeReserveHandle = null;
}
else if (eventType == 3)
{
globalInitiateActivationEvent.Reset();
localNode.StartCommunicationThreads();
globalNodeActivate.Set();
}
}
// Stop the communication threads and release the shared memory object so that the next parent can create it
localNode.StopCommunicationThreads();
globalNodeActive.Close();
globalNodeInUse.Close();
}
#endregion
#region Methods
/// <summary>
/// This method is run in its own thread, it is responsible for reading messages sent from the parent process
/// through the shared memory region.
/// </summary>
private void SharedMemoryReaderThread()
{
// Create an array of event to the node thread responds
WaitHandle[] waitHandles = new WaitHandle[2];
waitHandles[0] = communicationThreadExitEvent;
waitHandles[1] = sharedMemory.ReadFlag;
bool continueExecution = true;
try
{
while (continueExecution)
{
// Wait for the next work item or an exit command
int eventType = WaitHandle.WaitAny(waitHandles);
if (eventType == 0)
{
// Exit node event
continueExecution = false;
}
else
{
// Read the list of LocalCallDescriptors from sharedMemory,
// this will be null if a large object is being read from shared
// memory and will continue to be null until the large object has
// been completly sent.
IList localCallDescriptorList = sharedMemory.Read();
if (localCallDescriptorList != null)
{
foreach (LocalCallDescriptor callDescriptor in localCallDescriptorList)
{
// Execute the command method which relates to running on a child node
callDescriptor.NodeAction(node, this);
if ((callDescriptor.IsReply) && (callDescriptor is LocalReplyCallDescriptor))
{
// Process the reply from the parent so it can be looked in a hashtable based
// on the call descriptor who requested the reply.
engineCallback.PostReplyFromParent((LocalReplyCallDescriptor) callDescriptor);
}
}
}
}
}
}
catch (Exception e)
{
// Will rethrow the exception if necessary
ReportFatalCommunicationError(e);
}
// Dispose of the shared memory buffer
if (sharedMemory != null)
{
sharedMemory.Dispose();
sharedMemory = null;
}
}
/// <summary>
/// This method will shutdown the node being hosted by the child process and notify the parent process if requested,
/// </summary>
/// <param name="shutdownLevel">What kind of shutdown is causing the child node to shutdown</param>
/// <param name="exitProcess">should the child process exit as part of the shutdown process</param>
/// <param name="noParentNotification">Indicates if the parent process should be notified the child node is being shutdown</param>
internal void ShutdownNode(Node.NodeShutdownLevel shutdownLevel, bool exitProcess, bool noParentNotification)
{
if (node != null)
{
try
{
node.ShutdownNode(shutdownLevel);
if (!noParentNotification)
{
// Write the last event out directly
LocalCallDescriptorForShutdownComplete callDescriptor =
new LocalCallDescriptorForShutdownComplete(shutdownLevel, node.TotalTaskTime);
// Post the message indicating that the shutdown is complete
engineCallback.PostMessageToParent(callDescriptor, true);
}
}
catch (Exception e)
{
if (shutdownLevel != Node.NodeShutdownLevel.ErrorShutdown)
{
ReportNonFatalCommunicationError(e);
}
}
}
// If the shutdownLevel is not a build complete message, then this means there was a politeshutdown or an error shutdown, null the node out
// as either it is no longer needed due to the node goign idle or there was a error and it is now in a bad state.
if (shutdownLevel != Node.NodeShutdownLevel.BuildCompleteSuccess &&
shutdownLevel != Node.NodeShutdownLevel.BuildCompleteFailure)
{
node = null;
notInUseEvent.Set();
}
if (exitProcess)
{
// Even if we completed a build, if we are goign to exit the process we need to null out the node and set the notInUseEvent, this is
// accomplished by calling this method again with the ErrorShutdown handle
if ( shutdownLevel == Node.NodeShutdownLevel.BuildCompleteSuccess || shutdownLevel == Node.NodeShutdownLevel.BuildCompleteFailure )
{
ShutdownNode(Node.NodeShutdownLevel.ErrorShutdown, false, true);
}
// Signal all the communication threads to exit
shutdownEvent.Set();
}
}
/// <summary>
/// This methods activates the local node
/// </summary>
internal void Activate
(
Hashtable environmentVariables,
LoggerDescription[] nodeLoggers,
int nodeId,
BuildPropertyGroup parentGlobalProperties,
ToolsetDefinitionLocations toolsetSearchLocations,
int parentId,
string parentStartupDirectory
)
{
ErrorUtilities.VerifyThrow(node == null, "Expected node to be null on activation.");
this.parentProcessId = parentId;
engineCallback.Reset();
inUseEvent.Set();
// Clear the environment so that we dont have extra variables laying around, this
// may be a performance hog but needs to be done
IDictionary variableDictionary = Environment.GetEnvironmentVariables();
foreach (string variableName in variableDictionary.Keys)
{
Environment.SetEnvironmentVariable(variableName, null);
}
foreach(string key in environmentVariables.Keys)
{
Environment.SetEnvironmentVariable(key,(string)environmentVariables[key]);
}
// Host the msbuild engine and system
node = new Node(nodeId, nodeLoggers, engineCallback, parentGlobalProperties, toolsetSearchLocations, parentStartupDirectory);
// Write the initialization complete event out directly
LocalCallDescriptorForInitializationComplete callDescriptor =
new LocalCallDescriptorForInitializationComplete(Process.GetCurrentProcess().Id);
// Post the message indicating that the initialization is complete
engineCallback.PostMessageToParent(callDescriptor, true);
}
/// <summary>
/// This method checks is the parent process has not exited
/// </summary>
/// <returns>True if the parent process is still alive</returns>
private bool IsParentProcessAlive()
{
bool isParentAlive = true;
try
{
// Check if the parent is still there
if (Process.GetProcessById(parentProcessId).HasExited)
{
isParentAlive = false;
}
}
catch (ArgumentException)
{
isParentAlive = false;
}
if (!isParentAlive)
{
// No logging's going to reach the parent at this point:
// indicate on the console what's going on
string message = ResourceUtilities.FormatResourceString("ParentProcessUnexpectedlyDied", node.NodeId);
Console.WriteLine(message);
}
return isParentAlive;
}
/// <summary>
/// Any error occuring in the shared memory transport is considered to be fatal
/// </summary>
/// <param name="originalException"></param>
/// <exception cref="Exception">Re-throws exception passed in</exception>
internal void ReportFatalCommunicationError(Exception originalException)
{
try
{
DumpExceptionToFile(originalException);
}
finally
{
if (node != null)
{
node.ReportFatalCommunicationError(originalException, null);
}
}
}
/// <summary>
/// This function is used to report exceptions which don't indicate breakdown
/// of communication with the parent
/// </summary>
/// <param name="originalException"></param>
internal void ReportNonFatalCommunicationError(Exception originalException)
{
if (node != null)
{
try
{
DumpExceptionToFile(originalException);
}
finally
{
node.ReportUnhandledError(originalException);
}
}
else
{
// Since there is no node object report rethrow the exception
ReportFatalCommunicationError(originalException);
}
}
#endregion
#region Properties
internal static string DumpFileName
{
get
{
return dumpFileName;
}
}
#endregion
#region Member data
private Node node;
private SharedMemory sharedMemory;
private LocalNodeCallback engineCallback;
private int parentProcessId;
private int nodeNumber;
private Thread readerThread;
private static object dumpFileLocker = new Object();
// Public named events
// If this event is set the node host process is currently running
private static EventWaitHandle globalNodeActive;
// If this event is set the node is currently running a build
private static EventWaitHandle globalNodeInUse;
// If this event exists the node is reserved for use by a particular parent engine
// the node keeps a handle to this event during builds to prevent it from being used
// by another parent engine if the original dies
private static EventWaitHandle globalNodeReserveHandle;
// If this event is set the node will immediatelly exit. The event is used by the
// parent engine to cause the node to exit if communication is lost.
private static EventWaitHandle globalNodeErrorShutdown;
// This event is used to cause the child to create the shared memory structures to start communication
// with the parent
private static EventWaitHandle globalInitiateActivationEvent;
// This event is used to indicate to the parent that shared memory buffers have been created and are ready for
// use
private static EventWaitHandle globalNodeActivate;
// Private local events
private static ManualResetEvent communicationThreadExitEvent = new ManualResetEvent(false);
private static ManualResetEvent shutdownEvent = new ManualResetEvent(false);
private static ManualResetEvent notInUseEvent = new ManualResetEvent(false);
/// <summary>
/// Indicates the node is now in use. This means the node has recieved an activate command with initialization
/// data from the parent procss
/// </summary>
private static ManualResetEvent inUseEvent = new ManualResetEvent(false);
/// <summary>
/// Randomly generated file name for all exceptions thrown by this node that need to be dumped to a file.
/// (There may be more than one exception, if they occur on different threads.)
/// </summary>
private static string dumpFileName = null;
// Timeouts && Constants
private const int inactivityTimeout = 60 * 1000; // 60 seconds of inactivity to exit
private const int parentCheckInterval = 5 * 1000; // Check if the parent process is there every 5 seconds
#endregion
}
}
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using System;
using System.Collections.Generic;
namespace HUX.Utility
{
public class AABBTree<T> where T : class
{
#region Private Classes
/// <summary>
/// Node class for the tree. CAn be either a branch or a leaf.
/// </summary>
private class AABBNode
{
#region Public Static Functions
/// <summary>
/// Creates a node containing both bounds.
/// </summary>
/// <param name="rightBounds"></param>
/// <param name="leftBounds"></param>
/// <returns></returns>
public static AABBNode CreateNode(Bounds rightBounds, Bounds leftBounds)
{
AABBNode newNode = new AABBNode();
newNode.Bounds = rightBounds.ExpandToContian(leftBounds);
return newNode;
}
/// <summary>
/// Creates a node with the bounds and data.
/// </summary>
/// <param name="bounds"></param>
/// <param name="data"></param>
/// <returns></returns>
public static AABBNode CreateNode(Bounds bounds, T data)
{
AABBNode newNode = new AABBNode();
newNode.Bounds = bounds;
newNode.UserData = data;
// Determine if we want a margin bounds;
return newNode;
}
#endregion
//-----------------------------------------------------------------------------------------------------------
#region Public Variables
/// <summary>
/// Children of this node.
/// </summary>
public AABBNode[] Children = new AABBNode[2];
/// <summary>
/// The Axis Aligned Bounding Box for this node.
/// </summary>
public Bounds Bounds;
/// <summary>
/// User Data for this node.
/// </summary>
public T UserData;
#endregion
//-----------------------------------------------------------------------------------------------------------
#region Private Variables
/// <summary>
/// A weak reference to the parent so the tree will get cleaned up if the root node is no longer referenced.
/// </summary>
private WeakReference m_ParentRef;
#endregion
//-----------------------------------------------------------------------------------------------------------
#region Accessors
/// <summary>
/// True if this is a branch node with no children assigned.
/// </summary>
public bool IsLeaf
{
get
{
return Children[0] == null && Children[1] == null;
}
}
/// <summary>
/// Accessor for setting/getting the parent.
/// </summary>
public AABBNode Parent
{
get
{
return m_ParentRef != null && m_ParentRef.IsAlive ? m_ParentRef.Target as AABBNode : null;
}
set
{
if (value == null)
{
m_ParentRef = null;
}
else
{
m_ParentRef = new WeakReference(value);
}
}
}
#endregion
//-----------------------------------------------------------------------------------------------------------
#region Public Functions
/// <summary>
/// Sets the children for this node.
/// </summary>
/// <param name="child1"></param>
/// <param name="child2"></param>
public void SetChildren(AABBNode child1, AABBNode child2)
{
child1.Parent = this;
child2.Parent = this;
Children[0] = child1;
Children[1] = child2;
}
/// <summary>
/// Sets the bounds to the size of both children.
/// </summary>
public void RebuildBounds()
{
Bounds = Children[0].Bounds.ExpandToContian(Children[1].Bounds);
}
#endregion
}
#endregion
//-----------------------------------------------------------------------------------------------------------
#region Private Variables
/// <summary>
/// The root node of the tree.
/// </summary>
private AABBNode m_RootNode;
#endregion
//-----------------------------------------------------------------------------------------------------------
#region Public Functions
/// <summary>
/// Creates a new node with the provided bounds.
/// </summary>
/// <param name="bounds"></param>
/// <param name="data"></param>
public void Insert(Bounds bounds, T data)
{
AABBNode newNode = AABBNode.CreateNode(bounds, data);
if (m_RootNode == null)
{
m_RootNode = newNode;
}
else
{
RecursiveInsert(m_RootNode, newNode);
}
}
/// <summary>
/// Removes the node containing data.
/// </summary>
/// <param name="data"></param>
public void Remove(T data)
{
AABBNode node = FindNode(data);
RemoveNode(node);
}
/// <summary>
/// Removes the node with the bounds. If two nodes have the exact same bounds only the first one found will be removed.
/// </summary>
/// <param name="bounds"></param>
public void Remove(Bounds bounds)
{
AABBNode node = FindNode(bounds);
RemoveNode(node);
}
/// <summary>
/// Destroys all nodes in the tree.
/// </summary>
public void Clear()
{
// All we need to do is remove the root node reference. The garbage collector will do the rest.
m_RootNode = null;
}
#endregion
//-----------------------------------------------------------------------------------------------------------
#region Private Functions
/// <summary>
/// Recursively Insert the new Node until we hit a leaf node. Then branch and insert both nodes.
/// </summary>
/// <param name="currentNode"></param>
/// <param name="newNode"></param>
private void RecursiveInsert(AABBNode currentNode, AABBNode newNode)
{
AABBNode branch = currentNode;
if (currentNode.IsLeaf)
{
branch = AABBNode.CreateNode(currentNode.Bounds, newNode.Bounds);
branch.Parent = currentNode.Parent;
if (currentNode == m_RootNode)
{
m_RootNode = branch;
}
else
{
branch.Parent.Children[branch.Parent.Children[0] == currentNode ? 0 : 1] = branch;
}
branch.SetChildren(currentNode, newNode);
}
else
{
Bounds withChild1 = branch.Children[0].Bounds.ExpandToContian(newNode.Bounds);
Bounds withChild2 = branch.Children[1].Bounds.ExpandToContian(newNode.Bounds);
float volume1 = withChild1.Volume();
float volume2 = withChild2.Volume();
RecursiveInsert((volume1 <= volume2) ? branch.Children[0] : branch.Children[1], newNode);
}
branch.RebuildBounds();
}
/// <summary>
/// Finds the node that has the assigned user data.
/// </summary>
/// <param name="userData"></param>
/// <returns></returns>
private AABBNode FindNode(T userData)
{
AABBNode foundNode = null;
List<AABBNode> nodesToSearch = new List<AABBNode>();
nodesToSearch.Add(m_RootNode);
while (nodesToSearch.Count > 0)
{
AABBNode currentNode = nodesToSearch[0];
nodesToSearch.RemoveAt(0);
if (currentNode.UserData == userData)
{
foundNode = currentNode;
break;
}
else if (!currentNode.IsLeaf)
{
nodesToSearch.AddRange(currentNode.Children);
}
}
return foundNode;
}
/// <summary>
/// Finds the leaf node that matches bounds.
/// </summary>
/// <param name="bounds"></param>
/// <returns></returns>
private AABBNode FindNode(Bounds bounds)
{
AABBNode foundNode = null;
AABBNode currentNode = m_RootNode;
while (currentNode != null)
{
if (currentNode.IsLeaf)
{
foundNode = currentNode.Bounds == bounds ? currentNode : null;
break;
}
else
{
//Which child node if any would the bounds be in?
if (currentNode.Children[0].Bounds.ContainsBounds(bounds))
{
currentNode = currentNode.Children[0];
}
else if (currentNode.Children[1].Bounds.ContainsBounds(bounds))
{
currentNode = currentNode.Children[1];
}
else
{
currentNode = null;
}
}
}
return foundNode;
}
/// <summary>
/// Removes a node from the tree
/// </summary>
/// <param name="node"></param>
private void RemoveNode(AABBNode node)
{
AABBNode nodeParent = node.Parent;
if (node == m_RootNode)
{
m_RootNode = null;
}
else
{
AABBNode otherChild = nodeParent.Children[0] == node ? nodeParent.Children[1] : nodeParent.Children[0];
if (nodeParent.Parent == null)
{
m_RootNode = otherChild;
otherChild.Parent = null;
}
else
{
int childIndex = nodeParent.Parent.Children[0] == nodeParent ? 0 : 1;
nodeParent.Parent.Children[childIndex] = otherChild;
otherChild.Parent = nodeParent.Parent;
}
UpdateNodeBoundUp(otherChild.Parent);
}
}
/// <summary>
/// Updates the bounds nonleaf node object moving up the Parent tree to Root.
/// </summary>
/// <param name="node"></param>
private void UpdateNodeBoundUp(AABBNode node)
{
if (node != null)
{
if (!node.IsLeaf)
{
node.RebuildBounds();
}
UpdateNodeBoundUp(node.Parent);
}
}
#endregion
}
}
|
//
// Copyright (c) 2004-2006 Jaroslaw Kowalski <jaak@jkowalski.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 Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using NLog.Internal;
using NLog.Config;
using NLog.Conditions;
using System.Collections.Generic;
namespace NLog.Targets.Wrappers
{
/// <summary>
/// A target wrapper that filters buffered log entries based on a set of conditions
/// that are evaluated on all events.
/// </summary>
/// <remarks>
/// PostFilteringWrapper must be used with some type of buffering target or wrapper, such as
/// AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper.
/// </remarks>
/// <example>
/// <p>
/// This example works like this. If there are no Warn,Error or Fatal messages in the buffer
/// only Info messages are written to the file, but if there are any warnings or errors,
/// the output includes detailed trace (levels >= Debug). You can plug in a different type
/// of buffering wrapper (such as ASPNetBufferingWrapper) to achieve different
/// functionality.
/// </p>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" src="examples/targets/Configuration File/PostFilteringWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" src="examples/targets/Configuration API/PostFilteringWrapper/Simple/Example.cs" />
/// </example>
[Target("PostFilteringWrapper", IgnoresLayout = true, IsWrapper = true)]
public class PostFilteringTargetWrapper: WrapperTargetBase
{
private ConditionExpression _defaultFilter;
private FilteringRuleCollection _rules = new FilteringRuleCollection();
/// <summary>
/// Creates a new instance of <see cref="PostFilteringTargetWrapper"/>.
/// </summary>
public PostFilteringTargetWrapper()
{
}
/// <summary>
/// Default filter to be applied when no specific rule matches.
/// </summary>
public string DefaultFilter
{
get { return _defaultFilter.ToString(); }
set { _defaultFilter = ConditionParser.ParseExpression(value); }
}
/// <summary>
/// Collection of filtering rules. The rules are processed top-down
/// and the first rule that matches determines the filtering condition to
/// be applied to log events.
/// </summary>
[ArrayParameter(typeof(FilteringRule), "when")]
public FilteringRuleCollection Rules
{
get { return _rules; }
}
/// <summary>
/// Evaluates all filtering rules to find the first one that matches.
/// The matching rule determines the filtering condition to be applied
/// to all items in a buffer. If no condition matches, default filter
/// is applied to the array of log events.
/// </summary>
/// <param name="logEvents">Array of log events to be post-filtered.</param>
public override void Write(LogEventInfo[] logEvents)
{
ConditionExpression resultFilter = null;
if (InternalLogger.IsTraceEnabled)
{
InternalLogger.Trace("Input: {0} events", logEvents.Length);
}
// evaluate all the rules to get the filtering condition
for (int i = 0; i < logEvents.Length; ++i)
{
for (int j = 0; j < _rules.Count; ++j)
{
object v = _rules[j].ExistsCondition.Evaluate(logEvents[i]);
if (v is bool && (bool)v)
{
if (InternalLogger.IsTraceEnabled)
InternalLogger.Trace("Rule matched: {0}", _rules[j].ExistsCondition);
resultFilter = _rules[j].FilterCondition;
break;
}
}
if (resultFilter != null)
break;
}
if (resultFilter == null)
resultFilter = _defaultFilter;
if (InternalLogger.IsTraceEnabled)
InternalLogger.Trace("Filter to apply: {0}", resultFilter);
// apply the condition to the buffer
List<LogEventInfo> resultBuffer = new List<LogEventInfo>();
for (int i = 0; i < logEvents.Length; ++i)
{
object v = resultFilter.Evaluate(logEvents[i]);
if (v is bool && (bool)v)
resultBuffer.Add(logEvents[i]);
}
if (InternalLogger.IsTraceEnabled)
InternalLogger.Trace("After filtering: {0} events", resultBuffer.Count);
if (resultBuffer.Count > 0)
{
WrappedTarget.Write(resultBuffer.ToArray());
}
}
/// <summary>
/// Processes a single log event. Not very useful for this post-filtering
/// wrapper.
/// </summary>
/// <param name="logEvent">Log event.</param>
public override void Write(LogEventInfo logEvent)
{
Write(new LogEventInfo[] { logEvent });
}
/// <summary>
/// Adds all layouts used by this target to the specified collection.
/// </summary>
/// <param name="layouts">The collection to add layouts to.</param>
public override void PopulateLayouts(LayoutCollection layouts)
{
base.PopulateLayouts(layouts);
foreach (FilteringRule fr in Rules)
{
fr.FilterCondition.PopulateLayouts(layouts);
fr.ExistsCondition.PopulateLayouts(layouts);
}
_defaultFilter.PopulateLayouts(layouts);
}
}
} |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Messaging;
using System.Transactions;
using Common.Logging;
using Spring.Transaction;
namespace Spring.Messaging.Listener
{
/// <summary>
/// A MessageListenerContainer that uses distributed (DTC) based transactions. Exceptions are
/// handled by instances of <see cref="IDistributedTransactionExceptionHandler"/>.
/// </summary>
/// <remarks>
/// <para>
/// Starts a DTC based transaction before receiving the message. The transaction is
/// automaticaly promoted to 2PC to avoid the default behaivor of transactional promotion.
/// Database and messaging operations will commit or rollback together.
/// </para>
/// <para>
/// If you only want local message based transactions use the
/// <see cref="TransactionalMessageListenerContainer"/>. With some simple programming
/// you may also achieve 'exactly once' processing using the
/// <see cref="TransactionalMessageListenerContainer"/>.
/// </para>
/// <para>
/// Poison messages can be detected and sent to another queue using Spring's
/// <see cref="SendToQueueDistributedTransactionExceptionHandler"/>.
/// </para>
/// </remarks>
public class DistributedTxMessageListenerContainer : AbstractTransactionalMessageListenerContainer
{
#region Logging Definition
private static readonly ILog LOG = LogManager.GetLogger(typeof (DistributedTxMessageListenerContainer));
#endregion
private IDistributedTransactionExceptionHandler distributedTransactionExceptionHandler;
/// <summary>
/// Gets or sets the distributed transaction exception handler.
/// </summary>
/// <value>The distributed transaction exception handler.</value>
public IDistributedTransactionExceptionHandler DistributedTransactionExceptionHandler
{
get { return distributedTransactionExceptionHandler; }
set { distributedTransactionExceptionHandler = value; }
}
/// <summary>
/// Set the transaction name to be the spring object name.
/// Call base class Initialize() functionality.
/// </summary>
public override void Initialize()
{
// Use object name as default transaction name.
if (TransactionDefinition.Name == null)
{
TransactionDefinition.Name = ObjectName;
}
// Proceed with superclass initialization.
base.Initialize();
}
/// <summary>
/// Does the receive and execute using TxPlatformTransactionManager. Starts a distributed
/// transaction before calling Receive.
/// </summary>
/// <param name="mq">The message queue.</param>
/// <param name="status">The transactional status.</param>
/// <returns>
/// true if should continue peeking, false otherwise.
/// </returns>
protected override bool DoReceiveAndExecuteUsingPlatformTransactionManager(MessageQueue mq,
ITransactionStatus status)
{
#region Logging
if (LOG.IsDebugEnabled)
{
LOG.Debug("Executing DoReceiveAndExecuteUsingTxScopeTransactionManager");
}
#endregion Logging
//We are sure to be talking to a second resource manager, so avoid going through
//the promotable transaction and force a distributed transaction right from the start.
TransactionInterop.GetTransmitterPropagationToken(System.Transactions.Transaction.Current);
Message message;
try
{
message = mq.Receive(TimeSpan.Zero, MessageQueueTransactionType.Automatic);
}
catch (MessageQueueException ex)
{
if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
{
//expected to occur occasionally
#region Logging
if (LOG.IsTraceEnabled)
{
LOG.Trace(
"MessageQueueErrorCode.IOTimeout: No message available to receive. May have been processed by another thread.");
}
#endregion
status.SetRollbackOnly();
return false; // no more peeking unless this is the last listener thread
}
else
{
// A real issue in receiving the message
lock (messageQueueMonitor)
{
mq.Close();
MessageQueue.ClearConnectionCache();
}
throw; // will cause rollback in surrounding platform transaction manager and log exception
}
}
if (message == null)
{
#region Logging
if (LOG.IsTraceEnabled)
{
LOG.Trace("Message recieved is null from Queue = [" + mq.Path + "]");
}
#endregion
status.SetRollbackOnly();
return false; // no more peeking unless this is the last listener thread
}
try
{
#region Logging
if (LOG.IsDebugEnabled)
{
LOG.Debug("Received message [" + message.Id + "] on queue [" + mq.Path + "]");
}
#endregion
MessageReceived(message);
if (DistributedTransactionExceptionHandler != null)
{
if (DistributedTransactionExceptionHandler.IsPoisonMessage(message))
{
DistributedTransactionExceptionHandler.HandlePoisonMessage(message);
return true; // will remove from queue and continue receive loop.
}
}
DoExecuteListener(message);
}
catch (Exception ex)
{
HandleDistributedTransactionListenerException(ex, message);
throw; // will rollback and keep message on the queue.
}
finally
{
message.Dispose();
}
return true;
}
/// <summary>
/// Handles the distributed transaction listener exception by calling the
/// <see cref="IDistributedTransactionExceptionHandler"/> if not null.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
protected virtual void HandleDistributedTransactionListenerException(Exception exception, Message message)
{
IDistributedTransactionExceptionHandler exceptionHandler = DistributedTransactionExceptionHandler;
if (exceptionHandler != null)
{
exceptionHandler.OnException(exception, message);
}
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using FluentAssertions.Collections;
using FluentAssertions.Common;
using FluentAssertions.Equivalency;
using FluentAssertions.Numeric;
using FluentAssertions.Primitives;
using FluentAssertions.Types;
namespace FluentAssertions
{
/// <summary>
/// Contains extension methods for custom assertions in unit tests.
/// </summary>
[DebuggerNonUserCode]
internal static class InternalAssertionExtensions
{
/// <summary>
/// Invokes the specified action on an subject so that you can chain it with any of the ShouldThrow or ShouldNotThrow
/// overloads.
/// </summary>
public static Action Invoking<T>(this T subject, Action<T> action)
{
return () => action(subject);
}
/// <summary>
/// Forces enumerating a collection. Should be used to assert that a method that uses the
/// <c>yield</c> keyword throws a particular exception.
/// </summary>
public static Action Enumerating(this Func<IEnumerable> enumerable)
{
return () => ForceEnumeration(enumerable);
}
/// <summary>
/// Forces enumerating a collection. Should be used to assert that a method that uses the
/// <c>yield</c> keyword throws a particular exception.
/// </summary>
public static Action Enumerating<T>(this Func<IEnumerable<T>> enumerable)
{
return () => ForceEnumeration(() => (IEnumerable)enumerable());
}
private static void ForceEnumeration(Func<IEnumerable> enumerable)
{
foreach (object item in enumerable())
{
// Do nothing
}
}
/// <summary>
/// Returns an <see cref="ObjectAssertions"/> object that can be used to assert the
/// current <see cref="object"/>.
/// </summary>
public static ObjectAssertions Should(this object actualValue)
{
return new ObjectAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="BooleanAssertions"/> object that can be used to assert the
/// current <see cref="bool"/>.
/// </summary>
public static BooleanAssertions Should(this bool actualValue)
{
return new BooleanAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableBooleanAssertions"/> object that can be used to assert the
/// current nullable <see cref="bool"/>.
/// </summary>
public static NullableBooleanAssertions Should(this bool? actualValue)
{
return new NullableBooleanAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="GuidAssertions"/> object that can be used to assert the
/// current <see cref="Guid"/>.
/// </summary>
public static GuidAssertions Should(this Guid actualValue)
{
return new GuidAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableGuidAssertions"/> object that can be used to assert the
/// current nullable <see cref="Guid"/>.
/// </summary>
public static NullableGuidAssertions Should(this Guid? actualValue)
{
return new NullableGuidAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="NonGenericCollectionAssertions"/> object that can be used to assert the
/// current <see cref="IEnumerable"/>.
/// </summary>
public static NonGenericCollectionAssertions Should(this IEnumerable actualValue)
{
return new NonGenericCollectionAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="GenericCollectionAssertions{T}"/> object that can be used to assert the
/// current <see cref="IEnumerable{T}"/>.
/// </summary>
public static GenericCollectionAssertions<T> Should<T>(this IEnumerable<T> actualValue)
{
return new GenericCollectionAssertions<T>(actualValue);
}
/// <summary>
/// Returns an <see cref="StringCollectionAssertions"/> object that can be used to assert the
/// current <see cref="IEnumerable{T}"/>.
/// </summary>
public static StringCollectionAssertions Should(this IEnumerable<string> @this)
{
return new StringCollectionAssertions(@this);
}
/// <summary>
/// Returns an <see cref="GenericDictionaryAssertions{TKey, TValue}"/> object that can be used to assert the
/// current <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
public static GenericDictionaryAssertions<TKey, TValue> Should<TKey, TValue>(this IDictionary<TKey, TValue> actualValue)
{
return new GenericDictionaryAssertions<TKey, TValue>(actualValue);
}
/// <summary>
/// Returns an <see cref="DateTimeOffsetAssertions"/> object that can be used to assert the
/// current <see cref="DateTime"/>.
/// </summary>
public static DateTimeOffsetAssertions Should(this DateTime actualValue)
{
return new DateTimeOffsetAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableDateTimeOffsetAssertions"/> object that can be used to assert the
/// current nullable <see cref="DateTime"/>.
/// </summary>
public static NullableDateTimeOffsetAssertions Should(this DateTime? actualValue)
{
return new NullableDateTimeOffsetAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="ComparableTypeAssertions{T}"/> object that can be used to assert the
/// current <see cref="IComparable{T}"/>.
/// </summary>
public static ComparableTypeAssertions<T> Should<T>(this IComparable<T> comparableValue)
{
return new ComparableTypeAssertions<T>(comparableValue);
}
/// <summary>
/// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the
/// current <see cref="int"/>.
/// </summary>
public static NumericAssertions<int> Should(this int actualValue)
{
return new NumericAssertions<int>(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the
/// current nullable <see cref="int"/>.
/// </summary>
public static NullableNumericAssertions<int> Should(this int? actualValue)
{
return new NullableNumericAssertions<int>(actualValue);
}
/// <summary>
/// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the
/// current <see cref="decimal"/>.
/// </summary>
public static NumericAssertions<decimal> Should(this decimal actualValue)
{
return new NumericAssertions<decimal>(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the
/// current nullable <see cref="decimal"/>.
/// </summary>
public static NullableNumericAssertions<decimal> Should(this decimal? actualValue)
{
return new NullableNumericAssertions<decimal>(actualValue);
}
/// <summary>
/// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the
/// current <see cref="byte"/>.
/// </summary>
public static NumericAssertions<byte> Should(this byte actualValue)
{
return new NumericAssertions<byte>(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the
/// current nullable <see cref="byte"/>.
/// </summary>
public static NullableNumericAssertions<byte> Should(this byte? actualValue)
{
return new NullableNumericAssertions<byte>(actualValue);
}
/// <summary>
/// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the
/// current <see cref="short"/>.
/// </summary>
public static NumericAssertions<short> Should(this short actualValue)
{
return new NumericAssertions<short>(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the
/// current nullable <see cref="short"/>.
/// </summary>
public static NullableNumericAssertions<short> Should(this short? actualValue)
{
return new NullableNumericAssertions<short>(actualValue);
}
/// <summary>
/// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the
/// current <see cref="long"/>.
/// </summary>
public static NumericAssertions<long> Should(this long actualValue)
{
return new NumericAssertions<long>(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the
/// current nullable <see cref="long"/>.
/// </summary>
public static NullableNumericAssertions<long> Should(this long? actualValue)
{
return new NullableNumericAssertions<long>(actualValue);
}
/// <summary>
/// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the
/// current <see cref="float"/>.
/// </summary>
public static NumericAssertions<float> Should(this float actualValue)
{
return new NumericAssertions<float>(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the
/// current nullable <see cref="float"/>.
/// </summary>
public static NullableNumericAssertions<float> Should(this float? actualValue)
{
return new NullableNumericAssertions<float>(actualValue);
}
/// <summary>
/// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the
/// current <see cref="double"/>.
/// </summary>
public static NumericAssertions<double> Should(this double actualValue)
{
return new NumericAssertions<double>(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the
/// current nullable <see cref="double"/>.
/// </summary>
public static NullableNumericAssertions<double> Should(this double? actualValue)
{
return new NullableNumericAssertions<double>(actualValue);
}
/// <summary>
/// Returns an <see cref="StringAssertions"/> object that can be used to assert the
/// current <see cref="string"/>.
/// </summary>
public static StringAssertions Should(this string actualValue)
{
return new StringAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="SimpleTimeSpanAssertions"/> object that can be used to assert the
/// current <see cref="TimeSpan"/>.
/// </summary>
public static SimpleTimeSpanAssertions Should(this TimeSpan actualValue)
{
return new SimpleTimeSpanAssertions(actualValue);
}
/// <summary>
/// Returns an <see cref="NullableSimpleTimeSpanAssertions"/> object that can be used to assert the
/// current nullable <see cref="TimeSpan"/>.
/// </summary>
public static NullableSimpleTimeSpanAssertions Should(this TimeSpan? actualValue)
{
return new NullableSimpleTimeSpanAssertions(actualValue);
}
/// <summary>
/// Returns a <see cref="TypeAssertions"/> object that can be used to assert the
/// current <see cref="System.Type"/>.
/// </summary>
public static TypeAssertions Should(this Type subject)
{
return new TypeAssertions(subject);
}
/// <summary>
/// Returns a <see cref="TypeAssertions"/> object that can be used to assert the
/// current <see cref="System.Type"/>.
/// </summary>
public static TypeSelectorAssertions Should(this TypeSelector typeSelector)
{
return new TypeSelectorAssertions(typeSelector.ToArray());
}
/// <summary>
/// Returns a <see cref="MethodInfoAssertions"/> object that can be used to assert the current <see cref="MethodInfo"/>.
/// </summary>
/// <seealso cref="TypeAssertions"/>
public static MethodInfoAssertions Should(this MethodInfo methodInfo)
{
return new MethodInfoAssertions(methodInfo);
}
/// <summary>
/// Returns a <see cref="MethodInfoSelectorAssertions"/> object that can be used to assert the methods returned by the
/// current <see cref="MethodInfoSelector"/>.
/// </summary>
/// <seealso cref="TypeAssertions"/>
public static MethodInfoSelectorAssertions Should(this MethodInfoSelector methodSelector)
{
return new MethodInfoSelectorAssertions(methodSelector.ToArray());
}
/// <summary>
/// Returns a <see cref="PropertyInfoAssertions"/> object that can be used to assert the
/// current <see cref="PropertyInfoSelector"/>.
/// </summary>
/// <seealso cref="TypeAssertions"/>
public static PropertyInfoAssertions Should(this PropertyInfo propertyInfo)
{
return new PropertyInfoAssertions(propertyInfo);
}
/// <summary>
/// Returns a <see cref="PropertyInfoAssertions"/> object that can be used to assert the properties returned by the
/// current <see cref="PropertyInfoSelector"/>.
/// </summary>
/// <seealso cref="TypeAssertions"/>
public static PropertyInfoSelectorAssertions Should(this PropertyInfoSelector propertyInfoSelector)
{
return new PropertyInfoSelectorAssertions(propertyInfoSelector.ToArray());
}
/// <summary>
/// Asserts that an object is equivalent to another object.
/// </summary>
/// <remarks>
/// Objects are equivalent when both object graphs have equally named properties with the same value,
/// irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// Notice that actual behavior is determined by the <see cref="EquivalencyAssertionOptions.Default"/> instance of the
/// <see cref="EquivalencyAssertionOptions"/> class.
/// </remarks>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public static void ShouldBeEquivalentTo<T>(this T subject, object expectation, string because = "",
params object[] becauseArgs)
{
ShouldBeEquivalentTo(subject, expectation, config => config, because, becauseArgs);
}
/// <summary>
/// Asserts that an object is equivalent to another object.
/// </summary>
/// <remarks>
/// Objects are equivalent when both object graphs have equally named properties with the same value,
/// irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// </remarks>
/// <param name="config">
/// A reference to the <see cref="EquivalencyAssertionOptions.Default"/> configuration object that can be used
/// to influence the way the object graphs are compared. You can also provide an alternative instance of the
/// <see cref="EquivalencyAssertionOptions"/> class.
/// </param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public static void ShouldBeEquivalentTo<T>(this T subject, object expectation,
Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config, string because = "",
params object[] becauseArgs)
{
IEquivalencyAssertionOptions options = config(AssertionOptions.CloneDefaults<T>());
var context = new EquivalencyValidationContext
{
Subject = subject,
Expectation = expectation,
CompileTimeType = typeof(T),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter
};
new EquivalencyValidator(options).AssertEquality(context);
}
public static void ShouldAllBeEquivalentTo<T>(this IEnumerable<T> subject, IEnumerable expectation,
string because = "", params object[] becauseArgs)
{
ShouldAllBeEquivalentTo(subject, expectation, config => config, because, becauseArgs);
}
public static void ShouldAllBeEquivalentTo<T>(this IEnumerable<T> subject, IEnumerable expectation,
Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config, string because = "",
params object[] becauseArgs)
{
IEquivalencyAssertionOptions options = config(AssertionOptions.CloneDefaults<T>());
var context = new EquivalencyValidationContext
{
Subject = subject,
Expectation = expectation,
CompileTimeType = typeof(T),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter
};
new EquivalencyValidator(options).AssertEquality(context);
}
/// <summary>
/// Safely casts the specified object to the type specified through <typeparamref name="TTo"/>.
/// </summary>
/// <remarks>
/// Has been introduced to allow casting objects without breaking the fluent API.
/// </remarks>
/// <typeparam name="TTo"></typeparam>
public static TTo As<TTo>(this object subject)
{
return subject is TTo ? (TTo)subject : default(TTo);
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class TakesScreenshotTest : DriverTestFixture
{
[TearDown]
public void SwitchToTop()
{
driver.SwitchTo().DefaultContent();
}
[Test]
public void GetScreenshotAsFile()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = simpleTestPage;
string filename = Path.Combine(Path.GetTempPath(), "snapshot" + new Random().Next().ToString() + ".png");
Screenshot screenImage = screenshotCapableDriver.GetScreenshot();
screenImage.SaveAsFile(filename, ScreenshotImageFormat.Png);
Assert.That(File.Exists(filename), Is.True);
Assert.That(new FileInfo(filename).Length, Is.GreaterThan(0));
File.Delete(filename);
}
[Test]
public void GetScreenshotAsBase64()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = simpleTestPage;
Screenshot screenImage = screenshotCapableDriver.GetScreenshot();
string base64 = screenImage.AsBase64EncodedString;
Assert.That(base64.Length, Is.GreaterThan(0));
}
[Test]
public void GetScreenshotAsBinary()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = simpleTestPage;
Screenshot screenImage = screenshotCapableDriver.GetScreenshot();
byte[] bytes = screenImage.AsByteArray;
Assert.That(bytes.Length, Is.GreaterThan(0));
}
[Test]
public void ShouldCaptureScreenshotOfCurrentViewport()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step */ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
public void ShouldTakeScreenshotsOfAnElement()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html");
IWebElement element = driver.FindElement(By.Id("cell11"));
ITakesScreenshot screenshotCapableElement = element as ITakesScreenshot;
if (screenshotCapableElement == null)
{
return;
}
Screenshot screenImage = screenshotCapableElement.GetScreenshot();
byte[] imageData = screenImage.AsByteArray;
Assert.That(imageData, Is.Not.Null);
Assert.That(imageData.Length, Is.GreaterThan(0));
Color pixelColor = GetPixelColor(screenImage, 1, 1);
string pixelColorString = FormatColorToHex(pixelColor.ToArgb());
Assert.AreEqual("#0f12f7", pixelColorString);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithLongX()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 50,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithLongY()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 50);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithTooLongX()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_too_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 100,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithTooLongY()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_too_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 100);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithTooLongXandY()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_too_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 100,
/* stepY in pixels */ 100);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
public void ShouldCaptureScreenshotAtFramePage()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html");
WaitFor(FrameToBeAvailableAndSwitchedTo("frame1"), "Did not switch to frame1");
WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content");
driver.SwitchTo().DefaultContent();
WaitFor(FrameToBeAvailableAndSwitchedTo("frame2"), "Did not switch to frame2");
WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content");
driver.SwitchTo().DefaultContent();
WaitFor(TitleToBe("screen test"), "Title was not expected value");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with frames will be taken for full page
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.IE, "Color comparisons fail on IE")]
public void ShouldCaptureScreenshotAtIFramePage()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with Iframes will be taken for full page
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")]
public void ShouldCaptureScreenshotAtFramePageAfterSwitching()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html");
driver.SwitchTo().Frame(driver.FindElement(By.Id("frame2")));
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with frames after switching to a frame
// will be taken for full page
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.IE, "Color comparisons fail on IE")]
[IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")]
public void ShouldCaptureScreenshotAtIFramePageAfterSwitching()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html");
driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe2")));
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with Iframes after switching to a Iframe
// will be taken for full page
CompareColors(expectedColors, actualColors);
}
private string FormatColorToHex(int colorValue)
{
string pixelColorString = string.Format("#{0:x2}{1:x2}{2:x2}", (colorValue & 0xFF0000) >> 16, (colorValue & 0x00FF00) >> 8, (colorValue & 0x0000FF));
return pixelColorString;
}
private void CompareColors(HashSet<string> expectedColors, HashSet<string> actualColors)
{
// Ignore black and white for further comparison
actualColors.Remove("#000000");
actualColors.Remove("#ffffff");
Assert.That(actualColors, Is.EquivalentTo(expectedColors));
}
private HashSet<string> GenerateExpectedColors(int initialColor, int stepColor, int numberOfSamplesX, int numberOfSamplesY)
{
HashSet<string> colors = new HashSet<string>();
int count = 1;
for (int i = 1; i < numberOfSamplesX; i++)
{
for (int j = 1; j < numberOfSamplesY; j++)
{
int color = initialColor + (count * stepColor);
string hex = FormatColorToHex(color);
colors.Add(hex);
count++;
}
}
return colors;
}
private HashSet<string> ScanActualColors(Screenshot screenshot, int stepX, int stepY)
{
HashSet<string> colors = new HashSet<string>();
#if !NETCOREAPP2_0 && !NETSTANDARD2_0
try
{
Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray));
Bitmap bitmap = new Bitmap(image);
int height = bitmap.Height;
int width = bitmap.Width;
Assert.That(width, Is.GreaterThan(0));
Assert.That(height, Is.GreaterThan(0));
for (int i = 0; i < width; i = i + stepX)
{
for (int j = 0; j < height; j = j + stepY)
{
string hex = FormatColorToHex(bitmap.GetPixel(i, j).ToArgb());
colors.Add(hex);
}
}
}
catch (Exception e)
{
Assert.Fail("Unable to get actual colors from screenshot: " + e.Message);
}
Assert.That(colors.Count, Is.GreaterThan(0));
#endif
return colors;
}
private Color GetPixelColor(Screenshot screenshot, int x, int y)
{
Color pixelColor = Color.Black;
#if !NETCOREAPP2_0 && !NETSTANDARD2_0
Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray));
Bitmap bitmap = new Bitmap(image);
pixelColor = bitmap.GetPixel(1, 1);
#endif
return pixelColor;
}
private Func<bool> FrameToBeAvailableAndSwitchedTo(string frameId)
{
return () =>
{
try
{
IWebElement frameElement = driver.FindElement(By.Id(frameId));
driver.SwitchTo().Frame(frameElement);
}
catch(Exception)
{
return false;
}
return true;
};
}
private Func<bool> ElementToBeVisibleWithId(string elementId)
{
return () =>
{
try
{
IWebElement element = driver.FindElement(By.Id(elementId));
return element.Displayed;
}
catch(Exception)
{
return false;
}
};
}
private Func<bool> TitleToBe(string desiredTitle)
{
return () => driver.Title == desiredTitle;
}
}
}
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization.Formatters;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Commands.Resources.Models.Authorization;
using Microsoft.Azure.Commands.Tags.Model;
using Microsoft.Azure.Common.Authentication;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Azure.Management.Authorization.Models;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Newtonsoft.Json;
using ProjectResources = Microsoft.Azure.Commands.Resources.Properties.Resources;
namespace Microsoft.Azure.Commands.Resources.Models
{
public partial class ResourcesClient
{
/// <summary>
/// A string that indicates the value of the resource type name for the RP's operations api
/// </summary>
public const string Operations = "operations";
/// <summary>
/// A string that indicates the value of the registering state enum for a provider
/// </summary>
public const string RegisteredStateName = "Registered";
/// <summary>
/// Used when provisioning the deployment status.
/// </summary>
private List<DeploymentOperation> operations;
public IResourceManagementClient ResourceManagementClient { get; set; }
public IAuthorizationManagementClient AuthorizationManagementClient { get; set; }
public GalleryTemplatesClient GalleryTemplatesClient { get; set; }
// TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094
//public IEventsClient EventsClient { get; set; }
public Action<string> VerboseLogger { get; set; }
public Action<string> ErrorLogger { get; set; }
public Action<string> WarningLogger { get; set; }
/// <summary>
/// Creates new ResourceManagementClient
/// </summary>
/// <param name="profile">Profile containing resources to manipulate</param>
public ResourcesClient(AzureProfile profile)
: this(
AzureSession.ClientFactory.CreateClient<ResourceManagementClient>(profile, AzureEnvironment.Endpoint.ResourceManager),
new GalleryTemplatesClient(profile.Context),
// TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094
//AzureSession.ClientFactory.CreateClient<EventsClient>(context, AzureEnvironment.Endpoint.ResourceManager),
AzureSession.ClientFactory.CreateClient<AuthorizationManagementClient>(profile.Context, AzureEnvironment.Endpoint.ResourceManager))
{
}
/// <summary>
/// Creates new ResourcesClient instance
/// </summary>
/// <param name="resourceManagementClient">The IResourceManagementClient instance</param>
/// <param name="galleryTemplatesClient">The IGalleryClient instance</param>
/// <param name="authorizationManagementClient">The management client instance</param>
public ResourcesClient(
IResourceManagementClient resourceManagementClient,
GalleryTemplatesClient galleryTemplatesClient,
// TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094
//IEventsClient eventsClient,
IAuthorizationManagementClient authorizationManagementClient)
{
GalleryTemplatesClient = galleryTemplatesClient;
// TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094
//EventsClient = eventsClient;
AuthorizationManagementClient = authorizationManagementClient;
this.ResourceManagementClient = resourceManagementClient;
}
/// <summary>
/// Parameterless constructor for mocking
/// </summary>
public ResourcesClient()
{
}
private string GetDeploymentParameters(Hashtable templateParameterObject)
{
if (templateParameterObject != null)
{
return SerializeHashtable(templateParameterObject, addValueLayer: true);
}
else
{
return null;
}
}
public string SerializeHashtable(Hashtable templateParameterObject, bool addValueLayer)
{
if (templateParameterObject == null)
{
return null;
}
Dictionary<string, object> parametersDictionary = templateParameterObject.ToDictionary(addValueLayer);
return JsonConvert.SerializeObject(parametersDictionary, new JsonSerializerSettings
{
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
TypeNameHandling = TypeNameHandling.None,
Formatting = Formatting.Indented
});
}
public virtual PSResourceProvider UnregisterProvider(string providerName)
{
var response = this.ResourceManagementClient.Providers.Unregister(providerName);
if (response.Provider == null)
{
throw new KeyNotFoundException(string.Format(ProjectResources.ResourceProviderUnregistrationFailed, providerName));
}
return response.Provider.ToPSResourceProvider();
}
private string GetTemplate(string templateFile, string galleryTemplateName)
{
string template;
if (!string.IsNullOrEmpty(templateFile))
{
if (Uri.IsWellFormedUriString(templateFile, UriKind.Absolute))
{
template = GeneralUtilities.DownloadFile(templateFile);
}
else
{
template = FileUtilities.DataStore.ReadFileAsText(templateFile);
}
}
else
{
Debug.Assert(!string.IsNullOrEmpty(galleryTemplateName));
string templateUri = GalleryTemplatesClient.GetGalleryTemplateFile(galleryTemplateName);
template = GeneralUtilities.DownloadFile(templateUri);
}
return template;
}
private ResourceGroupExtended CreateOrUpdateResourceGroup(string name, string location, Hashtable[] tags)
{
Dictionary<string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(tags, validate: true);
var result = ResourceManagementClient.ResourceGroups.CreateOrUpdate(name,
new ResourceGroup
{
Location = location,
Tags = tagDictionary
});
return result.ResourceGroup;
}
private void WriteVerbose(string progress)
{
if (VerboseLogger != null)
{
VerboseLogger(progress);
}
}
private void WriteWarning(string warning)
{
if (WarningLogger != null)
{
WarningLogger(warning);
}
}
private void WriteError(string error)
{
if (ErrorLogger != null)
{
ErrorLogger(error);
}
}
private DeploymentExtended ProvisionDeploymentStatus(string resourceGroup, string deploymentName, Deployment deployment)
{
operations = new List<DeploymentOperation>();
return WaitDeploymentStatus(
resourceGroup,
deploymentName,
deployment,
WriteDeploymentProgress,
ProvisioningState.Canceled,
ProvisioningState.Succeeded,
ProvisioningState.Failed);
}
private void WriteDeploymentProgress(string resourceGroup, string deploymentName, Deployment deployment)
{
const string normalStatusFormat = "Resource {0} '{1}' provisioning status is {2}";
const string failureStatusFormat = "Resource {0} '{1}' failed with message '{2}'";
List<DeploymentOperation> newOperations;
DeploymentOperationsListResult result;
result = ResourceManagementClient.DeploymentOperations.List(resourceGroup, deploymentName, null);
newOperations = GetNewOperations(operations, result.Operations);
operations.AddRange(newOperations);
while (!string.IsNullOrEmpty(result.NextLink))
{
result = ResourceManagementClient.DeploymentOperations.ListNext(result.NextLink);
newOperations = GetNewOperations(operations, result.Operations);
operations.AddRange(newOperations);
}
foreach (DeploymentOperation operation in newOperations)
{
string statusMessage;
if (operation.Properties.ProvisioningState != ProvisioningState.Failed)
{
statusMessage = string.Format(normalStatusFormat,
operation.Properties.TargetResource.ResourceType,
operation.Properties.TargetResource.ResourceName,
operation.Properties.ProvisioningState.ToLower());
WriteVerbose(statusMessage);
}
else
{
string errorMessage = ParseErrorMessage(operation.Properties.StatusMessage);
statusMessage = string.Format(failureStatusFormat,
operation.Properties.TargetResource.ResourceType,
operation.Properties.TargetResource.ResourceName,
errorMessage);
WriteError(statusMessage);
}
}
}
public static string ParseErrorMessage(string statusMessage)
{
CloudError error = CloudException.ParseXmlOrJsonError(statusMessage);
if (error.Message == null)
{
return error.OriginalMessage;
}
else
{
return error.Message;
}
}
private DeploymentExtended WaitDeploymentStatus(
string resourceGroup,
string deploymentName,
Deployment basicDeployment,
Action<string, string, Deployment> job,
params string[] status)
{
DeploymentExtended deployment;
do
{
if (job != null)
{
job(resourceGroup, deploymentName, basicDeployment);
}
deployment = ResourceManagementClient.Deployments.Get(resourceGroup, deploymentName).Deployment;
Thread.Sleep(2000);
} while (!status.Any(s => s.Equals(deployment.Properties.ProvisioningState, StringComparison.OrdinalIgnoreCase)));
return deployment;
}
private List<DeploymentOperation> GetNewOperations(List<DeploymentOperation> old, IList<DeploymentOperation> current)
{
List<DeploymentOperation> newOperations = new List<DeploymentOperation>();
foreach (DeploymentOperation operation in current)
{
DeploymentOperation operationWithSameIdAndProvisioningState = old.Find(o => o.OperationId.Equals(operation.OperationId) && o.Properties.ProvisioningState.Equals(operation.Properties.ProvisioningState));
if (operationWithSameIdAndProvisioningState == null)
{
newOperations.Add(operation);
}
}
return newOperations;
}
private Deployment CreateBasicDeployment(ValidatePSResourceGroupDeploymentParameters parameters)
{
Deployment deployment = new Deployment
{
Properties = new DeploymentProperties {
Mode = DeploymentMode.Incremental,
Template = GetTemplate(parameters.TemplateFile, parameters.GalleryTemplateIdentity),
Parameters = GetDeploymentParameters(parameters.TemplateParameterObject)
}
};
return deployment;
}
private TemplateValidationInfo CheckBasicDeploymentErrors(string resourceGroup, string deploymentName, Deployment deployment)
{
DeploymentValidateResponse validationResult = ResourceManagementClient.Deployments.Validate(
resourceGroup,
deploymentName,
deployment);
return new TemplateValidationInfo(validationResult);
}
internal List<PSPermission> GetResourceGroupPermissions(string resourceGroup)
{
PermissionGetResult permissionsResult = AuthorizationManagementClient.Permissions.ListForResourceGroup(resourceGroup);
if (permissionsResult != null)
{
return permissionsResult.Permissions.Select(p => p.ToPSPermission()).ToList();
}
return null;
}
internal List<PSPermission> GetResourcePermissions(ResourceIdentifier identity)
{
PermissionGetResult permissionsResult = AuthorizationManagementClient.Permissions.ListForResource(
identity.ResourceGroupName,
identity.ToResourceIdentity());
if (permissionsResult != null)
{
return permissionsResult.Permissions.Select(p => p.ToPSPermission()).ToList();
}
return null;
}
public virtual PSResourceProvider[] ListPSResourceProviders(string providerName = null)
{
return this.ListResourceProviders(providerName: providerName, listAvailable: false)
.Select(provider => provider.ToPSResourceProvider())
.ToArray();
}
public virtual PSResourceProvider[] ListPSResourceProviders(bool listAvailable)
{
return this.ListResourceProviders(providerName: null, listAvailable: listAvailable)
.Select(provider => provider.ToPSResourceProvider())
.ToArray();
}
public virtual List<Provider> ListResourceProviders(string providerName = null, bool listAvailable = true)
{
if (!string.IsNullOrEmpty(providerName))
{
var provider = this.ResourceManagementClient.Providers.Get(providerName).Provider;
if (provider == null)
{
throw new KeyNotFoundException(string.Format(ProjectResources.ResourceProviderNotFound, providerName));
}
return new List<Provider> {provider};
}
else
{
var returnList = new List<Provider>();
var tempResult = this.ResourceManagementClient.Providers.List(null);
returnList.AddRange(tempResult.Providers);
while (!string.IsNullOrWhiteSpace(tempResult.NextLink))
{
tempResult = this.ResourceManagementClient.Providers.ListNext(tempResult.NextLink);
returnList.AddRange(tempResult.Providers);
}
return listAvailable
? returnList
: returnList.Where(this.IsProviderRegistered).ToList();
}
}
private bool IsProviderRegistered(Provider provider)
{
return string.Equals(
ResourcesClient.RegisteredStateName,
provider.RegistrationState,
StringComparison.InvariantCultureIgnoreCase);
}
public PSResourceProvider RegisterProvider(string providerName)
{
var response = this.ResourceManagementClient.Providers.Register(providerName);
if (response.Provider == null)
{
throw new KeyNotFoundException(string.Format(ProjectResources.ResourceProviderRegistrationFailed, providerName));
}
return response.Provider.ToPSResourceProvider();
}
/// <summary>
/// Parses an array of resource ids to extract the resource group name
/// </summary>
/// <param name="resourceIds">An array of resource ids</param>
public ResourceIdentifier[] ParseResourceIds(string[] resourceIds)
{
var splitResourceIds = resourceIds
.Select(resourceId => resourceId.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries))
.ToArray();
if (splitResourceIds.Any(splitResourceId => splitResourceId.Length % 2 != 0 ||
splitResourceId.Length < 8 ||
!string.Equals("subscriptions", splitResourceId[0], StringComparison.InvariantCultureIgnoreCase) ||
!string.Equals("resourceGroups", splitResourceId[2], StringComparison.InvariantCultureIgnoreCase) ||
!string.Equals("providers", splitResourceId[4], StringComparison.InvariantCultureIgnoreCase)))
{
throw new System.Management.Automation.PSArgumentException(ProjectResources.InvalidFormatOfResourceId);
}
return resourceIds
.Distinct(StringComparer.InvariantCultureIgnoreCase)
.Select(resourceId => new ResourceIdentifier(resourceId))
.ToArray();
}
/// <summary>
/// Get a mapping of Resource providers that support the operations API (/operations) to the operations api-version supported for that RP
/// (Current logic is to prefer the latest "non-test' api-version. If there are no such version, choose the latest one)
/// </summary>
public Dictionary<string, string> GetResourceProvidersWithOperationsSupport()
{
PSResourceProvider[] allProviders = this.ListPSResourceProviders(listAvailable: true);
Dictionary<string, string> providersSupportingOperations = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
PSResourceProviderResourceType[] providerResourceTypes = null;
foreach (PSResourceProvider provider in allProviders)
{
providerResourceTypes = provider.ResourceTypes;
if (providerResourceTypes != null && providerResourceTypes.Any())
{
PSResourceProviderResourceType operationsResourceType = providerResourceTypes.Where(r => r != null && r.ResourceTypeName == ResourcesClient.Operations).FirstOrDefault();
if (operationsResourceType != null &&
operationsResourceType.ApiVersions != null &&
operationsResourceType.ApiVersions.Any())
{
string[] allowedTestPrefixes = new[] { "-preview", "-alpha", "-beta", "-rc", "-privatepreview" };
List<string> nonTestApiVersions = new List<string>();
foreach (string apiVersion in operationsResourceType.ApiVersions)
{
bool isTestApiVersion = false;
foreach (string testPrefix in allowedTestPrefixes)
{
if (apiVersion.EndsWith(testPrefix, StringComparison.InvariantCultureIgnoreCase))
{
isTestApiVersion = true;
break;
}
}
if(isTestApiVersion == false && !nonTestApiVersions.Contains(apiVersion))
{
nonTestApiVersions.Add(apiVersion);
}
}
if(nonTestApiVersions.Any())
{
string latestNonTestApiVersion = nonTestApiVersions.OrderBy(o => o).Last();
providersSupportingOperations.Add(provider.ProviderNamespace, latestNonTestApiVersion);
}
else
{
providersSupportingOperations.Add(provider.ProviderNamespace, operationsResourceType.ApiVersions.OrderBy(o => o).Last());
}
}
}
}
return providersSupportingOperations;
}
/// <summary>
/// Get the list of resource provider operations for every provider specified by the identities list
/// </summary>
public IList<PSResourceProviderOperation> ListPSProviderOperations(IList<ResourceIdentity> identities)
{
var allProviderOperations = new List<PSResourceProviderOperation>();
Task<ResourceProviderOperationDetailListResult> task;
if(identities != null)
{
foreach (var identity in identities)
{
try
{
task = this.ResourceManagementClient.ResourceProviderOperationDetails.ListAsync(identity);
task.Wait(10000);
// Add operations for this provider.
if (task.IsCompleted)
{
allProviderOperations.AddRange(task.Result.ResourceProviderOperationDetails.Select(op => op.ToPSResourceProviderOperation()));
}
}
catch(AggregateException ae)
{
AggregateException flattened = ae.Flatten();
foreach (Exception inner in flattened.InnerExceptions)
{
// Do nothing for now - this is just a mitigation against one provider which hasn't implemented the operations API correctly
//WriteWarning(inner.ToString());
}
}
}
}
return allProviderOperations;
}
}
} |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using System;
namespace Google.Cloud.Bigtable.V2
{
/// <summary>
/// A version which uniquely identifies a cell within a column.
/// </summary>
/// <remarks>
/// <para>
/// Note: version values are stored on the server as if they are microseconds since the Unix epoch.
/// However, the server only supports millisecond granularity, so the server only allows microseconds
/// in multiples of 1,000. <see cref="BigtableVersion"/> attempts to hide this complexity by exposing
/// its underlying <see cref="Value"/> in terms of milliseconds, so if desired, a custom versioning
/// scheme of 1, 2, ... can be used rather than 1000, 2000, ... However, access to the underlying
/// microsecond value is still provided via <see cref="Micros"/>.
/// </para>
/// <para>
/// Note: when using ReadModifyWriteRow, modified columns automatically use a server version, which
/// is based on the current timestamp since the Unix epoch. For those columns, other reads and writes
/// should use <see cref="BigtableVersion"/> values constructed from DateTime values, as opposed to
/// using a custom versioning scheme with 64-bit values.
/// </para>
/// </remarks>
public struct BigtableVersion : IComparable, IComparable<BigtableVersion>, IEquatable<BigtableVersion>
{
private const long MillisPerMicro = 1000;
private const long TicksPerMicro = 10;
private const long TicksPerMilli = TicksPerMicro * MillisPerMicro;
// Visible for testing
internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private long _micros;
private BigtableVersion(long value, bool valueIsMillis)
{
if (valueIsMillis)
{
GaxPreconditions.CheckArgumentRange(value, nameof(value), -1, long.MaxValue / MillisPerMicro);
_micros = value == -1 ? MicrosFromTimestamp(DateTime.UtcNow) : value * MillisPerMicro;
}
else
{
GaxPreconditions.CheckArgumentRange(value, nameof(value), -1, long.MaxValue);
_micros = value;
}
}
/// <summary>
/// Creates a new <see cref="BigtableVersion"/> value from a 64-bit value.
/// </summary>
/// <remarks>
/// <para>
/// Note: version values are stored on the server as if they are microseconds since the Unix epoch.
/// However, the server only supports millisecond granularity, so the server only allows microseconds
/// in multiples of 1,000. <see cref="BigtableVersion"/> attempts to hide this complexity by exposing
/// its underlying <see cref="Value"/> in terms of milliseconds, so if desired, a custom versioning
/// scheme of 1, 2, ... can be used rather than 1000, 2000, ... However, access to the underlying
/// microsecond value is still provided via <see cref="Micros"/>.
/// </para>
/// <para>
/// Note: when using ReadModifyWriteRow, modified columns automatically use a server version, which
/// is based on the current timestamp since the Unix epoch. For those columns, other reads and writes
/// should use <see cref="BigtableVersion"/> values constructed from DateTime values, as opposed to
/// using a custom versioning scheme with 64-bit values.
/// </para>
/// </remarks>
/// <param name="value">
/// The non-negative version value, or -1 to initialize from the milliseconds of DateTime.UtcNow.
/// Must be less than or equal to 9223372036854775.
/// </param>
public BigtableVersion(long value) : this(value, valueIsMillis: true) { }
/// <summary>
/// Creates a new <see cref="BigtableVersion"/> value from the milliseconds of a timestamp since the Unix epoch.
/// </summary>
/// <remarks>
/// <para>
/// Note: version values are stored on the server as if they are microseconds since the Unix epoch.
/// However, the server only supports millisecond granularity, so the server only allows microseconds
/// in multiples of 1,000. <see cref="BigtableVersion"/> attempts to hide this complexity by exposing
/// its underlying <see cref="Value"/> in terms of milliseconds, so if desired, a custom versioning
/// scheme of 1, 2, ... can be used rather than 1000, 2000, ... However, access to the underlying
/// microsecond value is still provided via <see cref="Micros"/>.
/// </para>
/// <para>
/// Note: when using ReadModifyWriteRow, modified columns automatically use a server version, which
/// is based on the current timestamp since the Unix epoch. For those columns, other reads and writes
/// should use <see cref="BigtableVersion"/> values constructed from DateTime values, as opposed to
/// using a custom versioning scheme with 64-bit values.
/// </para>
/// </remarks>
/// <param name="timestamp">
/// The timestamp whose milliseconds since the Unix epoch should be used as the version value. It must be specified in UTC.
/// </param>
public BigtableVersion(DateTime timestamp)
{
GaxPreconditions.CheckArgument(
timestamp.Kind == DateTimeKind.Utc,
nameof(timestamp),
$"The {nameof(BigtableVersion)} timestamp must be specified in UTC.");
GaxPreconditions.CheckArgumentRange(
timestamp,
nameof(timestamp),
UnixEpoch,
DateTime.MaxValue);
_micros = MicrosFromTimestamp(timestamp);
}
internal static BigtableVersion FromMicros(long value) => new BigtableVersion(value, valueIsMillis: false);
private static long MicrosFromTimestamp(DateTime timestamp) => ((timestamp.Ticks - UnixEpoch.Ticks) / TicksPerMilli) * MillisPerMicro;
/// <summary>
/// Gets the version value interpreted as microseconds of a timestamp since the Unix epoch.
/// Greater version values indicate newer cell values.
/// </summary>
public long Micros => _micros;
/// <summary>
/// Gets the version value. Greater version values indicate newer cell values.
/// </summary>
/// <remarks>
/// If timestamps are used as versions, this would be the milliseconds since the Unix epoch.
/// </remarks>
public long Value => _micros / 1000;
/// <summary>
/// Gets the DateTime equivalent to the version assuming the value is a timestamp milliseconds value since the Unix epoch.
/// </summary>
/// <returns>The DateTime representing the version timestamp.</returns>
public DateTime ToDateTime() => new DateTime((_micros * TicksPerMicro) + UnixEpoch.Ticks, DateTimeKind.Utc);
/// <inheritdoc />
public int CompareTo(object obj)
{
if (obj is BigtableVersion other)
{
return CompareTo(other);
}
throw new ArgumentException($"The specified object cannot be compared with {nameof(BigtableVersion)}", nameof(obj));
}
/// <inheritdoc />
public int CompareTo(BigtableVersion other) => _micros.CompareTo(other._micros);
/// <summary>
/// Compares two nullable <see cref="BigtableVersion"/> values.
/// </summary>
/// <param name="x">Left value to compare</param>
/// <param name="y">Right value to compare</param>
/// <returns>true if <paramref name="x"/> is less than <paramref name="y"/>; otherwise false.</returns>
public static int Compare(BigtableVersion? x, BigtableVersion? y)
{
if (x == null)
{
return y == null ? 0 : -1;
}
else if (y == null)
{
return 1;
}
return x.Value.CompareTo(y.Value);
}
/// <inheritdoc />
public bool Equals(BigtableVersion other) => CompareTo(other) == 0;
/// <inheritdoc />
public override bool Equals(object obj) => obj is BigtableVersion other && Equals(other);
/// <inheritdoc />
public override int GetHashCode() => _micros.GetHashCode();
/// <inheritdoc />
public override string ToString() => $"{nameof(BigtableVersion)}: {Value}";
/// <summary>
/// Operator overload to compare two <see cref="BigtableVersion"/> values.
/// </summary>
/// <param name="x">Left value to compare</param>
/// <param name="y">Right value to compare</param>
/// <returns>true if <paramref name="x"/> is less than <paramref name="y"/>; otherwise false.</returns>
public static bool operator <(BigtableVersion x, BigtableVersion y) => x._micros < y._micros;
/// <summary>
/// Operator overload to compare two <see cref="BigtableVersion"/> values.
/// </summary>
/// <param name="x">Left value to compare</param>
/// <param name="y">Right value to compare</param>
/// <returns>true if <paramref name="x"/> is less than or equal <paramref name="y"/>; otherwise false.</returns>
public static bool operator <=(BigtableVersion x, BigtableVersion y) => x._micros <= y._micros;
/// <summary>
/// Operator overload to compare two <see cref="BigtableVersion"/> values for equality.
/// </summary>
/// <param name="x">Left value to compare</param>
/// <param name="y">Right value to compare</param>
/// <returns>true if <paramref name="x"/> is equal to <paramref name="y"/>; otherwise false.</returns>
public static bool operator ==(BigtableVersion x, BigtableVersion y) => x._micros == y._micros;
/// <summary>
/// Operator overload to compare two <see cref="BigtableVersion"/> values for inequality.
/// </summary>
/// <param name="x">Left value to compare</param>
/// <param name="y">Right value to compare</param>
/// <returns>true if <paramref name="x"/> is not equal to <paramref name="y"/>; otherwise false.</returns>
public static bool operator !=(BigtableVersion x, BigtableVersion y) => x._micros != y._micros;
/// <summary>
/// Operator overload to compare two <see cref="BigtableVersion"/> values.
/// </summary>
/// <param name="x">Left value to compare</param>
/// <param name="y">Right value to compare</param>
/// <returns>true if <paramref name="x"/> is greater than or equal <paramref name="y"/>; otherwise false.</returns>
public static bool operator >=(BigtableVersion x, BigtableVersion y) => x._micros >= y._micros;
/// <summary>
/// Operator overload to compare two <see cref="BigtableVersion"/> values.
/// </summary>
/// <param name="x">Left value to compare</param>
/// <param name="y">Right value to compare</param>
/// <returns>true if <paramref name="x"/> is greater than <paramref name="y"/>; otherwise false.</returns>
public static bool operator >(BigtableVersion x, BigtableVersion y) => x._micros > y._micros;
}
internal static class BigtableVersionExtensions
{
public static long ToTimestampMicros(this BigtableVersion? version) =>
version == null ? 0 : version.Value.Micros;
public static BigtableVersion? ToVersion(this long? timestampMillis) =>
timestampMillis == null ?
default(BigtableVersion?) :
new BigtableVersion(timestampMillis.Value);
public static BigtableVersion? ToVersion(this DateTime? timestamp) =>
timestamp == null ?
default(BigtableVersion?) :
new BigtableVersion(timestamp.Value);
}
} |
//-----------------------------------------------------------------------
// <copyright file="SourceSpec.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 System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.Dsl
{
public class SourceSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public SourceSpec(ITestOutputHelper helper) : base(helper)
{
Materializer = ActorMaterializer.Create(Sys);
}
[Fact]
public void Single_Source_must_produce_element()
{
var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(1);
c.ExpectNext(1);
c.ExpectComplete();
}
[Fact]
public void Single_Source_must_reject_later_subscriber()
{
var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c1 = TestSubscriber.CreateManualProbe<int>(this);
var c2 = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(1);
c1.ExpectNext(1);
c1.ExpectComplete();
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Empty_Source_must_complete_immediately()
{
var p = Source.Empty<int>().RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c);
c.ExpectSubscriptionAndComplete();
//reject additional subscriber
var c2 = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Failed_Source_must_emit_error_immediately()
{
var ex = new SystemException();
var p = Source.Failed<int>(ex).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c);
c.ExpectSubscriptionAndError();
//reject additional subscriber
var c2 = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Maybe_Source_must_complete_materialized_future_with_None_when_stream_cancels()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<object>();
var pubSink = Sink.AsPublisher<object>(false);
var t = neverSource.ToMaterialized(pubSink, Keep.Both).Run(Materializer);
var f = t.Item1;
var neverPub = t.Item2;
var c = TestSubscriber.CreateManualProbe<object>(this);
neverPub.Subscribe(c);
var subs = c.ExpectSubscription();
subs.Request(1000);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
subs.Cancel();
f.Task.Wait(500).Should().BeTrue();
f.Task.Result.Should().Be(null);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_empty_completion()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>().Where(_ => false);
var counterSink = Sink.Aggregate<int, int>(0, (acc, _) => acc + 1);
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.TrySetResult(0).Should().BeTrue();
counterFuture.Wait(500).Should().BeTrue();
counterFuture.Result.Should().Be(0);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_non_empty_completion()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>();
var counterSink = Sink.First<int>();
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.TrySetResult(6).Should().BeTrue();
counterFuture.Wait(500).Should().BeTrue();
counterFuture.Result.Should().Be(6);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_OnError()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>();
var counterSink = Sink.First<int>();
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.SetException(new Exception("Boom"));
counterFuture.Invoking(f => f.Wait(500)).ShouldThrow<Exception>()
.WithMessage("Boom");
}, Materializer);
}
[Fact]
public void Composite_Source_must_merge_from_many_inputs()
{
var probes = Enumerable.Range(1, 5).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList();
var source = Source.AsSubscriber<int>();
var outProbe = TestSubscriber.CreateManualProbe<int>(this);
var s =
Source.FromGraph(GraphDsl.Create(source, source, source, source, source,
(a, b, c, d, e) => new[] {a, b, c, d, e},
(b, i0, i1, i2, i3, i4) =>
{
var m = b.Add(new Merge<int>(5));
b.From(i0.Outlet).To(m.In(0));
b.From(i1.Outlet).To(m.In(1));
b.From(i2.Outlet).To(m.In(2));
b.From(i3.Outlet).To(m.In(3));
b.From(i4.Outlet).To(m.In(4));
return new SourceShape<int>(m.Out);
})).To(Sink.FromSubscriber(outProbe)).Run(Materializer);
for (var i = 0; i < 5; i++)
probes[i].Subscribe(s[i]);
var sub = outProbe.ExpectSubscription();
sub.Request(10);
for (var i = 0; i < 5; i++)
{
var subscription = probes[i].ExpectSubscription();
subscription.ExpectRequest();
subscription.SendNext(i);
subscription.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 5; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2, 3, 4});
outProbe.ExpectComplete();
}
[Fact]
public void Composite_Source_must_combine_from_many_inputs_with_simplified_API()
{
var probes = Enumerable.Range(1, 3).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList();
var source = probes.Select(Source.FromPublisher).ToList();
var outProbe = TestSubscriber.CreateManualProbe<int>(this);
Source.Combine(source[0], source[1], i => new Merge<int, int>(i), source[2])
.To(Sink.FromSubscriber(outProbe))
.Run(Materializer);
var sub = outProbe.ExpectSubscription();
sub.Request(3);
for (var i = 0; i < 3; i++)
{
var s = probes[i].ExpectSubscription();
s.ExpectRequest();
s.SendNext(i);
s.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 3; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2});
outProbe.ExpectComplete();
}
[Fact]
public void Composite_Source_must_combine_from_two_inputs_with_simplified_API()
{
var probes = Enumerable.Range(1, 2).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList();
var source = probes.Select(Source.FromPublisher).ToList();
var outProbe = TestSubscriber.CreateManualProbe<int>(this);
Source.Combine(source[0], source[1], i => new Merge<int, int>(i))
.To(Sink.FromSubscriber(outProbe))
.Run(Materializer);
var sub = outProbe.ExpectSubscription();
sub.Request(3);
for (var i = 0; i < 2; i++)
{
var s = probes[i].ExpectSubscription();
s.ExpectRequest();
s.SendNext(i);
s.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 2; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1});
outProbe.ExpectComplete();
}
[Fact]
public void Repeat_Source_must_repeat_as_long_as_it_takes()
{
var f = Source.Repeat(42).Grouped(1000).RunWith(Sink.First<IEnumerable<int>>(), Materializer);
f.Result.Should().HaveCount(1000).And.Match(x => x.All(i => i == 42));
}
private static readonly int[] Expected = {
9227465, 5702887, 3524578, 2178309, 1346269, 832040, 514229, 317811, 196418, 121393, 75025, 46368, 28657, 17711,
10946, 6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0
};
[Fact]
public void Unfold_Source_must_generate_a_finite_fibonacci_sequence()
{
Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
return null;
return Tuple.Create(Tuple.Create(b, a + b), a);
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Unfold_Source_must_terminate_with_a_failure_if_there_is_an_exception_thrown()
{
EventFilter.Exception<SystemException>(message: "expected").ExpectOne(() =>
{
var task = Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
throw new SystemException("expected");
return Tuple.Create(Tuple.Create(b, a + b), a);
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<SystemException>()
.WithMessage("expected");
});
}
[Fact]
public void Unfold_Source_must_generate_a_finite_fibonacci_sequence_asynchronously()
{
Source.UnfoldAsync(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
return Task.FromResult<Tuple<Tuple<int, int>, int>>(null);
return Task.FromResult(Tuple.Create(Tuple.Create(b, a + b), a));
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Unfold_Source_must_generate_a_unboundeed_fibonacci_sequence()
{
Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
return Tuple.Create(Tuple.Create(b, a + b), a);
})
.Take(36)
.RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Iterator_Source_must_properly_iterate()
{
var expected = new[] {false, true, false, true, false, true, false, true, false, true }.ToList();
Source.FromEnumerator(() => expected.GetEnumerator())
.Grouped(10)
.RunWith(Sink.First<IEnumerable<bool>>(), Materializer)
.Result.Should()
.Equal(expected);
}
[Fact]
public void A_Source_must_suitably_override_attribute_handling_methods()
{
Source.Single(42).Async().AddAttributes(Attributes.None).Named("");
}
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Protos.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 Messages {
/// <summary>Holder for reflection information generated from Protos.proto</summary>
public static partial class ProtosReflection {
#region Descriptor
/// <summary>File descriptor for Protos.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ProtosReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxQcm90b3MucHJvdG8SCG1lc3NhZ2VzIh0KDVJlbmFtZUNvbW1hbmQSDAoE",
"bmFtZRgBIAEoCSIbCgtSZW5hbWVFdmVudBIMCgRuYW1lGAEgASgJIhUKBVN0",
"YXRlEgwKBE5hbWUYASABKAlCC6oCCE1lc3NhZ2VzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Messages.RenameCommand), global::Messages.RenameCommand.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Messages.RenameEvent), global::Messages.RenameEvent.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Messages.State), global::Messages.State.Parser, new[]{ "Name" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class RenameCommand : pb::IMessage<RenameCommand> {
private static readonly pb::MessageParser<RenameCommand> _parser = new pb::MessageParser<RenameCommand>(() => new RenameCommand());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RenameCommand> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RenameCommand() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RenameCommand(RenameCommand other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RenameCommand Clone() {
return new RenameCommand(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RenameCommand);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RenameCommand other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.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 (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RenameCommand other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[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: {
Name = input.ReadString();
break;
}
}
}
}
}
public sealed partial class RenameEvent : pb::IMessage<RenameEvent> {
private static readonly pb::MessageParser<RenameEvent> _parser = new pb::MessageParser<RenameEvent>(() => new RenameEvent());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RenameEvent> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RenameEvent() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RenameEvent(RenameEvent other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RenameEvent Clone() {
return new RenameEvent(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RenameEvent);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RenameEvent other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.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 (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RenameEvent other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[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: {
Name = input.ReadString();
break;
}
}
}
}
}
public sealed partial class State : pb::IMessage<State> {
private static readonly pb::MessageParser<State> _parser = new pb::MessageParser<State>(() => new State());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<State> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public State() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public State(State other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public State Clone() {
return new State(this);
}
/// <summary>Field number for the "Name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as State);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(State other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.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 (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(State other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[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: {
Name = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ServiceBus.Amqp
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Amqp;
using Azure.Amqp.Encoding;
using Core;
using Framing;
using Primitives;
internal sealed class AmqpSubscriptionClient : IInnerSubscriptionClient
{
int prefetchCount;
readonly object syncLock;
MessageReceiver innerReceiver;
static AmqpSubscriptionClient()
{
AmqpCodec.RegisterKnownTypes(AmqpTrueFilterCodec.Name, AmqpTrueFilterCodec.Code, () => new AmqpTrueFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpFalseFilterCodec.Name, AmqpFalseFilterCodec.Code, () => new AmqpFalseFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpCorrelationFilterCodec.Name, AmqpCorrelationFilterCodec.Code, () => new AmqpCorrelationFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpSqlFilterCodec.Name, AmqpSqlFilterCodec.Code, () => new AmqpSqlFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpEmptyRuleActionCodec.Name, AmqpEmptyRuleActionCodec.Code, () => new AmqpEmptyRuleActionCodec());
AmqpCodec.RegisterKnownTypes(AmqpSqlRuleActionCodec.Name, AmqpSqlRuleActionCodec.Code, () => new AmqpSqlRuleActionCodec());
AmqpCodec.RegisterKnownTypes(AmqpRuleDescriptionCodec.Name, AmqpRuleDescriptionCodec.Code, () => new AmqpRuleDescriptionCodec());
}
public AmqpSubscriptionClient(
string path,
ServiceBusConnection servicebusConnection,
RetryPolicy retryPolicy,
ICbsTokenProvider cbsTokenProvider,
int prefetchCount = 0,
ReceiveMode mode = ReceiveMode.ReceiveAndDelete)
{
this.syncLock = new object();
this.Path = path;
this.ServiceBusConnection = servicebusConnection;
this.RetryPolicy = retryPolicy;
this.CbsTokenProvider = cbsTokenProvider;
this.PrefetchCount = prefetchCount;
this.ReceiveMode = mode;
}
public MessageReceiver InnerReceiver
{
get
{
if (this.innerReceiver == null)
{
lock (this.syncLock)
{
if (this.innerReceiver == null)
{
this.innerReceiver = new MessageReceiver(
this.Path,
MessagingEntityType.Subscriber,
this.ReceiveMode,
this.ServiceBusConnection,
this.CbsTokenProvider,
this.RetryPolicy,
this.PrefetchCount);
}
}
}
return this.innerReceiver;
}
}
/// <summary>
/// Gets or sets the number of messages that the subscription client can simultaneously request.
/// </summary>
/// <value>The number of messages that the subscription client can simultaneously request.</value>
public int PrefetchCount
{
get => this.prefetchCount;
set
{
if (value < 0)
{
throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0.");
}
this.prefetchCount = value;
if (this.innerReceiver != null)
{
this.innerReceiver.PrefetchCount = value;
}
}
}
ServiceBusConnection ServiceBusConnection { get; }
RetryPolicy RetryPolicy { get; }
ICbsTokenProvider CbsTokenProvider { get; }
ReceiveMode ReceiveMode { get; }
string Path { get; }
public Task CloseAsync()
{
return this.innerReceiver?.CloseAsync();
}
public async Task OnAddRuleAsync(RuleDescription description)
{
try
{
var amqpRequestMessage = AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.AddRuleOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = description.Name;
amqpRequestMessage.Map[ManagementConstants.Properties.RuleDescription] =
AmqpMessageConverter.GetRuleDescriptionMap(description);
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
if (response.StatusCode != AmqpResponseStatusCode.OK)
{
throw response.ToMessagingContractException();
}
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
public async Task OnRemoveRuleAsync(string ruleName)
{
try
{
var amqpRequestMessage =
AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.RemoveRuleOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = ruleName;
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
if (response.StatusCode != AmqpResponseStatusCode.OK)
{
throw response.ToMessagingContractException();
}
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
public async Task<IList<RuleDescription>> OnGetRulesAsync(int top, int skip)
{
try
{
var amqpRequestMessage =
AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.EnumerateRulesOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.Top] = top;
amqpRequestMessage.Map[ManagementConstants.Properties.Skip] = skip;
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
var ruleDescriptions = new List<RuleDescription>();
if (response.StatusCode == AmqpResponseStatusCode.OK)
{
var ruleList = response.GetListValue<AmqpMap>(ManagementConstants.Properties.Rules);
foreach (var entry in ruleList)
{
var amqpRule = (AmqpRuleDescriptionCodec)entry[ManagementConstants.Properties.RuleDescription];
var ruleDescription = AmqpMessageConverter.GetRuleDescription(amqpRule);
ruleDescriptions.Add(ruleDescription);
}
}
else if (response.StatusCode == AmqpResponseStatusCode.NoContent)
{
// Do nothing. Return empty list;
}
else
{
throw response.ToMessagingContractException();
}
return ruleDescriptions;
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
}
} |
/* 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:
*
* * 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.
*
* 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.Generic;
using System.Threading;
using XenAdmin.Network;
using XenAPI;
namespace XenAdmin.Actions
{
/// <summary>
/// ParallelAction takes a list of any number of actions and runs a certain number of them simultaneously.
/// Once one simultaneous action is finished the next one in the queue is started until all are complete
/// </summary>
public class ParallelAction : MultipleAction
{
//Change parameter to increase the number of concurrent actions running
private const int DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS = 25;
private Dictionary<IXenConnection, List<AsyncAction>> actionsByConnection = new Dictionary<IXenConnection, List<AsyncAction>>();
private Dictionary<IXenConnection, ProduceConsumerQueue> queuesByConnection = new Dictionary<IXenConnection, ProduceConsumerQueue>();
private List<AsyncAction> actionsWithNoConnection = new List<AsyncAction>();
private ProduceConsumerQueue queueWithNoConnection;
private readonly int maxNumberOfParallelActions;
private int actionsCount;
public ParallelAction(IXenConnection connection, string title, string startDescription, string endDescription, List<AsyncAction> subActions, bool suppressHistory, bool showSubActionsDetails, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS)
: base(connection, title, startDescription, endDescription, subActions, suppressHistory, showSubActionsDetails)
{
if (Connection != null)
{
actionsByConnection.Add(Connection, subActions);
actionsCount = subActions.Count;
}
else
GroupActionsByConnection();
this.maxNumberOfParallelActions = maxNumberOfParallelActions;
}
public ParallelAction(IXenConnection connection, string title, string startDescription, string endDescription, List<AsyncAction> subActions, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS)
: this(connection, title, startDescription, endDescription, subActions, false, false, maxNumberOfParallelActions)
{ }
/// <summary>
/// Use this constructor to create a cross connection ParallelAction.
/// It takes a list of any number of actions, separates them by connections
/// and runs a certain number of them simultaneously on each connection, all connections in parallel.
/// Once one simultaneous action is finished the next one in the queue is started until all are complete.
/// </summary>
public ParallelAction(string title, string startDescription, string endDescription, List<AsyncAction> subActions, bool suppressHistory, bool showSubActionsDetails, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS)
: base(null, title, startDescription, endDescription, subActions, suppressHistory, showSubActionsDetails)
{
GroupActionsByConnection();
this.maxNumberOfParallelActions = maxNumberOfParallelActions;
}
public ParallelAction(string title, string startDescription, string endDescription, List<AsyncAction> subActions, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS)
: this(title, startDescription, endDescription, subActions, false, false, maxNumberOfParallelActions)
{ }
private void GroupActionsByConnection()
{
actionsCount = 0;
foreach (AsyncAction action in subActions)
{
if (action.Connection != null)
{
if (action.Connection.IsConnected)
{
if (!actionsByConnection.ContainsKey(action.Connection))
{
actionsByConnection.Add(action.Connection, new List<AsyncAction>());
}
actionsByConnection[action.Connection].Add(action);
actionsCount++;
}
}
else
{
actionsWithNoConnection.Add(action);
actionsCount++;
}
}
}
protected override void RunSubActions(List<Exception> exceptions)
{
if (actionsCount == 0)
return;
foreach (IXenConnection connection in actionsByConnection.Keys)
{
queuesByConnection[connection] = new ProduceConsumerQueue(Math.Min(maxNumberOfParallelActions, actionsByConnection[connection].Count));
foreach (AsyncAction subAction in actionsByConnection[connection])
{
EnqueueAction(subAction, queuesByConnection[connection], exceptions);
}
}
if (actionsWithNoConnection.Count > 0)
queueWithNoConnection = new ProduceConsumerQueue(Math.Min(maxNumberOfParallelActions, actionsWithNoConnection.Count));
foreach (AsyncAction subAction in actionsWithNoConnection)
{
EnqueueAction(subAction, queueWithNoConnection, exceptions);
}
lock (_lock)
{
Monitor.Wait(_lock);
}
}
void EnqueueAction(AsyncAction action, ProduceConsumerQueue queue, List<Exception> exceptions)
{
action.Completed += action_Completed;
queue.EnqueueItem(
() =>
{
if (Cancelling) // don't start any more actions
return;
try
{
action.RunExternal(action.Session);
}
catch (Exception e)
{
Failure f = e as Failure;
if (f != null && Connection != null &&
f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
{
Failure.ParseRBACFailure(f, action.Connection, action.Session ?? action.Connection.Session);
}
exceptions.Add(e);
// Record the first exception we come to. Though later if there are more than one we will replace this with non specific one.
if (Exception == null)
Exception = e;
}
});
}
protected override void RecalculatePercentComplete()
{
int total = 0;
foreach (IXenConnection connection in actionsByConnection.Keys)
{
foreach (var action in actionsByConnection[connection])
total += action.PercentComplete;
}
foreach (var action in actionsWithNoConnection)
total += action.PercentComplete;
PercentComplete = (int)(total / actionsCount);
}
private readonly object _lock = new object();
private volatile int i = 0;
void action_Completed(ActionBase sender)
{
sender.Completed -= action_Completed;
lock (_lock)
{
i++;
if (i == actionsCount)
{
Monitor.Pulse(_lock);
PercentComplete = 100;
}
}
}
protected override void MultipleAction_Completed(ActionBase sender)
{
base.MultipleAction_Completed(sender);
foreach (IXenConnection connection in queuesByConnection.Keys)
{
queuesByConnection[connection].StopWorkers(false);
}
if (queueWithNoConnection != null)
queueWithNoConnection.StopWorkers(false);
}
}
}
|
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using ClearCanvas.Common;
using ClearCanvas.Desktop;
using ClearCanvas.Enterprise.Common;
using ClearCanvas.Ris.Application.Common;
using ClearCanvas.Ris.Application.Common.Admin.LocationAdmin;
using ClearCanvas.Ris.Application.Common.Admin.FacilityAdmin;
using ClearCanvas.Desktop.Validation;
namespace ClearCanvas.Ris.Client.Admin
{
/// <summary>
/// Extension point for views onto <see cref="LocationEditorComponent"/>
/// </summary>
[ExtensionPoint]
public class LocationEditorComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView>
{
}
/// <summary>
/// LocationEditorComponent class
/// </summary>
[AssociateView(typeof(LocationEditorComponentViewExtensionPoint))]
public class LocationEditorComponent : ApplicationComponent
{
private List<FacilitySummary> _facilityChoices;
private LocationDetail _locationDetail;
private EntityRef _locationRef;
private readonly bool _isNew;
private LocationSummary _locationSummary;
/// <summary>
/// Constructor
/// </summary>
public LocationEditorComponent()
{
_isNew = true;
}
public LocationEditorComponent(EntityRef locationRef)
{
_isNew = false;
_locationRef = locationRef;
}
public LocationSummary LocationSummary
{
get { return _locationSummary; }
}
public override void Start()
{
if (_isNew)
{
_locationDetail = new LocationDetail();
}
else
{
Platform.GetService(
delegate(ILocationAdminService service)
{
var response = service.LoadLocationForEdit(new LoadLocationForEditRequest(_locationRef));
_locationRef = response.LocationDetail.LocationRef;
_locationDetail = response.LocationDetail;
});
}
Platform.GetService(
delegate(IFacilityAdminService service)
{
var response = service.ListAllFacilities(new ListAllFacilitiesRequest());
_facilityChoices = response.Facilities;
if (_isNew && _locationDetail.Facility == null && response.Facilities.Count > 0)
{
_locationDetail.Facility = response.Facilities[0];
}
});
base.Start();
}
public LocationDetail LocationDetail
{
get { return _locationDetail; }
set { _locationDetail = value; }
}
#region Presentation Model
[ValidateNotNull]
public string Id
{
get { return _locationDetail.Id; }
set
{
_locationDetail.Id = value;
this.Modified = true;
}
}
[ValidateNotNull]
public string Name
{
get { return _locationDetail.Name; }
set
{
_locationDetail.Name = value;
this.Modified = true;
}
}
public string Description
{
get { return _locationDetail.Description; }
set
{
_locationDetail.Description = value;
this.Modified = true;
}
}
public IList FacilityChoices
{
get { return _facilityChoices; }
}
[ValidateNotNull]
public FacilitySummary Facility
{
get { return _locationDetail.Facility; }
set
{
_locationDetail.Facility = value;
this.Modified = true;
}
}
public string FormatFacility(object item)
{
var f = (FacilitySummary) item;
return f.Name;
}
public string Building
{
get { return _locationDetail.Building; }
set
{
_locationDetail.Building = value;
this.Modified = true;
}
}
public string Floor
{
get { return _locationDetail.Floor; }
set
{
_locationDetail.Floor = value;
this.Modified = true;
}
}
public string PointOfCare
{
get { return _locationDetail.PointOfCare; }
set
{
_locationDetail.PointOfCare = value;
this.Modified = true;
}
}
public void Accept()
{
if (this.HasValidationErrors)
{
this.ShowValidation(true);
}
else
{
try
{
SaveChanges();
this.Exit(ApplicationComponentExitCode.Accepted);
}
catch (Exception e)
{
ExceptionHandler.Report(e, SR.ExceptionSaveLocation, this.Host.DesktopWindow,
delegate
{
this.ExitCode = ApplicationComponentExitCode.Error;
this.Host.Exit();
});
}
}
}
public void Cancel()
{
this.ExitCode = ApplicationComponentExitCode.None;
Host.Exit();
}
public bool AcceptEnabled
{
get { return this.Modified; }
}
#endregion
private void SaveChanges()
{
if (_isNew)
{
Platform.GetService(
delegate(ILocationAdminService service)
{
var response = service.AddLocation(new AddLocationRequest(_locationDetail));
_locationRef = response.Location.LocationRef;
_locationSummary = response.Location;
});
}
else
{
Platform.GetService(
delegate(ILocationAdminService service)
{
var response = service.UpdateLocation(new UpdateLocationRequest(_locationDetail));
_locationRef = response.Location.LocationRef;
_locationSummary = response.Location;
});
}
}
public event EventHandler AcceptEnabledChanged
{
add { this.ModifiedChanged += value; }
remove { this.ModifiedChanged -= value; }
}
}
}
|
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using ClearCanvas.Common;
using ClearCanvas.Dicom.Utilities.Xml;
namespace ClearCanvas.Dicom.Samples
{
public class EditSop
{
private readonly string _sourceFilename;
private DicomFile _dicomFile;
public EditSop(string file)
{
_sourceFilename = file;
}
public DicomFile DicomFile
{
get { return _dicomFile; }
}
public void Load()
{
_dicomFile = new DicomFile(_sourceFilename);
try
{
_dicomFile.Load();
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e, "Unexpected exception loading DICOM file: {0}", _sourceFilename);
}
}
public string GetXmlRepresentation()
{
var theDoc = GetXmlDoc();
var xmlSettings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
ConformanceLevel = ConformanceLevel.Document,
Indent = true,
NewLineOnAttributes = false,
CheckCharacters = true,
IndentChars = " "
};
StringBuilder sb = new StringBuilder();
XmlWriter tw = XmlWriter.Create(sb, xmlSettings);
theDoc.WriteTo(tw);
tw.Flush();
tw.Close();
return sb.ToString();
}
private XmlDocument GetXmlDoc()
{
var theDocument = new XmlDocument();
XmlElement instance = theDocument.CreateElement("Instance");
XmlAttribute sopInstanceUid = theDocument.CreateAttribute("UID");
sopInstanceUid.Value = _dicomFile.MediaStorageSopInstanceUid;
instance.Attributes.Append(sopInstanceUid);
XmlAttribute sopClassAttribute = theDocument.CreateAttribute("SopClassUID");
sopClassAttribute.Value = _dicomFile.SopClass.Uid;
instance.Attributes.Append(sopClassAttribute);
theDocument.AppendChild(instance);
foreach (DicomAttribute attribute in _dicomFile.DataSet)
{
XmlElement instanceElement = CreateDicomAttributeElement(theDocument, attribute.Tag, "Attribute");
if (attribute is DicomAttributeSQ || attribute is DicomAttributeOW || attribute is DicomAttributeUN ||
attribute is DicomAttributeOF || attribute is DicomAttributeOB)
{
continue;
}
instanceElement.InnerText = XmlEscapeString(attribute);
instance.AppendChild(instanceElement);
}
return theDocument;
}
private static XmlElement CreateDicomAttributeElement(XmlDocument document, DicomTag dicomTag, string name)
{
XmlElement dicomAttributeElement = document.CreateElement(name);
XmlAttribute tag = document.CreateAttribute("Tag");
tag.Value = "$" + dicomTag.VariableName;
XmlAttribute vr = document.CreateAttribute("VR");
vr.Value = dicomTag.VR.ToString();
dicomAttributeElement.Attributes.Append(tag);
dicomAttributeElement.Attributes.Append(vr);
return dicomAttributeElement;
}
private static string XmlEscapeString(string input)
{
string result = input ?? string.Empty;
result = SecurityElement.Escape(result);
// Do the regular expression to escape out other invalid XML characters in the string not caught by the above.
// NOTE: the \x sequences you see below are C# escapes, not Regex escapes
result = Regex.Replace(result, "[^\x9\xA\xD\x20-\xFFFD]", m => string.Format("&#x{0:X};", (int)m.Value[0]));
return result;
}
public void UpdateTags(string xml)
{
var theDoc = new XmlDocument();
try
{
theDoc.LoadXml(xml);
var instanceXml = new InstanceXml(theDoc.DocumentElement, null);
DicomAttributeCollection queryMessage = instanceXml.Collection;
if (queryMessage == null)
{
Platform.Log(LogLevel.Error, "Unexpected error parsing move message");
return;
}
foreach (var attribute in queryMessage)
{
_dicomFile.DataSet[attribute.Tag] = attribute.Copy();
}
}
catch (Exception x)
{
Platform.Log(LogLevel.Error, x, "Unable to perform update");
}
}
public void Save(string filename)
{
try
{
_dicomFile.Save(filename);
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e, "Unexpected exception saving dicom file: {0}", filename);
}
}
}
}
|
// 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.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// This object is used to wrap a bunch of ConnectAsync operations
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class MultipleConnectAsync
{
protected SocketAsyncEventArgs _userArgs;
protected SocketAsyncEventArgs _internalArgs;
protected DnsEndPoint _endPoint;
protected IPAddress[] _addressList;
protected int _nextAddress;
private enum State
{
NotStarted,
DnsQuery,
ConnectAttempt,
Completed,
Canceled,
}
private State _state;
private object _lockObject = new object();
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
{
lock (_lockObject)
{
if (endPoint.AddressFamily != AddressFamily.Unspecified &&
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
_endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (_state == State.Canceled)
{
SyncFail(new SocketException((int)SocketError.OperationAborted));
return false;
}
if (_state != State.NotStarted)
{
NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.CompletedSynchronously)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
// Callback which fires when the Dns Resolve is complete
private void DnsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
DoDnsCallback(result, false);
}
}
// Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and
// starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous,
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
Exception exception = null;
lock (_lockObject)
{
// If the connection attempt was canceled during the dns query, the user's callback has already been
// called asynchronously and we simply need to return.
if (_state == State.Canceled)
{
return true;
}
if (_state != State.DnsQuery)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
}
try
{
_addressList = Dns.EndGetHostAddresses(result);
if (_addressList == null)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
{
_state = State.Completed;
exception = e;
}
// If the dns query succeeded, try to connect to the first address
if (exception == null)
{
_state = State.ConnectAttempt;
_internalArgs = new SocketAsyncEventArgs();
_internalArgs.Completed += InternalConnectCallback;
_internalArgs.CopyBufferFrom(_userArgs);
exception = AttemptConnection();
if (exception != null)
{
// There was a synchronous error while connecting
_state = State.Completed;
}
}
}
// Call this outside of the lock because it might call the user's callback.
if (exception != null)
{
return Fail(sync, exception);
}
else
{
return true;
}
}
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
{
Exception exception = null;
lock (_lockObject)
{
if (_state == State.Canceled)
{
// If Cancel was called before we got the lock, the Socket will be closed soon. We need to report
// OperationAborted (even though the connection actually completed), or the user will try to use a
// closed Socket.
exception = new SocketException((int)SocketError.OperationAborted);
}
else
{
Debug.Assert(_state == State.ConnectAttempt);
if (args.SocketError == SocketError.Success)
{
// The connection attempt succeeded; go to the completed state.
// The callback will be called outside the lock.
_state = State.Completed;
}
else if (args.SocketError == SocketError.OperationAborted)
{
// The socket was closed while the connect was in progress. This can happen if the user
// closes the socket, and is equivalent to a call to CancelConnectAsync
exception = new SocketException((int)SocketError.OperationAborted);
_state = State.Canceled;
}
else
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
Exception connectException = AttemptConnection();
if (connectException == null)
{
// don't call the callback, another connection attempt is successfully started
return;
}
else
{
SocketException socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// a connection to. Return the last error from an actual connection instead.
exception = new SocketException((int)currentFailure);
}
else
{
exception = connectException;
}
_state = State.Completed;
}
}
}
}
if (exception == null)
{
Succeed();
}
else
{
AsyncFail(exception);
}
}
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
private Exception AttemptConnection()
{
try
{
Socket attemptSocket;
IPAddress attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
return AttemptConnection(attemptSocket, _internalArgs);
}
catch (Exception e)
{
if (e is ObjectDisposedException)
{
NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
}
private Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
{
try
{
if (attemptSocket == null)
{
NetEventSource.Fail(null, "attemptSocket is null!");
}
bool pending = attemptSocket.ConnectAsync(args);
if (!pending)
{
InternalConnectCallback(null, args);
}
}
catch (ObjectDisposedException)
{
// This can happen if the user closes the socket, and is equivalent to a call
// to CancelConnectAsync
return new SocketException((int)SocketError.OperationAborted);
}
catch (Exception e)
{
return e;
}
return null;
}
protected abstract void OnSucceed();
private void Succeed()
{
OnSucceed();
_userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
protected abstract void OnFail(bool abortive);
private bool Fail(bool sync, Exception e)
{
if (sync)
{
SyncFail(e);
return false;
}
else
{
AsyncFail(e);
return true;
}
}
private void SyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
SocketException socketException = e as SocketException;
if (socketException != null)
{
_userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
}
else
{
ExceptionDispatchInfo.Throw(e);
}
}
private void AsyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
_userArgs.FinishOperationAsyncFailure(e, 0, SocketFlags.None);
}
public void Cancel()
{
bool callOnFail = false;
lock (_lockObject)
{
switch (_state)
{
case State.NotStarted:
// Cancel was called before the Dns query was started. The dns query won't be started
// and the connection attempt will fail synchronously after the state change to DnsQuery.
// All we need to do here is close all the sockets.
callOnFail = true;
break;
case State.DnsQuery:
// Cancel was called after the Dns query was started, but before it finished. We can't
// actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously
// from here, and silently dropping the connection attempt when the Dns query finishes.
Task.Factory.StartNew(
s => CallAsyncFail(s),
null,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
callOnFail = true;
break;
case State.ConnectAttempt:
// Cancel was called after the Dns query completed, but before we had a connection result to give
// to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately
// with OperationAborted, and will cause ObjectDisposedException from any new calls to ConnectAsync
// (which will be translated to OperationAborted by AttemptConnection).
callOnFail = true;
break;
case State.Completed:
// Cancel was called after we locked in a result to give to the user. Ignore it and give the user
// the real completion.
break;
default:
NetEventSource.Fail(this, "Unexpected object state");
break;
}
_state = State.Canceled;
}
// Call this outside the lock because Socket.Close may block
if (callOnFail)
{
OnFail(true);
}
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
private void CallAsyncFail(object ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
// an AddressFamily. There's only one Socket, and we only try addresses that match its
// AddressFamily
internal sealed class SingleSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket;
private bool _userSocket;
public SingleSocketMultipleConnectAsync(Socket socket, bool userSocket)
{
_socket = socket;
_userSocket = userSocket;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
_socket.ReplaceHandleIfNecessaryAfterFailedConnect();
IPAddress rval = null;
do
{
if (_nextAddress >= _addressList.Length)
{
attemptSocket = null;
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
}
while (!_socket.CanTryAddressFamily(rval.AddressFamily));
attemptSocket = _socket;
return rval;
}
protected override void OnFail(bool abortive)
{
// Close the socket if this is an abortive failure (CancelConnectAsync)
// or if we created it internally
if (abortive || !_userSocket)
{
_socket.Dispose();
}
}
// nothing to do on success
protected override void OnSucceed() { }
}
// This is used when the static ConnectAsync method is called. We don't know the address family
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket4;
private Socket _socket6;
public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
if (Socket.OSSupportsIPv4)
{
_socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType);
}
if (Socket.OSSupportsIPv6)
{
_socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
}
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
IPAddress rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
if (_nextAddress >= _addressList.Length)
{
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
if (rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = _socket6;
}
else if (rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = _socket4;
}
}
attemptSocket?.ReplaceHandleIfNecessaryAfterFailedConnect();
return rval;
}
// on success, close the socket that wasn't used
protected override void OnSucceed()
{
if (_socket4 != null && !_socket4.Connected)
{
_socket4.Dispose();
}
if (_socket6 != null && !_socket6.Connected)
{
_socket6.Dispose();
}
}
// close both sockets whether its abortive or not - we always create them internally
protected override void OnFail(bool abortive)
{
_socket4?.Dispose();
_socket6?.Dispose();
}
}
}
|
//---------------------------------------------------------------------
// <copyright file="QueryReferenceValue.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.Taupo.Query.Contracts
{
using System;
using System.Linq;
using Microsoft.Test.Taupo.Common;
/// <summary>
/// Result of a query evaluation which is a reference of entity
/// </summary>
public class QueryReferenceValue : QueryValue
{
internal QueryReferenceValue(QueryReferenceType type, QueryError evaluationError, IQueryEvaluationStrategy evaluationStrategy)
: base(evaluationError, evaluationStrategy)
{
ExceptionUtilities.CheckArgumentNotNull(type, "type");
this.Type = type;
}
/// <summary>
/// Gets the reference type.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "Must be the same as the base class.")]
public new QueryReferenceType Type { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is null.
/// </summary>
public override bool IsNull
{
get { return this.KeyValue == null; }
}
/// <summary>
/// Gets the entity value (for dereference)
/// </summary>
/// <remarks>For dangling reference, this should be null value</remarks>
public QueryStructuralValue EntityValue { get; private set; }
/// <summary>
/// Gets the entity set full name
/// </summary>
public string EntitySetFullName { get; private set; }
/// <summary>
/// Gets the key value
/// </summary>
public QueryRecordValue KeyValue { get; private set; }
/// <summary>
/// Casts a <see cref="QueryValue"/> to a <see cref="QueryType"/>. The cast will return the value type cast to the new type.
/// </summary>
/// <param name="type">The type for the cast operation.</param>
/// <returns><see cref="QueryValue"/> which is cast to the appropriate type</returns>
public override QueryValue Cast(QueryType type)
{
return type.CreateErrorValue(new QueryError("Cannot perform Cast on a reference value"));
}
/// <summary>
/// Checks if a <see cref="QueryValue"/> is of a particular <see cref="QueryType"/>. This operation will return a true if the value is of the specified type.
/// </summary>
/// <param name="type">The type for the IsOf operation.</param>
/// <param name="performExactMatch">Determines if an exact match needs to be performed.</param>
/// <returns>A <see cref="QueryValue"/> containing true or false depending on whether the value is of the specified type or not.</returns>
public override QueryValue IsOf(QueryType type, bool performExactMatch)
{
return type.CreateErrorValue(new QueryError("Cannot perform IsOf on a reference value"));
}
/// <summary>
/// Converts the <see cref="QueryValue"/> to a particular <see cref="QueryType"/>.
/// </summary>
/// <param name="type">The type for the As operation.</param>
/// <returns>The <see cref="QueryValue"/> converted to the specified type if successful. Returns null if this operation fails.</returns>
public override QueryValue TreatAs(QueryType type)
{
return type.CreateErrorValue(new QueryError("Cannot perform TreatAs on a reference value"));
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (this.EvaluationError != null)
{
return "Reference Value Error=" + this.EvaluationError + ", Type=" + this.Type.StringRepresentation;
}
else if (this.IsNull)
{
return "Null Reference, Type=" + this.Type.StringRepresentation;
}
else
{
return "Reference Value=" + this.EntitySetFullName + ", keyValue[" + this.KeyValue + "], Type=" + this.Type.StringRepresentation;
}
}
/// <summary>
/// The Accept method used to support the double-dispatch visitor pattern with a visitor that returns a result.
/// </summary>
/// <typeparam name="TResult">The result type returned by the visitor.</typeparam>
/// <param name="visitor">The visitor that is visiting this query value.</param>
/// <returns>The result of visiting this query value.</returns>
public override TResult Accept<TResult>(IQueryValueVisitor<TResult> visitor)
{
return visitor.Visit(this);
}
/// <summary>
/// Gets a <see cref="QueryReferenceValue"/> value indicating whether two values are equal.
/// </summary>
/// <param name="otherValue">The second value.</param>
/// <returns>
/// Instance of <see cref="QueryScalarValue"/> which represents the result of comparison.
/// </returns>
public QueryScalarValue EqualTo(QueryReferenceValue otherValue)
{
if ((this.IsNull && otherValue.IsNull) || object.ReferenceEquals(this.EntityValue, otherValue.EntityValue))
{
return new QueryScalarValue(EvaluationStrategy.BooleanType, true, this.EvaluationError, this.EvaluationStrategy);
}
else
{
return new QueryScalarValue(EvaluationStrategy.BooleanType, false, this.EvaluationError, this.EvaluationStrategy);
}
}
/// <summary>
/// Gets a <see cref="QueryReferenceValue"/> value indicating whether two values are not equal.
/// </summary>
/// <param name="otherValue">The second value.</param>
/// <returns>
/// Instance of <see cref="QueryScalarValue"/> which represents the result of comparison.
/// </returns>
public QueryScalarValue NotEqualTo(QueryReferenceValue otherValue)
{
bool areEqual = (bool)this.EqualTo(otherValue).Value;
return new QueryScalarValue(EvaluationStrategy.BooleanType, !areEqual, this.EvaluationError, this.EvaluationStrategy);
}
internal void SetReferenceValue(QueryStructuralValue entityValue)
{
ExceptionUtilities.CheckArgumentNotNull(entityValue, "entityValue");
this.EntityValue = entityValue;
// compute key value
QueryEntityType entityType = this.Type.QueryEntityType;
var keyType = new QueryRecordType(this.EvaluationStrategy);
keyType.AddProperties(entityType.Properties.Where(m => m.IsPrimaryKey));
this.KeyValue = keyType.CreateNewInstance();
for (int i = 0; i < keyType.Properties.Count; i++)
{
this.KeyValue.SetMemberValue(i, entityValue.GetValue(keyType.Properties[i].Name));
}
var set = entityType.EntitySet;
this.EntitySetFullName = set.Container.Name + "." + set.Name;
}
// this is only heppening when reading from product or creating dangling reference
internal void SetReferenceValue(string entitySetFullName, QueryRecordValue keyValue)
{
ExceptionUtilities.CheckStringArgumentIsNotNullOrEmpty(entitySetFullName, "entitySetFullName");
ExceptionUtilities.CheckArgumentNotNull(keyValue, "keyValue");
this.EntitySetFullName = entitySetFullName;
this.KeyValue = keyValue;
this.EntityValue = this.Type.QueryEntityType.NullValue;
}
/// <summary>
/// Gets the type of the value.
/// </summary>
/// <returns>Type of the value.</returns>
protected override QueryType GetTypeInternal()
{
return this.Type;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NSubstitute;
using Xunit;
using System.Threading.Tasks;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class SearchClientTests
{
public class TheConstructor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new SearchClient(null));
}
}
public class TheSearchUsersMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchUsers(new SearchUsersRequest("something"));
connection.Received().Get<SearchUsersResult>(Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchUsers(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github"));
}
[Fact]
public void TestingTheAccountTypeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.AccountType = AccountSearchType.User;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:User"));
}
[Fact]
public void TestingTheAccountTypeQualifier_Org()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.AccountType = AccountSearchType.Org;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:Org"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get users where the fullname contains 'github'
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Fullname };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Fullname"));
}
[Fact]
public void TestingTheInQualifier_Email()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Email };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Email"));
}
[Fact]
public void TestingTheInQualifier_Username()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Username };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Username, UserInQualifier.Fullname, UserInQualifier.Email };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username,Fullname,Email"));
}
[Fact]
public void TestingTheReposQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.GreaterThan(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>5"));
}
[Fact]
public void TestingTheReposQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.GreaterThanOrEquals(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>=5"));
}
[Fact]
public void TestingTheReposQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.LessThanOrEquals(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<=5"));
}
[Fact]
public void TestingTheReposQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.LessThan(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<5"));
}
[Fact]
public void TestingTheLocationQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Location = "San Francisco";
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+location:San Francisco"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get users who have mostly repos where language is Ruby
var request = new SearchUsersRequest("github");
request.Language = Language.Ruby;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.Between(new DateTime(2014, 1, 1), new DateTime(2014, 2, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:2014-01-01..2014-02-01"));
}
[Fact]
public void TestingTheFollowersQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.GreaterThan(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>1"));
}
[Fact]
public void TestingTheFollowersQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.GreaterThanOrEquals(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>=1"));
}
[Fact]
public void TestingTheFollowersQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.LessThan(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<1"));
}
[Fact]
public void TestingTheFollowersQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.LessThanOrEquals(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<=1"));
}
[Fact]
public void TestingTheFollowersQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = new Range(1, 1000);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:1..1000"));
}
}
public class TheSearchRepoMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchRepo(new SearchRepositoriesRequest("something"));
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchRepo(null));
}
[Fact]
public void TestingTheSizeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.Size = Range.GreaterThan(1);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+size:>1"));
}
[Fact]
public void TestingTheStarsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are greater than 500
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.GreaterThan(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:>500"));
}
[Fact]
public void TestingTheStarsQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are less than 500
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.LessThan(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<500"));
}
[Fact]
public void TestingTheStarsQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are less than 500 or equal to
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.LessThanOrEquals(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<=500"));
}
[Fact]
public void TestingTheForksQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos which has forks that are greater than 50
var request = new SearchRepositoriesRequest("github");
request.Forks = Range.GreaterThan(50);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+forks:>50"));
}
[Fact]
public void TestingTheForkQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//search repos that contains rails and forks are included in the search
var request = new SearchRepositoriesRequest("github");
request.Fork = ForkQualifier.IncludeForks;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+fork:IncludeForks"));
}
[Fact]
public void TestingTheLangaugeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos language is Ruby
var request = new SearchRepositoriesRequest("github");
request.Language = Language.Ruby;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the Description contains the test 'github'
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Description };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Description"));
}
[Fact]
public void TestingTheInQualifier_Name()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Name };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Name"));
}
[Fact]
public void TestingTheInQualifier_Readme()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Readme };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Readme, InQualifier.Description, InQualifier.Name };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme,Description,Name"));
}
[Fact]
public void TestingTheCreatedQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.GreaterThan(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.LessThan(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.LessThanOrEquals(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.Between(new DateTime(2011, 1, 1), new DateTime(2012, 11, 11));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:2011-01-01..2012-11-11"));
}
[Fact]
public void TestingTheUpdatedQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.GreaterThan(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>=2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.LessThan(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.LessThanOrEquals(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<=2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.Between(new DateTime(2012, 4, 30), new DateTime(2012, 7, 4));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:2012-04-30..2012-07-04"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where search contains 'github' and user/org is 'github'
var request = new SearchRepositoriesRequest("github");
request.User = "rails";
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+user:rails"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.SortField = RepoSearchSort.Stars;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "github" &&
d["sort"] == "stars"));
}
[Fact]
public void TestingTheSearchParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest();
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d =>
String.IsNullOrEmpty(d["q"])));
}
}
public class TheSearchIssuesMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchIssues(new SearchIssuesRequest("something"));
connection.Received().Get<SearchIssuesResult>(Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchIssues(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("pub");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "pub"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.SortField = IssueSearchSort.Comments;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "comments"));
}
[Fact]
public void TestingTheOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.SortField = IssueSearchSort.Updated;
request.Order = SortDirection.Ascending;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "updated" &&
d["order"] == "asc"));
}
[Fact]
public void TestingTheDefaultOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["order"] == "desc"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.In = new[] { IssueInQualifier.Comment };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:comment"));
}
[Fact]
public void TestingTheInQualifiers_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.In = new[] { IssueInQualifier.Body, IssueInQualifier.Title };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:body,title"));
}
[Fact]
public void TestingTheTypeQualifier_Issue()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Type = IssueTypeQualifier.Issue;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:issue"));
}
[Fact]
public void TestingTheTypeQualifier_PR()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Type = IssueTypeQualifier.PR;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:pr"));
}
[Fact]
public void TestingTheAuthorQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Author = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+author:alfhenrik"));
}
[Fact]
public void TestingTheAssigneeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Assignee = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+assignee:alfhenrik"));
}
[Fact]
public void TestingTheMentionsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Mentions = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+mentions:alfhenrik"));
}
[Fact]
public void TestingTheCommenterQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Commenter = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+commenter:alfhenrik"));
}
[Fact]
public void TestingTheInvolvesQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Involves = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+involves:alfhenrik"));
}
[Fact]
public void TestingTheStateQualifier_Open()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.State = ItemState.Open;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:open"));
}
[Fact]
public void TestingTheStateQualifier_Closed()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.State = ItemState.Closed;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:closed"));
}
[Fact]
public void TestingTheLabelsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Labels = new[] { "bug" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug"));
}
[Fact]
public void TestingTheLabelsQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Labels = new[] { "bug", "feature" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug+label:feature"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Language = Language.CSharp;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:CSharp"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.Between(new DateTime(2014, 1, 1), new DateTime(2014, 2, 2));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:2014-01-01..2014-02-02"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>=2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<=2014-01-01"));
}
[Fact]
public void TestingTheCommentsQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.GreaterThan(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>10"));
}
[Fact]
public void TestingTheCommentsQualifier_GreaterThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.GreaterThanOrEquals(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>=10"));
}
[Fact]
public void TestingTheCommentsQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.LessThan(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<10"));
}
[Fact]
public void TestingTheCommentsQualifier_LessThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.LessThanOrEquals(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<=10"));
}
[Fact]
public void TestingTheCommentsQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = new Range(10, 20);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:10..20"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.User = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik"));
}
[Fact]
public void TestingTheRepoQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Repos.Add("octokit", "octokit.net");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit/octokit.net"));
}
[Fact]
public async Task ErrorOccursWhenSpecifyingInvalidFormatForRepos()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("windows");
request.Repos = new RepositoryCollection {
"haha-business"
};
request.SortField = IssueSearchSort.Created;
request.Order = SortDirection.Descending;
await Assert.ThrowsAsync<RepositoryFormatException>(
async () => await client.SearchIssues(request));
}
[Fact]
public void TestingTheRepoAndUserAndLabelQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Repos.Add("octokit/octokit.net");
request.User = "alfhenrik";
request.Labels = new[] { "bug" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] ==
"something+label:bug+user:alfhenrik+repo:octokit/octokit.net"));
}
}
public class TheSearchCodeMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchCode(new SearchCodeRequest("something"));
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchCode(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.SortField = CodeSearchSort.Indexed;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["sort"] == "indexed"));
}
[Fact]
public void TestingTheOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.SortField = CodeSearchSort.Indexed;
request.Order = SortDirection.Ascending;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "indexed" &&
d["order"] == "asc"));
}
[Fact]
public void TestingTheDefaultOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["order"] == "desc"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.In = new[] { CodeInQualifier.File };
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.In = new[] { CodeInQualifier.File, CodeInQualifier.Path };
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file,path"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Language = Language.CSharp;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:C#"));
}
[Fact]
public void TestingTheForksQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Forks = true;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+fork:true"));
}
[Fact]
public void TestingTheSizeQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.GreaterThan(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>10"));
}
[Fact]
public void TestingTheSizeQualifier_GreaterThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.GreaterThanOrEquals(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>=10"));
}
[Fact]
public void TestingTheSizeQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.LessThan(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<10"));
}
[Fact]
public void TestingTheSizeQualifier_LessThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.LessThanOrEquals(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<=10"));
}
[Fact]
public void TestingTheSizeQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = new Range(10, 100);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:10..100"));
}
[Fact]
public void TestingThePathQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Path = "app/public";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+path:app/public"));
}
[Fact]
public void TestingTheExtensionQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Extension = "cs";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+extension:cs"));
}
[Fact]
public void TestingTheFileNameQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.FileName = "packages.config";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+filename:packages.config"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.User = "alfhenrik";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik"));
}
[Fact]
public void TestingTheRepoQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something", "octokit", "octokit.net");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit/octokit.net"));
}
[Fact]
public void TestingTheRepoQualifier_InConstructor()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something", "octokit", "octokit.net");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "something+repo:octokit/octokit.net"));
}
[Fact]
public void TestingTheRepoAndPathAndExtensionQualifiers()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something", "octokit", "octokit.net");
request.Path = "tools/FAKE.core";
request.Extension = "fs";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "something+path:tools/FAKE.core+extension:fs+repo:octokit/octokit.net"));
}
[Fact]
public async Task ErrorOccursWhenSpecifyingInvalidFormatForRepos()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("windows");
request.Repos = new RepositoryCollection {
"haha-business"
};
request.Order = SortDirection.Descending;
await Assert.ThrowsAsync<RepositoryFormatException>(
async () => await client.SearchCode(request));
}
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="ProjectItemInstance_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Tests for ProjectItemInstance public members</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.OM.Instance
{
/// <summary>
/// Tests for ProjectItemInstance public members
/// </summary>
[TestClass]
public class ProjectItemInstance_Tests
{
/// <summary>
/// The number of built-in metadata for items.
/// </summary>
public const int BuiltInMetadataCount = 15;
/// <summary>
/// Basic ProjectItemInstance without metadata
/// </summary>
[TestMethod]
public void AccessorsWithoutMetadata()
{
ProjectItemInstance item = GetItemInstance();
Assert.AreEqual("i", item.ItemType);
Assert.AreEqual("i1", item.EvaluatedInclude);
Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext());
}
/// <summary>
/// Basic ProjectItemInstance with metadata
/// </summary>
[TestMethod]
public void AccessorsWithMetadata()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m1", "v0");
item.SetMetadata("m1", "v1");
item.SetMetadata("m2", "v2");
Assert.AreEqual("m1", item.GetMetadata("m1").Name);
Assert.AreEqual("m2", item.GetMetadata("m2").Name);
Assert.AreEqual("v1", item.GetMetadataValue("m1"));
Assert.AreEqual("v2", item.GetMetadataValue("m2"));
}
/// <summary>
/// Get metadata not present
/// </summary>
[TestMethod]
public void GetMissingMetadata()
{
ProjectItemInstance item = GetItemInstance();
Assert.AreEqual(null, item.GetMetadata("X"));
Assert.AreEqual(String.Empty, item.GetMetadataValue("X"));
}
/// <summary>
/// Set include
/// </summary>
[TestMethod]
public void SetInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = "i1b";
Assert.AreEqual("i1b", item.EvaluatedInclude);
}
/// <summary>
/// Set include to empty string
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SetInvalidEmptyInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = String.Empty;
}
/// <summary>
/// Set include to invalid null value
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SetInvalidNullInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = null;
}
/// <summary>
/// Create an item with a metadatum that has a null value
/// </summary>
[TestMethod]
public void CreateItemWithNullMetadataValue()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
IDictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add("m", null);
ProjectItemInstance item = projectInstance.AddItem("i", "i1", metadata);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value
/// </summary>
[TestMethod]
public void SetMetadata()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
Assert.AreEqual("m1", item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value to empty string
/// </summary>
[TestMethod]
public void SetMetadataEmptyString()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", String.Empty);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value to null value -- this is allowed, but
/// internally converted to the empty string.
/// </summary>
[TestMethod]
public void SetNullMetadataValue()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", null);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata with invalid empty name
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SetInvalidNullMetadataName()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(null, "m1");
}
/// <summary>
/// Set metadata with invalid empty name
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SetInvalidEmptyMetadataName()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(String.Empty, "m1");
}
/// <summary>
/// Cast to ITaskItem
/// </summary>
[TestMethod]
public void CastToITaskItem()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
ITaskItem taskItem = (ITaskItem)item;
Assert.AreEqual(item.EvaluatedInclude, taskItem.ItemSpec);
Assert.AreEqual(1 + BuiltInMetadataCount, taskItem.MetadataCount);
Assert.AreEqual(1 + BuiltInMetadataCount, taskItem.MetadataNames.Count);
Assert.AreEqual("m1", taskItem.GetMetadata("m"));
taskItem.SetMetadata("m", "m2");
Assert.AreEqual("m2", item.GetMetadataValue("m"));
}
/// <summary>
/// Creates a ProjectItemInstance and casts it to ITaskItem2; makes sure that all escaped information is
/// maintained correctly. Also creates a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance
/// and verifies that none of the information is lost.
/// </summary>
[TestMethod]
public void ITaskItem2Operations()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectItemInstance item = projectInstance.AddItem("EscapedItem", "esca%20ped%3bitem");
item.SetMetadata("m", "m1");
item.SetMetadata("m;", "m%3b1");
ITaskItem2 taskItem = (ITaskItem2)item;
Assert.AreEqual(taskItem.EvaluatedIncludeEscaped, "esca%20ped%3bitem");
Assert.AreEqual(taskItem.ItemSpec, "esca ped;item");
Assert.AreEqual(taskItem.GetMetadata("m;"), "m;1");
Assert.AreEqual(taskItem.GetMetadataValueEscaped("m;"), "m%3b1");
Assert.AreEqual(taskItem.GetMetadataValueEscaped("m"), "m1");
Assert.AreEqual(taskItem.EvaluatedIncludeEscaped, "esca%20ped%3bitem");
Assert.AreEqual(taskItem.ItemSpec, "esca ped;item");
ITaskItem2 taskItem2 = new Microsoft.Build.Utilities.TaskItem(taskItem);
taskItem2.SetMetadataValueLiteral("m;", "m;2");
Assert.AreEqual(taskItem2.GetMetadataValueEscaped("m;"), "m%3b2");
Assert.AreEqual(taskItem2.GetMetadata("m;"), "m;2");
IDictionary<string, string> taskItem2Metadata = (IDictionary<string, string>)taskItem2.CloneCustomMetadata();
Assert.AreEqual(3, taskItem2Metadata.Count);
foreach (KeyValuePair<string, string> pair in taskItem2Metadata)
{
if (pair.Key.Equals("m"))
{
Assert.AreEqual("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.AreEqual("m;2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.AreEqual("esca ped;item", pair.Value);
}
}
IDictionary<string, string> taskItem2MetadataEscaped = (IDictionary<string, string>)taskItem2.CloneCustomMetadataEscaped();
Assert.AreEqual(3, taskItem2MetadataEscaped.Count);
foreach (KeyValuePair<string, string> pair in taskItem2MetadataEscaped)
{
if (pair.Key.Equals("m"))
{
Assert.AreEqual("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.AreEqual("m%3b2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.AreEqual("esca%20ped%3bitem", pair.Value);
}
}
}
/// <summary>
/// Cast to ITaskItem
/// </summary>
[TestMethod]
public void CastToITaskItemNoMetadata()
{
ProjectItemInstance item = GetItemInstance();
ITaskItem taskItem = (ITaskItem)item;
Assert.AreEqual(0 + BuiltInMetadataCount, taskItem.MetadataCount);
Assert.AreEqual(0 + BuiltInMetadataCount, taskItem.MetadataNames.Count);
Assert.AreEqual(String.Empty, taskItem.GetMetadata("m"));
}
/*
* We must repeat all the evaluation-related tests here,
* to exercise the path that evaluates directly to instance objects.
* Although the Evaluator class is shared, its interactions with the two
* different item classes could be different, and shouldn't be.
*/
/// <summary>
/// No metadata, simple case
/// </summary>
[TestMethod]
public void NoMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i", item.ItemType);
Assert.AreEqual("i1", item.EvaluatedInclude);
Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext());
Assert.AreEqual(0 + BuiltInMetadataCount, Helpers.MakeList(item.MetadataNames).Count);
Assert.AreEqual(0 + BuiltInMetadataCount, item.MetadataCount);
}
/// <summary>
/// Read off metadata
/// </summary>
[TestMethod]
public void ReadMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.AreEqual(2, itemMetadata.Count);
Assert.AreEqual("m1", itemMetadata[0].Name);
Assert.AreEqual("m2", itemMetadata[1].Name);
Assert.AreEqual("v1", itemMetadata[0].EvaluatedValue);
Assert.AreEqual("v2", itemMetadata[1].EvaluatedValue);
Assert.AreEqual(itemMetadata[0], item.GetMetadata("m1"));
Assert.AreEqual(itemMetadata[1], item.GetMetadata("m2"));
}
/// <summary>
/// Create a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance where the ProjectItemInstance
/// has item definition metadata on it.
///
/// Verify the Utilities task item gets the expanded metadata from the ItemDefintionGroup.
/// </summary>
[TestMethod]
public void InstanceItemToUtilItemIDG()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>;x86;</m0>
<m1>%(FileName).extension</m1>
<m2>;%(FileName).extension;</m2>
<m3>v1</m3>
<m4>%3bx86%3b</m4>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='foo.proj'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Microsoft.Build.Utilities.TaskItem taskItem = new Microsoft.Build.Utilities.TaskItem(item);
Assert.AreEqual(";x86;", taskItem.GetMetadata("m0"));
Assert.AreEqual("foo.extension", taskItem.GetMetadata("m1"));
Assert.AreEqual(";foo.extension;", taskItem.GetMetadata("m2"));
Assert.AreEqual("v1", taskItem.GetMetadata("m3"));
Assert.AreEqual(";x86;", taskItem.GetMetadata("m4"));
}
/// <summary>
/// Get metadata values inherited from item definitions
/// </summary>
[TestMethod]
public void GetMetadataValuesFromDefinition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>v0</m0>
<m1>v1</m1>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='i1'>
<m1>v1b</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("v0", item.GetMetadataValue("m0"));
Assert.AreEqual("v1b", item.GetMetadataValue("m1"));
Assert.AreEqual("v2", item.GetMetadataValue("m2"));
Assert.AreEqual(3, Helpers.MakeList(item.Metadata).Count);
Assert.AreEqual(3 + BuiltInMetadataCount, Helpers.MakeList(item.MetadataNames).Count);
Assert.AreEqual(3 + BuiltInMetadataCount, item.MetadataCount);
}
/// <summary>
/// Exclude against an include with item vectors in it
/// </summary>
[TestMethod]
public void ExcludeWithIncludeVector()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='b;y;v'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, x, z, a, c, u, w
Assert.AreEqual(9, items.Count);
AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "x", "z", "a", "c", "u", "w" });
}
/// <summary>
/// Exclude with item vectors against an include with item vectors in it
/// </summary>
[TestMethod]
public void ExcludeVectorWithIncludeVector()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
<j Include='b;y;v' />
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='x;@(j);w'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, z, a, c, u
Assert.AreEqual(7, items.Count);
AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "z", "a", "c", "u" });
}
/// <summary>
/// Metadata on items can refer to metadata above
/// </summary>
[TestMethod]
public void MetadataReferringToMetadataAbove()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>%(m1);v2;%(m0)</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.AreEqual(2, itemMetadata.Count);
Assert.AreEqual("v1;v2;", item.GetMetadataValue("m2"));
}
/// <summary>
/// Built-in metadata should work, too.
/// NOTE: To work properly, this should batch. This is a temporary "patch" to make it work for now.
/// It will only give correct results if there is exactly one item in the Include. Otherwise Batching would be needed.
/// </summary>
[TestMethod]
public void BuiltInMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i1", item.GetMetadataValue("m"));
}
/// <summary>
/// Qualified built in metadata should work
/// </summary>
[TestMethod]
public void BuiltInQualifiedMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(i.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i1", item.GetMetadataValue("m"));
}
/// <summary>
/// Mis-qualified built in metadata should not work
/// </summary>
[TestMethod]
public void BuiltInMisqualifiedMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(j.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Metadata condition should work correctly with built-in metadata
/// </summary>
[TestMethod]
public void BuiltInMetadataInMetadataCondition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m Condition=""'%(Identity)'=='i1'"">m1</m>
<n Condition=""'%(Identity)'=='i2'"">n1</n>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("m1", item.GetMetadataValue("m"));
Assert.AreEqual(String.Empty, item.GetMetadataValue("n"));
}
/// <summary>
/// Metadata on item condition not allowed (currently)
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void BuiltInMetadataInItemCondition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1' Condition=""'%(Identity)'=='i1'/>
</ItemGroup>
</Project>
";
GetOneItem(content);
}
/// <summary>
/// Two items should each get their own values for built-in metadata
/// </summary>
[TestMethod]
public void BuiltInMetadataTwoItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1.cpp;c:\bar\i2.cpp'>
<m>%(Filename).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i1.obj", items[0].GetMetadataValue("m"));
Assert.AreEqual(@"i2.obj", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Items from another list, but with different metadata
/// </summary>
[TestMethod]
public void DifferentMetadataItemsFromOtherList()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'>
<m>m1</m>
</h>
<h Include='h1'/>
<i Include='@(h)'>
<m>%(m)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"m1", items[0].GetMetadataValue("m"));
Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m"));
}
/// <summary>
/// Items from another list, but with different metadata
/// </summary>
[TestMethod]
public void DifferentBuiltInMetadataItemsFromOtherList()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0.x'/>
<h Include='h1.y'/>
<i Include='@(h)'>
<m>%(extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@".x", items[0].GetMetadataValue("m"));
Assert.AreEqual(@".y", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Two items coming from a transform
/// </summary>
[TestMethod]
public void BuiltInMetadataTransformInInclude()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include=""@(h->'%(Identity).baz')"">
<m>%(Filename)%(Extension).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"h0.baz.obj", items[0].GetMetadataValue("m"));
Assert.AreEqual(@"h1.baz.obj", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Transform in the metadata value; no bare metadata involved
/// </summary>
[TestMethod]
public void BuiltInMetadataTransformInMetadataValue()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0'/>
<i Include='i1;i2'>
<m>@(i);@(h->'%(Filename)')</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i0;h0;h1", items[1].GetMetadataValue("m"));
Assert.AreEqual(@"i0;h0;h1", items[2].GetMetadataValue("m"));
}
/// <summary>
/// Transform in the metadata value; bare metadata involved
/// </summary>
[TestMethod]
public void BuiltInMetadataTransformInMetadataValueBareMetadataPresent()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0.x'/>
<i Include='i1.y;i2'>
<m>@(i);@(h->'%(Filename)');%(Extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i0.x;h0;h1;.y", items[1].GetMetadataValue("m"));
Assert.AreEqual(@"i0.x;h0;h1;", items[2].GetMetadataValue("m"));
}
/// <summary>
/// Metadata on items can refer to item lists
/// </summary>
[TestMethod]
public void MetadataValueReferringToItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1>@(h);@(i)</m1>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("h0;i0", items[1].GetMetadataValue("m1"));
}
/// <summary>
/// Metadata on items' conditions can refer to item lists
/// </summary>
[TestMethod]
public void MetadataConditionReferringToItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1 Condition=""'@(h)'=='h0' and '@(i)'=='i0'"">v1</m1>
<m2 Condition=""'@(h)'!='h0' or '@(i)'!='i0'"">v2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("v1", items[1].GetMetadataValue("m1"));
Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m2"));
}
/// <summary>
/// Metadata on items' conditions can refer to other metadata
/// </summary>
[TestMethod]
public void MetadataConditionReferringToMetadataOnSameItem()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m0>0</m0>
<m1 Condition=""'%(m0)'=='0'"">1</m1>
<m2 Condition=""'%(m0)'=='3'"">2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("0", items[0].GetMetadataValue("m0"));
Assert.AreEqual("1", items[0].GetMetadataValue("m1"));
Assert.AreEqual(String.Empty, items[0].GetMetadataValue("m2"));
}
/// <summary>
/// Gets the first item of type 'i'
/// </summary>
private static ProjectItemInstance GetOneItem(string content)
{
return GetItems(content)[0];
}
/// <summary>
/// Get all items of type 'i'
/// </summary>
private static IList<ProjectItemInstance> GetItems(string content)
{
ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectInstance project = new ProjectInstance(xml);
return Helpers.MakeList(project.GetItems("i"));
}
/// <summary>
/// Asserts that the list of items has the specified includes.
/// </summary>
private static void AssertEvaluatedIncludes(IList<ProjectItemInstance> items, string[] includes)
{
for (int i = 0; i < includes.Length; i++)
{
Assert.AreEqual(includes[i], items[i].EvaluatedInclude);
}
}
/// <summary>
/// Get a single item instance
/// </summary>
private static ProjectItemInstance GetItemInstance()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectItemInstance item = projectInstance.AddItem("i", "i1");
return item;
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Diagnostics;
using System.Resources;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
namespace Microsoft.Build.Tasks
{
/// <summary>
/// Returns paths to the frameworks SDK.
/// </summary>
public class GetFrameworkSdkPath : TaskExtension
{
#region Properties
private static string s_path;
private static string s_version20Path;
private static string s_version35Path;
private static string s_version40Path;
private static string s_version45Path;
private static string s_version451Path;
private static string s_version46Path;
/// <summary>
/// The path to the latest .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string Path
{
get
{
if (s_path == null)
{
s_path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.VersionLatest, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.VersionLatest, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.VersionLatest, VisualStudioVersion.VersionLatest)
);
s_path = String.Empty;
}
else
{
s_path = FileUtilities.EnsureTrailingSlash(s_path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_path);
}
}
return s_path;
}
set
{
// Does nothing; for backwards compatibility only
}
}
/// <summary>
/// The path to the v2.0 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion20Path
{
get
{
if (s_version20Path == null)
{
s_version20Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version20);
if (String.IsNullOrEmpty(s_version20Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version20),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version20)
);
s_version20Path = String.Empty;
}
else
{
s_version20Path = FileUtilities.EnsureTrailingSlash(s_version20Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version20Path);
}
}
return s_version20Path;
}
}
/// <summary>
/// The path to the v3.5 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion35Path
{
get
{
if (s_version35Path == null)
{
s_version35Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version35Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest)
);
s_version35Path = String.Empty;
}
else
{
s_version35Path = FileUtilities.EnsureTrailingSlash(s_version35Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version35Path);
}
}
return s_version35Path;
}
}
/// <summary>
/// The path to the v4.0 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion40Path
{
get
{
if (s_version40Path == null)
{
s_version40Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version40Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest)
);
s_version40Path = String.Empty;
}
else
{
s_version40Path = FileUtilities.EnsureTrailingSlash(s_version40Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version40Path);
}
}
return s_version40Path;
}
}
/// <summary>
/// The path to the v4.5 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion45Path
{
get
{
if (s_version45Path == null)
{
s_version45Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version45Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest)
);
s_version45Path = String.Empty;
}
else
{
s_version45Path = FileUtilities.EnsureTrailingSlash(s_version45Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version45Path);
}
}
return s_version45Path;
}
}
/// <summary>
/// The path to the v4.5.1 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion451Path
{
get
{
if (s_version451Path == null)
{
s_version451Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version451Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest)
);
s_version451Path = String.Empty;
}
else
{
s_version451Path = FileUtilities.EnsureTrailingSlash(s_version451Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version451Path);
}
}
return s_version451Path;
}
}
/// <summary>
/// The path to the v4.6 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion46Path
{
get
{
if (s_version46Path == null)
{
s_version46Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version46Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest)
);
s_version46Path = String.Empty;
}
else
{
s_version46Path = FileUtilities.EnsureTrailingSlash(s_version46Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version46Path);
}
}
return s_version46Path;
}
}
#endregion
#region ITask Members
/// <summary>
/// Get the SDK.
/// </summary>
/// <returns>true</returns>
public override bool Execute()
{
//Does Nothing: getters do all the work
return true;
}
#endregion
}
}
|
//-----------------------------------------------------------------------
// <copyright file="SimpleJson.cs" company="The Outercurve Foundation">
// Copyright (c) 2011, The Outercurve Foundation.
//
// Licensed under the MIT License (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.opensource.org/licenses/mit-license.php
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>
// <website>https://github.com/facebook-csharp-sdk/simple-json</website>
//-----------------------------------------------------------------------
// VERSION:
// NOTE: uncomment the following line to make SimpleJson class internal.
//#define SIMPLE_JSON_INTERNAL
// NOTE: uncomment the following line to make JsonArray and JsonObject class internal.
//#define SIMPLE_JSON_OBJARRAYINTERNAL
// NOTE: uncomment the following line to enable dynamic support.
//#define SIMPLE_JSON_DYNAMIC
// NOTE: uncomment the following line to enable DataContract support.
//#define SIMPLE_JSON_DATACONTRACT
// NOTE: uncomment the following line to enable IReadOnlyCollection<T> and IReadOnlyList<T> support.
//#define SIMPLE_JSON_READONLY_COLLECTIONS
// NOTE: uncomment the following line if you are compiling under Window Metro style application/library.
// usually already defined in properties
#if UNITY_WSA && UNITY_WP8
#define NETFX_CORE
#endif
// If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to
#if UNITY_WP8 || UNITY_WP8_1 || UNITY_WSA
// #define SIMPLE_JSON_TYPEINFO
#endif
// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
#if NETFX_CORE
#define SIMPLE_JSON_TYPEINFO
#endif
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
#if SIMPLE_JSON_DYNAMIC
using System.Dynamic;
#endif
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
// ReSharper disable LoopCanBeConvertedToQuery
// ReSharper disable RedundantExplicitArrayCreation
// ReSharper disable SuggestUseVarKeywordEvident
namespace PlayFab.Json
{
public enum NullValueHandling
{
Include, // Include null values when serializing and deserializing objects
Ignore // Ignore null values when serializing and deserializing objects
}
/// <summary>
/// Customize the json output of a field or property
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class JsonProperty : Attribute
{
public string PropertyName = null;
public NullValueHandling NullValueHandling = NullValueHandling.Include;
}
/// <summary>
/// Represents the json array.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#if SIMPLE_JSON_OBJARRAYINTERNAL
internal
#else
public
#endif
class JsonArray : List<object>
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class.
/// </summary>
public JsonArray() { }
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class.
/// </summary>
/// <param name="capacity">The capacity of the json array.</param>
public JsonArray(int capacity) : base(capacity) { }
/// <summary>
/// The json representation of the array.
/// </summary>
/// <returns>The json representation of the array.</returns>
public override string ToString()
{
return PlayFabSimpleJson.SerializeObject(this) ?? string.Empty;
}
}
/// <summary>
/// Represents the json object.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#if SIMPLE_JSON_OBJARRAYINTERNAL
internal
#else
public
#endif
class JsonObject :
#if SIMPLE_JSON_DYNAMIC
DynamicObject,
#endif
IDictionary<string, object>
{
private const int DICTIONARY_DEFAULT_SIZE = 16;
/// <summary>
/// The internal member dictionary.
/// </summary>
private readonly Dictionary<string, object> _members;
/// <summary>
/// Initializes a new instance of <see cref="JsonObject"/>.
/// </summary>
public JsonObject()
{
_members = new Dictionary<string, object>(DICTIONARY_DEFAULT_SIZE);
}
/// <summary>
/// Initializes a new instance of <see cref="JsonObject"/>.
/// </summary>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer`1"/> implementation to use when comparing keys, or null to use the default <see cref="T:System.Collections.Generic.EqualityComparer`1"/> for the type of the key.</param>
public JsonObject(IEqualityComparer<string> comparer)
{
_members = new Dictionary<string, object>(comparer);
}
/// <summary>
/// Gets the <see cref="System.Object"/> at the specified index.
/// </summary>
/// <value></value>
public object this[int index]
{
get { return GetAtIndex(_members, index); }
}
internal static object GetAtIndex(IDictionary<string, object> obj, int index)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (index >= obj.Count)
throw new ArgumentOutOfRangeException("index");
int i = 0;
foreach (KeyValuePair<string, object> o in obj)
if (i++ == index) return o.Value;
return null;
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void Add(string key, object value)
{
_members.Add(key, value);
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(string key)
{
return _members.ContainsKey(key);
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<string> Keys
{
get { return _members.Keys; }
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public bool Remove(string key)
{
return _members.Remove(key);
}
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGetValue(string key, out object value)
{
return _members.TryGetValue(key, out value);
}
/// <summary>
/// Gets the values.
/// </summary>
/// <value>The values.</value>
public ICollection<object> Values
{
get { return _members.Values; }
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
public object this[string key]
{
get { return _members[key]; }
set { _members[key] = value; }
}
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item.</param>
public void Add(KeyValuePair<string, object> item)
{
_members.Add(item.Key, item.Value);
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
_members.Clear();
}
/// <summary>
/// Determines whether [contains] [the specified item].
/// </summary>
/// <param name="item">The item.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
/// </returns>
public bool Contains(KeyValuePair<string, object> item)
{
return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException("array");
int num = Count;
foreach (KeyValuePair<string, object> kvp in _members)
{
array[arrayIndex++] = kvp;
if (--num <= 0)
return;
}
}
/// <summary>
/// Gets the count.
/// </summary>
/// <value>The count.</value>
public int Count
{
get { return _members.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value>
/// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
/// </value>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
public bool Remove(KeyValuePair<string, object> item)
{
return _members.Remove(item.Key);
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns></returns>
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return _members.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _members.GetEnumerator();
}
/// <summary>
/// Returns a json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return PlayFabSimpleJson.SerializeObject(_members);
}
#if SIMPLE_JSON_DYNAMIC
/// <summary>
/// Provides implementation for type conversion operations. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.
/// </summary>
/// <param name="binder">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Type returns the <see cref="T:System.String"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>
/// <param name="result">The result of the type conversion operation.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryConvert(ConvertBinder binder, out object result)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
Type targetType = binder.Type;
if ((targetType == typeof(IEnumerable)) ||
(targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||
(targetType == typeof(IDictionary<string, object>)) ||
(targetType == typeof(IDictionary)))
{
result = this;
return true;
}
return base.TryConvert(binder, out result);
}
/// <summary>
/// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.
/// </summary>
/// <param name="binder">Provides information about the deletion.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
return _members.Remove(binder.Name);
}
/// <summary>
/// Provides the implementation for operations that get a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for indexing operations.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, <paramref name="indexes"/> is equal to 3.</param>
/// <param name="result">The result of the index operation.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes == null) throw new ArgumentNullException("indexes");
if (indexes.Length == 1)
{
result = ((IDictionary<string, object>)this)[(string)indexes[0]];
return true;
}
result = null;
return true;
}
/// <summary>
/// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
object value;
if (_members.TryGetValue(binder.Name, out value))
{
result = value;
return true;
}
result = null;
return true;
}
/// <summary>
/// Provides the implementation for operations that set a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="indexes"/> is equal to 3.</param>
/// <param name="value">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="value"/> is equal to 10.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.
/// </returns>
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (indexes == null) throw new ArgumentNullException("indexes");
if (indexes.Length == 1)
{
((IDictionary<string, object>)this)[(string)indexes[0]] = value;
return true;
}
return base.TrySetIndex(binder, indexes, value);
}
/// <summary>
/// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, the <paramref name="value"/> is "Test".</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
/// </returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
_members[binder.Name] = value;
return true;
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>
/// A sequence that contains dynamic member names.
/// </returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
foreach (var key in Keys)
yield return key;
}
#endif
}
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList<object>) and JsonObject(IDictionary<string,object>).
/// All numbers are parsed to doubles.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
static class PlayFabSimpleJson
{
private enum TokenType : byte
{
NONE = 0,
CURLY_OPEN = 1,
CURLY_CLOSE = 2,
SQUARED_OPEN = 3,
SQUARED_CLOSE = 4,
COLON = 5,
COMMA = 6,
STRING = 7,
NUMBER = 8,
TRUE = 9,
FALSE = 10,
NULL = 11,
}
private const int BUILDER_INIT = 2000;
private static readonly char[] EscapeTable;
private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' };
// private static readonly string EscapeCharactersString = new string(EscapeCharacters);
internal static readonly List<Type> NumberTypes = new List<Type> {
typeof(bool), typeof(byte), typeof(ushort), typeof(uint), typeof(ulong), typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(double), typeof(float), typeof(decimal)
};
// Performance stuff
[ThreadStatic]
private static StringBuilder _serializeObjectBuilder;
[ThreadStatic]
private static StringBuilder _parseStringBuilder;
static PlayFabSimpleJson()
{
EscapeTable = new char[93];
EscapeTable['"'] = '"';
EscapeTable['\\'] = '\\';
EscapeTable['\b'] = 'b';
EscapeTable['\f'] = 'f';
EscapeTable['\n'] = 'n';
EscapeTable['\r'] = 'r';
EscapeTable['\t'] = 't';
}
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An IList<object>, a IDictionary<string,object>, a double, a string, null, true, or false</returns>
public static object DeserializeObject(string json)
{
object obj;
if (TryDeserializeObject(json, out obj))
return obj;
throw new SerializationException("Invalid JSON string");
}
/// <summary>
/// Try parsing the json string into a value.
/// </summary>
/// <param name="json">
/// A JSON string.
/// </param>
/// <param name="obj">
/// The object.
/// </param>
/// <returns>
/// Returns true if successfull otherwise false.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
public static bool TryDeserializeObject(string json, out object obj)
{
bool success = true;
if (json != null)
{
int index = 0;
obj = ParseValue(json, ref index, ref success);
}
else
obj = null;
return success;
}
public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy = null)
{
object jsonObject = DeserializeObject(json);
if (type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type))
return jsonObject;
return (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type);
}
public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy = null)
{
return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);
}
/// <summary>
/// Converts a IDictionary<string,object> / IList<object> object into a JSON string
/// </summary>
/// <param name="json">A IDictionary<string,object> / IList<object></param>
/// <param name="jsonSerializerStrategy">Serializer strategy to use</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy = null)
{
if (_serializeObjectBuilder == null)
_serializeObjectBuilder = new StringBuilder(BUILDER_INIT);
_serializeObjectBuilder.Length = 0;
if (jsonSerializerStrategy == null)
jsonSerializerStrategy = CurrentJsonSerializerStrategy;
bool success = SerializeValue(jsonSerializerStrategy, json, _serializeObjectBuilder);
return (success ? _serializeObjectBuilder.ToString() : null);
}
public static string EscapeToJavascriptString(string jsonString)
{
if (string.IsNullOrEmpty(jsonString))
return jsonString;
StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < jsonString.Length;)
{
c = jsonString[i++];
if (c == '\\')
{
int remainingLength = jsonString.Length - i;
if (remainingLength >= 2)
{
char lookahead = jsonString[i];
if (lookahead == '\\')
{
sb.Append('\\');
++i;
}
else if (lookahead == '"')
{
sb.Append("\"");
++i;
}
else if (lookahead == 't')
{
sb.Append('\t');
++i;
}
else if (lookahead == 'b')
{
sb.Append('\b');
++i;
}
else if (lookahead == 'n')
{
sb.Append('\n');
++i;
}
else if (lookahead == 'r')
{
sb.Append('\r');
++i;
}
}
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
static IDictionary<string, object> ParseObject(string json, ref int index, ref bool success)
{
IDictionary<string, object> table = new JsonObject();
TokenType token;
// {
NextToken(json, ref index);
bool done = false;
while (!done)
{
token = LookAhead(json, index);
if (token == TokenType.NONE)
{
success = false;
return null;
}
else if (token == TokenType.COMMA)
NextToken(json, ref index);
else if (token == TokenType.CURLY_CLOSE)
{
NextToken(json, ref index);
return table;
}
else
{
// name
string name = ParseString(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != TokenType.COLON)
{
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
static JsonArray ParseArray(string json, ref int index, ref bool success)
{
JsonArray array = new JsonArray();
// [
NextToken(json, ref index);
bool done = false;
while (!done)
{
TokenType token = LookAhead(json, index);
if (token == TokenType.NONE)
{
success = false;
return null;
}
else if (token == TokenType.COMMA)
NextToken(json, ref index);
else if (token == TokenType.SQUARED_CLOSE)
{
NextToken(json, ref index);
break;
}
else
{
object value = ParseValue(json, ref index, ref success);
if (!success)
return null;
array.Add(value);
}
}
return array;
}
static object ParseValue(string json, ref int index, ref bool success)
{
switch (LookAhead(json, index))
{
case TokenType.STRING:
return ParseString(json, ref index, ref success);
case TokenType.NUMBER:
return ParseNumber(json, ref index, ref success);
case TokenType.CURLY_OPEN:
return ParseObject(json, ref index, ref success);
case TokenType.SQUARED_OPEN:
return ParseArray(json, ref index, ref success);
case TokenType.TRUE:
NextToken(json, ref index);
return true;
case TokenType.FALSE:
NextToken(json, ref index);
return false;
case TokenType.NULL:
NextToken(json, ref index);
return null;
case TokenType.NONE:
break;
}
success = false;
return null;
}
static string ParseString(string json, ref int index, ref bool success)
{
if (_parseStringBuilder == null)
_parseStringBuilder = new StringBuilder(BUILDER_INIT);
_parseStringBuilder.Length = 0;
EatWhitespace(json, ref index);
// "
char c = json[index++];
bool complete = false;
while (!complete)
{
if (index == json.Length)
break;
c = json[index++];
if (c == '"')
{
complete = true;
break;
}
else if (c == '\\')
{
if (index == json.Length)
break;
c = json[index++];
if (c == '"')
_parseStringBuilder.Append('"');
else if (c == '\\')
_parseStringBuilder.Append('\\');
else if (c == '/')
_parseStringBuilder.Append('/');
else if (c == 'b')
_parseStringBuilder.Append('\b');
else if (c == 'f')
_parseStringBuilder.Append('\f');
else if (c == 'n')
_parseStringBuilder.Append('\n');
else if (c == 'r')
_parseStringBuilder.Append('\r');
else if (c == 't')
_parseStringBuilder.Append('\t');
else if (c == 'u')
{
int remainingLength = json.Length - index;
if (remainingLength >= 4)
{
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(json.Substring(index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
return "";
// convert the integer codepoint to a unicode char and add to string
if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate
{
index += 4; // skip 4 chars
remainingLength = json.Length - index;
if (remainingLength >= 6)
{
uint lowCodePoint;
if (json.Substring(index, 2) == "\\u" && UInt32.TryParse(json.Substring(index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))
{
if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate
{
_parseStringBuilder.Append((char)codePoint);
_parseStringBuilder.Append((char)lowCodePoint);
index += 6; // skip 6 chars
continue;
}
}
}
success = false; // invalid surrogate pair
return "";
}
_parseStringBuilder.Append(ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
}
else
break;
}
}
else
_parseStringBuilder.Append(c);
}
if (!complete)
{
success = false;
return null;
}
return _parseStringBuilder.ToString();
}
private static string ConvertFromUtf32(int utf32)
{
// http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm
if (utf32 < 0 || utf32 > 0x10FFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
if (0xD800 <= utf32 && utf32 <= 0xDFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
if (utf32 < 0x10000)
return new string((char)utf32, 1);
utf32 -= 0x10000;
return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });
}
static object ParseNumber(string json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
object returnNumber;
string str = json.Substring(index, charLength);
if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
{
double number;
success = double.TryParse(json.Substring(index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
returnNumber = number;
}
else if (str.IndexOf("-", StringComparison.OrdinalIgnoreCase) == -1)
{
ulong number;
success = ulong.TryParse(json.Substring(index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
returnNumber = number;
}
else
{
long number;
success = long.TryParse(json.Substring(index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
returnNumber = number;
}
index = lastIndex + 1;
return returnNumber;
}
static int GetLastIndexOfNumber(string json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++)
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break;
return lastIndex - 1;
}
static void EatWhitespace(string json, ref int index)
{
for (; index < json.Length; index++)
if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break;
}
static TokenType LookAhead(string json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
static TokenType NextToken(string json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length)
return TokenType.NONE;
char c = json[index];
index++;
switch (c)
{
case '{':
return TokenType.CURLY_OPEN;
case '}':
return TokenType.CURLY_CLOSE;
case '[':
return TokenType.SQUARED_OPEN;
case ']':
return TokenType.SQUARED_CLOSE;
case ',':
return TokenType.COMMA;
case '"':
return TokenType.STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TokenType.NUMBER;
case ':':
return TokenType.COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5)
{
if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
{
index += 5;
return TokenType.FALSE;
}
}
// true
if (remainingLength >= 4)
{
if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
{
index += 4;
return TokenType.TRUE;
}
}
// null
if (remainingLength >= 4)
{
if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
{
index += 4;
return TokenType.NULL;
}
}
return TokenType.NONE;
}
static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder)
{
bool success = true;
string stringValue = value as string;
if (value == null)
builder.Append("null");
else if (stringValue != null)
success = SerializeString(stringValue, builder);
else
{
IDictionary<string, object> dict = value as IDictionary<string, object>;
Type type = value.GetType();
Type[] genArgs = ReflectionUtils.GetGenericTypeArguments(type);
var isStringKeyDictionary = type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>) && genArgs[0] == typeof(string);
if (isStringKeyDictionary)
{
var strDictValue = value as IDictionary;
success = SerializeObject(jsonSerializerStrategy, strDictValue.Keys, strDictValue.Values, builder);
}
else if (dict != null)
{
success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder);
}
else
{
IDictionary<string, string> stringDictionary = value as IDictionary<string, string>;
if (stringDictionary != null)
{
success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder);
}
else
{
IEnumerable enumerableValue = value as IEnumerable;
if (enumerableValue != null)
success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder);
else if (IsNumeric(value))
success = SerializeNumber(value, builder);
else if (value is bool)
builder.Append((bool)value ? "true" : "false");
else
{
object serializedObject;
success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject);
if (success)
SerializeValue(jsonSerializerStrategy, serializedObject, builder);
}
}
}
}
return success;
}
static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)
{
builder.Append("{");
IEnumerator ke = keys.GetEnumerator();
IEnumerator ve = values.GetEnumerator();
bool first = true;
while (ke.MoveNext() && ve.MoveNext())
{
object key = ke.Current;
object value = ve.Current;
if (!first)
builder.Append(",");
string stringKey = key as string;
if (stringKey != null)
SerializeString(stringKey, builder);
else
if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false;
builder.Append(":");
if (!SerializeValue(jsonSerializerStrategy, value, builder))
return false;
first = false;
}
builder.Append("}");
return true;
}
static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)
{
builder.Append("[");
bool first = true;
foreach (object value in anArray)
{
if (!first)
builder.Append(",");
if (!SerializeValue(jsonSerializerStrategy, value, builder))
return false;
first = false;
}
builder.Append("]");
return true;
}
static bool SerializeString(string aString, StringBuilder builder)
{
// Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged)
if (aString.IndexOfAny(EscapeCharacters) == -1)
{
builder.Append('"');
builder.Append(aString);
builder.Append('"');
return true;
}
builder.Append('"');
int safeCharacterCount = 0;
char[] charArray = aString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char c = charArray[i];
// Non ascii characters are fine, buffer them up and send them to the builder
// in larger chunks if possible. The escape table is a 1:1 translation table
// with \0 [default(char)] denoting a safe character.
if (c >= EscapeTable.Length || EscapeTable[c] == default(char))
{
safeCharacterCount++;
}
else
{
if (safeCharacterCount > 0)
{
builder.Append(charArray, i - safeCharacterCount, safeCharacterCount);
safeCharacterCount = 0;
}
builder.Append('\\');
builder.Append(EscapeTable[c]);
}
}
if (safeCharacterCount > 0)
{
builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount);
}
builder.Append('"');
return true;
}
static bool SerializeNumber(object number, StringBuilder builder)
{
if (number is decimal)
builder.Append(((decimal)number).ToString("R", CultureInfo.InvariantCulture));
else if (number is double)
builder.Append(((double)number).ToString("R", CultureInfo.InvariantCulture));
else if (number is float)
builder.Append(((float)number).ToString("R", CultureInfo.InvariantCulture));
else if (NumberTypes.IndexOf(number.GetType()) != -1)
builder.Append(number);
return true;
}
/// <summary>
/// Determines if a given object is numeric in any way
/// (can be integer, double, null, etc).
/// </summary>
static bool IsNumeric(object value)
{
if (value is sbyte) return true;
if (value is byte) return true;
if (value is short) return true;
if (value is ushort) return true;
if (value is int) return true;
if (value is uint) return true;
if (value is long) return true;
if (value is ulong) return true;
if (value is float) return true;
if (value is double) return true;
if (value is decimal) return true;
return false;
}
private static IJsonSerializerStrategy _currentJsonSerializerStrategy;
public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
{
get
{
return _currentJsonSerializerStrategy ??
(_currentJsonSerializerStrategy =
#if SIMPLE_JSON_DATACONTRACT
DataContractJsonSerializerStrategy
#else
PocoJsonSerializerStrategy
#endif
);
}
set
{
_currentJsonSerializerStrategy = value;
}
}
private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy;
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy
{
get
{
return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());
}
}
#if SIMPLE_JSON_DATACONTRACT
private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy;
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy
{
get
{
return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());
}
}
#endif
}
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
interface IJsonSerializerStrategy
{
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
bool TrySerializeNonPrimitiveObject(object input, out object output);
object DeserializeObject(object value, Type type);
}
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
class PocoJsonSerializerStrategy : IJsonSerializerStrategy
{
internal IDictionary<Type, ReflectionUtils.ConstructorDelegate> ConstructorCache;
internal IDictionary<Type, IDictionary<MemberInfo, ReflectionUtils.GetDelegate>> GetCache;
internal IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache;
internal static readonly Type[] EmptyTypes = new Type[0];
internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) };
private static readonly string[] Iso8601Format = new string[]
{
@"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
@"yyyy-MM-dd\THH:mm:ss\Z",
@"yyyy-MM-dd\THH:mm:ssK"
};
public PocoJsonSerializerStrategy()
{
ConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);
GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<MemberInfo, ReflectionUtils.GetDelegate>>(GetterValueFactory);
SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
}
protected virtual string MapClrMemberNameToJsonFieldName(MemberInfo memberInfo)
{
// TODO: Optimize and/or cache
foreach (JsonProperty eachAttr in memberInfo.GetCustomAttributes(typeof(JsonProperty), true))
if (!string.IsNullOrEmpty(eachAttr.PropertyName))
return eachAttr.PropertyName;
return memberInfo.Name;
}
protected virtual void MapClrMemberNameToJsonFieldName(MemberInfo memberInfo, out string jsonName, out JsonProperty jsonProp)
{
jsonName = memberInfo.Name;
jsonProp = null;
// TODO: Optimize and/or cache
foreach (JsonProperty eachAttr in memberInfo.GetCustomAttributes(typeof(JsonProperty), true))
{
jsonProp = eachAttr;
if (!string.IsNullOrEmpty(eachAttr.PropertyName))
jsonName = eachAttr.PropertyName;
}
}
internal virtual ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key)
{
return ReflectionUtils.GetContructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes);
}
internal virtual IDictionary<MemberInfo, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
{
IDictionary<MemberInfo, ReflectionUtils.GetDelegate> result = new Dictionary<MemberInfo, ReflectionUtils.GetDelegate>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanRead)
{
MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);
if (getMethod.IsStatic || !getMethod.IsPublic)
continue;
result[propertyInfo] = ReflectionUtils.GetGetMethod(propertyInfo);
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (fieldInfo.IsStatic || !fieldInfo.IsPublic)
continue;
result[fieldInfo] = ReflectionUtils.GetGetMethod(fieldInfo);
}
return result;
}
internal virtual IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
{
IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanWrite)
{
MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);
if (setMethod.IsStatic || !setMethod.IsPublic)
continue;
result[MapClrMemberNameToJsonFieldName(propertyInfo)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (fieldInfo.IsInitOnly || fieldInfo.IsStatic || !fieldInfo.IsPublic)
continue;
result[MapClrMemberNameToJsonFieldName(fieldInfo)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));
}
return result;
}
public virtual bool TrySerializeNonPrimitiveObject(object input, out object output)
{
return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public virtual object DeserializeObject(object value, Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (value != null && type.IsInstanceOfType(value)) return value;
string str = value as string;
if (type == typeof(Guid) && string.IsNullOrEmpty(str))
return default(Guid);
if (value == null)
return null;
object obj = null;
if (str != null)
{
if (str.Length != 0) // We know it can't be null now.
{
if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))
return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset)))
return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))
return new Guid(str);
if (type == typeof(Uri))
{
bool isValid = Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute);
Uri result;
if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result))
return result;
return null;
}
if (type == typeof(string))
return str;
return Convert.ChangeType(str, type, CultureInfo.InvariantCulture);
}
else
{
if (type == typeof(Guid))
obj = default(Guid);
else if (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
obj = null;
else
obj = str;
}
// Empty string case
if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
return str;
}
else if (value is bool)
return value;
bool valueIsLong = value is long;
bool valueIsUlong = value is ulong;
bool valueIsDouble = value is double;
Type nullableType = Nullable.GetUnderlyingType(type);
if (nullableType != null && PlayFabSimpleJson.NumberTypes.IndexOf(nullableType) != -1)
type = nullableType; // Just use the regular type for the conversion
bool isNumberType = PlayFabSimpleJson.NumberTypes.IndexOf(type) != -1;
bool isEnumType = type.GetTypeInfo().IsEnum;
if ((valueIsLong && type == typeof(long)) || (valueIsUlong && type == typeof(ulong)) || (valueIsDouble && type == typeof(double)))
return value;
if ((valueIsLong || valueIsUlong || valueIsDouble) && isEnumType)
return Enum.ToObject(type, Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture));
if ((valueIsLong || valueIsUlong || valueIsDouble) && isNumberType)
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
IDictionary<string, object> objects = value as IDictionary<string, object>;
if (objects != null)
{
IDictionary<string, object> jsonObject = objects;
if (ReflectionUtils.IsTypeDictionary(type))
{
// if dictionary then
Type[] types = ReflectionUtils.GetGenericTypeArguments(type);
Type keyType = types[0];
Type valueType = types[1];
Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
IDictionary dict = (IDictionary)ConstructorCache[genericType]();
foreach (KeyValuePair<string, object> kvp in jsonObject)
dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType));
obj = dict;
}
else
{
if (type == typeof(object))
obj = value;
else
{
obj = ConstructorCache[type]();
foreach (KeyValuePair<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> setter in SetCache[type])
{
object jsonValue;
if (jsonObject.TryGetValue(setter.Key, out jsonValue))
{
jsonValue = DeserializeObject(jsonValue, setter.Value.Key);
setter.Value.Value(obj, jsonValue);
}
}
}
}
}
else
{
IList<object> valueAsList = value as IList<object>;
if (valueAsList != null)
{
IList<object> jsonObject = valueAsList;
IList list = null;
if (type.IsArray)
{
list = (IList)ConstructorCache[type](jsonObject.Count);
int i = 0;
foreach (object o in jsonObject)
list[i++] = DeserializeObject(o, type.GetElementType());
}
else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type) || type == typeof(object))
{
Type innerType = ReflectionUtils.GetGenericListElementType(type);
ReflectionUtils.ConstructorDelegate ctrDelegate = null;
if (type != typeof(object))
ctrDelegate = ConstructorCache[type];
if (ctrDelegate == null)
ctrDelegate = ConstructorCache[typeof(List<>).MakeGenericType(innerType)];
list = (IList)ctrDelegate();
foreach (object o in jsonObject)
list.Add(DeserializeObject(o, innerType));
}
obj = list;
}
return obj;
}
if (ReflectionUtils.IsNullableType(type))
return ReflectionUtils.ToNullableType(obj, type);
return obj;
}
protected virtual object SerializeEnum(Enum p)
{
return Convert.ToDouble(p, CultureInfo.InvariantCulture);
}
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
protected virtual bool TrySerializeKnownTypes(object input, out object output)
{
bool returnValue = true;
if (input is DateTime)
output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
else if (input is DateTimeOffset)
output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
else if (input is Guid)
output = ((Guid)input).ToString("D");
else if (input is Uri)
output = input.ToString();
else
{
Enum inputEnum = input as Enum;
if (inputEnum != null)
output = SerializeEnum(inputEnum);
else
{
returnValue = false;
output = null;
}
}
return returnValue;
}
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
protected virtual bool TrySerializeUnknownTypes(object input, out object output)
{
if (input == null) throw new ArgumentNullException("input");
output = null;
Type type = input.GetType();
if (type.FullName == null)
return false;
IDictionary<string, object> obj = new JsonObject();
IDictionary<MemberInfo, ReflectionUtils.GetDelegate> getters = GetCache[type];
foreach (KeyValuePair<MemberInfo, ReflectionUtils.GetDelegate> getter in getters)
{
if (getter.Value == null)
continue;
string jsonKey;
JsonProperty jsonProp;
MapClrMemberNameToJsonFieldName(getter.Key, out jsonKey, out jsonProp);
if (obj.ContainsKey(jsonKey))
throw new Exception("The given key is defined multiple times in the same type: " + input.GetType().Name + "." + jsonKey);
object value = getter.Value(input);
if (jsonProp == null || jsonProp.NullValueHandling == NullValueHandling.Include || value != null)
obj.Add(jsonKey, value);
}
output = obj;
return true;
}
}
#if SIMPLE_JSON_DATACONTRACT
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy
{
public DataContractJsonSerializerStrategy()
{
GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);
SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
}
internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
{
bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
if (!hasDataContract)
return base.GetterValueFactory(type);
string jsonKey;
IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanRead)
{
MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);
if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo);
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo);
}
return result;
}
internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
{
bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
if (!hasDataContract)
return base.SetterValueFactory(type);
string jsonKey;
IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanWrite)
{
MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);
if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));
}
// todo implement sorting for DATACONTRACT.
return result;
}
private static bool CanAdd(MemberInfo info, out string jsonKey)
{
jsonKey = null;
if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)
return false;
DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));
if (dataMemberAttribute == null)
return false;
jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;
return true;
}
}
#endif
// This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules
// that might be in place in the target project.
[GeneratedCode("reflection-utils", "1.0.0")]
#if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC
public
#else
internal
#endif
class ReflectionUtils
{
private static readonly object[] EmptyObjects = new object[0];
public delegate object GetDelegate(object source);
public delegate void SetDelegate(object source, object value);
public delegate object ConstructorDelegate(params object[] args);
public delegate TValue ThreadSafeDictionaryValueFactory<TKey, TValue>(TKey key);
[ThreadStatic]
private static object[] _1ObjArray;
#if SIMPLE_JSON_TYPEINFO
public static TypeInfo GetTypeInfo(Type type)
{
return type.GetTypeInfo();
}
#else
public static Type GetTypeInfo(Type type)
{
return type;
}
#endif
public static Attribute GetAttribute(MemberInfo info, Type type)
{
#if SIMPLE_JSON_TYPEINFO
if (info == null || type == null || !info.IsDefined(type))
return null;
return info.GetCustomAttribute(type);
#else
if (info == null || type == null || !Attribute.IsDefined(info, type))
return null;
return Attribute.GetCustomAttribute(info, type);
#endif
}
public static Type GetGenericListElementType(Type type)
{
if (type == typeof(object))
return type;
IEnumerable<Type> interfaces;
#if SIMPLE_JSON_TYPEINFO
interfaces = type.GetTypeInfo().ImplementedInterfaces;
#else
interfaces = type.GetInterfaces();
#endif
foreach (Type implementedInterface in interfaces)
{
if (IsTypeGeneric(implementedInterface) &&
implementedInterface.GetGenericTypeDefinition() == typeof(IList<>))
{
return GetGenericTypeArguments(implementedInterface)[0];
}
}
return GetGenericTypeArguments(type)[0];
}
public static Attribute GetAttribute(Type objectType, Type attributeType)
{
#if SIMPLE_JSON_TYPEINFO
if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))
return null;
return objectType.GetTypeInfo().GetCustomAttribute(attributeType);
#else
if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))
return null;
return Attribute.GetCustomAttribute(objectType, attributeType);
#endif
}
public static Type[] GetGenericTypeArguments(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetTypeInfo().GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static bool IsTypeGeneric(Type type)
{
return GetTypeInfo(type).IsGenericType;
}
public static bool IsTypeGenericeCollectionInterface(Type type)
{
if (!IsTypeGeneric(type))
return false;
Type genericDefinition = type.GetGenericTypeDefinition();
return (genericDefinition == typeof(IList<>)
|| genericDefinition == typeof(ICollection<>)
|| genericDefinition == typeof(IEnumerable<>)
#if SIMPLE_JSON_READONLY_COLLECTIONS
|| genericDefinition == typeof(IReadOnlyCollection<>)
|| genericDefinition == typeof(IReadOnlyList<>)
#endif
);
}
public static bool IsAssignableFrom(Type type1, Type type2)
{
return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2));
}
public static bool IsTypeDictionary(Type type)
{
#if SIMPLE_JSON_TYPEINFO
if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
return true;
#else
if (typeof(System.Collections.IDictionary).IsAssignableFrom(type))
return true;
#endif
if (!GetTypeInfo(type).IsGenericType)
return false;
Type genericDefinition = type.GetGenericTypeDefinition();
return genericDefinition == typeof(IDictionary<,>) || genericDefinition == typeof(Dictionary<,>);
}
public static bool IsNullableType(Type type)
{
return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static object ToNullableType(object obj, Type nullableType)
{
return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);
}
public static bool IsValueType(Type type)
{
return GetTypeInfo(type).IsValueType;
}
public static IEnumerable<ConstructorInfo> GetConstructors(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetTypeInfo().DeclaredConstructors;
#else
return type.GetConstructors();
#endif
}
public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType)
{
IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type);
int i;
bool matches;
foreach (ConstructorInfo constructorInfo in constructorInfos)
{
ParameterInfo[] parameters = constructorInfo.GetParameters();
if (argsType.Length != parameters.Length)
continue;
i = 0;
matches = true;
foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters())
{
if (parameterInfo.ParameterType != argsType[i])
{
matches = false;
break;
}
}
if (matches)
return constructorInfo;
}
return null;
}
public static IEnumerable<PropertyInfo> GetProperties(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetRuntimeProperties();
#else
return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
#endif
}
public static IEnumerable<FieldInfo> GetFields(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetRuntimeFields();
#else
return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
#endif
}
public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_TYPEINFO
return propertyInfo.GetMethod;
#else
return propertyInfo.GetGetMethod(true);
#endif
}
public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_TYPEINFO
return propertyInfo.SetMethod;
#else
return propertyInfo.GetSetMethod(true);
#endif
}
public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo)
{
return GetConstructorByReflection(constructorInfo);
}
public static ConstructorDelegate GetContructor(Type type, params Type[] argsType)
{
return GetConstructorByReflection(type, argsType);
}
public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo)
{
return delegate (object[] args)
{
var x = constructorInfo;
return x.Invoke(args);
};
}
public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType)
{
ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);
return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo);
}
public static GetDelegate GetGetMethod(PropertyInfo propertyInfo)
{
return GetGetMethodByReflection(propertyInfo);
}
public static GetDelegate GetGetMethod(FieldInfo fieldInfo)
{
return GetGetMethodByReflection(fieldInfo);
}
public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo)
{
MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo);
return delegate (object source) { return methodInfo.Invoke(source, EmptyObjects); };
}
public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo)
{
return delegate (object source) { return fieldInfo.GetValue(source); };
}
public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)
{
return GetSetMethodByReflection(propertyInfo);
}
public static SetDelegate GetSetMethod(FieldInfo fieldInfo)
{
return GetSetMethodByReflection(fieldInfo);
}
public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo)
{
MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo);
return delegate (object source, object value)
{
if (_1ObjArray == null)
_1ObjArray = new object[1];
_1ObjArray[0] = value;
methodInfo.Invoke(source, _1ObjArray);
};
}
public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo)
{
return delegate (object source, object value) { fieldInfo.SetValue(source, value); };
}
public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly object _lock = new object();
private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory;
private Dictionary<TKey, TValue> _dictionary;
public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory)
{
_valueFactory = valueFactory;
}
private TValue Get(TKey key)
{
if (_dictionary == null)
return AddValue(key);
TValue value;
if (!_dictionary.TryGetValue(key, out value))
return AddValue(key);
return value;
}
private TValue AddValue(TKey key)
{
TValue value = _valueFactory(key);
lock (_lock)
{
if (_dictionary == null)
{
_dictionary = new Dictionary<TKey, TValue>();
_dictionary[key] = value;
}
else
{
TValue val;
if (_dictionary.TryGetValue(key, out val))
return val;
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(_dictionary);
dict[key] = value;
_dictionary = dict;
}
}
return value;
}
public void Add(TKey key, TValue value)
{
throw new NotImplementedException();
}
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get { return _dictionary.Keys; }
}
public bool Remove(TKey key)
{
throw new NotImplementedException();
}
public bool TryGetValue(TKey key, out TValue value)
{
value = this[key];
return true;
}
public ICollection<TValue> Values
{
get { return _dictionary.Values; }
}
public TValue this[TKey key]
{
get { return Get(key); }
set { throw new NotImplementedException(); }
}
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { return _dictionary.Count; }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _dictionary.GetEnumerator();
}
}
}
}
// ReSharper restore LoopCanBeConvertedToQuery
// ReSharper restore RedundantExplicitArrayCreation
// ReSharper restore SuggestUseVarKeywordEvident
|
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using SR = System.ServiceModel.SR;
sealed class TransactionChannelFactory<TChannel> : LayeredChannelFactory<TChannel>, ITransactionChannelManager
{
TransactionFlowOption flowIssuedTokens;
SecurityStandardsManager standardsManager;
Dictionary<DirectionalAction, TransactionFlowOption> dictionary;
TransactionProtocol transactionProtocol;
bool allowWildcardAction;
public TransactionChannelFactory(
TransactionProtocol transactionProtocol,
BindingContext context,
Dictionary<DirectionalAction, TransactionFlowOption> dictionary,
bool allowWildcardAction)
: base(context.Binding, context.BuildInnerChannelFactory<TChannel>())
{
this.dictionary = dictionary;
this.TransactionProtocol = transactionProtocol;
this.allowWildcardAction = allowWildcardAction;
this.standardsManager = SecurityStandardsHelper.CreateStandardsManager(this.TransactionProtocol);
}
public TransactionProtocol TransactionProtocol
{
get
{
return this.transactionProtocol;
}
set
{
if (!TransactionProtocol.IsDefined(value))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.GetString(SR.SFxBadTransactionProtocols)));
this.transactionProtocol = value;
}
}
public TransactionFlowOption FlowIssuedTokens
{
get { return this.flowIssuedTokens; }
set { this.flowIssuedTokens = value; }
}
public SecurityStandardsManager StandardsManager
{
get { return this.standardsManager; }
set
{
this.standardsManager = (value != null ? value : SecurityStandardsHelper.CreateStandardsManager(this.transactionProtocol));
}
}
public IDictionary<DirectionalAction, TransactionFlowOption> Dictionary
{
get { return this.dictionary; }
}
public TransactionFlowOption GetTransaction(MessageDirection direction, string action)
{
TransactionFlowOption txOption;
if (!dictionary.TryGetValue(new DirectionalAction(direction, action), out txOption))
{
//Fixinng this for clients that opted in for lesser validation before flowing out a transaction
if (this.allowWildcardAction && dictionary.TryGetValue(new DirectionalAction(direction, MessageHeaders.WildcardAction), out txOption))
{
return txOption;
}
else
return TransactionFlowOption.NotAllowed;
}
else
return txOption;
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
TChannel innerChannel = ((IChannelFactory<TChannel>)InnerChannelFactory).CreateChannel(remoteAddress, via);
return CreateTransactionChannel(innerChannel);
}
TChannel CreateTransactionChannel(TChannel innerChannel)
{
if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
return (TChannel)(object)new TransactionDuplexSessionChannel(this, (IDuplexSessionChannel)(object)innerChannel);
}
else if (typeof(TChannel) == typeof(IRequestSessionChannel))
{
return (TChannel)(object)new TransactionRequestSessionChannel(this, (IRequestSessionChannel)(object)innerChannel);
}
else if (typeof(TChannel) == typeof(IOutputSessionChannel))
{
return (TChannel)(object)new TransactionOutputSessionChannel(this, (IOutputSessionChannel)(object)innerChannel);
}
else if (typeof(TChannel) == typeof(IOutputChannel))
{
return (TChannel)(object)new TransactionOutputChannel(this, (IOutputChannel)(object)innerChannel);
}
else if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new TransactionRequestChannel(this, (IRequestChannel)(object)innerChannel);
}
else if (typeof(TChannel) == typeof(IDuplexChannel))
{
return (TChannel)(object)new TransactionDuplexChannel(this, (IDuplexChannel)(object)innerChannel);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateChannelTypeNotSupportedException(typeof(TChannel)));
}
}
//===========================================================
// Transaction Output Channel classes
//===========================================================
sealed class TransactionOutputChannel : TransactionOutputChannelGeneric<IOutputChannel>
{
public TransactionOutputChannel(ChannelManagerBase channelManager, IOutputChannel innerChannel)
: base(channelManager, innerChannel)
{
}
}
sealed class TransactionRequestChannel : TransactionRequestChannelGeneric<IRequestChannel>
{
public TransactionRequestChannel(ChannelManagerBase channelManager, IRequestChannel innerChannel)
: base(channelManager, innerChannel)
{
}
}
sealed class TransactionDuplexChannel : TransactionOutputDuplexChannelGeneric<IDuplexChannel>
{
public TransactionDuplexChannel(ChannelManagerBase channelManager, IDuplexChannel innerChannel)
: base(channelManager, innerChannel)
{
}
}
sealed class TransactionOutputSessionChannel : TransactionOutputChannelGeneric<IOutputSessionChannel>, IOutputSessionChannel
{
public TransactionOutputSessionChannel(ChannelManagerBase channelManager, IOutputSessionChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public IOutputSession Session { get { return InnerChannel.Session; } }
}
sealed class TransactionRequestSessionChannel : TransactionRequestChannelGeneric<IRequestSessionChannel>, IRequestSessionChannel
{
public TransactionRequestSessionChannel(ChannelManagerBase channelManager, IRequestSessionChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public IOutputSession Session { get { return InnerChannel.Session; } }
}
sealed class TransactionDuplexSessionChannel : TransactionOutputDuplexChannelGeneric<IDuplexSessionChannel>, IDuplexSessionChannel
{
public TransactionDuplexSessionChannel(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public IDuplexSession Session { get { return InnerChannel.Session; } }
}
}
static class SecurityStandardsHelper
{
static SecurityStandardsManager SecurityStandardsManager2007 =
CreateStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12);
static SecurityStandardsManager CreateStandardsManager(MessageSecurityVersion securityVersion)
{
return new SecurityStandardsManager(
securityVersion,
new WSSecurityTokenSerializer(securityVersion.SecurityVersion, securityVersion.TrustVersion, securityVersion.SecureConversationVersion, false, null, null, null));
}
public static SecurityStandardsManager CreateStandardsManager(TransactionProtocol transactionProtocol)
{
if (transactionProtocol == TransactionProtocol.WSAtomicTransactionOctober2004 ||
transactionProtocol == TransactionProtocol.OleTransactions)
{
return SecurityStandardsManager.DefaultInstance;
}
else
{
return SecurityStandardsHelper.SecurityStandardsManager2007;
}
}
}
//==============================================================
// Transaction channel base generic classes
//==============================================================
class TransactionOutputChannelGeneric<TChannel> : TransactionChannel<TChannel>, IOutputChannel
where TChannel : class, IOutputChannel
{
public TransactionOutputChannelGeneric(ChannelManagerBase channelManager, TChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public EndpointAddress RemoteAddress
{
get
{
return InnerChannel.RemoteAddress;
}
}
public Uri Via
{
get
{
return InnerChannel.Via;
}
}
public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
{
return this.BeginSend(message, this.DefaultSendTimeout, callback, state);
}
public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback asyncCallback, object state)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
WriteTransactionDataToMessage(message, MessageDirection.Input);
return InnerChannel.BeginSend(message, timeoutHelper.RemainingTime(), asyncCallback, state);
}
public void EndSend(IAsyncResult result)
{
InnerChannel.EndSend(result);
}
public void Send(Message message)
{
this.Send(message, this.DefaultSendTimeout);
}
public void Send(Message message, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
WriteTransactionDataToMessage(message, MessageDirection.Input);
InnerChannel.Send(message, timeoutHelper.RemainingTime());
}
}
class TransactionRequestChannelGeneric<TChannel> : TransactionChannel<TChannel>, IRequestChannel
where TChannel : class, IRequestChannel
{
public TransactionRequestChannelGeneric(ChannelManagerBase channelManager, TChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public EndpointAddress RemoteAddress
{
get
{
return InnerChannel.RemoteAddress;
}
}
public Uri Via
{
get
{
return InnerChannel.Via;
}
}
public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state)
{
return this.BeginRequest(message, this.DefaultSendTimeout, callback, state);
}
public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback asyncCallback, object state)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
WriteTransactionDataToMessage(message, MessageDirection.Input);
return InnerChannel.BeginRequest(message, timeoutHelper.RemainingTime(), asyncCallback, state);
}
public Message EndRequest(IAsyncResult result)
{
Message reply = InnerChannel.EndRequest(result);
if (reply != null)
this.ReadIssuedTokens(reply, MessageDirection.Output);
return reply;
}
public Message Request(Message message)
{
return this.Request(message, this.DefaultSendTimeout);
}
public Message Request(Message message, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
WriteTransactionDataToMessage(message, MessageDirection.Input);
Message reply = InnerChannel.Request(message, timeoutHelper.RemainingTime());
if (reply != null)
this.ReadIssuedTokens(reply, MessageDirection.Output);
return reply;
}
}
class TransactionOutputDuplexChannelGeneric<TChannel> : TransactionDuplexChannelGeneric<TChannel>
where TChannel : class, IDuplexChannel
{
public TransactionOutputDuplexChannelGeneric(ChannelManagerBase channelManager, TChannel innerChannel)
: base(channelManager, innerChannel, MessageDirection.Output)
{
}
}
}
|
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal class SpacingFormattingRule : BaseFormattingRule
{
public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation<AdjustSpacesOperation> nextOperation)
{
if (optionSet == null)
{
return nextOperation.Invoke();
}
System.Diagnostics.Debug.Assert(previousToken.Parent != null && currentToken.Parent != null);
var previousKind = previousToken.Kind();
var currentKind = currentToken.Kind();
var previousParentKind = previousToken.Parent.Kind();
var currentParentKind = currentToken.Parent.Kind();
// For Method Declaration
if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.IdentifierToken)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
// For Generic Method Declaration
if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.GreaterThanToken && previousParentKind == SyntaxKind.TypeParameterList)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
// Case: public static implicit operator string(Program p) { return null; }
if (previousToken.IsKeyword() && currentToken.IsOpenParenInParameterListOfAConversionOperatorDeclaration())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
// Case: public static Program operator !(Program p) { return null; }
if (previousToken.Parent.IsKind(SyntaxKind.OperatorDeclaration) && currentToken.IsOpenParenInParameterListOfAOperationDeclaration())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
if (previousToken.IsOpenParenInParameterList() && currentToken.IsCloseParenInParameterList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses);
}
if (previousToken.IsOpenParenInParameterList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis);
}
if (currentToken.IsCloseParenInParameterList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis);
}
// For Method Call
if (currentToken.IsOpenParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterMethodCallName);
}
if (previousToken.IsOpenParenInArgumentList() && currentToken.IsCloseParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses);
}
if (previousToken.IsOpenParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
if (currentToken.IsCloseParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
// For spacing around: typeof, default, and sizeof; treat like a Method Call
if (currentKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterMethodCallName);
}
if (previousKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(previousParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
if (currentKind == SyntaxKind.CloseParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
// For Spacing b/n control flow keyword and paren. Parent check not needed.
if (currentKind == SyntaxKind.OpenParenToken &&
(previousKind == SyntaxKind.IfKeyword || previousKind == SyntaxKind.WhileKeyword || previousKind == SyntaxKind.SwitchKeyword ||
previousKind == SyntaxKind.ForKeyword || previousKind == SyntaxKind.ForEachKeyword || previousKind == SyntaxKind.CatchKeyword ||
previousKind == SyntaxKind.UsingKeyword))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword);
}
// For spacing between parenthesis and expression
if ((previousParentKind == SyntaxKind.ParenthesizedExpression && previousKind == SyntaxKind.OpenParenToken) ||
(currentParentKind == SyntaxKind.ParenthesizedExpression && currentKind == SyntaxKind.CloseParenToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinExpressionParentheses);
}
// For spacing between the parenthesis and the cast expression
if ((previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.OpenParenToken) ||
(currentParentKind == SyntaxKind.CastExpression && currentKind == SyntaxKind.CloseParenToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinCastParentheses);
}
// For spacing between the parenthesis and the expression inside the control flow expression
if (previousKind == SyntaxKind.OpenParenToken && IsControlFlowLikeKeywordStatementKind(previousParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinOtherParentheses);
}
// Semicolons in an empty for statement. i.e. for(;;)
if (previousKind == SyntaxKind.OpenParenToken || previousKind == SyntaxKind.SemicolonToken)
{
if (previousToken.Parent.Kind() == SyntaxKind.ForStatement)
{
var forStatement = (ForStatementSyntax)previousToken.Parent;
if (forStatement.Initializers.Count == 0 &&
forStatement.Declaration == null &&
forStatement.Condition == null &&
forStatement.Incrementors.Count == 0)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
}
}
if (currentKind == SyntaxKind.CloseParenToken && IsControlFlowLikeKeywordStatementKind(currentParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinOtherParentheses);
}
// For spacing after the cast
if (previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.CloseParenToken)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterCast);
}
// For spacing Before Square Braces
if (currentKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(currentToken) && !previousToken.IsOpenBraceOrCommaOfObjectInitializer())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeOpenSquareBracket);
}
// For spacing empty square braces
if (previousKind == SyntaxKind.OpenBracketToken && (currentKind == SyntaxKind.CloseBracketToken || currentKind == SyntaxKind.OmittedArraySizeExpressionToken) && HasFormattableBracketParent(previousToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets);
}
// For spacing square brackets within
if (previousKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(previousToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets);
}
else if (currentKind == SyntaxKind.CloseBracketToken && HasFormattableBracketParent(currentToken))
{
if (currentToken.Parent is ArrayRankSpecifierSyntax)
{
var parent = currentToken.Parent as ArrayRankSpecifierSyntax;
if ((parent.Sizes.Any() && parent.Sizes.First().Kind() != SyntaxKind.OmittedArraySizeExpression) || parent.Sizes.SeparatorCount > 0)
{
// int []: added spacing operation on open [
// int[1], int[,]: need spacing operation
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets);
}
}
else
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets);
}
}
// For spacing delimiters - after colon
if (previousToken.IsColonInTypeBaseList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration);
}
// For spacing delimiters - before colon
if (currentToken.IsColonInTypeBaseList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration);
}
// For spacing delimiters - after comma
if ((previousToken.IsCommaInArgumentOrParameterList() && currentKind != SyntaxKind.OmittedTypeArgumentToken) ||
previousToken.IsCommaInInitializerExpression())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterComma);
}
// For spacing delimiters - before comma
if ((currentToken.IsCommaInArgumentOrParameterList() && previousKind != SyntaxKind.OmittedTypeArgumentToken) ||
currentToken.IsCommaInInitializerExpression())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeComma);
}
// For Spacing delimiters - after Dot
if (previousToken.IsDotInMemberAccessOrQualifiedName())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterDot);
}
// For spacing delimiters - before Dot
if (currentToken.IsDotInMemberAccessOrQualifiedName())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeDot);
}
// For spacing delimiters - after semicolon
if (previousToken.IsSemicolonInForStatement() && currentKind != SyntaxKind.CloseParenToken)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement);
}
// For spacing delimiters - before semicolon
if (currentToken.IsSemicolonInForStatement())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement);
}
// For spacing around the binary operators
if (currentToken.Parent is BinaryExpressionSyntax ||
previousToken.Parent is BinaryExpressionSyntax ||
currentToken.Parent is AssignmentExpressionSyntax ||
previousToken.Parent is AssignmentExpressionSyntax)
{
switch (optionSet.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator))
{
case BinaryOperatorSpacingOptions.Single:
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
case BinaryOperatorSpacingOptions.Remove:
if (currentKind == SyntaxKind.IsKeyword ||
currentKind == SyntaxKind.AsKeyword ||
previousKind == SyntaxKind.IsKeyword ||
previousKind == SyntaxKind.AsKeyword)
{
// User want spaces removed but at least one is required for the "as" & "is" keyword
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
else
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
case BinaryOperatorSpacingOptions.Ignore:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces);
default:
System.Diagnostics.Debug.Assert(false, "Invalid BinaryOperatorSpacingOptions");
break;
}
}
// No space after $" and $@" at the start of an interpolated string
if (previousKind == SyntaxKind.InterpolatedStringStartToken ||
previousKind == SyntaxKind.InterpolatedVerbatimStringStartToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// No space before " at the end of an interpolated string
if (currentKind == SyntaxKind.InterpolatedStringEndToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// No space before { or after } in interpolations
if ((currentKind == SyntaxKind.OpenBraceToken && currentToken.Parent is InterpolationSyntax) ||
(previousKind == SyntaxKind.CloseBraceToken && previousToken.Parent is InterpolationSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// Preserve space after { or before } in interpolations (i.e. between the braces and the expression)
if ((previousKind == SyntaxKind.OpenBraceToken && previousToken.Parent is InterpolationSyntax) ||
(currentKind == SyntaxKind.CloseBraceToken && currentToken.Parent is InterpolationSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces);
}
// No space before or after , in interpolation alignment clause
if ((previousKind == SyntaxKind.CommaToken && previousToken.Parent is InterpolationAlignmentClauseSyntax) ||
(currentKind == SyntaxKind.CommaToken && currentToken.Parent is InterpolationAlignmentClauseSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// No space before or after : in interpolation format clause
if ((previousKind == SyntaxKind.ColonToken && previousToken.Parent is InterpolationFormatClauseSyntax) ||
(currentKind == SyntaxKind.ColonToken && currentToken.Parent is InterpolationFormatClauseSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
return nextOperation.Invoke();
}
public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, SyntaxToken lastToken, OptionSet optionSet, NextAction<SuppressOperation> nextOperation)
{
nextOperation.Invoke(list);
SuppressVariableDeclaration(list, node, optionSet);
}
private void SuppressVariableDeclaration(List<SuppressOperation> list, SyntaxNode node, OptionSet optionSet)
{
if (node.IsKind(SyntaxKind.FieldDeclaration) || node.IsKind(SyntaxKind.EventDeclaration) ||
node.IsKind(SyntaxKind.EventFieldDeclaration) || node.IsKind(SyntaxKind.LocalDeclarationStatement))
{
if (optionSet.GetOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration))
{
var firstToken = node.GetFirstToken(includeZeroWidth: true);
var lastToken = node.GetLastToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateSuppressOperation(firstToken, lastToken, SuppressOption.NoSpacing));
}
}
}
private AdjustSpacesOperation AdjustSpacesOperationZeroOrOne(OptionSet optionSet, Option<bool> option, AdjustSpacesOption explicitOption = AdjustSpacesOption.ForceSpacesIfOnSingleLine)
{
if (optionSet.GetOption(option))
{
return CreateAdjustSpacesOperation(1, explicitOption);
}
else
{
return CreateAdjustSpacesOperation(0, explicitOption);
}
}
private bool HasFormattableBracketParent(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier, SyntaxKind.BracketedArgumentList, SyntaxKind.BracketedParameterList, SyntaxKind.ImplicitArrayCreationExpression);
}
private bool IsFunctionLikeKeywordExpressionKind(SyntaxKind syntaxKind)
{
return (syntaxKind == SyntaxKind.TypeOfExpression || syntaxKind == SyntaxKind.DefaultExpression || syntaxKind == SyntaxKind.SizeOfExpression);
}
private bool IsControlFlowLikeKeywordStatementKind(SyntaxKind syntaxKind)
{
return (syntaxKind == SyntaxKind.IfStatement || syntaxKind == SyntaxKind.WhileStatement || syntaxKind == SyntaxKind.SwitchStatement ||
syntaxKind == SyntaxKind.ForStatement || syntaxKind == SyntaxKind.ForEachStatement || syntaxKind == SyntaxKind.DoStatement ||
syntaxKind == SyntaxKind.CatchDeclaration || syntaxKind == SyntaxKind.UsingStatement || syntaxKind == SyntaxKind.LockStatement ||
syntaxKind == SyntaxKind.FixedStatement);
}
}
}
|
// 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 Xunit;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public class RefStructs : ParsingTests
{
public RefStructs(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
[Fact]
public void RefStructSimple()
{
var text = @"
class Program
{
ref struct S1{}
public ref struct S2{}
}
";
var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll);
comp.VerifyDiagnostics();
}
[Fact]
public void RefStructSimpleLangVer()
{
var text = @"
class Program
{
ref struct S1{}
public ref struct S2{}
}
";
var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7), options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (4,5): error CS8107: Feature 'ref structs' is not available in C# 7. Please use language version 7.2 or greater.
// ref struct S1{}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "ref").WithArguments("ref structs", "7.2").WithLocation(4, 5),
// (6,12): error CS8107: Feature 'ref structs' is not available in C# 7. Please use language version 7.2 or greater.
// public ref struct S2{}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "ref").WithArguments("ref structs", "7.2").WithLocation(6, 12)
);
}
[Fact]
public void RefStructErr()
{
var text = @"
class Program
{
ref class S1{}
public ref unsafe struct S2{}
ref interface I1{};
public ref delegate ref int D1();
}
";
var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (4,9): error CS1031: Type expected
// ref class S1{}
Diagnostic(ErrorCode.ERR_TypeExpected, "class"),
// (6,16): error CS1031: Type expected
// public ref unsafe struct S2{}
Diagnostic(ErrorCode.ERR_TypeExpected, "unsafe"),
// (8,9): error CS1031: Type expected
// ref interface I1{};
Diagnostic(ErrorCode.ERR_TypeExpected, "interface").WithLocation(8, 9),
// (10,16): error CS1031: Type expected
// public ref delegate ref int D1();
Diagnostic(ErrorCode.ERR_TypeExpected, "delegate").WithLocation(10, 16),
// (6,30): error CS0227: Unsafe code may only appear if compiling with /unsafe
// public ref unsafe struct S2{}
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S2")
);
}
[Fact]
public void PartialRefStruct()
{
var text = @"
class Program
{
partial ref struct S {}
partial ref struct S {}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (4,13): error CS1585: Member modifier 'ref' must precede the member type and name
// partial ref struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "ref").WithArguments("ref").WithLocation(4, 13),
// (5,13): error CS1585: Member modifier 'ref' must precede the member type and name
// partial ref struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "ref").WithArguments("ref").WithLocation(5, 13),
// (5,24): error CS0102: The type 'Program' already contains a definition for 'S'
// partial ref struct S {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("Program", "S").WithLocation(5, 24));
}
[Fact]
public void RefPartialStruct()
{
var comp = CreateCompilation(@"
class C
{
ref partial struct S {}
ref partial struct S {}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void RefPartialReadonlyStruct()
{
var comp = CreateCompilation(@"
class C
{
ref partial readonly struct S {}
ref partial readonly struct S {}
}");
comp.VerifyDiagnostics(
// (4,17): error CS1585: Member modifier 'readonly' must precede the member type and name
// ref partial readonly struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "readonly").WithArguments("readonly").WithLocation(4, 17),
// (5,17): error CS1585: Member modifier 'readonly' must precede the member type and name
// ref partial readonly struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "readonly").WithArguments("readonly").WithLocation(5, 17),
// (5,33): error CS0102: The type 'C' already contains a definition for 'S'
// ref partial readonly struct S {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S").WithLocation(5, 33));
}
[Fact]
public void RefReadonlyPartialStruct()
{
var comp = CreateCompilation(@"
class C
{
partial ref readonly struct S {}
partial ref readonly struct S {}
}");
comp.VerifyDiagnostics(
// (4,13): error CS1585: Member modifier 'ref' must precede the member type and name
// partial ref readonly struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "ref").WithArguments("ref").WithLocation(4, 13),
// (4,26): error CS1031: Type expected
// partial ref readonly struct S {}
Diagnostic(ErrorCode.ERR_TypeExpected, "struct").WithLocation(4, 26),
// (5,13): error CS1585: Member modifier 'ref' must precede the member type and name
// partial ref readonly struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "ref").WithArguments("ref").WithLocation(5, 13),
// (5,26): error CS1031: Type expected
// partial ref readonly struct S {}
Diagnostic(ErrorCode.ERR_TypeExpected, "struct").WithLocation(5, 26),
// (5,33): error CS0102: The type 'C' already contains a definition for 'S'
// partial ref readonly struct S {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S").WithLocation(5, 33));
}
[Fact]
public void ReadonlyPartialRefStruct()
{
var comp = CreateCompilation(@"
class C
{
readonly partial ref struct S {}
readonly partial ref struct S {}
}");
comp.VerifyDiagnostics(
// (4,22): error CS1585: Member modifier 'ref' must precede the member type and name
// readonly partial ref struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "ref").WithArguments("ref").WithLocation(4, 22),
// (5,22): error CS1585: Member modifier 'ref' must precede the member type and name
// readonly partial ref struct S {}
Diagnostic(ErrorCode.ERR_BadModifierLocation, "ref").WithArguments("ref").WithLocation(5, 22),
// (5,33): error CS0102: The type 'C' already contains a definition for 'S'
// readonly partial ref struct S {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S").WithLocation(5, 33));
}
[Fact]
public void ReadonlyRefPartialStruct()
{
var comp = CreateCompilation(@"
class C
{
readonly ref partial struct S {}
readonly ref partial struct S {}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void StackAllocParsedAsSpan_Declaration()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
unsafe public void M()
{
int* a = stackalloc int[10];
var b = stackalloc int[10];
Span<int> c = stackalloc int [10];
}
}", TestOptions.UnsafeDebugDll).GetParseDiagnostics().Verify();
}
[Fact]
public void StackAllocParsedAsSpan_LocalFunction()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public void M()
{
unsafe void local()
{
int* x = stackalloc int[10];
}
}
}").GetParseDiagnostics().Verify();
}
[Fact]
public void StackAllocParsedAsSpan_MethodCall()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public void M()
{
Visit(stackalloc int [10]);
}
public void Visit(Span<int> s) { }
}").GetParseDiagnostics().Verify();
}
[Fact]
public void StackAllocParsedAsSpan_DotAccess()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public void M()
{
Console.WriteLine((stackalloc int [10]).Length);
}
}").GetParseDiagnostics().Verify();
}
[Fact]
public void StackAllocParsedAsSpan_Cast()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public void M()
{
void* x = (void*)(stackalloc int[10]);
}
}").GetParseDiagnostics().Verify();
}
}
}
|
// 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.
#nullable disable
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpExtensionMethodReducer : AbstractCSharpReducer
{
private static readonly ObjectPool<IReductionRewriter> s_pool = new(
() => new Rewriter(s_pool));
public CSharpExtensionMethodReducer() : base(s_pool)
{
}
private static readonly Func<InvocationExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyExtensionMethod = SimplifyExtensionMethod;
private static SyntaxNode SimplifyExtensionMethod(
InvocationExpressionSyntax node,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
var rewrittenNode = node;
if (node.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
{
var memberAccessName = (MemberAccessExpressionSyntax)node.Expression;
rewrittenNode = TryReduceExtensionMethod(node, semanticModel, rewrittenNode, memberAccessName.Name);
}
else if (node.Expression is SimpleNameSyntax)
{
rewrittenNode = TryReduceExtensionMethod(node, semanticModel, rewrittenNode, (SimpleNameSyntax)node.Expression);
}
return rewrittenNode;
}
private static InvocationExpressionSyntax TryReduceExtensionMethod(InvocationExpressionSyntax node, SemanticModel semanticModel, InvocationExpressionSyntax rewrittenNode, SimpleNameSyntax expressionName)
{
var targetSymbol = semanticModel.GetSymbolInfo(expressionName);
if (targetSymbol.Symbol != null && targetSymbol.Symbol.Kind == SymbolKind.Method)
{
var targetMethodSymbol = (IMethodSymbol)targetSymbol.Symbol;
if (!targetMethodSymbol.IsReducedExtension())
{
var argumentList = node.ArgumentList;
var noOfArguments = argumentList.Arguments.Count;
if (noOfArguments > 0)
{
MemberAccessExpressionSyntax newMemberAccess = null;
var invocationExpressionNodeExpression = node.Expression;
// Ensure the first expression is parenthesized so that we don't cause any
// precedence issues when we take the extension method and tack it on the
// end of it.
var expression = argumentList.Arguments[0].Expression.Parenthesize();
if (node.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
{
newMemberAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression, expression,
((MemberAccessExpressionSyntax)invocationExpressionNodeExpression).OperatorToken,
((MemberAccessExpressionSyntax)invocationExpressionNodeExpression).Name);
}
else if (node.Expression.Kind() == SyntaxKind.IdentifierName)
{
newMemberAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression, expression,
(IdentifierNameSyntax)invocationExpressionNodeExpression.WithoutLeadingTrivia());
}
else if (node.Expression.Kind() == SyntaxKind.GenericName)
{
newMemberAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression, expression,
(GenericNameSyntax)invocationExpressionNodeExpression.WithoutLeadingTrivia());
}
else
{
Debug.Assert(false, "The expression kind is not MemberAccessExpression or IdentifierName or GenericName to be converted to Member Access Expression for Ext Method Reduction");
}
if (newMemberAccess == null)
{
return node;
}
// Preserve Trivia
newMemberAccess = newMemberAccess.WithLeadingTrivia(node.GetLeadingTrivia());
// Below removes the first argument
// we need to reuse the separators to maintain existing formatting & comments in the arguments itself
var newArguments = SyntaxFactory.SeparatedList<ArgumentSyntax>(argumentList.Arguments.GetWithSeparators().AsEnumerable().Skip(2));
var rewrittenArgumentList = argumentList.WithArguments(newArguments);
var candidateRewrittenNode = SyntaxFactory.InvocationExpression(newMemberAccess, rewrittenArgumentList);
var oldSymbol = semanticModel.GetSymbolInfo(node).Symbol;
var newSymbol = semanticModel.GetSpeculativeSymbolInfo(
node.SpanStart,
candidateRewrittenNode,
SpeculativeBindingOption.BindAsExpression).Symbol;
if (oldSymbol != null && newSymbol != null)
{
if (newSymbol.Kind == SymbolKind.Method && oldSymbol.Equals(((IMethodSymbol)newSymbol).GetConstructedReducedFrom()))
{
rewrittenNode = candidateRewrittenNode;
}
}
}
}
}
return rewrittenNode;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WebMatrix.Extensibility;
using NuGet;
using NuGet.WebMatrix.Data;
namespace NuGet.WebMatrix
{
internal class FilterManager
{
private ListViewFilter _installedFilter;
private ListViewFilter _updatesFilter;
private ListViewFilter _disabledFilter;
private VirtualizingListViewFilter _allFilter;
// Task scheduler for executing tasks on the primary thread
private TaskScheduler _scheduler;
/// <summary>
/// Initializes a new instance of the <see cref="T:FilterManager"/> class.
/// </summary>
internal FilterManager(NuGetModel model, TaskScheduler scheduler, INuGetGalleryDescriptor descriptor)
{
Debug.Assert(model != null, "Model must not be null");
Debug.Assert(scheduler != null, "TaskScheduler must not be null");
this.Model = model;
Filters = new ObservableCollection<IListViewFilter>();
_installedFilter = new ListViewFilter(Resources.Filter_Installed, string.Format(Resources.Filter_InstalledDescription, descriptor.PackageKind), supportsPrerelease: false);
_installedFilter.FilteredItems.SortDescriptions.Clear();
_updatesFilter = new ListViewFilter(Resources.Filter_Updated, string.Format(Resources.Filter_UpdatedDescription, descriptor.PackageKind), supportsPrerelease: true);
_updatesFilter.FilteredItems.SortDescriptions.Clear();
_disabledFilter = new ListViewFilter(Resources.Filter_Disabled, string.Format(Resources.Filter_DisabledDescription, descriptor.PackageKind), supportsPrerelease: false);
_disabledFilter.FilteredItems.SortDescriptions.Clear();
_scheduler = scheduler;
}
internal ObservableCollection<IListViewFilter> Filters
{
get;
private set;
}
public NuGetModel Model
{
get;
private set;
}
internal ListViewFilter InstalledFilter
{
get
{
return _installedFilter;
}
}
private VirtualizingListViewFilter AllFilter
{
get
{
return _allFilter;
}
}
private ListViewFilter DisabledFilter
{
get
{
return _disabledFilter;
}
}
public void UpdateFilters()
{
// populate the installed packages first, followed by disabled filter (other categories depend on this information)
var populateInstalledTask = StartPopulatingInstalledAndDisabledFilters();
populateInstalledTask.Wait();
// Start populating the filters
var populateFiltersTask = StartPopulatingAllAndUpdateFilters();
populateFiltersTask.Wait();
}
private Task StartPopulatingInstalledAndDisabledFilters()
{
return Task.Factory.StartNew(() =>
{
// after we get the installed packages, use them to populate the 'installed' and 'disabled' filters
var installedTask = Task.Factory
.StartNew<IEnumerable<PackageViewModel>>(GetInstalledPackages, TaskCreationOptions.AttachedToParent);
installedTask.ContinueWith(
UpdateInstalledFilter,
CancellationToken.None,
TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnRanToCompletion,
this._scheduler);
installedTask.ContinueWith(
UpdateDisabledFilter,
CancellationToken.None,
TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnRanToCompletion,
this._scheduler);
});
}
private Task StartPopulatingAllAndUpdateFilters()
{
// the child tasks here are created with AttachedToParent, the outer task will not
// complete until all children have.
return Task.Factory.StartNew(() =>
{
// each of these operations is a two-step process
// 1. Get the packages
// 2. Create view models and add to filters
Task.Factory
.StartNew(UpdateTheAllFilter, TaskCreationOptions.AttachedToParent);
Task.Factory
.StartNew<IEnumerable<IPackage>>(GetUpdatePackages, TaskCreationOptions.AttachedToParent)
.ContinueWith(
UpdateUpdatesFilter(),
CancellationToken.None,
TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnRanToCompletion,
this._scheduler);
})
.ContinueWith(AddFilters, this._scheduler);
}
private void AddFilters(Task task)
{
Filters.Clear();
// always show the 'all' filter
Filters.Add(_allFilter);
if (_updatesFilter.Count > 0)
{
Filters.Add(_updatesFilter);
}
// always show the installed filter
Filters.Add(_installedFilter);
if (_disabledFilter.Count > 0)
{
Filters.Add(_disabledFilter);
}
if (task.IsFaulted)
{
throw task.Exception;
}
}
private void UpdateTheAllFilter()
{
// updating the 'all' filter can take a matter of seconds -- so only update when it's timed out
if (this._allFilter == null)
{
this._allFilter = new VirtualizingListViewFilter(
Resources.Filter_All,
Resources.Filter_AllDescription,
(p) => new PackageViewModel(this.Model, p as IPackage, PackageViewModelAction.InstallOrUninstall));
this.AllFilter.Sort = (p) => p.DownloadCount;
if (!String.IsNullOrWhiteSpace(this.Model.FeedSource.FilterTag))
{
this.AllFilter.Filter = FilterManager.BuildTagFilterExpression(this.Model.FeedSource.FilterTag);
}
this.AllFilter.PackageManager = this.Model.PackageManager;
}
}
private void UpdateInstalledFilter(Task<IEnumerable<PackageViewModel>> task)
{
var installed = task.Result;
_installedFilter.Items.Clear();
foreach (var viewModel in installed)
{
_installedFilter.Items.Add(new ListViewItemWrapper()
{
Item = viewModel,
SearchText = viewModel.SearchText,
Name = viewModel.Name,
});
}
}
private void UpdateDisabledFilter(Task<IEnumerable<PackageViewModel>> task)
{
var installed = task.Result;
_disabledFilter.Items.Clear();
foreach (var viewModel in installed)
{
if (!viewModel.IsEnabled)
{
_disabledFilter.Items.Add(new ListViewItemWrapper()
{
Item = viewModel,
SearchText = viewModel.SearchText,
Name = viewModel.Name,
});
}
}
}
private Action<Task<IEnumerable<IPackage>>> UpdateUpdatesFilter()
{
return (task) =>
{
if (task.Result == null)
{
return;
}
_updatesFilter.Items.Clear();
var packages = task.Result;
foreach (var package in packages)
{
var packageViewModel = new PackageViewModel(this.Model, package, PackageViewModelAction.Update);
_updatesFilter.Items.Add(new ListViewItemWrapper()
{
Item = packageViewModel,
SearchText = packageViewModel.SearchText,
Name = packageViewModel.Name,
});
}
};
}
/// <summary>
/// Filters the given set of packages on the given tag. If the filter tag is null or whitespace,
/// all packages are returned. (Case-Insensitive)
/// </summary>
/// <param name="packages">Input packages</param>
/// <param name="filterTag">The tag to filter</param>
/// <returns>The set of packages containing the given tag tag</returns>
/// <remarks>
/// This implementation (IQueryable) is based on the nature of the NuGet remote package service.
/// The filter clause applied here is pushed up to the server, which will dramatically increase the
/// performance. If you tweak the body of this function, expect to find things that work locally,
/// and fail when hitting the server-side.
/// </remarks>
public static IQueryable<IPackage> FilterOnTag(IQueryable<IPackage> packages, string filterTag)
{
Debug.Assert(packages != null, "Packages cannot be null");
if (string.IsNullOrWhiteSpace(filterTag))
{
return packages;
}
// we're doing this padding because we don't get to call string.split
// when this is running on a remote package list (inside the lambda)
//
// the tag value on the package is considered untrusted input, so we make sure
// it has a leading and trailing space, as does the search text.
// it's also possible that package.Tags might be delimited by spaces and commas
// like: ' foo, bar '
string loweredFilterTag = filterTag.ToLowerInvariant().Trim();
string loweredPaddedFilterTag = " " + loweredFilterTag + " ";
string loweredCommaPaddedFilterTag = " " + loweredFilterTag + ", ";
return packages
.Where(package => package.Tags != null)
.Where(package =>
(" " + package.Tags.ToLower().Trim() + " ").Contains(loweredPaddedFilterTag)
|| (" " + package.Tags.ToLower().Trim() + " ").Contains(loweredCommaPaddedFilterTag));
}
public static Expression<Func<IPackage, bool>> BuildTagFilterExpression(string filterTag)
{
// we're doing this padding because we don't get to call string.split
// when this is running on a remote package list (inside the lambda)
//
// the tag value on the package is considered untrusted input, so we make sure
// it has a leading and trailing space, as does the search text.
// it's also possible that package.Tags might be delimited by spaces and commas
// like: ' foo, bar '
string loweredFilterTag = filterTag.ToLowerInvariant().Trim();
string loweredPaddedFilterTag = " " + loweredFilterTag + " ";
string loweredCommaPaddedFilterTag = " " + loweredFilterTag + ", ";
return (package) => package.Tags != null &&
((" " + package.Tags.ToLower().Trim() + " ").Contains(loweredPaddedFilterTag) ||
(" " + package.Tags.ToLower().Trim() + " ").Contains(loweredCommaPaddedFilterTag));
}
private IEnumerable<PackageViewModel> GetInstalledPackages()
{
var installed = FilterOnTag(this.Model.GetInstalledPackages().AsQueryable(), this.Model.FeedSource.FilterTag);
//// From the installed tab, the only possible operation is uninstall and update is NOT supported
//// For this reason, retrieving the remote package is not worthwhile
//// Plus, Downloads count will not be shown in installed tab, which is fine
//// Note that 'ALL' tab continues to support all applicable operations on a selected package including 'Update'
IEnumerable<PackageViewModel> viewModels;
viewModels = installed.Select((local) => new PackageViewModel(
this.Model,
local,
true,
PackageViewModelAction.InstallOrUninstall));
return viewModels;
}
private IEnumerable<IPackage> GetUpdatePackages()
{
IEnumerable<IPackage> allPackages = this.Model.GetPackagesWithUpdates();
return FilterOnTag(allPackages.AsQueryable(), this.Model.FeedSource.FilterTag);
}
}
}
|
// 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.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System
{
public static partial class Environment
{
private static string? GetEnvironmentVariableCore(string variable)
{
Span<char> buffer = stackalloc char[128]; // a somewhat reasonable default size
int requiredSize = Interop.Kernel32.GetEnvironmentVariable(variable, buffer);
if (requiredSize == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND)
{
return null;
}
if (requiredSize <= buffer.Length)
{
return new string(buffer.Slice(0, requiredSize));
}
char[] chars = ArrayPool<char>.Shared.Rent(requiredSize);
try
{
buffer = chars;
requiredSize = Interop.Kernel32.GetEnvironmentVariable(variable, buffer);
if ((requiredSize == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND) ||
requiredSize > buffer.Length)
{
return null;
}
return new string(buffer.Slice(0, requiredSize));
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
}
private static void SetEnvironmentVariableCore(string variable, string? value)
{
if (!Interop.Kernel32.SetEnvironmentVariable(variable, value))
{
int errorCode = Marshal.GetLastWin32Error();
switch (errorCode)
{
case Interop.Errors.ERROR_ENVVAR_NOT_FOUND:
// Allow user to try to clear a environment variable
return;
case Interop.Errors.ERROR_FILENAME_EXCED_RANGE:
// The error message from Win32 is "The filename or extension is too long",
// which is not accurate.
throw new ArgumentException(SR.Argument_LongEnvVarValue);
case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY:
case Interop.Errors.ERROR_NO_SYSTEM_RESOURCES:
throw new OutOfMemoryException(Interop.Kernel32.GetMessage(errorCode));
default:
throw new ArgumentException(Interop.Kernel32.GetMessage(errorCode));
}
}
}
public static unsafe IDictionary GetEnvironmentVariables()
{
char* pStrings = Interop.Kernel32.GetEnvironmentStrings();
if (pStrings == null)
{
throw new OutOfMemoryException();
}
try
{
// Format for GetEnvironmentStrings is:
// [=HiddenVar=value\0]* [Variable=value\0]* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Search for terminating \0\0 (two unicode \0's).
char* p = pStrings;
while (!(*p == '\0' && *(p + 1) == '\0'))
{
p++;
}
Span<char> block = new Span<char>(pStrings, (int)(p - pStrings + 1));
// Format for GetEnvironmentStrings is:
// (=HiddenVar=value\0 | Variable=value\0)* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Note the =HiddenVar's aren't always at the beginning.
// Copy strings out, parsing into pairs and inserting into the table.
// The first few environment variable entries start with an '='.
// The current working directory of every drive (except for those drives
// you haven't cd'ed into in your DOS window) are stored in the
// environment block (as =C:=pwd) and the program's exit code is
// as well (=ExitCode=00000000).
var results = new Hashtable();
for (int i = 0; i < block.Length; i++)
{
int startKey = i;
// Skip to key. On some old OS, the environment block can be corrupted.
// Some will not have '=', so we need to check for '\0'.
while (block[i] != '=' && block[i] != '\0')
{
i++;
}
if (block[i] == '\0')
{
continue;
}
// Skip over environment variables starting with '='
if (i - startKey == 0)
{
while (block[i] != 0)
{
i++;
}
continue;
}
string key = new string(block.Slice(startKey, i - startKey));
i++; // skip over '='
int startValue = i;
while (block[i] != 0)
{
i++; // Read to end of this entry
}
string value = new string(block.Slice(startValue, i - startValue)); // skip over 0 handled by for loop's i++
try
{
results.Add(key, value);
}
catch (ArgumentException)
{
// Throw and catch intentionally to provide non-fatal notification about corrupted environment block
}
}
return results;
}
finally
{
bool success = Interop.Kernel32.FreeEnvironmentStrings(pStrings);
Debug.Assert(success);
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.DirectoryServices.ActiveDirectory
{
public class GlobalCatalog : DomainController
{
// private variables
private ActiveDirectorySchema _schema = null;
private bool _disabled = false;
#region constructors
internal GlobalCatalog(DirectoryContext context, string globalCatalogName)
: base(context, globalCatalogName)
{ }
internal GlobalCatalog(DirectoryContext context, string globalCatalogName, DirectoryEntryManager directoryEntryMgr)
: base(context, globalCatalogName, directoryEntryMgr)
{ }
#endregion constructors
#region public methods
public static GlobalCatalog GetGlobalCatalog(DirectoryContext context)
{
string gcDnsName = null;
bool isGlobalCatalog = false;
DirectoryEntryManager directoryEntryMgr = null;
// check that the context argument is not null
if (context == null)
throw new ArgumentNullException("context");
// target should be GC
if (context.ContextType != DirectoryContextType.DirectoryServer)
{
throw new ArgumentException(SR.TargetShouldBeGC, "context");
}
// target should be a server
if (!(context.isServer()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
// work with copy of the context
context = new DirectoryContext(context);
try
{
// Get dns name of the dc
// by binding to root dse and getting the "dnsHostName" attribute
// (also check that the "isGlobalCatalogReady" attribute is true)
directoryEntryMgr = new DirectoryEntryManager(context);
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
gcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);
isGlobalCatalog = (bool)Boolean.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.IsGlobalCatalogReady));
if (!isGlobalCatalog)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
return new GlobalCatalog(context, gcDnsName, directoryEntryMgr);
}
public static new GlobalCatalog FindOne(DirectoryContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, "context");
}
return FindOneWithCredentialValidation(context, null, 0);
}
public static new GlobalCatalog FindOne(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, "context");
}
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
return FindOneWithCredentialValidation(context, siteName, 0);
}
public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, "context");
}
return FindOneWithCredentialValidation(context, null, flag);
}
public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, "context");
}
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
return FindOneWithCredentialValidation(context, siteName, flag);
}
public static new GlobalCatalogCollection FindAll(DirectoryContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, "context");
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, null);
}
public static new GlobalCatalogCollection FindAll(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, "context");
}
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, siteName);
}
public override GlobalCatalog EnableGlobalCatalog()
{
CheckIfDisposed();
throw new InvalidOperationException(SR.CannotPerformOnGCObject);
}
public DomainController DisableGlobalCatalog()
{
CheckIfDisposed();
CheckIfDisabled();
// bind to the server object
DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName);
// reset the NTDSDSA_OPT_IS_GC flag on the "options" property
int options = 0;
try
{
if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null)
{
options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value;
}
serverNtdsaEntry.Properties[PropertyManager.Options].Value = options & (~1);
serverNtdsaEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
// mark as disbaled
_disabled = true;
// return a domain controller object
return new DomainController(context, Name);
}
public override bool IsGlobalCatalog()
{
CheckIfDisposed();
CheckIfDisabled();
// since this is a global catalog object, this should always return true
return true;
}
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties()
{
CheckIfDisposed();
CheckIfDisabled();
// create an ActiveDirectorySchema object
if (_schema == null)
{
string schemaNC = null;
try
{
schemaNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
DirectoryContext schemaContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
_schema = new ActiveDirectorySchema(context, schemaNC);
}
// return the global catalog replicated properties
return _schema.FindAllProperties(PropertyTypes.InGlobalCatalog);
}
public override DirectorySearcher GetDirectorySearcher()
{
CheckIfDisposed();
CheckIfDisabled();
return InternalGetDirectorySearcher();
}
#endregion public methods
#region private methods
private void CheckIfDisabled()
{
if (_disabled)
{
throw new InvalidOperationException(SR.GCDisabled);
}
}
internal static new GlobalCatalog FindOneWithCredentialValidation(DirectoryContext context, string siteName, LocatorOptions flag)
{
GlobalCatalog gc;
bool retry = false;
bool credsValidated = false;
// work with copy of the context
context = new DirectoryContext(context);
// authenticate against this GC to validate the credentials
gc = FindOneInternal(context, context.Name, siteName, flag);
try
{
ValidateCredential(gc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down , so try again with force rediscovery if the flags did not already contain force rediscovery
if ((flag & LocatorOptions.ForceRediscovery) == 0)
{
retry = true;
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (!credsValidated)
{
gc.Dispose();
}
}
if (retry)
{
credsValidated = false;
gc = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery);
try
{
ValidateCredential(gc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (!credsValidated)
{
gc.Dispose();
}
}
}
return gc;
}
internal static new GlobalCatalog FindOneInternal(DirectoryContext context, string forestName, string siteName, LocatorOptions flag)
{
DomainControllerInfo domainControllerInfo;
int errorCode = 0;
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "siteName");
}
// check that the flags passed have only the valid bits set
if (((long)flag & (~((long)LocatorOptions.AvoidSelf | (long)LocatorOptions.ForceRediscovery | (long)LocatorOptions.KdcRequired | (long)LocatorOptions.TimeServerRequired | (long)LocatorOptions.WriteableRequired))) != 0)
{
throw new ArgumentException(SR.InvalidFlags, "flag");
}
if (forestName == null)
{
// get the dns name of the logged on forest
DomainControllerInfo tempDomainControllerInfo;
int error = Locator.DsGetDcNameWrapper(null, DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out tempDomainControllerInfo);
if (error == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// throw not found exception
throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(GlobalCatalog), null);
}
else if (error != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(tempDomainControllerInfo.DnsForestName != null);
forestName = tempDomainControllerInfo.DnsForestName;
}
// call DsGetDcName
errorCode = Locator.DsGetDcNameWrapper(null, forestName, siteName, (long)flag | (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , forestName), typeof(GlobalCatalog), null);
}
// this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid)
if (errorCode == NativeMethods.ERROR_INVALID_FLAGS)
{
throw new ArgumentException(SR.InvalidFlags, "flag");
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
// create a GlobalCatalog object
// the name is returned in the form "\\servername", so skip the "\\"
Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2);
string globalCatalogName = domainControllerInfo.DomainControllerName.Substring(2);
// create a new context object for the global catalog
DirectoryContext gcContext = Utils.GetNewDirectoryContext(globalCatalogName, DirectoryContextType.DirectoryServer, context);
return new GlobalCatalog(gcContext, globalCatalogName);
}
internal static GlobalCatalogCollection FindAllInternal(DirectoryContext context, string siteName)
{
ArrayList gcList = new ArrayList();
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "siteName");
}
foreach (string gcName in Utils.GetReplicaList(context, null /* not specific to any partition */, siteName, false /* isDefaultNC */, false /* isADAM */, true /* mustBeGC */))
{
DirectoryContext gcContext = Utils.GetNewDirectoryContext(gcName, DirectoryContextType.DirectoryServer, context);
gcList.Add(new GlobalCatalog(gcContext, gcName));
}
return new GlobalCatalogCollection(gcList);
}
private DirectorySearcher InternalGetDirectorySearcher()
{
DirectoryEntry de = new DirectoryEntry("GC://" + Name);
de.AuthenticationType = Utils.DefaultAuthType | AuthenticationTypes.ServerBind;
de.Username = context.UserName;
de.Password = context.Password;
return new DirectorySearcher(de);
}
#endregion
}
}
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Test.UnitTests.TSql;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Test.UnitTests.Database.Cmdlet
{
[TestClass]
public class SqlAuthv12MockTests
{
public static string username = "testlogin";
public static string password = "MyS3curePa$$w0rd";
public static string manageUrl = "https://mysvr2.database.windows.net";
[TestInitialize]
public void Setup()
{
}
[TestCleanup]
public void Cleanup()
{
// Do any test clean up here.
}
//[RecordMockDataResults("./")]
[TestMethod]
public void NewAzureSqlDatabaseWithSqlAuthv12()
{
var mockConn = new MockSqlConnection();
TSqlConnectionContext.MockSqlConnection = mockConn;
using (System.Management.Automation.PowerShell powershell =
System.Management.Automation.PowerShell.Create())
{
// Create a context
NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuthV12(
powershell,
manageUrl,
username,
password,
"$context");
Collection<PSObject> database1, database2, database3, database4;
database1 = powershell.InvokeBatchScript(
@"$testdb1 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 " +
@"-Force",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb2 " +
@"-Collation Japanese_CI_AS " +
@"-Edition Basic " +
@"-MaxSizeGB 2 " +
@"-Force",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb3 " +
@"-MaxSizeBytes 107374182400 " +
@"-Force",
@"$testdb3");
var slo = powershell.InvokeBatchScript(
@"$so = Get-AzureSqlDatabaseServiceObjective " +
@"-Context $context " +
@"-ServiceObjectiveName S2 ",
@"$so");
database4 = powershell.InvokeBatchScript(
@"$testdb4 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb4 " +
@"-Edition Standard " +
@"-ServiceObjective $so " +
@"-Force",
@"$testdb4");
Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
powershell.Streams.ClearStreams();
Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database2.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb2", "Basic", 2, 2147483648L, "Japanese_CI_AS", false, DatabaseTestHelper.BasicSloGuid);
database = database3.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb3", "Standard", 100, 107374182400L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database4.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb4", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS2SloGuid);
}
}
//[RecordMockDataResults("./")]
[TestMethod]
public void GetAzureSqlDatabaseWithSqlAuthv12()
{
var mockConn = new MockSqlConnection();
TSqlConnectionContext.MockSqlConnection = mockConn;
using (System.Management.Automation.PowerShell powershell =
System.Management.Automation.PowerShell.Create())
{
// Create a context
NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuthV12(
powershell,
manageUrl,
username,
password,
"$context");
Collection<PSObject> database1, database2, database3;
database1 = powershell.InvokeBatchScript(
@"$testdb1 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 ",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-Database $testdb1 ",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = Get-AzureSqlDatabase " +
@"-Context $context ",
@"$testdb3");
Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
powershell.Streams.ClearStreams();
Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database2.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
Assert.IsTrue(database3.Count == 5);
foreach (var entry in database3)
{
var db = entry.BaseObject as Services.Server.Database;
Assert.IsTrue(db != null, "Expecting a Database object");
}
}
}
//[RecordMockDataResults("./")]
[TestMethod]
public void SetAzureSqlDatabaseWithSqlAuthv12()
{
var mockConn = new MockSqlConnection();
TSqlConnectionContext.MockSqlConnection = mockConn;
using (System.Management.Automation.PowerShell powershell =
System.Management.Automation.PowerShell.Create())
{
// Create a context
NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuthV12(
powershell,
manageUrl,
username,
password,
"$context");
Collection<PSObject> database1, database2, database3, database4;
database1 = powershell.InvokeBatchScript(
@"$testdb1 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 " +
@"-Edition Basic " +
@"-MaxSizeGb 1 " +
@"-Force " +
@"-PassThru ",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb2 " +
@"-Edition Standard " +
@"-MaxSizeBytes 107374182400 " +
@"-Force " +
@"-PassThru ",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb3 " +
@"-NewDatabaseName testdb3alt " +
@"-Force " +
@"-PassThru ",
@"$testdb3");
var slo = powershell.InvokeBatchScript(
@"$so = Get-AzureSqlDatabaseServiceObjective " +
@"-Context $context " +
@"-ServiceObjectiveName S0 ",
@"$so");
database4 = powershell.InvokeBatchScript(
@"$testdb4 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb4 " +
@"-ServiceObjective $so " +
@"-Force " +
@"-PassThru ",
@"$testdb4");
//
// Wait for operations to complete
//
database1 = powershell.InvokeBatchScript(
@"$testdb1 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 ",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb2 ",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb3alt ",
@"$testdb3");
database4 = powershell.InvokeBatchScript(
@"$testdb4 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb4 ",
@"$testdb4");
Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
powershell.Streams.ClearStreams();
Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Basic", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.BasicSloGuid);
database = database2.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb2", "Standard", 100, 107374182400L, "Japanese_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database3.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb3alt", "Standard", 100, 107374182400L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database4.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb4", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
}
}
#region Helpers
/// <summary>
/// Validate the properties of a database against the expected values supplied as input.
/// </summary>
/// <param name="database">The database object to validate</param>
/// <param name="name">The expected name of the database</param>
/// <param name="edition">The expected edition of the database</param>
/// <param name="maxSizeGb">The expected max size of the database in GB</param>
/// <param name="collation">The expected Collation of the database</param>
/// <param name="isSystem">Whether or not the database is expected to be a system object.</param>
internal static void ValidateDatabaseProperties(
Services.Server.Database database,
string name,
string edition,
int maxSizeGb,
long maxSizeBytes,
string collation,
bool isSystem,
Guid slo)
{
Assert.AreEqual(name, database.Name);
Assert.AreEqual(edition, database.Edition);
Assert.AreEqual(maxSizeGb, database.MaxSizeGB);
Assert.AreEqual(maxSizeBytes, database.MaxSizeBytes);
Assert.AreEqual(collation, database.CollationName);
Assert.AreEqual(isSystem, database.IsSystemObject);
// Assert.AreEqual(slo, database.ServiceObjectiveId);
}
#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 Xunit;
namespace System.Numerics.Tests
{
public class op_leftshiftTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunLeftShiftTests()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// LeftShift Method - Large BigIntegers - large + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomPosByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - small + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)s_random.Next(1, 32) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - 32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)32 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - large - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomNegByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - small - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { unchecked((byte)s_random.Next(-31, 0)) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - -32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)0xe0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - 0 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - large + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - small + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)s_random.Next(1, 32) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - 32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)32 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - large - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomNegByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - small - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { unchecked((byte)s_random.Next(-31, 0)) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - -32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)0xe0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - 0 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Positive BigIntegers - Shift to 0
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 100);
tempByteArray2 = BitConverter.GetBytes(s_random.Next(-1000, -8 * tempByteArray1.Length));
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Negative BigIntegers - Shift to -1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomNegByteArray(s_random, 100);
tempByteArray2 = BitConverter.GetBytes(s_random.Next(-1000, -8 * tempByteArray1.Length));
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
}
private static void VerifyLeftShiftString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 1024));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static Byte[] GetRandomPosByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] &= 0x7F;
return value;
}
private static Byte[] GetRandomNegByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] |= 0x80;
return value;
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using SortedDictionaryTests.SortedDictionary_SortedDictionary_KeyCollection;
using SortedDictionary_SortedDictionaryUtils;
namespace SortedDictionaryTests
{
public class SortedDictionary_KeyCollectionTests
{
public class IntGenerator
{
private int _index;
public IntGenerator()
{
_index = 0;
}
public int NextValue()
{
return _index++;
}
public Object NextValueObject()
{
return (Object)NextValue();
}
}
public class StringGenerator
{
private int _index;
public StringGenerator()
{
_index = 0;
}
public String NextValue()
{
return (_index++).ToString();
}
public Object NextValueObject()
{
return (Object)NextValue();
}
}
[Fact]
public static void SortedDictionary_KeyCollectionTest1()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
//Scenario 1: Vanilla - fill in an SortedDictionary with 10 keys and check this property
Driver<int, int> IntDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
int count = 1000;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
for (int i = 0; i < count; i++)
ints[i] = i;
IntDriver.TestVanilla(ints, ints);
simpleRef.TestVanilla(simpleStrings, simpleStrings);
simpleVal.TestVanilla(simpleInts, simpleInts);
IntDriver.NonGenericIDictionaryTestVanilla(ints, ints);
simpleRef.NonGenericIDictionaryTestVanilla(simpleStrings, simpleStrings);
simpleVal.NonGenericIDictionaryTestVanilla(simpleInts, simpleInts);
//Scenario 2: Check for an empty SortedDictionary
IntDriver.TestVanilla(new int[0], new int[0]);
simpleRef.TestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.TestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]);
IntDriver.NonGenericIDictionaryTestVanilla(new int[0], new int[0]);
simpleRef.NonGenericIDictionaryTestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.NonGenericIDictionaryTestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]);
//Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the
//change is reflected
int half = count / 2;
SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half];
SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half];
int[] ints_1 = new int[half];
int[] ints_2 = new int[half];
for (int i = 0; i < half; i++)
{
simpleInts_1[i] = simpleInts[i];
simpleStrings_1[i] = simpleStrings[i];
ints_1[i] = ints[i];
simpleInts_2[i] = simpleInts[i + half];
simpleStrings_2[i] = simpleStrings[i + half];
ints_2[i] = ints[i + half];
}
IntDriver.TestModify(ints_1, ints_1, ints_2);
simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2);
IntDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2);
simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2);
}
[Fact]
public static void SortedDictionary_KeyCollectionTest_Negative()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
//Scenario 1: Vanilla - fill in SortedDictionary with 10 keys and check this property
Driver<int, int> IntDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
int count = 1000;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
for (int i = 0; i < count; i++)
ints[i] = i;
IntDriver.TestVanilla_Negative(ints, ints);
simpleRef.TestVanilla_Negative(simpleStrings, simpleStrings);
simpleVal.TestVanilla_Negative(simpleInts, simpleInts);
IntDriver.NonGenericIDictionaryTestVanilla_Negative(ints, ints);
simpleRef.NonGenericIDictionaryTestVanilla_Negative(simpleStrings, simpleStrings);
simpleVal.NonGenericIDictionaryTestVanilla_Negative(simpleInts, simpleInts);
//Scenario 2: Check for an empty SortedDictionary
IntDriver.TestVanilla_Negative(new int[0], new int[0]);
simpleRef.TestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.TestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]);
IntDriver.NonGenericIDictionaryTestVanilla_Negative(new int[0], new int[0]);
simpleRef.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]);
}
[Fact]
public static void SortedDictionary_KeyCollectionTest2()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
Driver<int, int> intDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
//Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the
//change is reflected
int count = 1000;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
int half = count / 2;
SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half];
SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half];
for (int i = 0; i < count; i++)
ints[i] = i;
int[] ints_1 = new int[half];
int[] ints_2 = new int[half];
for (int i = 0; i < half; i++)
{
simpleInts_1[i] = simpleInts[i];
simpleStrings_1[i] = simpleStrings[i];
ints_1[i] = ints[i];
simpleInts_2[i] = simpleInts[i + half];
simpleStrings_2[i] = simpleStrings[i + half];
ints_2[i] = ints[i + half];
}
intDriver.TestModify(ints_1, ints_1, ints_2);
simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2);
intDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2);
simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2);
}
}
namespace SortedDictionary_SortedDictionary_KeyCollection
{
public class Driver<KeyType, ValueType>
{
public void TestVanilla(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
Assert.Equal(_col.Count, _dic.Count); //"Err_1! Count not equal"
IEnumerator<KeyType> _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey(_enum.Current)); //"Err_2! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_3! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_4! Expected key to be present"
count = 0;
foreach (KeyType currKey in _dic.Keys)
{
Assert.True(_dic.ContainsKey(currKey)); //"Err_5! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_6! Count not equal"
try
{
//The behavior here is undefined as long as we don't AV we're fine
KeyType item = _enum.Current;
}
catch (Exception) { }
}
// verify we get InvalidOperationException when we call MoveNext() after adding a key
public void TestVanilla_Negative(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
IEnumerator<KeyType> _enum = _col.GetEnumerator();
if (keys.Length > 0)
{
_dic.Add(keys[keys.Length - 1], values[values.Length - 1]);
Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_7! Expected InvalidOperationException."
}
}
public void TestModify(KeyType[] keys, ValueType[] values, KeyType[] newKeys)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
{
_dic.Add(keys[i], values[i]);
}
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
for (int i = 0; i < keys.Length; i++)
_dic.Remove(keys[i]);
Assert.Equal(_col.Count, 0); //"Err_8! Expected count to be zero"
IEnumerator<KeyType> _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey(_enum.Current)); //"Err_9! Expected key to be present"
count++;
}
Assert.Equal(count, 0); //"Err_10! Expected count to be zero"
for (int i = 0; i < keys.Length; i++)
_dic.Add(newKeys[i], values[i]);
Assert.Equal(_col.Count, _dic.Count); //"Err_11! Count not equal"
_enum = _col.GetEnumerator();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey(_enum.Current)); //"Err_12! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_13! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_14! Expected key to be present"
}
public void NonGenericIDictionaryTestVanilla(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
Assert.Equal(_col.Count, _dic.Count); //"Err_15! Count not equal"
IEnumerator _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_16! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_17! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_18! Expected key to be present"
_enum.Reset();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_19! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_20! Count not equal"
_keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_21! Expected key to be present"
}
public void NonGenericIDictionaryTestVanilla_Negative(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
IEnumerator _enum = _col.GetEnumerator();
// get to the end
while (_enum.MoveNext()) { }
Assert.Throws<InvalidOperationException>((() => _dic.ContainsKey((KeyType)_enum.Current))); //"Err_22! Expected InvalidOperationException."
if (keys.Length > 0)
{
_dic.Add(keys[keys.Length - 1], values[values.Length - 1]);
Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_23! Expected InvalidOperationException."
Assert.Throws<InvalidOperationException>((() => _enum.Reset())); //"Err_24! Expected InvalidOperationException."
}
}
public void NonGenericIDictionaryTestModify(KeyType[] keys, ValueType[] values, KeyType[] newKeys)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
for (int i = 0; i < keys.Length; i++)
_dic.Remove(keys[i]);
Assert.Equal(_col.Count, 0); //"Err_25! Expected count to be zero"
IEnumerator _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_26! Expected key to be present"
count++;
}
Assert.Equal(count, 0); //"Err_27! Expected count to be zero"
for (int i = 0; i < keys.Length; i++)
_dic.Add(newKeys[i], values[i]);
Assert.Equal(_col.Count, _dic.Count); //"Err_28! Count not equal"
_enum = _col.GetEnumerator();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_29! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_30! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_31! Expected key to be present"
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// System.Array.Sort<T>(T[],System.Collections.Generic.IComparer<T>)
/// </summary>
public class ArraySort7
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
//Bug 385712: Wont fix
//retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using string comparer<string>");
try
{
string[] s1 = new string[7]{"Jack",
"Mary",
"Mike",
"Peter",
"Boy",
"Tom",
"Allin"};
IComparer<string> a = new A<string>();
Array.Sort<string>(s1, a);
string[] s2 = new string[7]{"Allin",
"Boy",
"Jack",
"Mary",
"Mike",
"Peter",
"Tom"};
for (int i = 0; i < 7; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using reverse comparer<int>");
try
{
int length = TestLibrary.Generator.GetInt16(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetByte(-55);
i1[i] = value;
i2[i] = value;
}
IComparer<int> b = new B<int>();
Array.Sort<int>(i1, b);
for (int i = 0; i < length - 1; i++) //manually quich sort
{
for (int j = i + 1; j < length; j++)
{
if (i2[i] < i2[j])
{
int temp = i2[i];
i2[i] = i2[j];
i2[j] = temp;
}
}
}
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using default comparer ");
try
{
int length = TestLibrary.Generator.GetInt16(-55);
char[] i1 = new char[length];
char[] i2 = new char[length];
for (int i = 0; i < length; i++)
{
char value = TestLibrary.Generator.GetChar(-55);
i1[i] = value;
i2[i] = value;
}
IComparer<char> c = null;
Array.Sort<char>(i1, c);
for (int i = 0; i < length - 1; i++) //manually quich sort
{
for (int j = i + 1; j < length; j++)
{
if (i2[i] > i2[j])
{
char temp = i2[i];
i2[i] = i2[j];
i2[j] = temp;
}
}
}
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Sort an array which has same elements using default Icomparer ");
try
{
int length = TestLibrary.Generator.GetByte(-55);
string[] s1 = new string[length];
string[] s2 = new string[length];
string value = TestLibrary.Generator.GetString(-55, false, 0, 10);
for (int i = 0; i < length; i++)
{
s1[i] = value;
s2[i] = value;
}
IComparer<string> c = null;
Array.Sort<string>(s1, c);
for (int i = 0; i < length; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Sort a string array including null reference and using customized comparer<T> interface");
try
{
string[] s1 = new string[9]{"Jack",
"Mary",
"Mike",
null,
"Peter",
"Boy",
"Tom",
null,
"Allin"};
IComparer<string> d = new D<string>();
Array.Sort<string>(s1, d);
string[] s2 = new string[9]{"Allin",
"Boy",
"Jack",
"Mary",
"Mike",
"Peter",
"Tom",
null,
null};
for (int i = 0; i < 7; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The array is null ");
try
{
string[] s1 = null;
IComparer<string> a = new A<string>();
Array.Sort<string>(s1, a);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: Elements in array do not implement the IComparable<T> interface ");
try
{
E<int>[] a1 = new E<int>[4] { new E<int>(), new E<int>(), new E<int>(), new E<int>() };
IComparer<E<int>> d = null;
Array.Sort<E<int>>(a1, d);
TestLibrary.TestFramework.LogError("103", "The InvalidOperationException is not throw as expected ");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3:The implementation of comparer<T> caused an error during the sort");
try
{
int[] i1 = new int[9] { 2, 34, 56, 87, 34, 23, 209, 34, 87 };
F f = new F();
Array.Sort<int>(i1, f);
TestLibrary.TestFramework.LogError("105", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArraySort7 test = new ArraySort7();
TestLibrary.TestFramework.BeginTestCase("ArraySort7");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
class A<T> : IComparer<T> where T : IComparable
{
#region IComparer Members
public int Compare(T x, T y)
{
return x.CompareTo(y);
}
#endregion
}
class B<T> : IComparer<T> where T : IComparable
{
#region IComparer Members
public int Compare(T x, T y)
{
return (-(x).CompareTo(y));
}
#endregion
}
class D<T> : IComparer<T> where T : IComparable
{
#region IComparer Members
public int Compare(T x, T y)
{
if (x == null)
{
return 1;
}
if (y == null)
{
return -1;
}
return x.CompareTo(y);
}
#endregion
}
class E<T>
{
public E() { }
}
class F : IComparer<int>
{
#region IComparer<int> Members
int IComparer<int>.Compare(int a, int b)
{
if (a.CompareTo(a) == 0)
{
return -1;
}
return a.CompareTo(b);
}
#endregion
}
}
|
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Leave Group Types Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class PLTDataSet : EduHubDataSet<PLT>
{
/// <inheritdoc />
public override string Name { get { return "PLT"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal PLTDataSet(EduHubContext Context)
: base(Context)
{
Index_LEAVE_CODE = new Lazy<NullDictionary<string, IReadOnlyList<PLT>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_CODE));
Index_LEAVE_GROUP = new Lazy<NullDictionary<string, IReadOnlyList<PLT>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_GROUP));
Index_LEAVE_GROUP_LEAVE_CODE = new Lazy<Dictionary<Tuple<string, string>, PLT>>(() => this.ToDictionary(i => Tuple.Create(i.LEAVE_GROUP, i.LEAVE_CODE)));
Index_PLTKEY = new Lazy<Dictionary<string, PLT>>(() => this.ToDictionary(i => i.PLTKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="PLT" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="PLT" /> fields for each CSV column header</returns>
internal override Action<PLT, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<PLT, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "PLTKEY":
mapper[i] = (e, v) => e.PLTKEY = v;
break;
case "LEAVE_GROUP":
mapper[i] = (e, v) => e.LEAVE_GROUP = v;
break;
case "LEAVE_CODE":
mapper[i] = (e, v) => e.LEAVE_CODE = v;
break;
case "CALC_METHOD":
mapper[i] = (e, v) => e.CALC_METHOD = v;
break;
case "PERIOD_ALLOT01":
mapper[i] = (e, v) => e.PERIOD_ALLOT01 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT02":
mapper[i] = (e, v) => e.PERIOD_ALLOT02 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT03":
mapper[i] = (e, v) => e.PERIOD_ALLOT03 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT04":
mapper[i] = (e, v) => e.PERIOD_ALLOT04 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT05":
mapper[i] = (e, v) => e.PERIOD_ALLOT05 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT06":
mapper[i] = (e, v) => e.PERIOD_ALLOT06 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT07":
mapper[i] = (e, v) => e.PERIOD_ALLOT07 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT08":
mapper[i] = (e, v) => e.PERIOD_ALLOT08 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT09":
mapper[i] = (e, v) => e.PERIOD_ALLOT09 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT10":
mapper[i] = (e, v) => e.PERIOD_ALLOT10 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT11":
mapper[i] = (e, v) => e.PERIOD_ALLOT11 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT12":
mapper[i] = (e, v) => e.PERIOD_ALLOT12 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_LENGTH01":
mapper[i] = (e, v) => e.PERIOD_LENGTH01 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH02":
mapper[i] = (e, v) => e.PERIOD_LENGTH02 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH03":
mapper[i] = (e, v) => e.PERIOD_LENGTH03 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH04":
mapper[i] = (e, v) => e.PERIOD_LENGTH04 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH05":
mapper[i] = (e, v) => e.PERIOD_LENGTH05 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH06":
mapper[i] = (e, v) => e.PERIOD_LENGTH06 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH07":
mapper[i] = (e, v) => e.PERIOD_LENGTH07 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH08":
mapper[i] = (e, v) => e.PERIOD_LENGTH08 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH09":
mapper[i] = (e, v) => e.PERIOD_LENGTH09 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH10":
mapper[i] = (e, v) => e.PERIOD_LENGTH10 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH11":
mapper[i] = (e, v) => e.PERIOD_LENGTH11 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH12":
mapper[i] = (e, v) => e.PERIOD_LENGTH12 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_UNITS":
mapper[i] = (e, v) => e.PERIOD_UNITS = v;
break;
case "ANNUAL_ENTITLEMENT":
mapper[i] = (e, v) => e.ANNUAL_ENTITLEMENT = v == null ? (double?)null : double.Parse(v);
break;
case "ROLL_OVER":
mapper[i] = (e, v) => e.ROLL_OVER = v;
break;
case "ROLL_PERCENT":
mapper[i] = (e, v) => e.ROLL_PERCENT = v == null ? (double?)null : double.Parse(v);
break;
case "LEAVE_LOADING":
mapper[i] = (e, v) => e.LEAVE_LOADING = v;
break;
case "LOADING_PERCENT":
mapper[i] = (e, v) => e.LOADING_PERCENT = v == null ? (double?)null : double.Parse(v);
break;
case "ACTIVE":
mapper[i] = (e, v) => e.ACTIVE = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="PLT" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="PLT" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="PLT" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{PLT}"/> of entities</returns>
internal override IEnumerable<PLT> ApplyDeltaEntities(IEnumerable<PLT> Entities, List<PLT> DeltaEntities)
{
HashSet<Tuple<string, string>> Index_LEAVE_GROUP_LEAVE_CODE = new HashSet<Tuple<string, string>>(DeltaEntities.Select(i => Tuple.Create(i.LEAVE_GROUP, i.LEAVE_CODE)));
HashSet<string> Index_PLTKEY = new HashSet<string>(DeltaEntities.Select(i => i.PLTKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.PLTKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = false;
overwritten = overwritten || Index_LEAVE_GROUP_LEAVE_CODE.Remove(Tuple.Create(entity.LEAVE_GROUP, entity.LEAVE_CODE));
overwritten = overwritten || Index_PLTKEY.Remove(entity.PLTKEY);
if (entity.PLTKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<PLT>>> Index_LEAVE_CODE;
private Lazy<NullDictionary<string, IReadOnlyList<PLT>>> Index_LEAVE_GROUP;
private Lazy<Dictionary<Tuple<string, string>, PLT>> Index_LEAVE_GROUP_LEAVE_CODE;
private Lazy<Dictionary<string, PLT>> Index_PLTKEY;
#endregion
#region Index Methods
/// <summary>
/// Find PLT by LEAVE_CODE field
/// </summary>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>List of related PLT entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> FindByLEAVE_CODE(string LEAVE_CODE)
{
return Index_LEAVE_CODE.Value[LEAVE_CODE];
}
/// <summary>
/// Attempt to find PLT by LEAVE_CODE field
/// </summary>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <param name="Value">List of related PLT entities</param>
/// <returns>True if the list of related PLT entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLEAVE_CODE(string LEAVE_CODE, out IReadOnlyList<PLT> Value)
{
return Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out Value);
}
/// <summary>
/// Attempt to find PLT by LEAVE_CODE field
/// </summary>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>List of related PLT entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> TryFindByLEAVE_CODE(string LEAVE_CODE)
{
IReadOnlyList<PLT> value;
if (Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find PLT by LEAVE_GROUP field
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <returns>List of related PLT entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> FindByLEAVE_GROUP(string LEAVE_GROUP)
{
return Index_LEAVE_GROUP.Value[LEAVE_GROUP];
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP field
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="Value">List of related PLT entities</param>
/// <returns>True if the list of related PLT entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLEAVE_GROUP(string LEAVE_GROUP, out IReadOnlyList<PLT> Value)
{
return Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out Value);
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP field
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <returns>List of related PLT entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> TryFindByLEAVE_GROUP(string LEAVE_GROUP)
{
IReadOnlyList<PLT> value;
if (Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find PLT by LEAVE_GROUP and LEAVE_CODE fields
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>Related PLT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT FindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE)
{
return Index_LEAVE_GROUP_LEAVE_CODE.Value[Tuple.Create(LEAVE_GROUP, LEAVE_CODE)];
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP and LEAVE_CODE fields
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <param name="Value">Related PLT entity</param>
/// <returns>True if the related PLT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE, out PLT Value)
{
return Index_LEAVE_GROUP_LEAVE_CODE.Value.TryGetValue(Tuple.Create(LEAVE_GROUP, LEAVE_CODE), out Value);
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP and LEAVE_CODE fields
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>Related PLT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT TryFindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE)
{
PLT value;
if (Index_LEAVE_GROUP_LEAVE_CODE.Value.TryGetValue(Tuple.Create(LEAVE_GROUP, LEAVE_CODE), out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find PLT by PLTKEY field
/// </summary>
/// <param name="PLTKEY">PLTKEY value used to find PLT</param>
/// <returns>Related PLT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT FindByPLTKEY(string PLTKEY)
{
return Index_PLTKEY.Value[PLTKEY];
}
/// <summary>
/// Attempt to find PLT by PLTKEY field
/// </summary>
/// <param name="PLTKEY">PLTKEY value used to find PLT</param>
/// <param name="Value">Related PLT entity</param>
/// <returns>True if the related PLT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByPLTKEY(string PLTKEY, out PLT Value)
{
return Index_PLTKEY.Value.TryGetValue(PLTKEY, out Value);
}
/// <summary>
/// Attempt to find PLT by PLTKEY field
/// </summary>
/// <param name="PLTKEY">PLTKEY value used to find PLT</param>
/// <returns>Related PLT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT TryFindByPLTKEY(string PLTKEY)
{
PLT value;
if (Index_PLTKEY.Value.TryGetValue(PLTKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a PLT table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PLT](
[PLTKEY] varchar(16) NOT NULL,
[LEAVE_GROUP] varchar(8) NULL,
[LEAVE_CODE] varchar(8) NULL,
[CALC_METHOD] varchar(8) NULL,
[PERIOD_ALLOT01] float NULL,
[PERIOD_ALLOT02] float NULL,
[PERIOD_ALLOT03] float NULL,
[PERIOD_ALLOT04] float NULL,
[PERIOD_ALLOT05] float NULL,
[PERIOD_ALLOT06] float NULL,
[PERIOD_ALLOT07] float NULL,
[PERIOD_ALLOT08] float NULL,
[PERIOD_ALLOT09] float NULL,
[PERIOD_ALLOT10] float NULL,
[PERIOD_ALLOT11] float NULL,
[PERIOD_ALLOT12] float NULL,
[PERIOD_LENGTH01] smallint NULL,
[PERIOD_LENGTH02] smallint NULL,
[PERIOD_LENGTH03] smallint NULL,
[PERIOD_LENGTH04] smallint NULL,
[PERIOD_LENGTH05] smallint NULL,
[PERIOD_LENGTH06] smallint NULL,
[PERIOD_LENGTH07] smallint NULL,
[PERIOD_LENGTH08] smallint NULL,
[PERIOD_LENGTH09] smallint NULL,
[PERIOD_LENGTH10] smallint NULL,
[PERIOD_LENGTH11] smallint NULL,
[PERIOD_LENGTH12] smallint NULL,
[PERIOD_UNITS] varchar(6) NULL,
[ANNUAL_ENTITLEMENT] float NULL,
[ROLL_OVER] varchar(1) NULL,
[ROLL_PERCENT] float NULL,
[LEAVE_LOADING] varchar(1) NULL,
[LOADING_PERCENT] float NULL,
[ACTIVE] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [PLT_Index_PLTKEY] PRIMARY KEY CLUSTERED (
[PLTKEY] ASC
)
);
CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT]
(
[LEAVE_CODE] ASC
);
CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT]
(
[LEAVE_GROUP] ASC
);
CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT]
(
[LEAVE_GROUP] ASC,
[LEAVE_CODE] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP')
ALTER INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP')
ALTER INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="PLT"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="PLT"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<PLT> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<Tuple<string, string>> Index_LEAVE_GROUP_LEAVE_CODE = new List<Tuple<string, string>>();
List<string> Index_PLTKEY = new List<string>();
foreach (var entity in Entities)
{
Index_LEAVE_GROUP_LEAVE_CODE.Add(Tuple.Create(entity.LEAVE_GROUP, entity.LEAVE_CODE));
Index_PLTKEY.Add(entity.PLTKEY);
}
builder.AppendLine("DELETE [dbo].[PLT] WHERE");
// Index_LEAVE_GROUP_LEAVE_CODE
builder.Append("(");
for (int index = 0; index < Index_LEAVE_GROUP_LEAVE_CODE.Count; index++)
{
if (index != 0)
builder.Append(" OR ");
// LEAVE_GROUP
if (Index_LEAVE_GROUP_LEAVE_CODE[index].Item1 == null)
{
builder.Append("([LEAVE_GROUP] IS NULL");
}
else
{
var parameterLEAVE_GROUP = $"@p{parameterIndex++}";
builder.Append("([LEAVE_GROUP]=").Append(parameterLEAVE_GROUP);
command.Parameters.Add(parameterLEAVE_GROUP, SqlDbType.VarChar, 8).Value = Index_LEAVE_GROUP_LEAVE_CODE[index].Item1;
}
// LEAVE_CODE
if (Index_LEAVE_GROUP_LEAVE_CODE[index].Item2 == null)
{
builder.Append(" AND [LEAVE_CODE] IS NULL)");
}
else
{
var parameterLEAVE_CODE = $"@p{parameterIndex++}";
builder.Append(" AND [LEAVE_CODE]=").Append(parameterLEAVE_CODE).Append(")");
command.Parameters.Add(parameterLEAVE_CODE, SqlDbType.VarChar, 8).Value = Index_LEAVE_GROUP_LEAVE_CODE[index].Item2;
}
}
builder.AppendLine(") OR");
// Index_PLTKEY
builder.Append("[PLTKEY] IN (");
for (int index = 0; index < Index_PLTKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// PLTKEY
var parameterPLTKEY = $"@p{parameterIndex++}";
builder.Append(parameterPLTKEY);
command.Parameters.Add(parameterPLTKEY, SqlDbType.VarChar, 16).Value = Index_PLTKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the PLT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the PLT data set</returns>
public override EduHubDataSetDataReader<PLT> GetDataSetDataReader()
{
return new PLTDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the PLT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the PLT data set</returns>
public override EduHubDataSetDataReader<PLT> GetDataSetDataReader(List<PLT> Entities)
{
return new PLTDataReader(new EduHubDataSetLoadedReader<PLT>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class PLTDataReader : EduHubDataSetDataReader<PLT>
{
public PLTDataReader(IEduHubDataSetReader<PLT> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 38; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // PLTKEY
return Current.PLTKEY;
case 1: // LEAVE_GROUP
return Current.LEAVE_GROUP;
case 2: // LEAVE_CODE
return Current.LEAVE_CODE;
case 3: // CALC_METHOD
return Current.CALC_METHOD;
case 4: // PERIOD_ALLOT01
return Current.PERIOD_ALLOT01;
case 5: // PERIOD_ALLOT02
return Current.PERIOD_ALLOT02;
case 6: // PERIOD_ALLOT03
return Current.PERIOD_ALLOT03;
case 7: // PERIOD_ALLOT04
return Current.PERIOD_ALLOT04;
case 8: // PERIOD_ALLOT05
return Current.PERIOD_ALLOT05;
case 9: // PERIOD_ALLOT06
return Current.PERIOD_ALLOT06;
case 10: // PERIOD_ALLOT07
return Current.PERIOD_ALLOT07;
case 11: // PERIOD_ALLOT08
return Current.PERIOD_ALLOT08;
case 12: // PERIOD_ALLOT09
return Current.PERIOD_ALLOT09;
case 13: // PERIOD_ALLOT10
return Current.PERIOD_ALLOT10;
case 14: // PERIOD_ALLOT11
return Current.PERIOD_ALLOT11;
case 15: // PERIOD_ALLOT12
return Current.PERIOD_ALLOT12;
case 16: // PERIOD_LENGTH01
return Current.PERIOD_LENGTH01;
case 17: // PERIOD_LENGTH02
return Current.PERIOD_LENGTH02;
case 18: // PERIOD_LENGTH03
return Current.PERIOD_LENGTH03;
case 19: // PERIOD_LENGTH04
return Current.PERIOD_LENGTH04;
case 20: // PERIOD_LENGTH05
return Current.PERIOD_LENGTH05;
case 21: // PERIOD_LENGTH06
return Current.PERIOD_LENGTH06;
case 22: // PERIOD_LENGTH07
return Current.PERIOD_LENGTH07;
case 23: // PERIOD_LENGTH08
return Current.PERIOD_LENGTH08;
case 24: // PERIOD_LENGTH09
return Current.PERIOD_LENGTH09;
case 25: // PERIOD_LENGTH10
return Current.PERIOD_LENGTH10;
case 26: // PERIOD_LENGTH11
return Current.PERIOD_LENGTH11;
case 27: // PERIOD_LENGTH12
return Current.PERIOD_LENGTH12;
case 28: // PERIOD_UNITS
return Current.PERIOD_UNITS;
case 29: // ANNUAL_ENTITLEMENT
return Current.ANNUAL_ENTITLEMENT;
case 30: // ROLL_OVER
return Current.ROLL_OVER;
case 31: // ROLL_PERCENT
return Current.ROLL_PERCENT;
case 32: // LEAVE_LOADING
return Current.LEAVE_LOADING;
case 33: // LOADING_PERCENT
return Current.LOADING_PERCENT;
case 34: // ACTIVE
return Current.ACTIVE;
case 35: // LW_DATE
return Current.LW_DATE;
case 36: // LW_TIME
return Current.LW_TIME;
case 37: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // LEAVE_GROUP
return Current.LEAVE_GROUP == null;
case 2: // LEAVE_CODE
return Current.LEAVE_CODE == null;
case 3: // CALC_METHOD
return Current.CALC_METHOD == null;
case 4: // PERIOD_ALLOT01
return Current.PERIOD_ALLOT01 == null;
case 5: // PERIOD_ALLOT02
return Current.PERIOD_ALLOT02 == null;
case 6: // PERIOD_ALLOT03
return Current.PERIOD_ALLOT03 == null;
case 7: // PERIOD_ALLOT04
return Current.PERIOD_ALLOT04 == null;
case 8: // PERIOD_ALLOT05
return Current.PERIOD_ALLOT05 == null;
case 9: // PERIOD_ALLOT06
return Current.PERIOD_ALLOT06 == null;
case 10: // PERIOD_ALLOT07
return Current.PERIOD_ALLOT07 == null;
case 11: // PERIOD_ALLOT08
return Current.PERIOD_ALLOT08 == null;
case 12: // PERIOD_ALLOT09
return Current.PERIOD_ALLOT09 == null;
case 13: // PERIOD_ALLOT10
return Current.PERIOD_ALLOT10 == null;
case 14: // PERIOD_ALLOT11
return Current.PERIOD_ALLOT11 == null;
case 15: // PERIOD_ALLOT12
return Current.PERIOD_ALLOT12 == null;
case 16: // PERIOD_LENGTH01
return Current.PERIOD_LENGTH01 == null;
case 17: // PERIOD_LENGTH02
return Current.PERIOD_LENGTH02 == null;
case 18: // PERIOD_LENGTH03
return Current.PERIOD_LENGTH03 == null;
case 19: // PERIOD_LENGTH04
return Current.PERIOD_LENGTH04 == null;
case 20: // PERIOD_LENGTH05
return Current.PERIOD_LENGTH05 == null;
case 21: // PERIOD_LENGTH06
return Current.PERIOD_LENGTH06 == null;
case 22: // PERIOD_LENGTH07
return Current.PERIOD_LENGTH07 == null;
case 23: // PERIOD_LENGTH08
return Current.PERIOD_LENGTH08 == null;
case 24: // PERIOD_LENGTH09
return Current.PERIOD_LENGTH09 == null;
case 25: // PERIOD_LENGTH10
return Current.PERIOD_LENGTH10 == null;
case 26: // PERIOD_LENGTH11
return Current.PERIOD_LENGTH11 == null;
case 27: // PERIOD_LENGTH12
return Current.PERIOD_LENGTH12 == null;
case 28: // PERIOD_UNITS
return Current.PERIOD_UNITS == null;
case 29: // ANNUAL_ENTITLEMENT
return Current.ANNUAL_ENTITLEMENT == null;
case 30: // ROLL_OVER
return Current.ROLL_OVER == null;
case 31: // ROLL_PERCENT
return Current.ROLL_PERCENT == null;
case 32: // LEAVE_LOADING
return Current.LEAVE_LOADING == null;
case 33: // LOADING_PERCENT
return Current.LOADING_PERCENT == null;
case 34: // ACTIVE
return Current.ACTIVE == null;
case 35: // LW_DATE
return Current.LW_DATE == null;
case 36: // LW_TIME
return Current.LW_TIME == null;
case 37: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // PLTKEY
return "PLTKEY";
case 1: // LEAVE_GROUP
return "LEAVE_GROUP";
case 2: // LEAVE_CODE
return "LEAVE_CODE";
case 3: // CALC_METHOD
return "CALC_METHOD";
case 4: // PERIOD_ALLOT01
return "PERIOD_ALLOT01";
case 5: // PERIOD_ALLOT02
return "PERIOD_ALLOT02";
case 6: // PERIOD_ALLOT03
return "PERIOD_ALLOT03";
case 7: // PERIOD_ALLOT04
return "PERIOD_ALLOT04";
case 8: // PERIOD_ALLOT05
return "PERIOD_ALLOT05";
case 9: // PERIOD_ALLOT06
return "PERIOD_ALLOT06";
case 10: // PERIOD_ALLOT07
return "PERIOD_ALLOT07";
case 11: // PERIOD_ALLOT08
return "PERIOD_ALLOT08";
case 12: // PERIOD_ALLOT09
return "PERIOD_ALLOT09";
case 13: // PERIOD_ALLOT10
return "PERIOD_ALLOT10";
case 14: // PERIOD_ALLOT11
return "PERIOD_ALLOT11";
case 15: // PERIOD_ALLOT12
return "PERIOD_ALLOT12";
case 16: // PERIOD_LENGTH01
return "PERIOD_LENGTH01";
case 17: // PERIOD_LENGTH02
return "PERIOD_LENGTH02";
case 18: // PERIOD_LENGTH03
return "PERIOD_LENGTH03";
case 19: // PERIOD_LENGTH04
return "PERIOD_LENGTH04";
case 20: // PERIOD_LENGTH05
return "PERIOD_LENGTH05";
case 21: // PERIOD_LENGTH06
return "PERIOD_LENGTH06";
case 22: // PERIOD_LENGTH07
return "PERIOD_LENGTH07";
case 23: // PERIOD_LENGTH08
return "PERIOD_LENGTH08";
case 24: // PERIOD_LENGTH09
return "PERIOD_LENGTH09";
case 25: // PERIOD_LENGTH10
return "PERIOD_LENGTH10";
case 26: // PERIOD_LENGTH11
return "PERIOD_LENGTH11";
case 27: // PERIOD_LENGTH12
return "PERIOD_LENGTH12";
case 28: // PERIOD_UNITS
return "PERIOD_UNITS";
case 29: // ANNUAL_ENTITLEMENT
return "ANNUAL_ENTITLEMENT";
case 30: // ROLL_OVER
return "ROLL_OVER";
case 31: // ROLL_PERCENT
return "ROLL_PERCENT";
case 32: // LEAVE_LOADING
return "LEAVE_LOADING";
case 33: // LOADING_PERCENT
return "LOADING_PERCENT";
case 34: // ACTIVE
return "ACTIVE";
case 35: // LW_DATE
return "LW_DATE";
case 36: // LW_TIME
return "LW_TIME";
case 37: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "PLTKEY":
return 0;
case "LEAVE_GROUP":
return 1;
case "LEAVE_CODE":
return 2;
case "CALC_METHOD":
return 3;
case "PERIOD_ALLOT01":
return 4;
case "PERIOD_ALLOT02":
return 5;
case "PERIOD_ALLOT03":
return 6;
case "PERIOD_ALLOT04":
return 7;
case "PERIOD_ALLOT05":
return 8;
case "PERIOD_ALLOT06":
return 9;
case "PERIOD_ALLOT07":
return 10;
case "PERIOD_ALLOT08":
return 11;
case "PERIOD_ALLOT09":
return 12;
case "PERIOD_ALLOT10":
return 13;
case "PERIOD_ALLOT11":
return 14;
case "PERIOD_ALLOT12":
return 15;
case "PERIOD_LENGTH01":
return 16;
case "PERIOD_LENGTH02":
return 17;
case "PERIOD_LENGTH03":
return 18;
case "PERIOD_LENGTH04":
return 19;
case "PERIOD_LENGTH05":
return 20;
case "PERIOD_LENGTH06":
return 21;
case "PERIOD_LENGTH07":
return 22;
case "PERIOD_LENGTH08":
return 23;
case "PERIOD_LENGTH09":
return 24;
case "PERIOD_LENGTH10":
return 25;
case "PERIOD_LENGTH11":
return 26;
case "PERIOD_LENGTH12":
return 27;
case "PERIOD_UNITS":
return 28;
case "ANNUAL_ENTITLEMENT":
return 29;
case "ROLL_OVER":
return 30;
case "ROLL_PERCENT":
return 31;
case "LEAVE_LOADING":
return 32;
case "LOADING_PERCENT":
return 33;
case "ACTIVE":
return 34;
case "LW_DATE":
return 35;
case "LW_TIME":
return 36;
case "LW_USER":
return 37;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
|
using HoloToolkit.Unity;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Networking;
public class AuthorizationManager : Singleton<AuthorizationManager>
{
[SerializeField]
private string clientId = "c4ced10f-ce0f-4155-b6f7-a4c40ffa410c";
private string clientSecret;
[SerializeField]
private string debugToken;
private string accessToken;
private string authorizationCode;
const string learningLayersAuthorizationEndpoint = "https://api.learning-layers.eu/o/oauth2/authorize";
const string learningLayersTokenEndpoint = "https://api.learning-layers.eu/o/oauth2/token";
const string learningLayersUserInfoEndpoint = "https://api.learning-layers.eu/o/oauth2/userinfo";
const string scopes = "openid%20profile%20email";
const string gamrRedirectURI = "gamr://";
public string AccessToken { get { return accessToken; } }
private void Start()
{
// skip the login by using the debug token
if (Application.isEditor)
{
if (accessToken == null || accessToken == "")
{
accessToken = debugToken;
AddAccessTokenToHeader();
RestManager.Instance.GET(learningLayersUserInfoEndpoint + "?access_token=" + accessToken, GetUserInfoForDebugToken);
}
}
else // else: fetch the client secret
{
TextAsset secretAsset = (TextAsset)Resources.Load("values/client_secret");
clientSecret = secretAsset.text;
}
}
private void GetUserInfoForDebugToken(UnityWebRequest req)
{
if (req.responseCode == 200)
{
string json = req.downloadHandler.text;
Debug.Log(json);
UserInfo info = JsonUtility.FromJson<UserInfo>(json);
InformationManager.Instance.UserInfo = info;
}
else if (req.responseCode == 401)
{
Debug.LogError("Unauthorized: access token is wrong");
}
}
public void Login()
{
if (Application.isEditor)
{
SceneManager.LoadScene("Scene", LoadSceneMode.Single);
return;
}
Application.OpenURL(learningLayersAuthorizationEndpoint + "?response_type=code&scope=" + scopes + "&client_id=" + clientId + "&redirect_uri=" + gamrRedirectURI);
}
public void Logout()
{
accessToken = "";
SceneManager.LoadScene("Login", LoadSceneMode.Single);
}
private void StartedByProtocol(Uri uri)
{
if (uri.Fragment != null)
{
char[] splitters = { '?', '&' };
string[] arguments = uri.AbsoluteUri.Split(splitters);
foreach (string argument in arguments)
{
if (argument.StartsWith("code="))
{
authorizationCode = argument.Replace("code=", "");
Debug.Log("authorizationCode: " + authorizationCode);
// now exchange authorization code for access token
RestManager.Instance.POST(learningLayersTokenEndpoint + "?code=" + authorizationCode + "&client_id=" + clientId +
"&client_secret=" + clientSecret + "&redirect_uri=" + gamrRedirectURI + "&grant_type=authorization_code", (req) =>
{
string json = req.downloadHandler.text;
Debug.Log("Token json: " + json);
AuthorizationFlowAnswer answer = JsonUtility.FromJson<AuthorizationFlowAnswer>(json);
if (!string.IsNullOrEmpty(answer.error))
{
MessageBox.Show(answer.error_description, MessageBoxType.ERROR);
}
else
{
// extract access token and check it
accessToken = answer.access_token;
Debug.Log("The access token is " + accessToken);
AddAccessTokenToHeader();
CheckAccessToken();
}
}
);
break;
}
}
}
}
private void AddAccessTokenToHeader()
{
if (RestManager.Instance.StandardHeader.ContainsKey("access_token"))
{
RestManager.Instance.StandardHeader["access_token"] = accessToken;
}
else
{
RestManager.Instance.StandardHeader.Add("access_token", accessToken);
}
}
private void CheckAccessToken()
{
RestManager.Instance.GET(learningLayersUserInfoEndpoint + "?access_token=" + accessToken, OnLogin);
}
private void OnLogin(UnityWebRequest result)
{
if (result.responseCode == 200)
{
string json = result.downloadHandler.text;
Debug.Log(json);
UserInfo info = JsonUtility.FromJson<UserInfo>(json);
InformationManager.Instance.UserInfo = info;
GamificationFramework.Instance.ValidateLogin(LoginValidated);
}
else
{
MessageBox.Show(LocalizationManager.Instance.ResolveString("Error while retrieving the user data. Login failed"), MessageBoxType.ERROR);
}
}
private void LoginValidated(UnityWebRequest req)
{
if (req.responseCode == 200)
{
SceneManager.LoadScene("Scene", LoadSceneMode.Single);
}
else if (req.responseCode == 401)
{
MessageBox.Show(LocalizationManager.Instance.ResolveString("The login could not be validated"), MessageBoxType.ERROR);
}
else
{
MessageBox.Show(LocalizationManager.Instance.ResolveString("An error concerning the user data occured. The login failed.\nCode: ") + req.responseCode + "\n" + req.downloadHandler.text, MessageBoxType.ERROR);
}
}
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace VSCodeDebug
{
// ---- Types -------------------------------------------------------------------------
public class Message
{
public int id { get; }
public string format { get; }
public dynamic variables { get; }
public dynamic showUser { get; }
public dynamic sendTelemetry { get; }
public Message(int id, string format, dynamic variables = null, bool user = true, bool telemetry = false) {
this.id = id;
this.format = format;
this.variables = variables;
this.showUser = user;
this.sendTelemetry = telemetry;
}
}
public class StackFrame
{
public int id { get; }
public Source source { get; }
public int line { get; }
public int column { get; }
public string name { get; }
public string presentationHint { get; }
public StackFrame(int id, string name, Source source, int line, int column, string hint) {
this.id = id;
this.name = name;
this.source = source;
// These should NEVER be negative
this.line = Math.Max(0, line);
this.column = Math.Max(0, column);
this.presentationHint = hint;
}
}
public class Scope
{
public string name { get; }
public int variablesReference { get; }
public bool expensive { get; }
public Scope(string name, int variablesReference, bool expensive = false) {
this.name = name;
this.variablesReference = variablesReference;
this.expensive = expensive;
}
}
public class Variable
{
public string name { get; }
public string value { get; }
public string type { get; }
public int variablesReference { get; }
public Variable(string name, string value, string type, int variablesReference = 0) {
this.name = name;
this.value = value;
this.type = type;
this.variablesReference = variablesReference;
}
}
public class Thread
{
public int id { get; }
public string name { get; }
public Thread(int id, string name) {
this.id = id;
if (name == null || name.Length == 0) {
this.name = string.Format("Thread #{0}", id);
} else {
this.name = name;
}
}
}
public class Source
{
public string name { get; }
public string path { get; }
public int sourceReference { get; }
public string presentationHint { get; }
public Source(string name, string path, int sourceReference, string hint) {
this.name = name;
this.path = path;
this.sourceReference = sourceReference;
this.presentationHint = hint;
}
}
public class Breakpoint
{
public bool verified { get; }
public int line { get; }
public Breakpoint(bool verified, int line) {
this.verified = verified;
this.line = line;
}
}
// ---- Events -------------------------------------------------------------------------
public class InitializedEvent : Event
{
public InitializedEvent()
: base("initialized") { }
}
public class StoppedEvent : Event
{
public StoppedEvent(int tid, string reasn, string txt = null)
: base("stopped", new {
threadId = tid,
reason = reasn,
text = txt
}) { }
}
public class ExitedEvent : Event
{
public ExitedEvent(int exCode)
: base("exited", new { exitCode = exCode } ) { }
}
public class TerminatedEvent : Event
{
public TerminatedEvent()
: base("terminated") { }
}
public class ThreadEvent : Event
{
public ThreadEvent(string reasn, int tid)
: base("thread", new {
reason = reasn,
threadId = tid
}) { }
}
public class OutputEvent : Event
{
public OutputEvent(string cat, string outpt)
: base("output", new {
category = cat,
output = outpt
}) { }
}
// ---- Response -------------------------------------------------------------------------
public class Capabilities : ResponseBody {
public bool supportsConfigurationDoneRequest;
public bool supportsFunctionBreakpoints;
public bool supportsConditionalBreakpoints;
public bool supportsEvaluateForHovers;
public dynamic[] exceptionBreakpointFilters;
}
public class ErrorResponseBody : ResponseBody {
public Message error { get; }
public ErrorResponseBody(Message error) {
this.error = error;
}
}
public class StackTraceResponseBody : ResponseBody
{
public StackFrame[] stackFrames { get; }
public int totalFrames { get; }
public StackTraceResponseBody(List<StackFrame> frames, int total) {
stackFrames = frames.ToArray<StackFrame>();
totalFrames = total;
}
}
public class ScopesResponseBody : ResponseBody
{
public Scope[] scopes { get; }
public ScopesResponseBody(List<Scope> scps) {
scopes = scps.ToArray<Scope>();
}
}
public class VariablesResponseBody : ResponseBody
{
public Variable[] variables { get; }
public VariablesResponseBody(List<Variable> vars) {
variables = vars.ToArray<Variable>();
}
}
public class ThreadsResponseBody : ResponseBody
{
public Thread[] threads { get; }
public ThreadsResponseBody(List<Thread> ths) {
threads = ths.ToArray<Thread>();
}
}
public class EvaluateResponseBody : ResponseBody
{
public string result { get; }
public int variablesReference { get; }
public EvaluateResponseBody(string value, int reff = 0) {
result = value;
variablesReference = reff;
}
}
public class SetBreakpointsResponseBody : ResponseBody
{
public Breakpoint[] breakpoints { get; }
public SetBreakpointsResponseBody(List<Breakpoint> bpts = null) {
if (bpts == null)
breakpoints = new Breakpoint[0];
else
breakpoints = bpts.ToArray<Breakpoint>();
}
}
// ---- The Session --------------------------------------------------------
public abstract class DebugSession : ProtocolServer
{
private bool _clientLinesStartAt1 = true;
private bool _clientPathsAreURI = true;
public DebugSession()
{
}
public void SendResponse(Response response, dynamic body = null)
{
if (body != null) {
response.SetBody(body);
}
SendMessage(response);
}
public void SendErrorResponse(Response response, int id, string format, dynamic arguments = null, bool user = true, bool telemetry = false)
{
var msg = new Message(id, format, arguments, user, telemetry);
var message = Utilities.ExpandVariables(msg.format, msg.variables);
response.SetErrorBody(message, new ErrorResponseBody(msg));
SendMessage(response);
}
protected override void DispatchRequest(string command, dynamic args, Response response)
{
if (args == null) {
args = new { };
}
try {
switch (command) {
case "initialize":
if (args.linesStartAt1 != null) {
_clientLinesStartAt1 = (bool)args.linesStartAt1;
}
var pathFormat = (string)args.pathFormat;
if (pathFormat != null) {
switch (pathFormat) {
case "uri":
_clientPathsAreURI = true;
break;
case "path":
_clientPathsAreURI = false;
break;
default:
SendErrorResponse(response, 1015, "initialize: bad value '{_format}' for pathFormat", new { _format = pathFormat });
return;
}
}
Initialize(response, args);
break;
case "launch":
Launch(response, args);
break;
case "attach":
Attach(response, args);
break;
case "disconnect":
Disconnect(response, args);
break;
case "next":
Next(response, args);
break;
case "continue":
Continue(response, args);
break;
case "stepIn":
StepIn(response, args);
break;
case "stepOut":
StepOut(response, args);
break;
case "pause":
Pause(response, args);
break;
case "stackTrace":
StackTrace(response, args);
break;
case "scopes":
Scopes(response, args);
break;
case "variables":
Variables(response, args);
break;
case "source":
Source(response, args);
break;
case "threads":
Threads(response, args);
break;
case "setBreakpoints":
SetBreakpoints(response, args);
break;
case "setFunctionBreakpoints":
SetFunctionBreakpoints(response, args);
break;
case "setExceptionBreakpoints":
SetExceptionBreakpoints(response, args);
break;
case "evaluate":
Evaluate(response, args);
break;
default:
SendErrorResponse(response, 1014, "unrecognized request: {_request}", new { _request = command });
break;
}
}
catch (Exception e) {
SendErrorResponse(response, 1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = e.Message });
}
if (command == "disconnect") {
Stop();
}
}
public abstract void Initialize(Response response, dynamic args);
public abstract void Launch(Response response, dynamic arguments);
public abstract void Attach(Response response, dynamic arguments);
public abstract void Disconnect(Response response, dynamic arguments);
public virtual void SetFunctionBreakpoints(Response response, dynamic arguments)
{
}
public virtual void SetExceptionBreakpoints(Response response, dynamic arguments)
{
}
public abstract void SetBreakpoints(Response response, dynamic arguments);
public abstract void Continue(Response response, dynamic arguments);
public abstract void Next(Response response, dynamic arguments);
public abstract void StepIn(Response response, dynamic arguments);
public abstract void StepOut(Response response, dynamic arguments);
public abstract void Pause(Response response, dynamic arguments);
public abstract void StackTrace(Response response, dynamic arguments);
public abstract void Scopes(Response response, dynamic arguments);
public abstract void Variables(Response response, dynamic arguments);
public abstract void Source(Response response, dynamic arguments);
public abstract void Threads(Response response, dynamic arguments);
public abstract void Evaluate(Response response, dynamic arguments);
// protected
protected int ConvertDebuggerLineToClient(int line)
{
return _clientLinesStartAt1 ? line : line - 1;
}
protected int ConvertClientLineToDebugger(int line)
{
return _clientLinesStartAt1 ? line : line + 1;
}
protected string ConvertDebuggerPathToClient(string path)
{
if (_clientPathsAreURI) {
try {
var uri = new System.Uri(path);
return uri.AbsoluteUri;
}
catch {
return null;
}
}
else {
return path;
}
}
protected string ConvertClientPathToDebugger(string clientPath)
{
if (clientPath == null) {
return null;
}
if (_clientPathsAreURI) {
if (Uri.IsWellFormedUriString(clientPath, UriKind.Absolute)) {
Uri uri = new Uri(clientPath);
return uri.LocalPath;
}
Program.Log("path not well formed: '{0}'", clientPath);
return null;
}
else {
return clientPath;
}
}
}
}
|
//
// GuidExtensions.cs
//
// Author:
// Craig Fowler <craig@csf-dev.com>
//
// Copyright (c) 2015 CSF Software Limited
//
// 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;
namespace CSF
{
/// <summary>
/// Extension methods for the <c>System.Guid</c> type.
/// </summary>
public static class GuidExtensions
{
#region constants
private const int GUID_BYTE_COUNT = 16;
private static readonly int[] REORDERING_MAP = new[] { 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15 };
#endregion
#region extension methods
/// <summary>
/// Returns a byte array representing the given <c>System.Guid</c> in an RFC-4122 compliant format.
/// </summary>
/// <remarks>
/// <para>
/// The rationale for this method (and the reason for requiring it) is because Microsoft internally represent the
/// GUID structure in a manner which does not comply with RFC-4122's definition of a UUID. The first three blocks
/// of data (out of 4 total) are stored using the machine's native endianness. The RFC defines that these three
/// blocks should be represented in big-endian format. This does not cause a problem when getting a
/// string-representation of the GUID, since the framework automatically converts to big-endian format before
/// formatting as a string. When getting a byte array equivalent of the GUID though, it can cause issues if the
/// recipient of that byte array expects a standards-compliant UUID.
/// </para>
/// <para>
/// This method checks the architecture of the current machine. If it is little-endian then - before returning a
/// value - the byte-order of the first three blocks of data are reversed. If the machine is big-endian then the
/// bytes are left untouched (since they are already correct).
/// </para>
/// <para>
/// For more information, see https://en.wikipedia.org/wiki/Globally_unique_identifier#Binary_encoding
/// </para>
/// </remarks>
/// <returns>
/// A byte array representation of the GUID, in RFC-4122 compliant form.
/// </returns>
/// <param name='guid'>
/// The GUID for which to get the byte array.
/// </param>
public static byte[] ToRFC4122ByteArray(this Guid guid)
{
return BitConverter.IsLittleEndian? ReorderBytes(guid.ToByteArray()) : guid.ToByteArray();
}
/// <summary>
/// Returns a <c>System.Guid</c>, created from the given RFC-4122 compliant byte array.
/// </summary>
/// <remarks>
/// <para>
/// The rationale for this method (and the reason for requiring it) is because Microsoft internally represent the
/// GUID structure in a manner which does not comply with RFC-4122's definition of a UUID. The first three blocks
/// of data (out of 4 total) are stored using the machine's native endianness. The RFC defines that these three
/// blocks should be represented in big-endian format. This does not cause a problem when getting a
/// string-representation of the GUID, since the framework automatically converts to big-endian format before
/// formatting as a string. When getting a byte array equivalent of the GUID though, it can cause issues if the
/// recipient of that byte array expects a standards-compliant UUID.
/// </para>
/// <para>
/// This method checks the architecture of the current machine. If it is little-endian then - before returning a
/// value - the byte-order of the first three blocks of data are reversed. If the machine is big-endian then the
/// bytes are left untouched (since they are already correct).
/// </para>
/// <para>
/// For more information, see https://en.wikipedia.org/wiki/Globally_unique_identifier#Binary_encoding
/// </para>
/// </remarks>
/// <returns>
/// A GUID, created from the given byte array.
/// </returns>
/// <param name='guidBytes'>
/// A byte array representing a GUID, in RFC-4122 compliant form.
/// </param>
public static Guid FromRFC4122ByteArray(this byte[] guidBytes)
{
return new Guid(BitConverter.IsLittleEndian? ReorderBytes(guidBytes) : guidBytes);
}
#endregion
#region static methods
/// <summary>
/// Copies a byte array that represents a GUID, reversing the order of the bytes in data-blocks one to three.
/// </summary>
/// <returns>
/// A copy of the original byte array, with the modifications.
/// </returns>
/// <param name='guidBytes'>
/// A byte array representing a GUID.
/// </param>
public static byte[] ReorderBytes(byte[] guidBytes)
{
if(guidBytes == null)
{
throw new ArgumentNullException(nameof(guidBytes));
}
else if(guidBytes.Length != GUID_BYTE_COUNT)
{
throw new ArgumentException(Resources.ExceptionMessages.MustBeSixteenBytesInAGuid, nameof(guidBytes));
}
byte[] output = new byte[GUID_BYTE_COUNT];
for(int i = 0; i < GUID_BYTE_COUNT; i++)
{
output[i] = guidBytes[REORDERING_MAP[i]];
}
return output;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace NAudio.Lame
{
/// <summary>
/// Decoder for ID3v2 tags
/// </summary>
public static class ID3Decoder
{
/// <summary>
/// Read an ID3v2 Tag from the current position in a stream.
/// </summary>
/// <param name="stream"><see cref="Stream"/> positioned at start of ID3v2 Tag.</param>
/// <returns><see cref="ID3TagData"/> with tag content.</returns>
public static ID3TagData Decode(Stream stream)
{
byte[] header = new byte[10];
int rc = stream.Read(header, 0, 10);
if (rc != 10 || !ValidateTagHeader(header))
throw new InvalidDataException("Bad ID3 Tag Header");
// decode size field and confirm range
int size = DecodeHeaderSize(header, 6);
if (size < 10 || size >= (1 << 28))
throw new InvalidDataException($"ID3 header size '{size:#,0}' out of range.");
// Load entire tag into buffer and parse
var buffer = new byte[10 + size];
#pragma warning disable IDE0059 // Unnecessary assignment of a value
rc = stream.Read(buffer, 0, buffer.Length);
#pragma warning restore IDE0059 // Unnecessary assignment of a value
return InternalDecode(buffer, 0, size, header[5]);
}
/// <summary>
/// Read an ID3v2 Tag from the supplied array.
/// </summary>
/// <param name="buffer">Array containing complete ID3v2 Tag.</param>
/// <returns><see cref="ID3TagData"/> with tag content.</returns>
public static ID3TagData Decode(byte[] buffer)
{
// Check header
if (!ValidateTagHeader(buffer))
throw new InvalidDataException("Bad ID3 Tag Header");
// decode size field and confirm range
int size = DecodeHeaderSize(buffer, 6);
if (size < 10 || size > (buffer.Length - 10))
throw new InvalidDataException($"ID3 header size '{size:#,0}' out of range.");
// Decode tag content
return InternalDecode(buffer, 10, size, buffer[5]);
}
/// <summary>
/// Decode frames from ID3 tag
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="size"></param>
/// <param name="flags"></param>
/// <returns></returns>
private static ID3TagData InternalDecode(byte[] buffer, int offset, int size, byte flags)
{
// copy tag body data into array and remove unsynchronization padding if present
byte[] bytes = new byte[size];
Array.Copy(buffer, offset, bytes, 0, size);
if ((flags & 0x80) != 0)
bytes = UnsyncBytes(bytes);
var res = new ID3TagData();
int pos = 0;
// skip extended header if present
if ((flags & 0x40) != 0)
{
var ehSize = DecodeBEInt32(bytes, pos);
pos += ehSize + 4;
}
// load all frames from the tag buffer
for (var frame = ID3FrameData.ReadFrame(bytes, pos, out int frameSize); frameSize > 0 && frame != null; frame = ID3FrameData.ReadFrame(bytes, pos, out frameSize))
{
switch (frame.FrameID)
{
case "TIT2":
res.Title = frame.ParseString();
break;
case "TPE1":
res.Artist = frame.ParseString();
break;
case "TALB":
res.Album = frame.ParseString();
break;
case "TYER":
res.Year = frame.ParseString();
break;
case "COMM":
res.Comment = frame.ParseCommentText();
break;
case "TCON":
res.Genre = frame.ParseString();
break;
case "TRCK":
res.Track = frame.ParseString();
break;
case "TIT3":
res.Subtitle = frame.ParseString();
break;
case "TPE2":
res.AlbumArtist = frame.ParseString();
break;
case "TXXX":
{
var udt = frame.ParseUserDefinedText();
res.UserDefinedText[udt.Key] = udt.Value;
break;
}
case "APIC":
{
var pic = frame.ParseAPIC();
res.AlbumArt = pic?.ImageBytes;
break;
}
default:
break;
}
pos += frameSize;
}
return res;
}
/// <summary>
/// Check ID3v2 tag header is correctly formed
/// </summary>
/// <param name="buffer">Array containing ID3v2 header</param>
/// <returns>True if checks pass, else false</returns>
private static bool ValidateTagHeader(byte[] buffer)
=> buffer?.Length >= 4 && buffer[0] == 'I' && buffer[1] == 'D' && buffer[2] == '3' && buffer[3] == 3 && buffer[4] == 0;
/// <summary>
/// Decode a 28-bit integer stored in the low 7 bits of 4 bytes at the offset, most-significant bits first (big-endian).
/// </summary>
/// <param name="buffer">Array containing value to decode.</param>
/// <param name="offset">Offset in array of the 4 bytes containing the value.</param>
/// <returns>Decoded value.</returns>
private static int DecodeHeaderSize(byte[] buffer, int offset)
=> (int)(
((uint)buffer[offset] << 21) |
((uint)buffer[offset + 1] << 14) |
((uint)buffer[offset + 2] << 7) |
buffer[offset + 3]
);
/// <summary>
/// Read 16-bit integer from <paramref name="buffer"/> as 2 big-endian bytes at <paramref name="offset"/>.
/// </summary>
/// <param name="buffer">Byte array containing value.</param>
/// <param name="offset">Offset in byte array to start of value.</param>
/// <returns>16-bit integer value.</returns>
private static short DecodeBEInt16(byte[] buffer, int offset)
=> (short)((buffer[offset] << 8) | buffer[offset + 1]);
/// <summary>
/// Read 32-bit integer from <paramref name="buffer"/> as 4 big-endian bytes at <paramref name="offset"/>.
/// </summary>
/// <param name="buffer">Byte array containing value.</param>
/// <param name="offset">Offset in byte array to start of value.</param>
/// <returns>32-bit integer value.</returns>
private static int DecodeBEInt32(byte[] buffer, int offset)
=> ((buffer[offset] << 24) | (buffer[offset + 1] << 16) | (buffer[offset + 2] << 8) | (buffer[offset + 3]));
/// <summary>
/// Remove NUL bytes inserted by 'unsynchronisation' of data buffer.
/// </summary>
/// <param name="buffer">Buffer with 'unsynchronized' data.</param>
/// <returns>New array with insertions removed.</returns>
private static byte[] UnsyncBytes(IEnumerable<byte> buffer)
{
IEnumerable<byte> ProcessBuffer()
{
byte prev = 0;
foreach (var b in buffer)
{
if (b != 0 || prev != 0xFF)
yield return b;
prev = b;
}
}
return ProcessBuffer().ToArray();
}
/// <summary>
/// Represents an ID3 frame read from the tag.
/// </summary>
private class ID3FrameData
{
/// <summary>
/// Four-character Frame ID.
/// </summary>
public readonly string FrameID;
/// <summary>
/// Size of the frame in bytes, not including the header. Should equal the size of the Data buffer.
/// </summary>
public readonly int Size;
/// <summary>
/// Frame header flags.
/// </summary>
public readonly short Flags;
/// <summary>
/// Frame content as bytes.
/// </summary>
public readonly byte[] Data;
// private constructor
private ID3FrameData(string frameID, int size, short flags, byte[] data)
{
FrameID = frameID;
Size = size;
Flags = flags;
Data = data;
}
/// <summary>
/// Read an ID3v2 content frame from the supplied buffer.
/// </summary>
/// <param name="buffer">Array containing content frame data.</param>
/// <param name="offset">Offset of start of content frame data.</param>
/// <param name="size">Output: total bytes consumed by frame, including header, or -1 if no frame available.</param>
/// <returns><see cref="ID3FrameData"/> with frame, or null if no frame available.</returns>
public static ID3FrameData ReadFrame(byte[] buffer, int offset, out int size)
{
size = -1;
if ((buffer.Length - offset) <= 10)
return null;
// Extract header data
string frameID = Encoding.ASCII.GetString(buffer, offset, 4);
int frameLength = DecodeBEInt32(buffer, offset + 4);
short frameFlags = DecodeBEInt16(buffer, offset + 8);
// copy frame content to byte array
byte[] content = new byte[frameLength];
Array.Copy(buffer, offset + 10, content, 0, frameLength);
// Decompress if necessary
if ((frameFlags & 0x80) != 0)
{
using (var ms = new MemoryStream())
using (var dec = new DeflateStream(new MemoryStream(content), CompressionMode.Decompress))
{
dec.CopyTo(ms);
content = ms.ToArray();
}
}
// return frame
size = 10 + frameLength;
return new ID3FrameData(frameID, frameLength, frameFlags, content);
}
/// <summary>
/// Read an ASCII string from an array, NUL-terminated or optionally end of buffer.
/// </summary>
/// <param name="buffer">Array containing ASCII string.</param>
/// <param name="offset">Start of string in array.</param>
/// <param name="requireTerminator">If true then fail if no terminator found.</param>
/// <returns>String from buffer, string.Empty if 0-length, null on failure.</returns>
private static string GetASCIIString(byte[] buffer, ref int offset, bool requireTerminator)
{
int start = offset;
int position = offset;
for (; position < buffer.Length && buffer[position] != 0; position++) ;
if (requireTerminator && position >= buffer.Length)
return null;
int length = position - start;
offset = position + 1;
return length < 1 ? string.Empty : Encoding.ASCII.GetString(buffer, start, length);
}
/// <summary>
/// Read a Unicode string from an array, NUL-terminated or optionally end of buffer.
/// </summary>
/// <param name="buffer">Array containing ASCII string.</param>
/// <param name="offset">Start of string in array.</param>
/// <param name="requireTerminator">If true then fail if no terminator found.</param>
/// <returns>String from buffer, string.Empty if 0-length, null on failure.</returns>
private static string GetUnicodeString(byte[] buffer, ref int offset, bool requireTerminator = true)
{
int start = offset;
int position = offset;
for (; position < buffer.Length - 1 && (buffer[position] != 0 || buffer[position + 1] != 0); position += 2) ;
if (requireTerminator && position >= buffer.Length)
return null;
int length = position - start;
offset = position + 2;
string res = LameDLLWrap.UCS2.GetString(buffer, start, length);
return res;
}
delegate string delGetString(byte[] buffer, ref int offset, bool requireTeminator);
private delGetString GetGetString()
{
byte encoding = Data[0];
if (encoding == 0)
return GetASCIIString;
if (encoding == 1)
return GetUnicodeString;
throw new InvalidDataException($"Invalid string encoding: {encoding}");
}
/// <summary>
/// Parse the frame content as a string.
/// </summary>
/// <returns>String content, string.Empty if 0-length.</returns>
/// <exception cref="InvalidDataException">Invalid string encoding.</exception>
public string ParseString()
{
int position = 1;
return GetGetString()(Data, ref position, false);
}
/// <summary>
/// Parse the frame content as a Comment (COMM) frame, return comment text only.
/// </summary>
/// <returns>Comment text only. Language and short description omitted.</returns>
public string ParseCommentText()
{
var getstr = GetGetString();
int position = 1;
string language = Encoding.ASCII.GetString(Data, position, 3);
position += 3;
string shortdesc = getstr(Data, ref position, true);
string comment = getstr(Data, ref position, false);
return comment;
}
/// <summary>
/// Parse the frame content as a User-Defined Text Information (TXXX) frame.
/// </summary>
/// <returns><see cref="KeyValuePair{TKey, TValue}"/> with content, or exception on error.</returns>
public KeyValuePair<string, string> ParseUserDefinedText()
{
byte encoding = Data[0];
delGetString getstring;
if (encoding == 0)
getstring = GetASCIIString;
else if (encoding == 1)
getstring = GetUnicodeString;
else
throw new InvalidDataException($"Unknown string encoding: {encoding}");
int position = 1;
string description = getstring(Data, ref position, true);
string value = getstring(Data, ref position, false);
return new KeyValuePair<string, string>(description, value);
}
/// <summary>
/// Parse the frame content as an attached picture (APIC) frame.
/// </summary>
/// <returns><see cref="APICData"/> object </returns>
public APICData ParseAPIC()
{
if (FrameID != "APIC")
return null;
var getstr = GetGetString();
// get attributes
int position = 1;
string mime = getstr(Data, ref position, true);
byte type = Data[position++];
string description = getstr(Data, ref position, true);
// get image content
int datalength = Data.Length - position;
byte[] imgdata = new byte[datalength];
Array.Copy(Data, position, imgdata, 0, datalength);
return new APICData
{
MIMEType = mime,
ImageType = type,
Description = description,
ImageBytes = imgdata,
};
}
/// <summary>
/// Data for an Attached Picture (APIC) frame.
/// </summary>
public class APICData
{
/// <summary>
/// MIME type of contained image
/// </summary>
public string MIMEType;
/// <summary>
/// Type of image. Refer to http://id3.org/id3v2.3.0#Attached_picture for list of values.
/// </summary>
public byte ImageType;
/// <summary>
/// Picture description.
/// </summary>
public string Description;
/// <summary>
/// Picture file content.
/// </summary>
public byte[] ImageBytes;
}
}
}
}
|
// PS4Macro (File: Forms/MainForm.cs)
//
// Copyright (c) 2018 Komefai
//
// Visit http://komefai.com for more information
//
// 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 PS4Macro.Classes;
using PS4Macro.Classes.GlobalHooks;
using PS4Macro.Classes.Remapping;
using PS4RemotePlayInterceptor;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PS4Macro.Forms
{
enum ControlMode
{
Macro,
Script,
Remapper,
StatusChecker
}
public partial class MainForm : Form
{
private const string CURRENT_TICK_DEFAULT_TEXT = "-";
private GlobalKeyboardHook m_GlobalKeyboardHook;
private GlobalMouseHook m_GlobalMouseHook;
private MacroPlayer m_MacroPlayer;
private Remapper m_Remapper;
private StatusChecker m_StatusChecker;
private ControlMode m_ControlMode;
private PS4MacroAPI.ScriptBase m_SelectedScript;
private ScriptHost m_ScriptHost;
private SaveLoadHelper m_SaveLoadHelper;
private Process m_RemotePlayProcess;
/* Constructor */
public MainForm()
{
InitializeComponent();
// Setup global keyboard hook
m_GlobalKeyboardHook = new GlobalKeyboardHook();
m_GlobalKeyboardHook.KeyboardPressed += OnKeyPressed;
// Setup global mouse hook
m_GlobalMouseHook = new GlobalMouseHook();
m_GlobalMouseHook.MouseEvent += OnMouseEvent;
// Create macro player
m_MacroPlayer = new MacroPlayer();
m_MacroPlayer.Loop = true;
m_MacroPlayer.RecordShortcut = true;
m_MacroPlayer.PropertyChanged += MacroPlayer_PropertyChanged;
// Create remapper
m_Remapper = new Remapper();
// Create status checker
m_StatusChecker = new StatusChecker();
// Set control mode
SetControlMode(ControlMode.Macro);
// Create save/load helper
m_SaveLoadHelper = new SaveLoadHelper(this, m_MacroPlayer);
m_SaveLoadHelper.PropertyChanged += SaveLoadHelper_PropertyChanged;
// Initialize interceptor
InitInterceptor();
}
private void InitInterceptor()
{
// Set controller emulation based on settings
Interceptor.EmulateController = Program.Settings.EmulateController;
emulatedToolStripStatusLabel.Visible = Program.Settings.EmulateController;
// Enable watchdog based on settings
if (!Program.Settings.AutoInject)
{
Interceptor.InjectionMode = InjectionMode.Compatibility;
}
// Inject if not bypassed
if (!Program.Settings.BypassInjection)
{
// Attempt to inject into PS4 Remote Play
try
{
int pid = Interceptor.Inject();
m_RemotePlayProcess = Process.GetProcessById(pid);
// Set process
ForwardRemotePlayProcess();
}
// Injection failed
catch (InterceptorException ex)
{
// Only handle when PS4 Remote Play is in used by another injection
if (ex.InnerException != null && ex.InnerException.Message.Equals("STATUS_INTERNAL_ERROR: Unknown error in injected C++ completion routine. (Code: 15)"))
{
MessageBox.Show("The process has been injected by another executable. Restart PS4 Remote Play and try again.", "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
else
{
// Handle exception if watchdog is disabled
if (!Program.Settings.AutoInject)
{
MessageBox.Show(string.Format("[{0}] - {1}", ex.GetType(), ex.Message), "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
}
}
// Start watchdog to automatically inject when possible
if (Program.Settings.AutoInject)
{
Interceptor.Watchdog.Start();
// Watchdog callbacks
Interceptor.Watchdog.OnInjectionSuccess = () =>
{
ForwardRemotePlayProcess();
};
Interceptor.Watchdog.OnInjectionFailure = () =>
{
};
}
}
}
private void SetControlMode(ControlMode controlMode)
{
m_ControlMode = controlMode;
if (m_ControlMode == ControlMode.Macro)
{
// Stop script and remove
if (m_ScriptHost != null && m_ScriptHost.IsRunning)
{
m_ScriptHost.Stop();
m_ScriptHost = null;
}
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_MacroPlayer.OnReceiveData);
recordButton.Enabled = true;
recordToolStripMenuItem.Enabled = true;
loopCheckBox.Enabled = true;
loopCheckBox.Checked = m_MacroPlayer.Loop;
loopToolStripMenuItem.Enabled = true;
recordOnTouchToolStripMenuItem.Enabled = true;
scriptButton.Enabled = false;
saveToolStripMenuItem.Enabled = true;
saveAsToolStripMenuItem.Enabled = true;
clearMacroToolStripMenuItem.Enabled = true;
trimMacroToolStripMenuItem.Enabled = true;
}
else if (m_ControlMode == ControlMode.Script)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_ScriptHost.OnReceiveData);
recordButton.Enabled = false;
recordToolStripMenuItem.Enabled = false;
loopCheckBox.Enabled = false;
loopCheckBox.Checked = false;
loopToolStripMenuItem.Enabled = false;
recordOnTouchToolStripMenuItem.Enabled = false;
scriptButton.Enabled = true;
saveToolStripMenuItem.Enabled = false;
saveAsToolStripMenuItem.Enabled = false;
clearMacroToolStripMenuItem.Enabled = false;
trimMacroToolStripMenuItem.Enabled = false;
currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT;
}
else if (m_ControlMode == ControlMode.Remapper)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Stop script
if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop();
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_Remapper.OnReceiveData);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Stop script
if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop();
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_StatusChecker.OnReceiveData);
}
}
private void TemporarilySetControlMode(ControlMode controlMode, Action action)
{
// Store current control mode and temporarily set it
ControlMode oldControlMode = m_ControlMode;
SetControlMode(controlMode);
// Invoke action
action?.Invoke();
// Restore control mode
SetControlMode(oldControlMode);
}
private void ForwardRemotePlayProcess()
{
m_Remapper.RemotePlayProcess = m_RemotePlayProcess;
m_StatusChecker.RemotePlayProcess = m_RemotePlayProcess;
}
public void LoadMacro(string path)
{
SetControlMode(ControlMode.Macro);
m_MacroPlayer.LoadFile(path);
}
public void LoadScript(string path)
{
var script = PS4MacroAPI.Internal.ScriptUtility.LoadScript(path);
m_SelectedScript = script;
m_ScriptHost = new ScriptHost(this, m_SelectedScript);
m_ScriptHost.PropertyChanged += ScriptHost_PropertyChanged;
SetControlMode(ControlMode.Script);
}
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
if (m_ControlMode == ControlMode.Remapper)
{
m_Remapper.OnKeyPressed(sender, e);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
m_StatusChecker.OnKeyPressed(sender, e);
}
}
private void OnMouseEvent(object sender, GlobalMouseHookEventArgs e)
{
if (m_ControlMode == ControlMode.Remapper)
{
m_Remapper.OnMouseEvent(sender, e);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
m_StatusChecker.OnMouseEvent(sender, e);
}
}
private void MainForm_Load(object sender, EventArgs e)
{
// Load startup file
if (!string.IsNullOrWhiteSpace(Program.Settings.StartupFile))
m_SaveLoadHelper.DirectLoad(Program.Settings.StartupFile);
}
/* Macro Player */
#region MacroPlayer_PropertyChanged
private void UpdateCurrentTick()
{
BeginInvoke((MethodInvoker)delegate
{
// Invalid sequence
if (m_MacroPlayer.Sequence == null || m_MacroPlayer.Sequence.Count <= 0)
{
currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT;
}
// Valid sequence
else
{
currentTickToolStripStatusLabel.Text = string.Format("{0}/{1}",
m_MacroPlayer.CurrentTick.ToString(),
m_MacroPlayer.Sequence.Count.ToString()
);
}
});
}
private void MacroPlayer_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "IsPlaying":
{
playButton.ForeColor = m_MacroPlayer.IsPlaying ? Color.Green : DefaultForeColor;
break;
}
case "IsPaused":
{
playButton.ForeColor = m_MacroPlayer.IsPaused ? DefaultForeColor : playButton.ForeColor;
break;
}
case "IsRecording":
{
recordButton.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor;
currentTickToolStripStatusLabel.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor;
break;
}
case "CurrentTick":
{
UpdateCurrentTick();
break;
}
case "Sequence":
{
UpdateCurrentTick();
break;
}
case "Loop":
{
loopCheckBox.Checked = m_MacroPlayer.Loop;
loopToolStripMenuItem.Checked = m_MacroPlayer.Loop;
break;
}
case "RecordShortcut":
{
recordOnTouchToolStripMenuItem.Checked = m_MacroPlayer.RecordShortcut;
break;
}
}
}
#endregion
/* Script Host */
#region ScriptHost_PropertyChanged
private void ScriptHost_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "IsRunning":
{
playButton.ForeColor = m_ScriptHost.IsRunning ? Color.Green : DefaultForeColor;
break;
}
case "IsPaused":
{
if (m_ScriptHost.IsPaused && m_ScriptHost.IsRunning)
{
playButton.ForeColor = DefaultForeColor;
}
else if (!m_ScriptHost.IsPaused && m_ScriptHost.IsRunning)
{
playButton.ForeColor = Color.Green;
}
break;
}
}
}
#endregion
/* Save/Load Helper */
#region SaveLoadHelper_PropertyChanged
private void SaveLoadHelper_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentFile")
{
if (m_SaveLoadHelper.CurrentFile == null)
{
fileNameToolStripStatusLabel.Text = SaveLoadHelper.DEFAULT_FILE_NAME;
currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT;
}
else
{
fileNameToolStripStatusLabel.Text = System.IO.Path.GetFileName(m_SaveLoadHelper.CurrentFile);
}
}
}
#endregion
/* Playback buttons methods */
#region Playback Buttons
private void playButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Play();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Play();
}
}
private void pauseButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Pause();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Pause();
}
}
private void stopButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Stop();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Stop();
}
}
private void recordButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Record();
}
}
private void loopCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Loop = loopCheckBox.Checked;
}
}
#endregion
/* Script buttons methods */
#region Script Buttons
private void scriptButton_Click(object sender, EventArgs e)
{
m_ScriptHost.ShowForm(this);
}
#endregion
/* Menu strip methods */
#region Menu Strip
#region File
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
SetControlMode(ControlMode.Macro);
m_MacroPlayer.Clear();
m_SaveLoadHelper.ClearCurrentFile();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
m_SaveLoadHelper.Load();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
m_SaveLoadHelper.Save();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
m_SaveLoadHelper.SaveAs();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
#region Edit
private void clearMacroToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Clear();
}
}
private void trimMacroToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MacroPlayer.Stop();
var oldSequenceLength = m_MacroPlayer.Sequence.Count;
m_MacroPlayer.Sequence = MacroUtility.TrimMacro(m_MacroPlayer.Sequence);
// Show results
var difference = oldSequenceLength - m_MacroPlayer.Sequence.Count;
MessageBox.Show(
$"{difference} frames removed" + "\n\n" +
$"Before: {oldSequenceLength} frames" + "\n" +
$"After: {m_MacroPlayer.Sequence.Count} frames", "Trim Macro",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
#region Playback
private void playToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Play();
}
}
private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Pause();
}
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Stop();
}
}
private void recordToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Record();
}
}
private void loopToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Loop = !loopToolStripMenuItem.Checked;
}
}
private void recordOnTouchToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.RecordShortcut = !recordOnTouchToolStripMenuItem.Checked;
}
}
#endregion
#region Tools
private void screenshotToolStripMenuItem_Click(object sender, EventArgs e)
{
var backgroundMode = !(ModifierKeys == Keys.Shift);
var frame = PS4MacroAPI.Internal.ScriptUtility.CaptureFrame(backgroundMode);
var folder = "screenshots";
// Create folder if not exist
Directory.CreateDirectory(folder);
if (frame != null)
{
var fileName = folder + @"\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
frame.Save(fileName);
Console.WriteLine($"{DateTime.Now.ToString()} - Screenshot saved to {Path.GetFullPath(fileName)}");
}
else
{
MessageBox.Show("Unable to capture screenshot!");
}
}
private void imageHashToolToolStripMenuItem_Click(object sender, EventArgs e)
{
new ImageHashForm().Show(this);
}
private void resizeRemotePlayToolStripMenuItem_Click(object sender, EventArgs e)
{
new ResizeRemotePlayForm().ShowDialog(this);
}
private void macroCompressorToolStripMenuItem_Click(object sender, EventArgs e)
{
new MacroCompressorForm().ShowDialog(this);
}
private void remapperToolStripMenuItem_Click(object sender, EventArgs e)
{
TemporarilySetControlMode(ControlMode.Remapper, () =>
{
new RemapperForm(m_Remapper).ShowDialog(this);
});
}
#endregion
#region Help
private void statusCheckerToolStripMenuItem_Click(object sender, EventArgs e)
{
TemporarilySetControlMode(ControlMode.StatusChecker, () =>
{
m_StatusChecker.SetActive(true);
new StatusCheckerForm(m_StatusChecker).ShowDialog(this);
m_StatusChecker.SetActive(false);
});
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
var aboutForm = new AboutForm();
aboutForm.ShowDialog(this);
}
#endregion
#endregion
/* Status strip methods */
#region Status Strip
#endregion
}
}
|
namespace Azure.Security.Attestation
{
public partial class AttestationAdministrationClient : System.IDisposable
{
protected AttestationAdministrationClient() { }
public AttestationAdministrationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
public AttestationAdministrationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Security.Attestation.AttestationClientOptions options) { }
public System.Uri Endpoint { get { throw null; } }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult> AddPolicyManagementCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 newSigningCertificate, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult>> AddPolicyManagementCertificateAsync(System.Security.Cryptography.X509Certificates.X509Certificate2 newSigningCertificate, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual Azure.Security.Attestation.AttestationResponse<string> GetPolicy(Azure.Security.Attestation.AttestationType attestationType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<string>> GetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesResult> GetPolicyManagementCertificates(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesResult>> GetPolicyManagementCertificatesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult> RemovePolicyManagementCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificateToRemove, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyCertificatesModificationResult>> RemovePolicyManagementCertificateAsync(System.Security.Cryptography.X509Certificates.X509Certificate2 certificateToRemove, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult> ResetPolicy(Azure.Security.Attestation.AttestationType attestationType, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult>> ResetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult> SetPolicy(Azure.Security.Attestation.AttestationType attestationType, string policyToSet, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult>> SetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, string policyToSet, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class AttestationClient : System.IDisposable
{
protected AttestationClient() { }
public AttestationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
public AttestationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Security.Attestation.AttestationClientOptions options) { }
public System.Uri Endpoint { get { throw null; } }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult> AttestOpenEnclave(System.ReadOnlyMemory<byte> report, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult>> AttestOpenEnclaveAsync(System.ReadOnlyMemory<byte> report, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult> AttestSgxEnclave(System.ReadOnlyMemory<byte> quote, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult>> AttestSgxEnclaveAsync(System.ReadOnlyMemory<byte> quote, System.BinaryData initTimeData, bool initTimeDataIsObject, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<System.BinaryData> AttestTpm(System.BinaryData request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.BinaryData>> AttestTpmAsync(System.BinaryData request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner>> GetSigningCertificates(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner>>> GetSigningCertificatesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class AttestationClientOptions : Azure.Core.ClientOptions
{
public AttestationClientOptions(Azure.Security.Attestation.AttestationClientOptions.ServiceVersion version = Azure.Security.Attestation.AttestationClientOptions.ServiceVersion.V2020_10_01, Azure.Security.Attestation.TokenValidationOptions tokenOptions = null) { }
public enum ServiceVersion
{
V2020_10_01 = 1,
}
}
public partial class AttestationResponse<T> : Azure.Response<T> where T : class
{
internal AttestationResponse() { }
public Azure.Security.Attestation.AttestationToken Token { get { throw null; } }
public override T Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
}
public partial class AttestationResult
{
internal AttestationResult() { }
public object Confirmation { get { throw null; } }
public byte[] DeprecatedEnclaveHeldData { get { throw null; } }
public byte[] DeprecatedEnclaveHeldData2 { get { throw null; } }
public bool? DeprecatedIsDebuggable { get { throw null; } }
public string DeprecatedMrEnclave { get { throw null; } }
public string DeprecatedMrSigner { get { throw null; } }
public byte[] DeprecatedPolicyHash { get { throw null; } }
public float? DeprecatedProductId { get { throw null; } }
public string DeprecatedRpData { get { throw null; } }
public object DeprecatedSgxCollateral { get { throw null; } }
public float? DeprecatedSvn { get { throw null; } }
public string DeprecatedTee { get { throw null; } }
public string DeprecatedVersion { get { throw null; } }
public byte[] EnclaveHeldData { get { throw null; } }
public System.DateTimeOffset Expiration { get { throw null; } }
public object InittimeClaims { get { throw null; } }
public bool? IsDebuggable { get { throw null; } }
public System.DateTimeOffset IssuedAt { get { throw null; } }
public System.Uri Issuer { get { throw null; } }
public string MrEnclave { get { throw null; } }
public string MrSigner { get { throw null; } }
public string Nonce { get { throw null; } }
public System.DateTimeOffset NotBefore { get { throw null; } }
public object PolicyClaims { get { throw null; } }
public byte[] PolicyHash { get { throw null; } }
public float? ProductId { get { throw null; } }
public object RuntimeClaims { get { throw null; } }
public object SgxCollateral { get { throw null; } }
public float? Svn { get { throw null; } }
public string UniqueIdentifier { get { throw null; } }
public string VerifierType { get { throw null; } }
public string Version { get { throw null; } }
}
public partial class AttestationSigner
{
public AttestationSigner(System.Security.Cryptography.X509Certificates.X509Certificate2[] signingCertificates, string certificateKeyId) { }
public string CertificateKeyId { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<System.Security.Cryptography.X509Certificates.X509Certificate2> SigningCertificates { get { throw null; } }
}
public partial class AttestationToken
{
protected AttestationToken() { }
public AttestationToken(Azure.Security.Attestation.TokenSigningKey signingKey) { }
public AttestationToken(object body) { }
public AttestationToken(object body, Azure.Security.Attestation.TokenSigningKey signingKey) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
protected internal AttestationToken(string token) { }
public virtual string Algorithm { get { throw null; } }
public virtual string CertificateThumbprint { get { throw null; } }
public virtual string ContentType { get { throw null; } }
public virtual bool? Critical { get { throw null; } }
public virtual System.DateTimeOffset? ExpirationTime { get { throw null; } }
public virtual System.DateTimeOffset? IssuedAtTime { get { throw null; } }
public virtual string Issuer { get { throw null; } }
public virtual string KeyId { get { throw null; } }
public virtual System.Uri KeyUrl { get { throw null; } }
public virtual System.DateTimeOffset? NotBeforeTime { get { throw null; } }
public virtual Azure.Security.Attestation.AttestationSigner SigningCertificate { get { throw null; } }
public virtual string TokenBody { get { throw null; } }
public virtual System.ReadOnlyMemory<byte> TokenBodyBytes { get { throw null; } }
public virtual string TokenHeader { get { throw null; } }
public virtual System.ReadOnlyMemory<byte> TokenHeaderBytes { get { throw null; } }
public virtual System.ReadOnlyMemory<byte> TokenSignatureBytes { get { throw null; } }
public virtual string Type { get { throw null; } }
public virtual System.Security.Cryptography.X509Certificates.X509Certificate2[] X509CertificateChain { get { throw null; } }
public virtual string X509CertificateSha256Thumbprint { get { throw null; } }
public virtual string X509CertificateThumbprint { get { throw null; } }
public virtual System.Uri X509Url { get { throw null; } }
public virtual T GetBody<T>() where T : class { throw null; }
public override string ToString() { throw null; }
public virtual bool ValidateToken(Azure.Security.Attestation.TokenValidationOptions options, System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner> attestationSigningCertificates, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<bool> ValidateTokenAsync(Azure.Security.Attestation.TokenValidationOptions options, System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner> attestationSigningCertificates, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct AttestationType : System.IEquatable<Azure.Security.Attestation.AttestationType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public AttestationType(string value) { throw null; }
public static Azure.Security.Attestation.AttestationType OpenEnclave { get { throw null; } }
public static Azure.Security.Attestation.AttestationType SgxEnclave { get { throw null; } }
public static Azure.Security.Attestation.AttestationType Tpm { get { throw null; } }
public bool Equals(Azure.Security.Attestation.AttestationType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Security.Attestation.AttestationType left, Azure.Security.Attestation.AttestationType right) { throw null; }
public static implicit operator Azure.Security.Attestation.AttestationType (string value) { throw null; }
public static bool operator !=(Azure.Security.Attestation.AttestationType left, Azure.Security.Attestation.AttestationType right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct CertificateModification : System.IEquatable<Azure.Security.Attestation.CertificateModification>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public CertificateModification(string value) { throw null; }
public static Azure.Security.Attestation.CertificateModification IsAbsent { get { throw null; } }
public static Azure.Security.Attestation.CertificateModification IsPresent { get { throw null; } }
public bool Equals(Azure.Security.Attestation.CertificateModification other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Security.Attestation.CertificateModification left, Azure.Security.Attestation.CertificateModification right) { throw null; }
public static implicit operator Azure.Security.Attestation.CertificateModification (string value) { throw null; }
public static bool operator !=(Azure.Security.Attestation.CertificateModification left, Azure.Security.Attestation.CertificateModification right) { throw null; }
public override string ToString() { throw null; }
}
public partial class PolicyCertificatesModificationResult
{
internal PolicyCertificatesModificationResult() { }
public Azure.Security.Attestation.CertificateModification? CertificateResolution { get { throw null; } }
public string CertificateThumbprint { get { throw null; } }
}
public partial class PolicyCertificatesResult
{
public PolicyCertificatesResult() { }
public System.Collections.Generic.IReadOnlyList<System.Security.Cryptography.X509Certificates.X509Certificate2> GetPolicyCertificates() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct PolicyModification : System.IEquatable<Azure.Security.Attestation.PolicyModification>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public PolicyModification(string value) { throw null; }
public static Azure.Security.Attestation.PolicyModification Removed { get { throw null; } }
public static Azure.Security.Attestation.PolicyModification Updated { get { throw null; } }
public bool Equals(Azure.Security.Attestation.PolicyModification other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Security.Attestation.PolicyModification left, Azure.Security.Attestation.PolicyModification right) { throw null; }
public static implicit operator Azure.Security.Attestation.PolicyModification (string value) { throw null; }
public static bool operator !=(Azure.Security.Attestation.PolicyModification left, Azure.Security.Attestation.PolicyModification right) { throw null; }
public override string ToString() { throw null; }
}
public partial class PolicyResult
{
public PolicyResult() { }
public Azure.Security.Attestation.PolicyModification PolicyResolution { get { throw null; } }
public Azure.Security.Attestation.AttestationSigner PolicySigner { get { throw null; } }
public byte[] PolicyTokenHash { get { throw null; } }
}
public partial class StoredAttestationPolicy
{
public StoredAttestationPolicy() { }
public string AttestationPolicy { get { throw null; } set { } }
}
public partial class TokenSigningKey
{
public TokenSigningKey(System.Security.Cryptography.AsymmetricAlgorithm signer, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public TokenSigningKey(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } }
public System.Security.Cryptography.AsymmetricAlgorithm Signer { get { throw null; } }
}
public partial class TokenValidationOptions
{
public TokenValidationOptions(bool validateToken = true, bool validateExpirationTime = true, bool validateNotBeforeTime = true, bool validateIssuer = false, string expectedIssuer = null, int timeValidationSlack = 0, System.Func<Azure.Security.Attestation.AttestationToken, Azure.Security.Attestation.AttestationSigner, bool> validationCallback = null) { }
public string ExpectedIssuer { get { throw null; } }
public long TimeValidationSlack { get { throw null; } }
public bool ValidateExpirationTime { get { throw null; } }
public bool ValidateIssuer { get { throw null; } }
public bool ValidateNotBeforeTime { get { throw null; } }
public bool ValidateToken { get { throw null; } }
public System.Func<Azure.Security.Attestation.AttestationToken, Azure.Security.Attestation.AttestationSigner, bool> ValidationCallback { get { throw null; } }
}
public partial class TpmAttestationRequest
{
public TpmAttestationRequest() { }
public System.ReadOnlyMemory<byte> Data { get { throw null; } set { } }
}
public partial class TpmAttestationResponse
{
internal TpmAttestationResponse() { }
public System.ReadOnlyMemory<byte> Data { get { throw null; } }
}
}
|
using System;
using System.Linq;
namespace CapnProto.Schema.Parser
{
class CapnpVisitor
{
protected Boolean mEnableNestedType = true;
protected CapnpModule mActiveModule;
protected void EnableNestedType()
{
mEnableNestedType = true;
}
protected void DisableNestedType()
{
mEnableNestedType = false;
}
public virtual CapnpType Visit(CapnpType target)
{
if (target == null) return null;
return target.Accept(this);
}
protected internal virtual CapnpType VisitPrimitive(CapnpPrimitive primitive)
{
return primitive;
}
protected internal virtual CapnpType VisitList(CapnpList list)
{
list.Parameter = Visit(list.Parameter);
return list;
}
protected internal virtual Value VisitValue(Value value)
{
return value;
}
protected internal virtual CapnpModule VisitModule(CapnpModule module)
{
// An imported module has already been processed.
if (mActiveModule != null && mActiveModule != module) return module;
mActiveModule = module;
module.Structs = module.Structs.Select(s => VisitStruct(s)).ToArray();
module.Interfaces = module.Interfaces.Select(i => VisitInterface(i)).ToArray();
module.Constants = module.Constants.Select(c => VisitConst(c)).ToArray();
module.Enumerations = module.Enumerations.Select(e => VisitEnum(e)).ToArray();
module.AnnotationDefs = module.AnnotationDefs.Select(a => VisitAnnotationDecl(a)).ToArray();
module.Usings = module.Usings.Select(u => VisitUsing(u)).ToArray();
module.Annotations = module.Annotations.Select(a => VisitAnnotation(a)).ToArray();
return module;
}
protected internal virtual Annotation VisitAnnotation(Annotation annotation)
{
if (annotation == null) return null;
annotation.Declaration = Visit(annotation.Declaration);
annotation.Argument = VisitValue(annotation.Argument);
return annotation;
}
protected internal virtual CapnpStruct VisitStruct(CapnpStruct @struct)
{
if (!mEnableNestedType) return @struct;
@struct.Structs = @struct.Structs.Select(s => VisitStruct(s)).ToArray();
@struct.Interfaces = @struct.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@struct.Enumerations = @struct.Enumerations.Select(e => VisitEnum(e)).ToArray();
@struct.Fields = @struct.Fields.Select(f => VisitField(f)).ToArray();
@struct.AnnotationDefs = @struct.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@struct.Annotations = @struct.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@struct.Usings = @struct.Usings.Select(u => VisitUsing(u)).ToArray();
@struct.Constants = @struct.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @struct;
}
protected internal virtual CapnpInterface VisitInterface(CapnpInterface @interface)
{
if (!mEnableNestedType) return @interface;
@interface.Structs = @interface.Structs.Select(s => VisitStruct(s)).ToArray();
@interface.Interfaces = @interface.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@interface.Enumerations = @interface.Enumerations.Select(e => VisitEnum(e)).ToArray();
@interface.BaseInterfaces = @interface.BaseInterfaces.Select(i => Visit(i)).ToArray();
@interface.AnnotationDefs = @interface.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@interface.Annotations = @interface.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@interface.Methods = @interface.Methods.Select(m => VisitMethod(m)).ToArray();
@interface.Usings = @interface.Usings.Select(u => VisitUsing(u)).ToArray();
@interface.Constants = @interface.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @interface;
}
protected internal virtual CapnpGenericParameter VisitGenericParameter(CapnpGenericParameter @param)
{
return @param;
}
protected internal virtual CapnpBoundGenericType VisitClosedType(CapnpBoundGenericType closed)
{
closed.OpenType = (CapnpNamedType)Visit(closed.OpenType);
if (closed.ParentScope != null)
closed.ParentScope = VisitClosedType(closed.ParentScope);
return closed;
}
protected internal virtual CapnpEnum VisitEnum(CapnpEnum @enum)
{
@enum.Annotations = @enum.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@enum.Enumerants = @enum.Enumerants.Select(e => VisitEnumerant(e)).ToArray();
return @enum;
}
protected internal virtual Enumerant VisitEnumerant(Enumerant e)
{
e.Annotation = VisitAnnotation(e.Annotation);
return e;
}
protected internal virtual Field VisitField(Field fld)
{
fld.Type = Visit(fld.Type);
fld.Value = VisitValue(fld.Value);
fld.Annotation = VisitAnnotation(fld.Annotation);
return fld;
}
protected internal virtual Method VisitMethod(Method method)
{
if (method.Arguments.Params != null)
method.Arguments.Params = method.Arguments.Params.Select(p => VisitParameter(p)).ToArray();
else
method.Arguments.Struct = Visit(method.Arguments.Struct);
if (method.ReturnType.Params != null)
method.ReturnType.Params = method.ReturnType.Params.Select(p => VisitParameter(p)).ToArray();
else
method.ReturnType.Struct = Visit(method.ReturnType.Struct);
method.Annotation = VisitAnnotation(method.Annotation);
return method;
}
protected internal virtual Parameter VisitParameter(Parameter p)
{
p.Type = Visit(p.Type);
p.Annotation = VisitAnnotation(p.Annotation);
p.DefaultValue = VisitValue(p.DefaultValue);
return p;
}
protected internal virtual CapnpGroup VisitGroup(CapnpGroup grp)
{
grp.Fields = grp.Fields.Select(f => VisitField(f)).ToArray();
return grp;
}
protected internal virtual CapnpUnion VisitUnion(CapnpUnion union)
{
union.Fields = union.Fields.Select(u => VisitField(u)).ToArray();
return union;
}
protected internal virtual CapnpType VisitReference(CapnpReference @ref)
{
return @ref;
}
protected internal virtual CapnpConst VisitConst(CapnpConst @const)
{
@const.Value = VisitValue(@const.Value);
return @const;
}
protected internal virtual CapnpType VisitImport(CapnpImport import)
{
import.Type = Visit(import.Type);
return import;
}
protected internal virtual CapnpUsing VisitUsing(CapnpUsing @using)
{
@using.Target = Visit(@using.Target);
return @using;
}
protected internal virtual CapnpAnnotation VisitAnnotationDecl(CapnpAnnotation annotation)
{
annotation.ArgumentType = Visit(annotation.ArgumentType);
return annotation;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using alby.core.threadpool ;
namespace alby.codegen.generator
{
public partial class ViewGeneratorParameters
{
public Program p ;
public string fqview ;
public Exception exception ;
} // end class
public partial class ViewGeneratorThreadPoolItem : MyThreadPoolItemBase
{
protected ViewGeneratorParameters _vgp ;
public ViewGeneratorThreadPoolItem( ViewGeneratorParameters vgp )
{
_vgp = vgp ;
}
public override void Run()
{
Helper h = new Helper() ;
try
{
DoView( _vgp.p, _vgp.fqview ) ;
}
catch( Exception ex )
{
_vgp.exception = ex ;
h.Message( "[DoTable() EXCEPTION]\n{0}", ex ) ;
}
}
protected void DoView( Program p, string fqview )
{
Helper h = new Helper() ;
ColumnInfo ci = new ColumnInfo() ;
Tuple<string,string> schemaview = h.SplitSchemaFromTable( fqview ) ;
string thedatabase = h.GetCsharpClassName( null, null, p._databaseName ) ;
string csharpnamespace = p._namespace + "." + p._viewSubDirectory;
string resourcenamespace = p._resourceNamespace + "." + p._viewSubDirectory;
string theclass = h.GetCsharpClassName( p._prefixObjectsWithSchema, schemaview.Item1, schemaview.Item2);
string csharpfile = p._directory + @"\" + p._viewSubDirectory + @"\" + theclass + ".cs" ;
string csharpfactoryfile = csharpfile.Replace(".cs", "Factory.cs");
string thefactoryclass = theclass + "Factory";
// config for this view, if any
string xpath = "/CodeGen/Views/View[@Class='" + theclass + "']" ;
XmlNode view = p._codegen.SelectSingleNode(xpath);
// select sql
string selectsql = "select * from {0} t ";
// do class
h.MessageVerbose( "[{0}]", csharpfile );
using ( StreamWriter sw = new StreamWriter( csharpfile, false, UTF8Encoding.UTF8 ) )
{
int tab = 0;
// header
h.WriteCodeGenHeader(sw);
h.WriteUsing(sw);
// namespace
using (NamespaceBlock nsb = new NamespaceBlock(sw, tab++, csharpnamespace))
{
using (ClassBlock cb = new ClassBlock(sw, tab++, theclass, "acr.RowBase"))
{
List< Tuple<string,string> > columns = ci.GetViewColumns( fqview ) ;
// properties and constructor
using (RowConstructorBlock conb = new RowConstructorBlock(sw, tab, theclass, columns, null, ""))
{}
} // end class
} // end namespace
} // eof
// do class factory
h.MessageVerbose( "[{0}]", csharpfactoryfile );
using (StreamWriter sw = new StreamWriter(csharpfactoryfile, false, UTF8Encoding.UTF8))
{
int tab = 0;
// header
h.WriteCodeGenHeader(sw);
h.WriteUsing(sw, p._namespace );
// namespace
using (NamespaceBlock nsb = new NamespaceBlock(sw, tab++, csharpnamespace))
{
using (ClassBlock cb = new ClassBlock(sw, tab++, thefactoryclass,
"acr.FactoryBase< " +
theclass + ", " +
"ns." + p._databaseSubDirectory + "." + thedatabase + "DatabaseSingletonHelper, " +
"ns." + p._databaseSubDirectory + "." + thedatabase + "Database >"
) )
{
// constructor
using (ViewFactoryConstructorBlock conb = new ViewFactoryConstructorBlock( sw, tab, fqview, selectsql, thefactoryclass))
{}
// default load all method
List<string> parameters = new List<string>();
Dictionary<string, string> parameterdictionary = new Dictionary<string, string>();
parameters = new List<string>() ;
parameters.Add("connˡ" );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary.Add("connˡ", "sds.SqlConnection");
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
// method
h.MessageVerbose("[{0}].[{1}].[{2}]", csharpnamespace, theclass, "Loadˡ");
using (ViewFactoryMethodBlock mb = new ViewFactoryMethodBlock(sw, tab, "Loadˡ", parameters, parameterdictionary, "", theclass, resourcenamespace))
{}
// load by where
parameters = new List<string>() ;
parameters.Add("connˡ" );
parameters.Add("whereˡ" );
parameters.Add("parametersˡ" );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary = new Dictionary<string, string>();
parameterdictionary.Add("connˡ", "sds.SqlConnection");
parameterdictionary.Add("whereˡ", "string");
parameterdictionary.Add("parametersˡ", "scg.List<sds.SqlParameter>");
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
h.MessageVerbose("[{0}].[{1}].[{2}]", csharpnamespace, theclass, "LoadByWhereˡ");
using (ViewFactoryMethodBlock mb = new ViewFactoryMethodBlock(sw, tab, "LoadByWhereˡ", parameters, parameterdictionary, "", theclass, resourcenamespace))
{}
// other methods
if ( view != null )
{
XmlNodeList xmlmethods = view.SelectNodes("Methods/Method");
foreach ( XmlNode xmlmethod in xmlmethods )
{
string themethod = xmlmethod.SelectSingleNode("@Name").InnerText;
// where resource
string whereresource = xmlmethod.SelectSingleNode("@Where").InnerText;
// parameters
parameters = new List<string>() ;
parameters.Add("connˡ" );
XmlNodeList xmlparameters = xmlmethod.SelectNodes("Parameters/Parameter");
foreach ( XmlNode xmlparameter in xmlparameters )
parameters.Add( xmlparameter.SelectSingleNode("@Name").InnerText );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary = new Dictionary<string, string>();
parameterdictionary.Add("connˡ", "sds.SqlConnection");
xmlparameters = xmlmethod.SelectNodes("Parameters/Parameter");
foreach ( XmlNode xmlparameter in xmlparameters )
parameterdictionary.Add( xmlparameter.SelectSingleNode("@Name").InnerText,
xmlparameter.SelectSingleNode("@Type").InnerText );
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
// method
h.MessageVerbose( "[{0}].[{1}].method [{2}]", csharpnamespace, theclass, themethod );
using (ViewFactoryMethodBlock mb = new ViewFactoryMethodBlock(sw, tab, themethod, parameters, parameterdictionary, whereresource, theclass, resourcenamespace))
{}
}
}
} // end class
} // end namespace
} // eof
} // end do view
} // end class
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Treorisoft.Net.Utilities
{
/// <summary>
/// Provides properties and instance methods for sending files over a <see cref="Winsock"/> objects.
/// </summary>
[Serializable]
public class FileData : ISerializable
{
/// <summary>
/// Initializes a new instance of the <see cref="FileData"/> class.
/// </summary>
/// <param name="info">A <see cref="FileInfo"/> object that contains data about the file.</param>
public FileData(FileInfo info)
{
Guid = Guid.NewGuid();
FileName = info.Name;
FileSize = info.Length;
Info = info;
}
/// <summary>
/// Initializes a new instance of the <see cref="FileData"/> class with serialized data.
/// </summary>
/// <param name="info">The object that holds the serialized object data.</param>
/// <param name="context">The contextual information about the source or destination.</param>
protected FileData(SerializationInfo info, StreamingContext context)
{
Guid = (Guid)info.GetValue("guid", typeof(Guid));
FileName = info.GetString("filename");
FileSize = info.GetInt64("filesize");
}
/// <summary>
/// Implements the <see cref="ISerializable"/> interface and returns the data needed to serialize the <see cref="FileData"/> object.
/// </summary>
/// <param name="info">A SerializationInfo object containing information required to serialize the FileData object.</param>
/// <param name="context">A StreamingContext object containing the source and destination of the serialized stream associated with the FileData object.</param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("guid", Guid);
info.AddValue("filename", FileName);
info.AddValue("filesize", FileSize);
}
/// <summary>
/// Gets a <see cref="Guid"/> identifier for the file.
/// </summary>
public Guid Guid { get; private set; }
/// <summary>
/// Gets the name of the file.
/// </summary>
public string FileName { get; private set; }
/// <summary>
/// Gets the size, in bytes, of the file.
/// </summary>
public long FileSize { get; private set; }
/// <summary>
/// Gets the <see cref="FileInfo"/> of the file being transmitted.
/// </summary>
/// <remarks>
/// During sending this contains the details of the actual file being transmitted.
/// During receiving this contains the details of a temporary file, that upon arrival can be moved to another location.
/// </remarks>
public FileInfo Info { get; internal set; }
#region Sending/Receiving Helpers
/// <summary>
/// Field backing the SyncRoot property.
/// </summary>
internal object _syncRoot = null;
/// <summary>
/// Field backing the MetaSize property.
/// </summary>
internal static int _fileDataMetaSize = -1;
/// <summary>
/// Gets an object that can be used to synchronize access to the file being read/written.
/// </summary>
private object SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
/// <summary>
/// Gets a value the estimates the size of an empty <see cref="FileDataPart"/> object.
/// </summary>
internal static int MetaSize
{
get
{
if (_fileDataMetaSize < 0)
_fileDataMetaSize = EstimatePartSize(0) + 1;
return _fileDataMetaSize;
}
}
/// <summary>
/// Gets an estimate of a <see cref="FileDataPart"/> object of the specified data size.
/// </summary>
/// <param name="size">The size of the data that should be used in the size estimate.</param>
/// <returns>The estimated size, in bytes, of a serialized <see cref="FileDataPart"/>.</returns>
internal static int EstimatePartSize(int size)
{
return EstimatePartSize(Guid.Empty, long.MaxValue, size);
}
/// <summary>
/// Gets an estimate of a <see cref="FileDataPart"/>.
/// </summary>
/// <param name="guid">The <see cref="Guid"/> that should be used in the size estimate.</param>
/// <param name="start">The start position that should be used in the size estimate.</param>
/// <param name="size">The size of the data that should be used in the size estimate.</param>
/// <returns>The estimated size, in bytes, of a serialized <see cref="FileDataPart"/>.</returns>
internal static int EstimatePartSize(Guid guid, long start, int size)
{
var part = new FileDataPart(guid, start, new byte[size]);
var bytes = ObjectPacker.Pack(part);
return bytes.Length + PacketHeader.HeaderSize(bytes.Length);
}
#endregion
#region Sending
/// <summary>
/// Gets the total number of bytes sent.
/// </summary>
internal long SentBytes { get; set; } = 0;
/// <summary>
/// Gets a boolean value indicating whether if the file has been completely sent or not.
/// </summary>
internal bool SendCompleted { get { return (SentBytes == FileSize); } }
/// <summary>
/// Gets the next <see cref="FileDataPart"/> that will be sent over the network.
/// </summary>
/// <param name="bufferSize">The size of the buffer and amount of data to return.</param>
/// <returns>The bufferSize is adjusted by an estimate of how large the metadata would be, so that the size of the serialized <see cref="FileDataPart"/> should be the same as the bufferSize.</returns>
internal FileDataPart GetNextPart(int bufferSize)
{
if (SendCompleted) return null;
if (Info == null) throw new NullReferenceException("File information not found.");
if (!Info.Exists) throw new FileNotFoundException(Info.FullName);
bufferSize -= MetaSize;
byte[] buffer = new byte[bufferSize];
lock (SyncRoot)
{
using (FileStream fs = new FileStream(Info.FullName, FileMode.Open, FileAccess.Read))
{
fs.Seek(SentBytes, SeekOrigin.Begin);
int readSize = fs.Read(buffer, 0, bufferSize);
byte[] sizedBuffer = ArrayMethods.Shrink(ref buffer, readSize);
var part = new FileDataPart(Guid, SentBytes, sizedBuffer);
SentBytes += readSize;
return part;
}
}
}
/// <summary>
/// Gets the total size of all the parts of the file at the given buffer size.
/// </summary>
/// <param name="bufferSize">The size of the buffer and amount of data to estimate with.</param>
/// <returns>
/// This routine is used by <see cref="SendProgress"/> to help determine the total number of bytes to send, and therefore also the percent completed.
/// The bufferSize is adjusted by an estimate of how large the metadata would be, so that the size of the serialized <see cref="FileDataPart"/> should be the same as the bufferSize.
/// </returns>
internal long GetTotalPartSize(int bufferSize)
{
long sum = 0;
foreach (int size in GetPartSizes(bufferSize))
sum += size;
return sum;
}
/// <summary>
/// Gets the sizes of all the parts of the file at the given buffer size.
/// </summary>
/// <param name="bufferSize">The size of the buffer and amount of data to estimate with.</param>
/// <returns>
/// Returns an IEnumerable containing the sizes of all the different parts of the file - including the <see cref="FileData"/> header.
/// </returns>
internal IEnumerable<int> GetPartSizes(int bufferSize)
{
if (Info == null) throw new NullReferenceException("File information not found.");
if (!Info.Exists) throw new FileNotFoundException(Info.FullName);
var bytes = ObjectPacker.Pack(this);
yield return bytes.Length + PacketHeader.HeaderSize(bytes.Length);
bufferSize -= MetaSize;
long fileSize = Info.Length;
long start = 0;
while (fileSize > 0)
{
if (fileSize > bufferSize)
{
yield return EstimatePartSize(Guid, start, bufferSize);
fileSize -= bufferSize;
start += bufferSize;
}
else
{
yield return EstimatePartSize(Guid, start, (int)fileSize);
fileSize = 0;
}
}
}
#endregion
#region Receiving
/// <summary>
/// Gets the total number of received bytes.
/// </summary>
public long ReceivedBytes { get; private set; } = 0;
/// <summary>
/// Gets a boolean value indicating if the file has been completely received or not.
/// </summary>
public bool ReceiveCompleted { get { return (ReceivedBytes == FileSize); } }
/// <summary>
/// Gets the size of the last received <see cref="FileDataPart"/>.
/// </summary>
/// <remarks>This is used to help setup the <see cref="ReceiveProgressEventArgs"/> that is raised.</remarks>
internal int LastReceivedSize { get; set; }
/// <summary>
/// Receives the <see cref="FileDataPart"/> into the specified file.
/// </summary>
/// <param name="fileName">The fully qualified name of the file, or the relative file name. Do not end the path with the directory separator character.</param>
/// <param name="part">The <see cref="FileDataPart"/> to be received.</param>
internal void ReceivePart(string fileName, FileDataPart part)
{
ReceivePart(new FileInfo(fileName), part);
}
/// <summary>
/// Receives the <see cref="FileDataPart"/> into the specified file.
/// </summary>
/// <param name="file">A <see cref="FileInfo"/> object containing the fully qualified name of the file to receiving the data to.</param>
/// <param name="part">The <see cref="FileDataPart"/> to be received.</param>
internal void ReceivePart(FileInfo file, FileDataPart part)
{
if (ReceiveCompleted)
throw new InvalidOperationException("Receive operation for this file has already been completed.");
lock (SyncRoot)
{
using (FileStream fs = new FileStream(file.FullName, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Seek(part.Start, SeekOrigin.Begin);
fs.Write(part.Data, 0, part.Data.Length);
}
LastReceivedSize = part.Data.Length;
ReceivedBytes += part.Data.Length;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HTLib2.Bioinfo
{
public partial class ForceField
{
public class PwVdw : INonbonded, IHessBuilder4PwIntrAct
{
public virtual string[] FrcFldType { get { return new string[] { "Nonbonded", "LennardJones" }; } }
public virtual double? GetDefaultMinimizeStep() { return 0.0001; }
public virtual void EnvClear() { }
public virtual bool EnvAdd(string key, object value) { return false; }
// ! Wildcards used to minimize memory requirements
// NONBONDED NBXMOD 5 ATOM CDIEL FSHIFT VATOM VDISTANCE VFSWITCH -
// CUTNB 14.0 CTOFNB 12.0 CTONNB 10.0 EPS 1.0 E14FAC 1.0 WMIN 1.5
// !
// !V(Lennard-Jones) = Eps,i,j[(Rmin,i,j/ri,j)**12 - 2(Rmin,i,j/ri,j)**6]
// !
// !epsilon: kcal/mole, Eps,i,j = sqrt(eps,i * eps,j)
// !Rmin/2: A, Rmin,i,j = Rmin/2,i + Rmin/2,j
// !
// !atom ignored epsilon Rmin/2 ignored eps,1-4 Rmin/2,1-4
// !
// HT 0.0 -0.0460 0.2245 ! TIP3P
// HN1 0.0 -0.0460 0.2245
// CN7 0.0 -0.02 2.275 0.0 -0.01 1.90 !equivalent to protein CT1
// CN7B 0.0 -0.02 2.275 0.0 -0.01 1.90 !equivalent to protein CT1
// ...
/////////////////////////////////////////////////////////////
public virtual void Compute(Universe.Nonbonded14 nonbonded, Vector[] coords, ref double energy, ref Vector[] forces, ref MatrixByArr[,] hessian, double[,] pwfrc=null, double[,] pwspr=null)
{
Universe.Atom atom1 = nonbonded.atoms[0];
Universe.Atom atom2 = nonbonded.atoms[1];
double radi = atom1.Rmin2_14; radi = (double.IsNaN(radi)==false) ? radi : atom1.Rmin2;
double radj = atom2.Rmin2_14; radj = (double.IsNaN(radj)==false) ? radj : atom2.Rmin2;
double epsi = atom1.eps_14; epsi = (double.IsNaN(epsi)==false) ? epsi : atom1.epsilon;
double epsj = atom2.eps_14; epsj = (double.IsNaN(epsj)==false) ? epsj : atom2.epsilon;
Compute(nonbonded, coords, ref energy, ref forces, ref hessian, radi, radj, epsi, epsj, pwfrc, pwspr);
}
public virtual void Compute(Universe.Nonbonded nonbonded, Vector[] coords, ref double energy, ref Vector[] forces, ref MatrixByArr[,] hessian, double[,] pwfrc=null, double[,] pwspr=null)
{
Universe.Atom atom1 = nonbonded.atoms[0];
Universe.Atom atom2 = nonbonded.atoms[1];
double radi = atom1.Rmin2;
double radj = atom2.Rmin2;
double epsi = atom1.epsilon;
double epsj = atom2.epsilon;
Compute(nonbonded, coords, ref energy, ref forces, ref hessian, radi, radj, epsi, epsj, pwfrc, pwspr);
}
public virtual void Compute(Universe.AtomPack nonbonded, Vector[] coords, ref double energy, ref Vector[] forces, ref MatrixByArr[,] hessian
,double radi ,double radj ,double epsi ,double epsj, double[,] pwfrc=null, double[,] pwspr=null)
{
Universe.Atom atom1 = nonbonded.atoms[0];
Universe.Atom atom2 = nonbonded.atoms[1];
Vector pos0 = coords[0];
Vector pos1 = coords[1];
double rmin = (radi + radj);
double epsij = Math.Sqrt(epsi * epsj);
double lenergy, forceij, springij;
Compute(coords, out lenergy, out forceij, out springij, epsij, rmin);
double abs_forceij = Math.Abs(forceij);
if(pwfrc != null) pwfrc[0, 1] = pwfrc[1, 0] = forceij;
if(pwspr != null) pwspr[0, 1] = pwspr[1, 0] = springij;
///////////////////////////////////////////////////////////////////////////////
// energy
energy += lenergy;
///////////////////////////////////////////////////////////////////////////////
// force
if(forces != null)
{
Vector frc0, frc1;
GetForceVector(pos0, pos1, forceij, out frc0, out frc1);
forces[0] += frc0;
forces[1] += frc1;
}
///////////////////////////////////////////////////////////////////////////////
// hessian
if(hessian != null)
{
hessian[0, 1] += GetHessianBlock(coords[0], coords[1], springij, forceij);
hessian[1, 0] += GetHessianBlock(coords[1], coords[0], springij, forceij);
}
}
public static void Compute(Vector[] coords, out double energy, out double forceij, out double springij, double epsij, double rmin)
{
/// !V(Lennard-Jones) = Eps,i,j[(Rmin,i,j/ri,j)**12 - 2(Rmin,i,j/ri,j)**6]
/// !epsilon: kcal/mole, Eps,i,j = sqrt(eps,i * eps,j)
/// !Rmin/2: A, Rmin,i,j = Rmin/2,i + Rmin/2,j
///
/// V(r) = epsij * r0^12 * rij^-12 - 2 * epsij * r0^6 * rij^-6
/// = epsij * (r0 / rij)^12 - 2 * epsij * (r0 / rij)^6
/// F(r) = -12 * epsij * r0^12 * rij^-13 - -6*2 * epsij * r0^6 * rij^-7
/// = -12 * epsij * (r0 / rij)^12 / rij - -6*2 * epsij * (r0 / rij)^6 / rij
/// K(r) = -13*-12 * epsij * r0^12 * rij^-14 - -7*-6*2 * epsij * r0^6 * rij^-8
/// = -13*-12 * epsij * (r0 / rij)^12 / rij^2 - -7*-6*2 * epsij * (r0 / rij)^6 / rij^2
double rij = (coords[1] - coords[0]).Dist;
double rij2 = rij*rij;
double rmin_rij = rmin / rij;
double rmin_rij_2 = rmin_rij * rmin_rij;
double rmin_rij_6 = rmin_rij_2 * rmin_rij_2 * rmin_rij_2;
double rmin_rij_12 = rmin_rij_6 * rmin_rij_6;
energy = epsij * rmin_rij_12 - 2 * epsij * rmin_rij_6;
forceij = (-12) * epsij * rmin_rij_12 / rij - (-6*2) * epsij * rmin_rij_6 / rij;
springij = (-13*-12) * epsij * rmin_rij_12 / rij2 - (-7*-6*2) * epsij * rmin_rij_6 / rij2;
HDebug.AssertIf(forceij>0, rmin<rij); // positive force => attractive
HDebug.AssertIf(forceij<0, rij<rmin); // negative force => repulsive
}
public void BuildHess4PwIntrAct(Universe.AtomPack info, Vector[] coords, out ValueTuple<int, int>[] pwidxs, out PwIntrActInfo[] pwhessinfos)
{
int idx1 = 0; // nonbonded.atoms[0].ID;
int idx2 = 1; // nonbonded.atoms[1].ID;
Universe.Atom atom1 = info.atoms[0];
Universe.Atom atom2 = info.atoms[1];
Vector diff = (coords[idx2] - coords[idx1]);
double dx = diff[0];
double dy = diff[1];
double dz = diff[2];
double radi = double.NaN;
double radj = double.NaN;
double epsi = double.NaN;
double epsj = double.NaN;
if(typeof(Universe.Nonbonded14).IsInstanceOfType(info))
{
radi = atom1.Rmin2_14; radi = (double.IsNaN(radi)==false) ? radi : atom1.Rmin2;
radj = atom2.Rmin2_14; radj = (double.IsNaN(radj)==false) ? radj : atom2.Rmin2;
epsi = atom1.eps_14; epsi = (double.IsNaN(epsi)==false) ? epsi : atom1.epsilon;
epsj = atom2.eps_14; epsj = (double.IsNaN(epsj)==false) ? epsj : atom2.epsilon;
}
if(typeof(Universe.Nonbonded).IsInstanceOfType(info))
{
radi = atom1.Rmin2;
radj = atom2.Rmin2;
epsi = atom1.epsilon;
epsj = atom2.epsilon;
}
HDebug.Assert(double.IsNaN(radi) == false, double.IsNaN(radj) == false, double.IsNaN(epsi) == false, double.IsNaN(epsj) == false);
// !V(Lennard-Jones) = Eps,i,j[(Rmin,i,j/ri,j)**12 - 2(Rmin,i,j/ri,j)**6]
// !epsilon: kcal/mole, Eps,i,j = sqrt(eps,i * eps,j)
// !Rmin/2: A, Rmin,i,j = Rmin/2,i + Rmin/2,j
//
// V(r) = epsij * r0^12 * rij^-12 - 2 * epsij * r0^6 * rij^-6
// F(r) = -12 * epsij * r0^12 * rij^-13 - -6*2 * epsij * r0^6 * rij^-7
// K(r) = -13*-12 * epsij * r0^12 * rij^-14 - -7*-6*2 * epsij * r0^6 * rij^-8
double r = (radi + radj);
double r6 = Math.Pow(r, 6);
double r12 = Math.Pow(r, 12);
double rij2 = (dx*dx + dy*dy + dz*dz);
double rij = Math.Sqrt(rij2);
double rij7 = Math.Pow(rij2, 3)*rij;
double rij8 = Math.Pow(rij2, 4);
double rij13 = Math.Pow(rij2, 6)*rij;
double rij14 = Math.Pow(rij2, 7);
double epsij = epsi*epsj;
double fij = ( -12) * epsij * r12 / rij13 - ( -6*2) * epsij * r6 / rij7;
double kij = (-13*-12) * epsij * r12 / rij14 - (-7*-6*2) * epsij * r6 / rij8;
pwidxs = new ValueTuple<int, int>[1];
pwidxs[0] = new ValueTuple<int, int>(0, 1);
pwhessinfos = new PwIntrActInfo[1];
pwhessinfos[0] = new PwIntrActInfo(kij, fij);
}
}
}
}
|
//
// Copyright (c) 2009-2021 Krueger Systems, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE
#define USE_CSHARP_SQLITE
#endif
using System;
using System.Collections;
using System.Diagnostics;
#if !USE_SQLITEPCL_RAW
using System.Runtime.InteropServices;
#endif
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
#if USE_CSHARP_SQLITE
using Sqlite3 = Community.CsharpSqlite.Sqlite3;
using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3;
using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe;
#elif USE_WP8_NATIVE_SQLITE
using Sqlite3 = Sqlite.Sqlite3;
using Sqlite3DatabaseHandle = Sqlite.Database;
using Sqlite3Statement = Sqlite.Statement;
#elif USE_SQLITEPCL_RAW
using Sqlite3DatabaseHandle = SQLitePCL.sqlite3;
using Sqlite3BackupHandle = SQLitePCL.sqlite3_backup;
using Sqlite3Statement = SQLitePCL.sqlite3_stmt;
using Sqlite3 = SQLitePCL.raw;
#else
using Sqlite3DatabaseHandle = System.IntPtr;
using Sqlite3BackupHandle = System.IntPtr;
using Sqlite3Statement = System.IntPtr;
#endif
#pragma warning disable 1591 // XML Doc Comments
namespace SQLite
{
public class SQLiteException : Exception
{
public SQLite3.Result Result { get; private set; }
protected SQLiteException (SQLite3.Result r, string message) : base (message)
{
Result = r;
}
public static SQLiteException New (SQLite3.Result r, string message)
{
return new SQLiteException (r, message);
}
}
public class NotNullConstraintViolationException : SQLiteException
{
public IEnumerable<TableMapping.Column> Columns { get; protected set; }
protected NotNullConstraintViolationException (SQLite3.Result r, string message)
: this (r, message, null, null)
{
}
protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj)
: base (r, message)
{
if (mapping != null && obj != null) {
this.Columns = from c in mapping.Columns
where c.IsNullable == false && c.GetValue (obj) == null
select c;
}
}
public static new NotNullConstraintViolationException New (SQLite3.Result r, string message)
{
return new NotNullConstraintViolationException (r, message);
}
public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (r, message, mapping, obj);
}
public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj);
}
}
[Flags]
public enum SQLiteOpenFlags
{
ReadOnly = 1, ReadWrite = 2, Create = 4,
NoMutex = 0x8000, FullMutex = 0x10000,
SharedCache = 0x20000, PrivateCache = 0x40000,
ProtectionComplete = 0x00100000,
ProtectionCompleteUnlessOpen = 0x00200000,
ProtectionCompleteUntilFirstUserAuthentication = 0x00300000,
ProtectionNone = 0x00400000
}
[Flags]
public enum CreateFlags
{
/// <summary>
/// Use the default creation options
/// </summary>
None = 0x000,
/// <summary>
/// Create a primary key index for a property called 'Id' (case-insensitive).
/// This avoids the need for the [PrimaryKey] attribute.
/// </summary>
ImplicitPK = 0x001,
/// <summary>
/// Create indices for properties ending in 'Id' (case-insensitive).
/// </summary>
ImplicitIndex = 0x002,
/// <summary>
/// Create a primary key for a property called 'Id' and
/// create an indices for properties ending in 'Id' (case-insensitive).
/// </summary>
AllImplicit = 0x003,
/// <summary>
/// Force the primary key property to be auto incrementing.
/// This avoids the need for the [AutoIncrement] attribute.
/// The primary key property on the class should have type int or long.
/// </summary>
AutoIncPK = 0x004,
/// <summary>
/// Create virtual table using FTS3
/// </summary>
FullTextSearch3 = 0x100,
/// <summary>
/// Create virtual table using FTS4
/// </summary>
FullTextSearch4 = 0x200
}
/// <summary>
/// An open connection to a SQLite database.
/// </summary>
[Preserve (AllMembers = true)]
public partial class SQLiteConnection : IDisposable
{
private bool _open;
private TimeSpan _busyTimeout;
readonly static Dictionary<string, TableMapping> _mappings = new Dictionary<string, TableMapping> ();
private System.Diagnostics.Stopwatch _sw;
private long _elapsedMilliseconds = 0;
private int _transactionDepth = 0;
private Random _rand = new Random ();
public Sqlite3DatabaseHandle Handle { get; private set; }
static readonly Sqlite3DatabaseHandle NullHandle = default (Sqlite3DatabaseHandle);
static readonly Sqlite3BackupHandle NullBackupHandle = default (Sqlite3BackupHandle);
/// <summary>
/// Gets the database path used by this connection.
/// </summary>
public string DatabasePath { get; private set; }
/// <summary>
/// Gets the SQLite library version number. 3007014 would be v3.7.14
/// </summary>
public int LibVersionNumber { get; private set; }
/// <summary>
/// Whether Trace lines should be written that show the execution time of queries.
/// </summary>
public bool TimeExecution { get; set; }
/// <summary>
/// Whether to write queries to <see cref="Tracer"/> during execution.
/// </summary>
public bool Trace { get; set; }
/// <summary>
/// The delegate responsible for writing trace lines.
/// </summary>
/// <value>The tracer.</value>
public Action<string> Tracer { get; set; }
/// <summary>
/// Whether to store DateTime properties as ticks (true) or strings (false).
/// </summary>
public bool StoreDateTimeAsTicks { get; private set; }
/// <summary>
/// Whether to store TimeSpan properties as ticks (true) or strings (false).
/// </summary>
public bool StoreTimeSpanAsTicks { get; private set; }
/// <summary>
/// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true.
/// </summary>
/// <value>The date time string format.</value>
public string DateTimeStringFormat { get; private set; }
/// <summary>
/// The DateTimeStyles value to use when parsing a DateTime property string.
/// </summary>
/// <value>The date time style.</value>
internal System.Globalization.DateTimeStyles DateTimeStyle { get; private set; }
#if USE_SQLITEPCL_RAW && !NO_SQLITEPCL_RAW_BATTERIES
static SQLiteConnection ()
{
SQLitePCL.Batteries_V2.Init ();
}
#endif
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="openFlags">
/// Flags controlling how the connection should be opened.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="connectionString">
/// Details on how to find and open the database.
/// </param>
public SQLiteConnection (SQLiteConnectionString connectionString)
{
if (connectionString == null)
throw new ArgumentNullException (nameof (connectionString));
if (connectionString.DatabasePath == null)
throw new InvalidOperationException ("DatabasePath must be specified");
DatabasePath = connectionString.DatabasePath;
LibVersionNumber = SQLite3.LibVersionNumber ();
#if NETFX_CORE
SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif
Sqlite3DatabaseHandle handle;
#if SILVERLIGHT || USE_CSHARP_SQLITE || USE_SQLITEPCL_RAW
var r = SQLite3.Open (connectionString.DatabasePath, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#else
// open using the byte[]
// in the case where the path may include Unicode
// force open to using UTF-8 using sqlite3_open_v2
var databasePathAsBytes = GetNullTerminatedUtf8 (connectionString.DatabasePath);
var r = SQLite3.Open (databasePathAsBytes, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#endif
Handle = handle;
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
}
_open = true;
StoreDateTimeAsTicks = connectionString.StoreDateTimeAsTicks;
StoreTimeSpanAsTicks = connectionString.StoreTimeSpanAsTicks;
DateTimeStringFormat = connectionString.DateTimeStringFormat;
DateTimeStyle = connectionString.DateTimeStyle;
BusyTimeout = TimeSpan.FromSeconds (1.0);
Tracer = line => Debug.WriteLine (line);
connectionString.PreKeyAction?.Invoke (this);
if (connectionString.Key is string stringKey) {
SetKey (stringKey);
}
else if (connectionString.Key is byte[] bytesKey) {
SetKey (bytesKey);
}
else if (connectionString.Key != null) {
throw new InvalidOperationException ("Encryption keys must be strings or byte arrays");
}
connectionString.PostKeyAction?.Invoke (this);
}
/// <summary>
/// Enables the write ahead logging. WAL is significantly faster in most scenarios
/// by providing better concurrency and better disk IO performance than the normal
/// journal mode. You only need to call this function once in the lifetime of the database.
/// </summary>
public void EnableWriteAheadLogging ()
{
ExecuteScalar<string> ("PRAGMA journal_mode=WAL");
}
/// <summary>
/// Convert an input string to a quoted SQL string that can be safely used in queries.
/// </summary>
/// <returns>The quoted string.</returns>
/// <param name="unsafeString">The unsafe string to quote.</param>
static string Quote (string unsafeString)
{
// TODO: Doesn't call sqlite3_mprintf("%Q", u) because we're waiting on https://github.com/ericsink/SQLitePCL.raw/issues/153
if (unsafeString == null)
return "NULL";
var safe = unsafeString.Replace ("'", "''");
return "'" + safe + "'";
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database with "pragma key = ...".
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">Ecryption key plain text that is converted to the real encryption key using PBKDF2 key derivation</param>
void SetKey (string key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
var q = Quote (key);
ExecuteScalar<string> ("pragma key = " + q);
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database.
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">256-bit (32 byte) ecryption key data</param>
void SetKey (byte[] key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
if (key.Length != 32 && key.Length != 48)
throw new ArgumentException ("Key must be 32 bytes (256-bit) or 48 bytes (384-bit)", nameof (key));
var s = String.Join ("", key.Select (x => x.ToString ("X2")));
ExecuteScalar<string> ("pragma key = \"x'" + s + "'\"");
}
/// <summary>
/// Enable or disable extension loading.
/// </summary>
public void EnableLoadExtension (bool enabled)
{
SQLite3.Result r = SQLite3.EnableLoadExtension (Handle, enabled ? 1 : 0);
if (r != SQLite3.Result.OK) {
string msg = SQLite3.GetErrmsg (Handle);
throw SQLiteException.New (r, msg);
}
}
#if !USE_SQLITEPCL_RAW
static byte[] GetNullTerminatedUtf8 (string s)
{
var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s);
var bytes = new byte [utf8Length + 1];
utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
return bytes;
}
#endif
/// <summary>
/// Sets a busy handler to sleep the specified amount of time when a table is locked.
/// The handler will sleep multiple times until a total time of <see cref="BusyTimeout"/> has accumulated.
/// </summary>
public TimeSpan BusyTimeout {
get { return _busyTimeout; }
set {
_busyTimeout = value;
if (Handle != NullHandle) {
SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds);
}
}
}
/// <summary>
/// Returns the mappings from types to tables that the connection
/// currently understands.
/// </summary>
public IEnumerable<TableMapping> TableMappings {
get {
lock (_mappings) {
return new List<TableMapping> (_mappings.Values);
}
}
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="type">
/// The type whose mapping to the database is returned.
/// </param>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None)
{
TableMapping map;
var key = type.FullName;
lock (_mappings) {
if (_mappings.TryGetValue (key, out map)) {
if (createFlags != CreateFlags.None && createFlags != map.CreateFlags) {
map = new TableMapping (type, createFlags);
_mappings[key] = map;
}
}
else {
map = new TableMapping (type, createFlags);
_mappings.Add (key, map);
}
}
return map;
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping<T> (CreateFlags createFlags = CreateFlags.None)
{
return GetMapping (typeof (T), createFlags);
}
private struct IndexedColumn
{
public int Order;
public string ColumnName;
}
private struct IndexInfo
{
public string IndexName;
public string TableName;
public bool Unique;
public List<IndexedColumn> Columns;
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
public int DropTable<T> ()
{
return DropTable (GetMapping (typeof (T)));
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
public int DropTable (TableMapping map)
{
var query = string.Format ("drop table if exists \"{0}\"", map.TableName);
return Execute (query);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable<T> (CreateFlags createFlags = CreateFlags.None)
{
return CreateTable (typeof (T), createFlags);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <param name="ty">Type to reflect to a database table.</param>
/// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None)
{
var map = GetMapping (ty, createFlags);
// Present a nice error if no columns specified
if (map.Columns.Length == 0) {
throw new Exception (string.Format ("Cannot create a table without columns (does '{0}' have public properties?)", ty.FullName));
}
// Check if the table exists
var result = CreateTableResult.Created;
var existingCols = GetTableInfo (map.TableName);
// Create or migrate it
if (existingCols.Count == 0) {
// Facilitate virtual tables a.k.a. full-text search.
bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0;
bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0;
bool fts = fts3 || fts4;
var @virtual = fts ? "virtual " : string.Empty;
var @using = fts3 ? "using fts3 " : fts4 ? "using fts4 " : string.Empty;
// Build query.
var query = "create " + @virtual + "table if not exists \"" + map.TableName + "\" " + @using + "(\n";
var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks));
var decl = string.Join (",\n", decls.ToArray ());
query += decl;
query += ")";
if (map.WithoutRowId) {
query += " without rowid";
}
Execute (query);
}
else {
result = CreateTableResult.Migrated;
MigrateTable (map, existingCols);
}
var indexes = new Dictionary<string, IndexInfo> ();
foreach (var c in map.Columns) {
foreach (var i in c.Indices) {
var iname = i.Name ?? map.TableName + "_" + c.Name;
IndexInfo iinfo;
if (!indexes.TryGetValue (iname, out iinfo)) {
iinfo = new IndexInfo {
IndexName = iname,
TableName = map.TableName,
Unique = i.Unique,
Columns = new List<IndexedColumn> ()
};
indexes.Add (iname, iinfo);
}
if (i.Unique != iinfo.Unique)
throw new Exception ("All the columns in an index must have the same value for their Unique property");
iinfo.Columns.Add (new IndexedColumn {
Order = i.Order,
ColumnName = c.Name
});
}
}
foreach (var indexName in indexes.Keys) {
var index = indexes[indexName];
var columns = index.Columns.OrderBy (i => i.Order).Select (i => i.ColumnName).ToArray ();
CreateIndex (indexName, index.TableName, columns, index.Unique);
}
return result;
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
where T5 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types)
{
var result = new CreateTablesResult ();
foreach (Type type in types) {
var aResult = CreateTable (type, createFlags);
result.Results[type] = aResult;
}
return result;
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false)
{
const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
var sql = String.Format (sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName);
return Execute (sql);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string columnName, bool unique = false)
{
return CreateIndex (indexName, tableName, new string[] { columnName }, unique);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string columnName, bool unique = false)
{
return CreateIndex (tableName + "_" + columnName, tableName, columnName, unique);
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string[] columnNames, bool unique = false)
{
return CreateIndex (tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique);
}
/// <summary>
/// Creates an index for the specified object property.
/// e.g. CreateIndex<Client>(c => c.Name);
/// </summary>
/// <typeparam name="T">Type to reflect to a database table.</typeparam>
/// <param name="property">Property to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex<T> (Expression<Func<T, object>> property, bool unique = false)
{
MemberExpression mx;
if (property.Body.NodeType == ExpressionType.Convert) {
mx = ((UnaryExpression)property.Body).Operand as MemberExpression;
}
else {
mx = (property.Body as MemberExpression);
}
var propertyInfo = mx.Member as PropertyInfo;
if (propertyInfo == null) {
throw new ArgumentException ("The lambda expression 'property' should point to a valid Property");
}
var propName = propertyInfo.Name;
var map = GetMapping<T> ();
var colName = map.FindColumnWithPropertyName (propName).Name;
return CreateIndex (map.TableName, colName, unique);
}
[Preserve (AllMembers = true)]
public class ColumnInfo
{
// public int cid { get; set; }
[Column ("name")]
public string Name { get; set; }
// [Column ("type")]
// public string ColumnType { get; set; }
public int notnull { get; set; }
// public string dflt_value { get; set; }
// public int pk { get; set; }
public override string ToString ()
{
return Name;
}
}
/// <summary>
/// Query the built-in sqlite table_info table for a specific tables columns.
/// </summary>
/// <returns>The columns contains in the table.</returns>
/// <param name="tableName">Table name.</param>
public List<ColumnInfo> GetTableInfo (string tableName)
{
var query = "pragma table_info(\"" + tableName + "\")";
return Query<ColumnInfo> (query);
}
void MigrateTable (TableMapping map, List<ColumnInfo> existingCols)
{
var toBeAdded = new List<TableMapping.Column> ();
foreach (var p in map.Columns) {
var found = false;
foreach (var c in existingCols) {
found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0);
if (found)
break;
}
if (!found) {
toBeAdded.Add (p);
}
}
foreach (var p in toBeAdded) {
var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks);
Execute (addCol);
}
}
/// <summary>
/// Creates a new SQLiteCommand. Can be overridden to provide a sub-class.
/// </summary>
/// <seealso cref="SQLiteCommand.OnInstanceCreated"/>
protected virtual SQLiteCommand NewCommand ()
{
return new SQLiteCommand (this);
}
/// <summary>
/// Creates a new SQLiteCommand given the command text with arguments. Place a '?'
/// in the command text for each of the arguments.
/// </summary>
/// <param name="cmdText">
/// The fully escaped SQL.
/// </param>
/// <param name="ps">
/// Arguments to substitute for the occurences of '?' in the command text.
/// </param>
/// <returns>
/// A <see cref="SQLiteCommand"/>
/// </returns>
public SQLiteCommand CreateCommand (string cmdText, params object[] ps)
{
if (!_open)
throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
var cmd = NewCommand ();
cmd.CommandText = cmdText;
foreach (var o in ps) {
cmd.Bind (o);
}
return cmd;
}
/// <summary>
/// Creates a new SQLiteCommand given the command text with named arguments. Place a "[@:$]VVV"
/// in the command text for each of the arguments. VVV represents an alphanumeric identifier.
/// For example, @name :name and $name can all be used in the query.
/// </summary>
/// <param name="cmdText">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of "[@:$]VVV" in the command text.
/// </param>
/// <returns>
/// A <see cref="SQLiteCommand" />
/// </returns>
public SQLiteCommand CreateCommand (string cmdText, Dictionary<string, object> args)
{
if (!_open)
throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
SQLiteCommand cmd = NewCommand ();
cmd.CommandText = cmdText;
foreach (var kv in args) {
cmd.Bind (kv.Key, kv.Value);
}
return cmd;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// Use this method instead of Query when you don't expect rows back. Such cases include
/// INSERTs, UPDATEs, and DELETEs.
/// You can set the Trace or TimeExecution properties of the connection
/// to profile execution.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The number of rows modified in the database as a result of this execution.
/// </returns>
public int Execute (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
if (TimeExecution) {
if (_sw == null) {
_sw = new Stopwatch ();
}
_sw.Reset ();
_sw.Start ();
}
var r = cmd.ExecuteNonQuery ();
if (TimeExecution) {
_sw.Stop ();
_elapsedMilliseconds += _sw.ElapsedMilliseconds;
Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
}
return r;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// Use this method when return primitive values.
/// You can set the Trace or TimeExecution properties of the connection
/// to profile execution.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The number of rows modified in the database as a result of this execution.
/// </returns>
public T ExecuteScalar<T> (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
if (TimeExecution) {
if (_sw == null) {
_sw = new Stopwatch ();
}
_sw.Reset ();
_sw.Start ();
}
var r = cmd.ExecuteScalar<T> ();
if (TimeExecution) {
_sw.Stop ();
_elapsedMilliseconds += _sw.ElapsedMilliseconds;
Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
}
return r;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the mapping automatically generated for
/// the given type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<T> Query<T> (string query, params object[] args) where T : new()
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<T> ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns the first column of each row of the result.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for the first column of each row returned by the query.
/// </returns>
public List<T> QueryScalars<T> (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQueryScalars<T> ().ToList ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the mapping automatically generated for
/// the given type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
/// will call sqlite3_step on each call to MoveNext, so the database
/// connection must remain open for the lifetime of the enumerator.
/// </returns>
public IEnumerable<T> DeferredQuery<T> (string query, params object[] args) where T : new()
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteDeferredQuery<T> ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the specified mapping. This function is
/// only used by libraries in order to query the database via introspection. It is
/// normally not used.
/// </summary>
/// <param name="map">
/// A <see cref="TableMapping"/> to use to convert the resulting rows
/// into objects.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<object> Query (TableMapping map, string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<object> (map);
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the specified mapping. This function is
/// only used by libraries in order to query the database via introspection. It is
/// normally not used.
/// </summary>
/// <param name="map">
/// A <see cref="TableMapping"/> to use to convert the resulting rows
/// into objects.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
/// will call sqlite3_step on each call to MoveNext, so the database
/// connection must remain open for the lifetime of the enumerator.
/// </returns>
public IEnumerable<object> DeferredQuery (TableMapping map, string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteDeferredQuery<object> (map);
}
/// <summary>
/// Returns a queryable interface to the table represented by the given type.
/// </summary>
/// <returns>
/// A queryable object that is able to translate Where, OrderBy, and Take
/// queries into native SQL.
/// </returns>
public TableQuery<T> Table<T> () where T : new()
{
return new TableQuery<T> (this);
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <returns>
/// The object with the given primary key. Throws a not found exception
/// if the object is not found.
/// </returns>
public T Get<T> (object pk) where T : new()
{
var map = GetMapping (typeof (T));
return Query<T> (map.GetByPrimaryKeySql, pk).First ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The object with the given primary key. Throws a not found exception
/// if the object is not found.
/// </returns>
public object Get (object pk, TableMapping map)
{
return Query (map, map.GetByPrimaryKeySql, pk).First ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the predicate from the table
/// associated with the specified type.
/// </summary>
/// <param name="predicate">
/// A predicate for which object to find.
/// </param>
/// <returns>
/// The object that matches the given predicate. Throws a not found exception
/// if the object is not found.
/// </returns>
public T Get<T> (Expression<Func<T, bool>> predicate) where T : new()
{
return Table<T> ().Where (predicate).First ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <returns>
/// The object with the given primary key or null
/// if the object is not found.
/// </returns>
public T Find<T> (object pk) where T : new()
{
var map = GetMapping (typeof (T));
return Query<T> (map.GetByPrimaryKeySql, pk).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The object with the given primary key or null
/// if the object is not found.
/// </returns>
public object Find (object pk, TableMapping map)
{
return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the predicate from the table
/// associated with the specified type.
/// </summary>
/// <param name="predicate">
/// A predicate for which object to find.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public T Find<T> (Expression<Func<T, bool>> predicate) where T : new()
{
return Table<T> ().Where (predicate).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the query from the table
/// associated with the specified type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public T FindWithQuery<T> (string query, params object[] args) where T : new()
{
return Query<T> (query, args).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the query from the table
/// associated with the specified type.
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public object FindWithQuery (TableMapping map, string query, params object[] args)
{
return Query (map, query, args).FirstOrDefault ();
}
/// <summary>
/// Whether <see cref="BeginTransaction"/> has been called and the database is waiting for a <see cref="Commit"/>.
/// </summary>
public bool IsInTransaction {
get { return _transactionDepth > 0; }
}
/// <summary>
/// Begins a new transaction. Call <see cref="Commit"/> to end the transaction.
/// </summary>
/// <example cref="System.InvalidOperationException">Throws if a transaction has already begun.</example>
public void BeginTransaction ()
{
// The BEGIN command only works if the transaction stack is empty,
// or in other words if there are no pending transactions.
// If the transaction stack is not empty when the BEGIN command is invoked,
// then the command fails with an error.
// Rather than crash with an error, we will just ignore calls to BeginTransaction
// that would result in an error.
if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) {
try {
Execute ("begin transaction");
}
catch (Exception ex) {
var sqlExp = ex as SQLiteException;
if (sqlExp != null) {
// It is recommended that applications respond to the errors listed below
// by explicitly issuing a ROLLBACK command.
// TODO: This rollback failsafe should be localized to all throw sites.
switch (sqlExp.Result) {
case SQLite3.Result.IOError:
case SQLite3.Result.Full:
case SQLite3.Result.Busy:
case SQLite3.Result.NoMem:
case SQLite3.Result.Interrupt:
RollbackTo (null, true);
break;
}
}
else {
// Call decrement and not VolatileWrite in case we've already
// created a transaction point in SaveTransactionPoint since the catch.
Interlocked.Decrement (ref _transactionDepth);
}
throw;
}
}
else {
// Calling BeginTransaction on an already open transaction is invalid
throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction.");
}
}
/// <summary>
/// Creates a savepoint in the database at the current point in the transaction timeline.
/// Begins a new transaction if one is not in progress.
///
/// Call <see cref="RollbackTo(string)"/> to undo transactions since the returned savepoint.
/// Call <see cref="Release"/> to commit transactions after the savepoint returned here.
/// Call <see cref="Commit"/> to end the transaction, committing all changes.
/// </summary>
/// <returns>A string naming the savepoint.</returns>
public string SaveTransactionPoint ()
{
int depth = Interlocked.Increment (ref _transactionDepth) - 1;
string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth;
try {
Execute ("savepoint " + retVal);
}
catch (Exception ex) {
var sqlExp = ex as SQLiteException;
if (sqlExp != null) {
// It is recommended that applications respond to the errors listed below
// by explicitly issuing a ROLLBACK command.
// TODO: This rollback failsafe should be localized to all throw sites.
switch (sqlExp.Result) {
case SQLite3.Result.IOError:
case SQLite3.Result.Full:
case SQLite3.Result.Busy:
case SQLite3.Result.NoMem:
case SQLite3.Result.Interrupt:
RollbackTo (null, true);
break;
}
}
else {
Interlocked.Decrement (ref _transactionDepth);
}
throw;
}
return retVal;
}
/// <summary>
/// Rolls back the transaction that was begun by <see cref="BeginTransaction"/> or <see cref="SaveTransactionPoint"/>.
/// </summary>
public void Rollback ()
{
RollbackTo (null, false);
}
/// <summary>
/// Rolls back the savepoint created by <see cref="BeginTransaction"/> or SaveTransactionPoint.
/// </summary>
/// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
public void RollbackTo (string savepoint)
{
RollbackTo (savepoint, false);
}
/// <summary>
/// Rolls back the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
/// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
/// <param name="noThrow">true to avoid throwing exceptions, false otherwise</param>
void RollbackTo (string savepoint, bool noThrow)
{
// Rolling back without a TO clause rolls backs all transactions
// and leaves the transaction stack empty.
try {
if (String.IsNullOrEmpty (savepoint)) {
if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) {
Execute ("rollback");
}
}
else {
DoSavePointExecute (savepoint, "rollback to ");
}
}
catch (SQLiteException) {
if (!noThrow)
throw;
}
// No need to rollback if there are no transactions open.
}
/// <summary>
/// Releases a savepoint returned from <see cref="SaveTransactionPoint"/>. Releasing a savepoint
/// makes changes since that savepoint permanent if the savepoint began the transaction,
/// or otherwise the changes are permanent pending a call to <see cref="Commit"/>.
///
/// The RELEASE command is like a COMMIT for a SAVEPOINT.
/// </summary>
/// <param name="savepoint">The name of the savepoint to release. The string should be the result of a call to <see cref="SaveTransactionPoint"/></param>
public void Release (string savepoint)
{
try {
DoSavePointExecute (savepoint, "release ");
}
catch (SQLiteException ex) {
if (ex.Result == SQLite3.Result.Busy) {
// Force a rollback since most people don't know this function can fail
// Don't call Rollback() since the _transactionDepth is 0 and it won't try
// Calling rollback makes our _transactionDepth variable correct.
// Writes to the database only happen at depth=0, so this failure will only happen then.
try {
Execute ("rollback");
}
catch {
// rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
}
}
throw;
}
}
void DoSavePointExecute (string savepoint, string cmd)
{
// Validate the savepoint
int firstLen = savepoint.IndexOf ('D');
if (firstLen >= 2 && savepoint.Length > firstLen + 1) {
int depth;
if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) {
// TODO: Mild race here, but inescapable without locking almost everywhere.
if (0 <= depth && depth < _transactionDepth) {
#if NETFX_CORE || USE_SQLITEPCL_RAW || NETCORE
Volatile.Write (ref _transactionDepth, depth);
#elif SILVERLIGHT
_transactionDepth = depth;
#else
Thread.VolatileWrite (ref _transactionDepth, depth);
#endif
Execute (cmd + savepoint);
return;
}
}
}
throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint");
}
/// <summary>
/// Commits the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
public void Commit ()
{
if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) {
try {
Execute ("commit");
}
catch {
// Force a rollback since most people don't know this function can fail
// Don't call Rollback() since the _transactionDepth is 0 and it won't try
// Calling rollback makes our _transactionDepth variable correct.
try {
Execute ("rollback");
}
catch {
// rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
}
throw;
}
}
// Do nothing on a commit with no open transaction
}
/// <summary>
/// Executes <paramref name="action"/> within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an
/// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception
/// is rethrown.
/// </summary>
/// <param name="action">
/// The <see cref="Action"/> to perform within a transaction. <paramref name="action"/> can contain any number
/// of operations on the connection but should never call <see cref="BeginTransaction"/> or
/// <see cref="Commit"/>.
/// </param>
public void RunInTransaction (Action action)
{
try {
var savePoint = SaveTransactionPoint ();
action ();
Release (savePoint);
}
catch (Exception) {
Rollback ();
throw;
}
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// <param name="runInTransaction"/>
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r);
}
}
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, string extra, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r, extra);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r, extra);
}
}
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, Type objType, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r, objType);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r, objType);
}
}
return c;
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj)
{
if (obj == null) {
return 0;
}
return Insert (obj, "", Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace (object obj)
{
if (obj == null) {
return 0;
}
return Insert (obj, "OR REPLACE", Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, Type objType)
{
return Insert (obj, "", objType);
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace (object obj, Type objType)
{
return Insert (obj, "OR REPLACE", objType);
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, string extra)
{
if (obj == null) {
return 0;
}
return Insert (obj, extra, Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, string extra, Type objType)
{
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
if (map.PK != null && map.PK.IsAutoGuid) {
if (map.PK.GetValue (obj).Equals (Guid.Empty)) {
map.PK.SetValue (obj, Guid.NewGuid ());
}
}
var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns;
var vals = new object[cols.Length];
for (var i = 0; i < vals.Length; i++) {
vals[i] = cols[i].GetValue (obj);
}
var insertCmd = GetInsertCommand (map, extra);
int count;
lock (insertCmd) {
// We lock here to protect the prepared statement returned via GetInsertCommand.
// A SQLite prepared statement can be bound for only one operation at a time.
try {
count = insertCmd.ExecuteNonQuery (vals);
}
catch (SQLiteException ex) {
if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj);
}
throw;
}
if (map.HasAutoIncPK) {
var id = SQLite3.LastInsertRowid (Handle);
map.SetAutoIncPK (obj, id);
}
}
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Insert);
return count;
}
readonly Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> _insertCommandMap = new Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> ();
PreparedSqlLiteInsertCommand GetInsertCommand (TableMapping map, string extra)
{
PreparedSqlLiteInsertCommand prepCmd;
var key = Tuple.Create (map.MappedType.FullName, extra);
lock (_insertCommandMap) {
if (_insertCommandMap.TryGetValue (key, out prepCmd)) {
return prepCmd;
}
}
prepCmd = CreateInsertCommand (map, extra);
lock (_insertCommandMap) {
if (_insertCommandMap.TryGetValue (key, out var existing)) {
prepCmd.Dispose ();
return existing;
}
_insertCommandMap.Add (key, prepCmd);
}
return prepCmd;
}
PreparedSqlLiteInsertCommand CreateInsertCommand (TableMapping map, string extra)
{
var cols = map.InsertColumns;
string insertSql;
if (cols.Length == 0 && map.Columns.Length == 1 && map.Columns[0].IsAutoInc) {
insertSql = string.Format ("insert {1} into \"{0}\" default values", map.TableName, extra);
}
else {
var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
if (replacing) {
cols = map.InsertOrReplaceColumns;
}
insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", map.TableName,
string.Join (",", (from c in cols
select "\"" + c.Name + "\"").ToArray ()),
string.Join (",", (from c in cols
select "?").ToArray ()), extra);
}
var insertCommand = new PreparedSqlLiteInsertCommand (this, insertSql);
return insertCommand;
}
/// <summary>
/// Updates all of the columns of a table using the specified object
/// except for its primary key.
/// The object is required to have a primary key.
/// </summary>
/// <param name="obj">
/// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows updated.
/// </returns>
public int Update (object obj)
{
if (obj == null) {
return 0;
}
return Update (obj, Orm.GetType (obj));
}
/// <summary>
/// Updates all of the columns of a table using the specified object
/// except for its primary key.
/// The object is required to have a primary key.
/// </summary>
/// <param name="obj">
/// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows updated.
/// </returns>
public int Update (object obj, Type objType)
{
int rowsAffected = 0;
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK");
}
var cols = from p in map.Columns
where p != pk
select p;
var vals = from c in cols
select c.GetValue (obj);
var ps = new List<object> (vals);
if (ps.Count == 0) {
// There is a PK but no accompanying data,
// so reset the PK to make the UPDATE work.
cols = map.Columns;
vals = from c in cols
select c.GetValue (obj);
ps = new List<object> (vals);
}
ps.Add (pk.GetValue (obj));
var q = string.Format ("update \"{0}\" set {1} where \"{2}\" = ? ", map.TableName, string.Join (",", (from c in cols
select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name);
try {
rowsAffected = Execute (q, ps.ToArray ());
}
catch (SQLiteException ex) {
if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (ex, map, obj);
}
throw ex;
}
if (rowsAffected > 0)
OnTableChanged (map, NotifyTableChangedAction.Update);
return rowsAffected;
}
/// <summary>
/// Updates all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int UpdateAll (System.Collections.IEnumerable objects, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Update (r);
}
});
}
else {
foreach (var r in objects) {
c += Update (r);
}
}
return c;
}
/// <summary>
/// Deletes the given object from the database using its primary key.
/// </summary>
/// <param name="objectToDelete">
/// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows deleted.
/// </returns>
public int Delete (object objectToDelete)
{
var map = GetMapping (Orm.GetType (objectToDelete));
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
}
var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
var count = Execute (q, pk.GetValue (objectToDelete));
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Deletes the object with the specified primary key.
/// </summary>
/// <param name="primaryKey">
/// The primary key of the object to delete.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
/// <typeparam name='T'>
/// The type of object.
/// </typeparam>
public int Delete<T> (object primaryKey)
{
return Delete (primaryKey, GetMapping (typeof (T)));
}
/// <summary>
/// Deletes the object with the specified primary key.
/// </summary>
/// <param name="primaryKey">
/// The primary key of the object to delete.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
public int Delete (object primaryKey, TableMapping map)
{
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
}
var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
var count = Execute (q, primaryKey);
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Deletes all the objects from the specified table.
/// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
/// specified table. Do you really want to do that?
/// </summary>
/// <returns>
/// The number of objects deleted.
/// </returns>
/// <typeparam name='T'>
/// The type of objects to delete.
/// </typeparam>
public int DeleteAll<T> ()
{
var map = GetMapping (typeof (T));
return DeleteAll (map);
}
/// <summary>
/// Deletes all the objects from the specified table.
/// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
/// specified table. Do you really want to do that?
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
public int DeleteAll (TableMapping map)
{
var query = string.Format ("delete from \"{0}\"", map.TableName);
var count = Execute (query);
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Backup the entire database to the specified path.
/// </summary>
/// <param name="destinationDatabasePath">Path to backup file.</param>
/// <param name="databaseName">The name of the database to backup (usually "main").</param>
public void Backup (string destinationDatabasePath, string databaseName = "main")
{
// Open the destination
var r = SQLite3.Open (destinationDatabasePath, out var destHandle);
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, "Failed to open destination database");
}
// Init the backup
var backup = SQLite3.BackupInit (destHandle, databaseName, Handle, databaseName);
if (backup == NullBackupHandle) {
SQLite3.Close (destHandle);
throw new Exception ("Failed to create backup");
}
// Perform it
SQLite3.BackupStep (backup, -1);
SQLite3.BackupFinish (backup);
// Check for errors
r = SQLite3.GetResult (destHandle);
string msg = "";
if (r != SQLite3.Result.OK) {
msg = SQLite3.GetErrmsg (destHandle);
}
// Close everything and report errors
SQLite3.Close (destHandle);
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, msg);
}
}
~SQLiteConnection ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public void Close ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
var useClose2 = LibVersionNumber >= 3007014;
if (_open && Handle != NullHandle) {
try {
if (disposing) {
lock (_insertCommandMap) {
foreach (var sqlInsertCommand in _insertCommandMap.Values) {
sqlInsertCommand.Dispose ();
}
_insertCommandMap.Clear ();
}
var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
if (r != SQLite3.Result.OK) {
string msg = SQLite3.GetErrmsg (Handle);
throw SQLiteException.New (r, msg);
}
}
else {
var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
}
}
finally {
Handle = NullHandle;
_open = false;
}
}
}
void OnTableChanged (TableMapping table, NotifyTableChangedAction action)
{
var ev = TableChanged;
if (ev != null)
ev (this, new NotifyTableChangedEventArgs (table, action));
}
public event EventHandler<NotifyTableChangedEventArgs> TableChanged;
}
public class NotifyTableChangedEventArgs : EventArgs
{
public TableMapping Table { get; private set; }
public NotifyTableChangedAction Action { get; private set; }
public NotifyTableChangedEventArgs (TableMapping table, NotifyTableChangedAction action)
{
Table = table;
Action = action;
}
}
public enum NotifyTableChangedAction
{
Insert,
Update,
Delete,
}
/// <summary>
/// Represents a parsed connection string.
/// </summary>
public class SQLiteConnectionString
{
const string DateTimeSqliteDefaultFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff";
public string UniqueKey { get; }
public string DatabasePath { get; }
public bool StoreDateTimeAsTicks { get; }
public bool StoreTimeSpanAsTicks { get; }
public string DateTimeStringFormat { get; }
public System.Globalization.DateTimeStyles DateTimeStyle { get; }
public object Key { get; }
public SQLiteOpenFlags OpenFlags { get; }
public Action<SQLiteConnection> PreKeyAction { get; }
public Action<SQLiteConnection> PostKeyAction { get; }
public string VfsName { get; }
#if NETFX_CORE
static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
public static readonly string[] InMemoryDbPaths = new[]
{
":memory:",
"file::memory:"
};
public static bool IsInMemoryPath(string databasePath)
{
return InMemoryDbPaths.Any(i => i.Equals(databasePath, StringComparison.OrdinalIgnoreCase));
}
#endif
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks = true)
: this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks)
{
}
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
/// <param name="key">
/// Specifies the encryption key to use on the database. Should be a string or a byte[].
/// </param>
/// <param name="preKeyAction">
/// Executes prior to setting key for SQLCipher databases
/// </param>
/// <param name="postKeyAction">
/// Executes after setting key for SQLCipher databases
/// </param>
/// <param name="vfsName">
/// Specifies the Virtual File System to use on the database.
/// </param>
public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null)
: this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks, key, preKeyAction, postKeyAction, vfsName)
{
}
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="openFlags">
/// Flags controlling how the connection should be opened.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
/// <param name="key">
/// Specifies the encryption key to use on the database. Should be a string or a byte[].
/// </param>
/// <param name="preKeyAction">
/// Executes prior to setting key for SQLCipher databases
/// </param>
/// <param name="postKeyAction">
/// Executes after setting key for SQLCipher databases
/// </param>
/// <param name="vfsName">
/// Specifies the Virtual File System to use on the database.
/// </param>
/// <param name="dateTimeStringFormat">
/// Specifies the format to use when storing DateTime properties as strings.
/// </param>
/// <param name="storeTimeSpanAsTicks">
/// Specifies whether to store TimeSpan properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeTimeSpanAsTicks = true.
/// </param>
public SQLiteConnectionString (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null, string dateTimeStringFormat = DateTimeSqliteDefaultFormat, bool storeTimeSpanAsTicks = true)
{
if (key != null && !((key is byte[]) || (key is string)))
throw new ArgumentException ("Encryption keys must be strings or byte arrays", nameof (key));
UniqueKey = string.Format ("{0}_{1:X8}", databasePath, (uint)openFlags);
StoreDateTimeAsTicks = storeDateTimeAsTicks;
StoreTimeSpanAsTicks = storeTimeSpanAsTicks;
DateTimeStringFormat = dateTimeStringFormat;
DateTimeStyle = "o".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) || "r".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) ? System.Globalization.DateTimeStyles.RoundtripKind : System.Globalization.DateTimeStyles.None;
Key = key;
PreKeyAction = preKeyAction;
PostKeyAction = postKeyAction;
OpenFlags = openFlags;
VfsName = vfsName;
#if NETFX_CORE
DatabasePath = IsInMemoryPath(databasePath)
? databasePath
: System.IO.Path.Combine(MetroStyleDataPath, databasePath);
#else
DatabasePath = databasePath;
#endif
}
}
[AttributeUsage (AttributeTargets.Class)]
public class TableAttribute : Attribute
{
public string Name { get; set; }
/// <summary>
/// Flag whether to create the table without rowid (see https://sqlite.org/withoutrowid.html)
///
/// The default is <c>false</c> so that sqlite adds an implicit <c>rowid</c> to every table created.
/// </summary>
public bool WithoutRowId { get; set; }
public TableAttribute (string name)
{
Name = name;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string Name { get; set; }
public ColumnAttribute (string name)
{
Name = name;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class PrimaryKeyAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class AutoIncrementAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class IndexedAttribute : Attribute
{
public string Name { get; set; }
public int Order { get; set; }
public virtual bool Unique { get; set; }
public IndexedAttribute ()
{
}
public IndexedAttribute (string name, int order)
{
Name = name;
Order = order;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class IgnoreAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class UniqueAttribute : IndexedAttribute
{
public override bool Unique {
get { return true; }
set { /* throw? */ }
}
}
[AttributeUsage (AttributeTargets.Property)]
public class MaxLengthAttribute : Attribute
{
public int Value { get; private set; }
public MaxLengthAttribute (int length)
{
Value = length;
}
}
public sealed class PreserveAttribute : System.Attribute
{
public bool AllMembers;
public bool Conditional;
}
/// <summary>
/// Select the collating sequence to use on a column.
/// "BINARY", "NOCASE", and "RTRIM" are supported.
/// "BINARY" is the default.
/// </summary>
[AttributeUsage (AttributeTargets.Property)]
public class CollationAttribute : Attribute
{
public string Value { get; private set; }
public CollationAttribute (string collation)
{
Value = collation;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class NotNullAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Enum)]
public class StoreAsTextAttribute : Attribute
{
}
public class TableMapping
{
public Type MappedType { get; private set; }
public string TableName { get; private set; }
public bool WithoutRowId { get; private set; }
public Column[] Columns { get; private set; }
public Column PK { get; private set; }
public string GetByPrimaryKeySql { get; private set; }
public CreateFlags CreateFlags { get; private set; }
internal MapMethod Method { get; private set; } = MapMethod.ByName;
readonly Column _autoPk;
readonly Column[] _insertColumns;
readonly Column[] _insertOrReplaceColumns;
public TableMapping (Type type, CreateFlags createFlags = CreateFlags.None)
{
MappedType = type;
CreateFlags = createFlags;
var typeInfo = type.GetTypeInfo ();
#if ENABLE_IL2CPP
var tableAttr = typeInfo.GetCustomAttribute<TableAttribute> ();
#else
var tableAttr =
typeInfo.CustomAttributes
.Where (x => x.AttributeType == typeof (TableAttribute))
.Select (x => (TableAttribute)Orm.InflateAttribute (x))
.FirstOrDefault ();
#endif
TableName = (tableAttr != null && !string.IsNullOrEmpty (tableAttr.Name)) ? tableAttr.Name : MappedType.Name;
WithoutRowId = tableAttr != null ? tableAttr.WithoutRowId : false;
var members = GetPublicMembers(type);
var cols = new List<Column>(members.Count);
foreach(var m in members)
{
var ignore = m.IsDefined(typeof(IgnoreAttribute), true);
if(!ignore)
cols.Add(new Column(m, createFlags));
}
Columns = cols.ToArray ();
foreach (var c in Columns) {
if (c.IsAutoInc && c.IsPK) {
_autoPk = c;
}
if (c.IsPK) {
PK = c;
}
}
HasAutoIncPK = _autoPk != null;
if (PK != null) {
GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
}
else {
// People should not be calling Get/Find without a PK
GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName);
}
_insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray ();
_insertOrReplaceColumns = Columns.ToArray ();
}
private IReadOnlyCollection<MemberInfo> GetPublicMembers(Type type)
{
if(type.Name.StartsWith("ValueTuple`"))
return GetFieldsFromValueTuple(type);
var members = new List<MemberInfo>();
var memberNames = new HashSet<string>();
var newMembers = new List<MemberInfo>();
do
{
var ti = type.GetTypeInfo();
newMembers.Clear();
newMembers.AddRange(
from p in ti.DeclaredProperties
where !memberNames.Contains(p.Name) &&
p.CanRead && p.CanWrite &&
p.GetMethod != null && p.SetMethod != null &&
p.GetMethod.IsPublic && p.SetMethod.IsPublic &&
!p.GetMethod.IsStatic && !p.SetMethod.IsStatic
select p);
members.AddRange(newMembers);
foreach(var m in newMembers)
memberNames.Add(m.Name);
type = ti.BaseType;
}
while(type != typeof(object));
return members;
}
private IReadOnlyCollection<MemberInfo> GetFieldsFromValueTuple(Type type)
{
Method = MapMethod.ByPosition;
var fields = type.GetFields();
// https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest
if(fields.Length >= 8)
throw new NotSupportedException("ValueTuple with more than 7 members not supported due to nesting; see https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest");
return fields;
}
public bool HasAutoIncPK { get; private set; }
public void SetAutoIncPK (object obj, long id)
{
if (_autoPk != null) {
_autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null));
}
}
public Column[] InsertColumns {
get {
return _insertColumns;
}
}
public Column[] InsertOrReplaceColumns {
get {
return _insertOrReplaceColumns;
}
}
public Column FindColumnWithPropertyName (string propertyName)
{
var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName);
return exact;
}
public Column FindColumn (string columnName)
{
if(Method != MapMethod.ByName)
throw new InvalidOperationException($"This {nameof(TableMapping)} is not mapped by name, but {Method}.");
var exact = Columns.FirstOrDefault (c => c.Name.ToLower () == columnName.ToLower ());
return exact;
}
public class Column
{
MemberInfo _member;
public string Name { get; private set; }
public PropertyInfo PropertyInfo => _member as PropertyInfo;
public string PropertyName { get { return _member.Name; } }
public Type ColumnType { get; private set; }
public string Collation { get; private set; }
public bool IsAutoInc { get; private set; }
public bool IsAutoGuid { get; private set; }
public bool IsPK { get; private set; }
public IEnumerable<IndexedAttribute> Indices { get; set; }
public bool IsNullable { get; private set; }
public int? MaxStringLength { get; private set; }
public bool StoreAsText { get; private set; }
public Column (MemberInfo member, CreateFlags createFlags = CreateFlags.None)
{
_member = member;
var memberType = GetMemberType(member);
var colAttr = member.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (ColumnAttribute));
#if ENABLE_IL2CPP
var ca = member.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
Name = ca == null ? member.Name : ca.Name;
#else
Name = (colAttr != null && colAttr.ConstructorArguments.Count > 0) ?
colAttr.ConstructorArguments[0].Value?.ToString () :
member.Name;
#endif
//If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
ColumnType = Nullable.GetUnderlyingType (memberType) ?? memberType;
Collation = Orm.Collation (member);
IsPK = Orm.IsPK (member) ||
(((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
string.Compare (member.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);
var isAuto = Orm.IsAutoInc (member) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));
IsAutoGuid = isAuto && ColumnType == typeof (Guid);
IsAutoInc = isAuto && !IsAutoGuid;
Indices = Orm.GetIndices (member);
if (!Indices.Any ()
&& !IsPK
&& ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex)
&& Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase)
) {
Indices = new IndexedAttribute[] { new IndexedAttribute () };
}
IsNullable = !(IsPK || Orm.IsMarkedNotNull (member));
MaxStringLength = Orm.MaxStringLength (member);
StoreAsText = memberType.GetTypeInfo ().CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
}
public Column (PropertyInfo member, CreateFlags createFlags = CreateFlags.None)
: this((MemberInfo)member, createFlags)
{ }
public void SetValue (object obj, object val)
{
if(_member is PropertyInfo propy)
{
if (val != null && ColumnType.GetTypeInfo ().IsEnum)
propy.SetValue (obj, Enum.ToObject (ColumnType, val));
else
propy.SetValue (obj, val);
}
else if(_member is FieldInfo field)
{
if (val != null && ColumnType.GetTypeInfo ().IsEnum)
field.SetValue (obj, Enum.ToObject (ColumnType, val));
else
field.SetValue (obj, val);
}
else
throw new InvalidProgramException("unreachable condition");
}
public object GetValue (object obj)
{
if(_member is PropertyInfo propy)
return propy.GetValue(obj);
else if(_member is FieldInfo field)
return field.GetValue(obj);
else
throw new InvalidProgramException("unreachable condition");
}
private static Type GetMemberType(MemberInfo m)
{
switch(m.MemberType)
{
case MemberTypes.Property: return ((PropertyInfo)m).PropertyType;
case MemberTypes.Field: return ((FieldInfo)m).FieldType;
default: throw new InvalidProgramException($"{nameof(TableMapping)} supports properties or fields only.");
}
}
}
internal enum MapMethod
{
ByName,
ByPosition
}
}
class EnumCacheInfo
{
public EnumCacheInfo (Type type)
{
var typeInfo = type.GetTypeInfo ();
IsEnum = typeInfo.IsEnum;
if (IsEnum) {
StoreAsText = typeInfo.CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
if (StoreAsText) {
EnumValues = new Dictionary<int, string> ();
foreach (object e in Enum.GetValues (type)) {
EnumValues[Convert.ToInt32 (e)] = e.ToString ();
}
}
}
}
public bool IsEnum { get; private set; }
public bool StoreAsText { get; private set; }
public Dictionary<int, string> EnumValues { get; private set; }
}
static class EnumCache
{
static readonly Dictionary<Type, EnumCacheInfo> Cache = new Dictionary<Type, EnumCacheInfo> ();
public static EnumCacheInfo GetInfo<T> ()
{
return GetInfo (typeof (T));
}
public static EnumCacheInfo GetInfo (Type type)
{
lock (Cache) {
EnumCacheInfo info = null;
if (!Cache.TryGetValue (type, out info)) {
info = new EnumCacheInfo (type);
Cache[type] = info;
}
return info;
}
}
}
public static class Orm
{
public const int DefaultMaxStringLength = 140;
public const string ImplicitPkName = "Id";
public const string ImplicitIndexSuffix = "Id";
public static Type GetType (object obj)
{
if (obj == null)
return typeof (object);
var rt = obj as IReflectableType;
if (rt != null)
return rt.GetTypeInfo ().AsType ();
return obj.GetType ();
}
public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
{
string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks, storeTimeSpanAsTicks) + " ";
if (p.IsPK) {
decl += "primary key ";
}
if (p.IsAutoInc) {
decl += "autoincrement ";
}
if (!p.IsNullable) {
decl += "not null ";
}
if (!string.IsNullOrEmpty (p.Collation)) {
decl += "collate " + p.Collation + " ";
}
return decl;
}
public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
{
var clrType = p.ColumnType;
if (clrType == typeof (Boolean) || clrType == typeof (Byte) || clrType == typeof (UInt16) || clrType == typeof (SByte) || clrType == typeof (Int16) || clrType == typeof (Int32) || clrType == typeof (UInt32) || clrType == typeof (Int64)) {
return "integer";
}
else if (clrType == typeof (Single) || clrType == typeof (Double) || clrType == typeof (Decimal)) {
return "float";
}
else if (clrType == typeof (String) || clrType == typeof (StringBuilder) || clrType == typeof (Uri) || clrType == typeof (UriBuilder)) {
int? len = p.MaxStringLength;
if (len.HasValue)
return "varchar(" + len.Value + ")";
return "varchar";
}
else if (clrType == typeof (TimeSpan)) {
return storeTimeSpanAsTicks ? "bigint" : "time";
}
else if (clrType == typeof (DateTime)) {
return storeDateTimeAsTicks ? "bigint" : "datetime";
}
else if (clrType == typeof (DateTimeOffset)) {
return "bigint";
}
else if (clrType.GetTypeInfo ().IsEnum) {
if (p.StoreAsText)
return "varchar";
else
return "integer";
}
else if (clrType == typeof (byte[])) {
return "blob";
}
else if (clrType == typeof (Guid)) {
return "varchar(36)";
}
else {
throw new NotSupportedException ("Don't know about " + clrType);
}
}
public static bool IsPK (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (PrimaryKeyAttribute));
}
public static string Collation (MemberInfo p)
{
#if ENABLE_IL2CPP
return (p.GetCustomAttribute<CollationAttribute> ()?.Value) ?? "";
#else
return
(p.CustomAttributes
.Where (x => typeof (CollationAttribute) == x.AttributeType)
.Select (x => {
var args = x.ConstructorArguments;
return args.Count > 0 ? ((args[0].Value as string) ?? "") : "";
})
.FirstOrDefault ()) ?? "";
#endif
}
public static bool IsAutoInc (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (AutoIncrementAttribute));
}
public static FieldInfo GetField (TypeInfo t, string name)
{
var f = t.GetDeclaredField (name);
if (f != null)
return f;
return GetField (t.BaseType.GetTypeInfo (), name);
}
public static PropertyInfo GetProperty (TypeInfo t, string name)
{
var f = t.GetDeclaredProperty (name);
if (f != null)
return f;
return GetProperty (t.BaseType.GetTypeInfo (), name);
}
public static object InflateAttribute (CustomAttributeData x)
{
var atype = x.AttributeType;
var typeInfo = atype.GetTypeInfo ();
#if ENABLE_IL2CPP
var r = Activator.CreateInstance (x.AttributeType);
#else
var args = x.ConstructorArguments.Select (a => a.Value).ToArray ();
var r = Activator.CreateInstance (x.AttributeType, args);
foreach (var arg in x.NamedArguments) {
if (arg.IsField) {
GetField (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
}
else {
GetProperty (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
}
}
#endif
return r;
}
public static IEnumerable<IndexedAttribute> GetIndices (MemberInfo p)
{
#if ENABLE_IL2CPP
return p.GetCustomAttributes<IndexedAttribute> ();
#else
var indexedInfo = typeof (IndexedAttribute).GetTypeInfo ();
return
p.CustomAttributes
.Where (x => indexedInfo.IsAssignableFrom (x.AttributeType.GetTypeInfo ()))
.Select (x => (IndexedAttribute)InflateAttribute (x));
#endif
}
public static int? MaxStringLength (MemberInfo p)
{
#if ENABLE_IL2CPP
return p.GetCustomAttribute<MaxLengthAttribute> ()?.Value;
#else
var attr = p.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (MaxLengthAttribute));
if (attr != null) {
var attrv = (MaxLengthAttribute)InflateAttribute (attr);
return attrv.Value;
}
return null;
#endif
}
public static int? MaxStringLength (PropertyInfo p) => MaxStringLength((MemberInfo)p);
public static bool IsMarkedNotNull (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (NotNullAttribute));
}
}
public partial class SQLiteCommand
{
SQLiteConnection _conn;
private List<Binding> _bindings;
public string CommandText { get; set; }
public SQLiteCommand (SQLiteConnection conn)
{
_conn = conn;
_bindings = new List<Binding> ();
CommandText = "";
}
public int ExecuteNonQuery ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing: " + this);
}
var r = SQLite3.Result.OK;
var stmt = Prepare ();
r = SQLite3.Step (stmt);
Finalize (stmt);
if (r == SQLite3.Result.Done) {
int rowsAffected = SQLite3.Changes (_conn.Handle);
return rowsAffected;
}
else if (r == SQLite3.Result.Error) {
string msg = SQLite3.GetErrmsg (_conn.Handle);
throw SQLiteException.New (r, msg);
}
else if (r == SQLite3.Result.Constraint) {
if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
}
throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
public IEnumerable<T> ExecuteDeferredQuery<T> ()
{
return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T)));
}
public List<T> ExecuteQuery<T> ()
{
return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T))).ToList ();
}
public List<T> ExecuteQuery<T> (TableMapping map)
{
return ExecuteDeferredQuery<T> (map).ToList ();
}
/// <summary>
/// Invoked every time an instance is loaded from the database.
/// </summary>
/// <param name='obj'>
/// The newly created object.
/// </param>
/// <remarks>
/// This can be overridden in combination with the <see cref="SQLiteConnection.NewCommand"/>
/// method to hook into the life-cycle of objects.
/// </remarks>
protected virtual void OnInstanceCreated (object obj)
{
// Can be overridden.
}
public IEnumerable<T> ExecuteDeferredQuery<T> (TableMapping map)
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
var stmt = Prepare ();
try {
var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)];
var fastColumnSetters = new Action<object, Sqlite3Statement, int>[SQLite3.ColumnCount (stmt)];
if (map.Method == TableMapping.MapMethod.ByPosition)
{
Array.Copy(map.Columns, cols, Math.Min(cols.Length, map.Columns.Length));
}
else if (map.Method == TableMapping.MapMethod.ByName) {
MethodInfo getSetter = null;
if (typeof(T) != map.MappedType) {
getSetter = typeof(FastColumnSetter)
.GetMethod (nameof(FastColumnSetter.GetFastSetter),
BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod (map.MappedType);
}
for (int i = 0; i < cols.Length; i++) {
var name = SQLite3.ColumnName16 (stmt, i);
cols[i] = map.FindColumn (name);
if (cols[i] != null)
if (getSetter != null) {
fastColumnSetters[i] = (Action<object, Sqlite3Statement, int>)getSetter.Invoke(null, new object[]{ _conn, cols[i]});
}
else {
fastColumnSetters[i] = FastColumnSetter.GetFastSetter<T>(_conn, cols[i]);
}
}
}
while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var obj = Activator.CreateInstance (map.MappedType);
for (int i = 0; i < cols.Length; i++) {
if (cols[i] == null)
continue;
if (fastColumnSetters[i] != null) {
fastColumnSetters[i].Invoke (obj, stmt, i);
}
else {
var colType = SQLite3.ColumnType (stmt, i);
var val = ReadCol (stmt, i, colType, cols[i].ColumnType);
cols[i].SetValue (obj, val);
}
}
OnInstanceCreated (obj);
yield return (T)obj;
}
}
finally {
SQLite3.Finalize (stmt);
}
}
public T ExecuteScalar<T> ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
T val = default (T);
var stmt = Prepare ();
try {
var r = SQLite3.Step (stmt);
if (r == SQLite3.Result.Row) {
var colType = SQLite3.ColumnType (stmt, 0);
var colval = ReadCol (stmt, 0, colType, typeof (T));
if (colval != null) {
val = (T)colval;
}
}
else if (r == SQLite3.Result.Done) {
}
else {
throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
}
finally {
Finalize (stmt);
}
return val;
}
public IEnumerable<T> ExecuteQueryScalars<T> ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
var stmt = Prepare ();
try {
if (SQLite3.ColumnCount (stmt) < 1) {
throw new InvalidOperationException ("QueryScalars should return at least one column");
}
while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var colType = SQLite3.ColumnType (stmt, 0);
var val = ReadCol (stmt, 0, colType, typeof (T));
if (val == null) {
yield return default (T);
}
else {
yield return (T)val;
}
}
}
finally {
Finalize (stmt);
}
}
public void Bind (string name, object val)
{
_bindings.Add (new Binding {
Name = name,
Value = val
});
}
public void Bind (object val)
{
Bind (null, val);
}
public override string ToString ()
{
var parts = new string[1 + _bindings.Count];
parts[0] = CommandText;
var i = 1;
foreach (var b in _bindings) {
parts[i] = string.Format (" {0}: {1}", i - 1, b.Value);
i++;
}
return string.Join (Environment.NewLine, parts);
}
Sqlite3Statement Prepare ()
{
var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText);
BindAll (stmt);
return stmt;
}
void Finalize (Sqlite3Statement stmt)
{
SQLite3.Finalize (stmt);
}
void BindAll (Sqlite3Statement stmt)
{
int nextIdx = 1;
foreach (var b in _bindings) {
if (b.Name != null) {
b.Index = SQLite3.BindParameterIndex (stmt, b.Name);
}
else {
b.Index = nextIdx++;
}
BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks, _conn.DateTimeStringFormat, _conn.StoreTimeSpanAsTicks);
}
}
static IntPtr NegativePointer = new IntPtr (-1);
internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks, string dateTimeStringFormat, bool storeTimeSpanAsTicks)
{
if (value == null) {
SQLite3.BindNull (stmt, index);
}
else {
if (value is Int32) {
SQLite3.BindInt (stmt, index, (int)value);
}
else if (value is String) {
SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer);
}
else if (value is Byte || value is UInt16 || value is SByte || value is Int16) {
SQLite3.BindInt (stmt, index, Convert.ToInt32 (value));
}
else if (value is Boolean) {
SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0);
}
else if (value is UInt32 || value is Int64) {
SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value));
}
else if (value is Single || value is Double || value is Decimal) {
SQLite3.BindDouble (stmt, index, Convert.ToDouble (value));
}
else if (value is TimeSpan) {
if (storeTimeSpanAsTicks) {
SQLite3.BindInt64 (stmt, index, ((TimeSpan)value).Ticks);
}
else {
SQLite3.BindText (stmt, index, ((TimeSpan)value).ToString (), -1, NegativePointer);
}
}
else if (value is DateTime) {
if (storeDateTimeAsTicks) {
SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks);
}
else {
SQLite3.BindText (stmt, index, ((DateTime)value).ToString (dateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture), -1, NegativePointer);
}
}
else if (value is DateTimeOffset) {
SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks);
}
else if (value is byte[]) {
SQLite3.BindBlob (stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer);
}
else if (value is Guid) {
SQLite3.BindText (stmt, index, ((Guid)value).ToString (), 72, NegativePointer);
}
else if (value is Uri) {
SQLite3.BindText (stmt, index, ((Uri)value).ToString (), -1, NegativePointer);
}
else if (value is StringBuilder) {
SQLite3.BindText (stmt, index, ((StringBuilder)value).ToString (), -1, NegativePointer);
}
else if (value is UriBuilder) {
SQLite3.BindText (stmt, index, ((UriBuilder)value).ToString (), -1, NegativePointer);
}
else {
// Now we could possibly get an enum, retrieve cached info
var valueType = value.GetType ();
var enumInfo = EnumCache.GetInfo (valueType);
if (enumInfo.IsEnum) {
var enumIntValue = Convert.ToInt32 (value);
if (enumInfo.StoreAsText)
SQLite3.BindText (stmt, index, enumInfo.EnumValues[enumIntValue], -1, NegativePointer);
else
SQLite3.BindInt (stmt, index, enumIntValue);
}
else {
throw new NotSupportedException ("Cannot store type: " + Orm.GetType (value));
}
}
}
}
class Binding
{
public string Name { get; set; }
public object Value { get; set; }
public int Index { get; set; }
}
object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType)
{
if (type == SQLite3.ColType.Null) {
return null;
}
else {
var clrTypeInfo = clrType.GetTypeInfo ();
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
clrType = clrTypeInfo.GenericTypeArguments[0];
clrTypeInfo = clrType.GetTypeInfo ();
}
if (clrType == typeof (String)) {
return SQLite3.ColumnString (stmt, index);
}
else if (clrType == typeof (Int32)) {
return (int)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Boolean)) {
return SQLite3.ColumnInt (stmt, index) == 1;
}
else if (clrType == typeof (double)) {
return SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (float)) {
return (float)SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (TimeSpan)) {
if (_conn.StoreTimeSpanAsTicks) {
return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
}
else {
var text = SQLite3.ColumnString (stmt, index);
TimeSpan resultTime;
if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
resultTime = TimeSpan.Parse (text);
}
return resultTime;
}
}
else if (clrType == typeof (DateTime)) {
if (_conn.StoreDateTimeAsTicks) {
return new DateTime (SQLite3.ColumnInt64 (stmt, index));
}
else {
var text = SQLite3.ColumnString (stmt, index);
DateTime resultDate;
if (!DateTime.TryParseExact (text, _conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, _conn.DateTimeStyle, out resultDate)) {
resultDate = DateTime.Parse (text);
}
return resultDate;
}
}
else if (clrType == typeof (DateTimeOffset)) {
return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
}
else if (clrTypeInfo.IsEnum) {
if (type == SQLite3.ColType.Text) {
var value = SQLite3.ColumnString (stmt, index);
return Enum.Parse (clrType, value.ToString (), true);
}
else
return SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Int64)) {
return SQLite3.ColumnInt64 (stmt, index);
}
else if (clrType == typeof (UInt32)) {
return (uint)SQLite3.ColumnInt64 (stmt, index);
}
else if (clrType == typeof (decimal)) {
return (decimal)SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (Byte)) {
return (byte)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (UInt16)) {
return (ushort)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Int16)) {
return (short)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (sbyte)) {
return (sbyte)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (byte[])) {
return SQLite3.ColumnByteArray (stmt, index);
}
else if (clrType == typeof (Guid)) {
var text = SQLite3.ColumnString (stmt, index);
return new Guid (text);
}
else if (clrType == typeof (Uri)) {
var text = SQLite3.ColumnString (stmt, index);
return new Uri (text);
}
else if (clrType == typeof (StringBuilder)) {
var text = SQLite3.ColumnString (stmt, index);
return new StringBuilder (text);
}
else if (clrType == typeof (UriBuilder)) {
var text = SQLite3.ColumnString (stmt, index);
return new UriBuilder (text);
}
else {
throw new NotSupportedException ("Don't know how to read " + clrType);
}
}
}
}
internal class FastColumnSetter
{
/// <summary>
/// Creates a delegate that can be used to quickly set object members from query columns.
///
/// Note that this frontloads the slow reflection-based type checking for columns to only happen once at the beginning of a query,
/// and then afterwards each row of the query can invoke the delegate returned by this function to get much better performance (up to 10x speed boost, depending on query size and platform).
/// </summary>
/// <typeparam name="T">The type of the destination object that the query will read into</typeparam>
/// <param name="conn">The active connection. Note that this is primarily needed in order to read preferences regarding how certain data types (such as TimeSpan / DateTime) should be encoded in the database.</param>
/// <param name="column">The table mapping used to map the statement column to a member of the destination object type</param>
/// <returns>
/// A delegate for fast-setting of object members from statement columns.
///
/// If no fast setter is available for the requested column (enums in particular cause headache), then this function returns null.
/// </returns>
internal static Action<object, Sqlite3Statement, int> GetFastSetter<T> (SQLiteConnection conn, TableMapping.Column column)
{
Action<object, Sqlite3Statement, int> fastSetter = null;
Type clrType = column.PropertyInfo.PropertyType;
var clrTypeInfo = clrType.GetTypeInfo ();
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
clrType = clrTypeInfo.GenericTypeArguments[0];
clrTypeInfo = clrType.GetTypeInfo ();
}
if (clrType == typeof (String)) {
fastSetter = CreateTypedSetterDelegate<T, string> (column, (stmt, index) => {
return SQLite3.ColumnString (stmt, index);
});
}
else if (clrType == typeof (Int32)) {
fastSetter = CreateNullableTypedSetterDelegate<T, int> (column, (stmt, index)=>{
return SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (Boolean)) {
fastSetter = CreateNullableTypedSetterDelegate<T, bool> (column, (stmt, index) => {
return SQLite3.ColumnInt (stmt, index) == 1;
});
}
else if (clrType == typeof (double)) {
fastSetter = CreateNullableTypedSetterDelegate<T, double> (column, (stmt, index) => {
return SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (float)) {
fastSetter = CreateNullableTypedSetterDelegate<T, float> (column, (stmt, index) => {
return (float) SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (TimeSpan)) {
if (conn.StoreTimeSpanAsTicks) {
fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
});
}
else {
fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
TimeSpan resultTime;
if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
resultTime = TimeSpan.Parse (text);
}
return resultTime;
});
}
}
else if (clrType == typeof (DateTime)) {
if (conn.StoreDateTimeAsTicks) {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
return new DateTime (SQLite3.ColumnInt64 (stmt, index));
});
}
else {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
DateTime resultDate;
if (!DateTime.TryParseExact (text, conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, conn.DateTimeStyle, out resultDate)) {
resultDate = DateTime.Parse (text);
}
return resultDate;
});
}
}
else if (clrType == typeof (DateTimeOffset)) {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTimeOffset> (column, (stmt, index) => {
return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
});
}
else if (clrTypeInfo.IsEnum) {
// NOTE: Not sure of a good way (if any?) to do a strongly-typed fast setter like this for enumerated types -- for now, return null and column sets will revert back to the safe (but slow) Reflection-based method of column prop.Set()
}
else if (clrType == typeof (Int64)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Int64> (column, (stmt, index) => {
return SQLite3.ColumnInt64 (stmt, index);
});
}
else if (clrType == typeof (UInt32)) {
fastSetter = CreateNullableTypedSetterDelegate<T, UInt32> (column, (stmt, index) => {
return (uint)SQLite3.ColumnInt64 (stmt, index);
});
}
else if (clrType == typeof (decimal)) {
fastSetter = CreateNullableTypedSetterDelegate<T, decimal> (column, (stmt, index) => {
return (decimal)SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (Byte)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Byte> (column, (stmt, index) => {
return (byte)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (UInt16)) {
fastSetter = CreateNullableTypedSetterDelegate<T, UInt16> (column, (stmt, index) => {
return (ushort)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (Int16)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Int16> (column, (stmt, index) => {
return (short)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (sbyte)) {
fastSetter = CreateNullableTypedSetterDelegate<T, sbyte> (column, (stmt, index) => {
return (sbyte)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (byte[])) {
fastSetter = CreateTypedSetterDelegate<T, byte[]> (column, (stmt, index) => {
return SQLite3.ColumnByteArray (stmt, index);
});
}
else if (clrType == typeof (Guid)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Guid> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new Guid (text);
});
}
else if (clrType == typeof (Uri)) {
fastSetter = CreateTypedSetterDelegate<T, Uri> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new Uri (text);
});
}
else if (clrType == typeof (StringBuilder)) {
fastSetter = CreateTypedSetterDelegate<T, StringBuilder> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new StringBuilder (text);
});
}
else if (clrType == typeof (UriBuilder)) {
fastSetter = CreateTypedSetterDelegate<T, UriBuilder> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new UriBuilder (text);
});
}
else {
// NOTE: Will fall back to the slow setter method in the event that we are unable to create a fast setter delegate for a particular column type
}
return fastSetter;
}
/// <summary>
/// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
///
/// Note that this is identical to CreateTypedSetterDelegate(), but has an extra check to see if it should create a nullable version of the delegate.
/// </summary>
/// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
/// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
/// <param name="column">The column mapping that identifies the target member of the destination object</param>
/// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
/// <returns>A strongly-typed delegate</returns>
private static Action<object, Sqlite3Statement, int> CreateNullableTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue) where ColumnMemberType : struct
{
var clrTypeInfo = column.PropertyInfo.PropertyType.GetTypeInfo();
bool isNullable = false;
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
isNullable = true;
}
if (isNullable) {
var setProperty = (Action<ObjectType, ColumnMemberType?>)Delegate.CreateDelegate (
typeof (Action<ObjectType, ColumnMemberType?>), null,
column.PropertyInfo.GetSetMethod ());
return (o, stmt, i) => {
var colType = SQLite3.ColumnType (stmt, i);
if (colType != SQLite3.ColType.Null)
setProperty.Invoke ((ObjectType)o, getColumnValue.Invoke (stmt, i));
};
}
return CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (column, getColumnValue);
}
/// <summary>
/// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
/// </summary>
/// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
/// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
/// <param name="column">The column mapping that identifies the target member of the destination object</param>
/// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
/// <returns>A strongly-typed delegate</returns>
private static Action<object, Sqlite3Statement, int> CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue)
{
var setProperty = (Action<ObjectType, ColumnMemberType>)Delegate.CreateDelegate (
typeof (Action<ObjectType, ColumnMemberType>), null,
column.PropertyInfo.GetSetMethod ());
return (o, stmt, i) => {
var colType = SQLite3.ColumnType (stmt, i);
if (colType != SQLite3.ColType.Null)
setProperty.Invoke ((ObjectType)o, getColumnValue.Invoke (stmt, i));
};
}
}
/// <summary>
/// Since the insert never changed, we only need to prepare once.
/// </summary>
class PreparedSqlLiteInsertCommand : IDisposable
{
bool Initialized;
SQLiteConnection Connection;
string CommandText;
Sqlite3Statement Statement;
static readonly Sqlite3Statement NullStatement = default (Sqlite3Statement);
public PreparedSqlLiteInsertCommand (SQLiteConnection conn, string commandText)
{
Connection = conn;
CommandText = commandText;
}
public int ExecuteNonQuery (object[] source)
{
if (Initialized && Statement == NullStatement) {
throw new ObjectDisposedException (nameof (PreparedSqlLiteInsertCommand));
}
if (Connection.Trace) {
Connection.Tracer?.Invoke ("Executing: " + CommandText);
}
var r = SQLite3.Result.OK;
if (!Initialized) {
Statement = SQLite3.Prepare2 (Connection.Handle, CommandText);
Initialized = true;
}
//bind the values.
if (source != null) {
for (int i = 0; i < source.Length; i++) {
SQLiteCommand.BindParameter (Statement, i + 1, source[i], Connection.StoreDateTimeAsTicks, Connection.DateTimeStringFormat, Connection.StoreTimeSpanAsTicks);
}
}
r = SQLite3.Step (Statement);
if (r == SQLite3.Result.Done) {
int rowsAffected = SQLite3.Changes (Connection.Handle);
SQLite3.Reset (Statement);
return rowsAffected;
}
else if (r == SQLite3.Result.Error) {
string msg = SQLite3.GetErrmsg (Connection.Handle);
SQLite3.Reset (Statement);
throw SQLiteException.New (r, msg);
}
else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
SQLite3.Reset (Statement);
throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle));
}
else {
SQLite3.Reset (Statement);
throw SQLiteException.New (r, SQLite3.GetErrmsg (Connection.Handle));
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
void Dispose (bool disposing)
{
var s = Statement;
Statement = NullStatement;
Connection = null;
if (s != NullStatement) {
SQLite3.Finalize (s);
}
}
~PreparedSqlLiteInsertCommand ()
{
Dispose (false);
}
}
public enum CreateTableResult
{
Created,
Migrated,
}
public class CreateTablesResult
{
public Dictionary<Type, CreateTableResult> Results { get; private set; }
public CreateTablesResult ()
{
Results = new Dictionary<Type, CreateTableResult> ();
}
}
public abstract class BaseTableQuery
{
protected class Ordering
{
public string ColumnName { get; set; }
public bool Ascending { get; set; }
}
}
public class TableQuery<T> : BaseTableQuery, IEnumerable<T>
{
public SQLiteConnection Connection { get; private set; }
public TableMapping Table { get; private set; }
Expression _where;
List<Ordering> _orderBys;
int? _limit;
int? _offset;
BaseTableQuery _joinInner;
Expression _joinInnerKeySelector;
BaseTableQuery _joinOuter;
Expression _joinOuterKeySelector;
Expression _joinSelector;
Expression _selector;
TableQuery (SQLiteConnection conn, TableMapping table)
{
Connection = conn;
Table = table;
}
public TableQuery (SQLiteConnection conn)
{
Connection = conn;
Table = Connection.GetMapping (typeof (T));
}
public TableQuery<U> Clone<U> ()
{
var q = new TableQuery<U> (Connection, Table);
q._where = _where;
q._deferred = _deferred;
if (_orderBys != null) {
q._orderBys = new List<Ordering> (_orderBys);
}
q._limit = _limit;
q._offset = _offset;
q._joinInner = _joinInner;
q._joinInnerKeySelector = _joinInnerKeySelector;
q._joinOuter = _joinOuter;
q._joinOuterKeySelector = _joinOuterKeySelector;
q._joinSelector = _joinSelector;
q._selector = _selector;
return q;
}
/// <summary>
/// Filters the query based on a predicate.
/// </summary>
public TableQuery<T> Where (Expression<Func<T, bool>> predExpr)
{
if (predExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)predExpr;
var pred = lambda.Body;
var q = Clone<T> ();
q.AddWhere (pred);
return q;
}
else {
throw new NotSupportedException ("Must be a predicate");
}
}
/// <summary>
/// Delete all the rows that match this query.
/// </summary>
public int Delete ()
{
return Delete (null);
}
/// <summary>
/// Delete all the rows that match this query and the given predicate.
/// </summary>
public int Delete (Expression<Func<T, bool>> predExpr)
{
if (_limit.HasValue || _offset.HasValue)
throw new InvalidOperationException ("Cannot delete with limits or offsets");
if (_where == null && predExpr == null)
throw new InvalidOperationException ("No condition specified");
var pred = _where;
if (predExpr != null && predExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)predExpr;
pred = pred != null ? Expression.AndAlso (pred, lambda.Body) : lambda.Body;
}
var args = new List<object> ();
var cmdText = "delete from \"" + Table.TableName + "\"";
var w = CompileExpr (pred, args);
cmdText += " where " + w.CommandText;
var command = Connection.CreateCommand (cmdText, args.ToArray ());
int result = command.ExecuteNonQuery ();
return result;
}
/// <summary>
/// Yields a given number of elements from the query and then skips the remainder.
/// </summary>
public TableQuery<T> Take (int n)
{
var q = Clone<T> ();
q._limit = n;
return q;
}
/// <summary>
/// Skips a given number of elements from the query and then yields the remainder.
/// </summary>
public TableQuery<T> Skip (int n)
{
var q = Clone<T> ();
q._offset = n;
return q;
}
/// <summary>
/// Returns the element at a given index
/// </summary>
public T ElementAt (int index)
{
return Skip (index).Take (1).First ();
}
bool _deferred;
public TableQuery<T> Deferred ()
{
var q = Clone<T> ();
q._deferred = true;
return q;
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, true);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, false);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> ThenBy<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, true);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> ThenByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, false);
}
TableQuery<T> AddOrderBy<U> (Expression<Func<T, U>> orderExpr, bool asc)
{
if (orderExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)orderExpr;
MemberExpression mem = null;
var unary = lambda.Body as UnaryExpression;
if (unary != null && unary.NodeType == ExpressionType.Convert) {
mem = unary.Operand as MemberExpression;
}
else {
mem = lambda.Body as MemberExpression;
}
if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) {
var q = Clone<T> ();
if (q._orderBys == null) {
q._orderBys = new List<Ordering> ();
}
q._orderBys.Add (new Ordering {
ColumnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name,
Ascending = asc
});
return q;
}
else {
throw new NotSupportedException ("Order By does not support: " + orderExpr);
}
}
else {
throw new NotSupportedException ("Must be a predicate");
}
}
private void AddWhere (Expression pred)
{
if (_where == null) {
_where = pred;
}
else {
_where = Expression.AndAlso (_where, pred);
}
}
///// <summary>
///// Performs an inner join of two queries based on matching keys extracted from the elements.
///// </summary>
//public TableQuery<TResult> Join<TInner, TKey, TResult> (
// TableQuery<TInner> inner,
// Expression<Func<T, TKey>> outerKeySelector,
// Expression<Func<TInner, TKey>> innerKeySelector,
// Expression<Func<T, TInner, TResult>> resultSelector)
//{
// var q = new TableQuery<TResult> (Connection, Connection.GetMapping (typeof (TResult))) {
// _joinOuter = this,
// _joinOuterKeySelector = outerKeySelector,
// _joinInner = inner,
// _joinInnerKeySelector = innerKeySelector,
// _joinSelector = resultSelector,
// };
// return q;
//}
// Not needed until Joins are supported
// Keeping this commented out forces the default Linq to objects processor to run
//public TableQuery<TResult> Select<TResult> (Expression<Func<T, TResult>> selector)
//{
// var q = Clone<TResult> ();
// q._selector = selector;
// return q;
//}
private SQLiteCommand GenerateCommand (string selectionList)
{
if (_joinInner != null && _joinOuter != null) {
throw new NotSupportedException ("Joins are not supported.");
}
else {
var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\"";
var args = new List<object> ();
if (_where != null) {
var w = CompileExpr (_where, args);
cmdText += " where " + w.CommandText;
}
if ((_orderBys != null) && (_orderBys.Count > 0)) {
var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ());
cmdText += " order by " + t;
}
if (_limit.HasValue) {
cmdText += " limit " + _limit.Value;
}
if (_offset.HasValue) {
if (!_limit.HasValue) {
cmdText += " limit -1 ";
}
cmdText += " offset " + _offset.Value;
}
return Connection.CreateCommand (cmdText, args.ToArray ());
}
}
class CompileResult
{
public string CommandText { get; set; }
public object Value { get; set; }
}
private CompileResult CompileExpr (Expression expr, List<object> queryArgs)
{
if (expr == null) {
throw new NotSupportedException ("Expression is NULL");
}
else if (expr is BinaryExpression) {
var bin = (BinaryExpression)expr;
// VB turns 'x=="foo"' into 'CompareString(x,"foo",true/false)==0', so we need to unwrap it
// http://blogs.msdn.com/b/vbteam/archive/2007/09/18/vb-expression-trees-string-comparisons.aspx
if (bin.Left.NodeType == ExpressionType.Call) {
var call = (MethodCallExpression)bin.Left;
if (call.Method.DeclaringType.FullName == "Microsoft.VisualBasic.CompilerServices.Operators"
&& call.Method.Name == "CompareString")
bin = Expression.MakeBinary (bin.NodeType, call.Arguments[0], call.Arguments[1]);
}
var leftr = CompileExpr (bin.Left, queryArgs);
var rightr = CompileExpr (bin.Right, queryArgs);
//If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
string text;
if (leftr.CommandText == "?" && leftr.Value == null)
text = CompileNullBinaryExpression (bin, rightr);
else if (rightr.CommandText == "?" && rightr.Value == null)
text = CompileNullBinaryExpression (bin, leftr);
else
text = "(" + leftr.CommandText + " " + GetSqlName (bin) + " " + rightr.CommandText + ")";
return new CompileResult { CommandText = text };
}
else if (expr.NodeType == ExpressionType.Not) {
var operandExpr = ((UnaryExpression)expr).Operand;
var opr = CompileExpr (operandExpr, queryArgs);
object val = opr.Value;
if (val is bool)
val = !((bool)val);
return new CompileResult {
CommandText = "NOT(" + opr.CommandText + ")",
Value = val
};
}
else if (expr.NodeType == ExpressionType.Call) {
var call = (MethodCallExpression)expr;
var args = new CompileResult[call.Arguments.Count];
var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null;
for (var i = 0; i < args.Length; i++) {
args[i] = CompileExpr (call.Arguments[i], queryArgs);
}
var sqlCall = "";
if (call.Method.Name == "Like" && args.Length == 2) {
sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")";
}
else if (call.Method.Name == "Contains" && args.Length == 2) {
sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")";
}
else if (call.Method.Name == "Contains" && args.Length == 1) {
if (call.Object != null && call.Object.Type == typeof (string)) {
sqlCall = "( instr(" + obj.CommandText + "," + args[0].CommandText + ") >0 )";
}
else {
sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")";
}
}
else if (call.Method.Name == "StartsWith" && args.Length >= 1) {
var startsWithCmpOp = StringComparison.CurrentCulture;
if (args.Length == 2) {
startsWithCmpOp = (StringComparison)args[1].Value;
}
switch (startsWithCmpOp) {
case StringComparison.Ordinal:
case StringComparison.CurrentCulture:
sqlCall = "( substr(" + obj.CommandText + ", 1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
break;
case StringComparison.OrdinalIgnoreCase:
case StringComparison.CurrentCultureIgnoreCase:
sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))";
break;
}
}
else if (call.Method.Name == "EndsWith" && args.Length >= 1) {
var endsWithCmpOp = StringComparison.CurrentCulture;
if (args.Length == 2) {
endsWithCmpOp = (StringComparison)args[1].Value;
}
switch (endsWithCmpOp) {
case StringComparison.Ordinal:
case StringComparison.CurrentCulture:
sqlCall = "( substr(" + obj.CommandText + ", length(" + obj.CommandText + ") - " + args[0].Value.ToString ().Length + "+1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
break;
case StringComparison.OrdinalIgnoreCase:
case StringComparison.CurrentCultureIgnoreCase:
sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))";
break;
}
}
else if (call.Method.Name == "Equals" && args.Length == 1) {
sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
}
else if (call.Method.Name == "ToLower") {
sqlCall = "(lower(" + obj.CommandText + "))";
}
else if (call.Method.Name == "ToUpper") {
sqlCall = "(upper(" + obj.CommandText + "))";
}
else if (call.Method.Name == "Replace" && args.Length == 2) {
sqlCall = "(replace(" + obj.CommandText + "," + args[0].CommandText + "," + args[1].CommandText + "))";
}
else if (call.Method.Name == "IsNullOrEmpty" && args.Length == 1) {
sqlCall = "(" + args[0].CommandText + " is null or" + args[0].CommandText + " ='' )";
}
else {
sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")";
}
return new CompileResult { CommandText = sqlCall };
}
else if (expr.NodeType == ExpressionType.Constant) {
var c = (ConstantExpression)expr;
queryArgs.Add (c.Value);
return new CompileResult {
CommandText = "?",
Value = c.Value
};
}
else if (expr.NodeType == ExpressionType.Convert) {
var u = (UnaryExpression)expr;
var ty = u.Type;
var valr = CompileExpr (u.Operand, queryArgs);
return new CompileResult {
CommandText = valr.CommandText,
Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null
};
}
else if (expr.NodeType == ExpressionType.MemberAccess) {
var mem = (MemberExpression)expr;
var paramExpr = mem.Expression as ParameterExpression;
if (paramExpr == null) {
var convert = mem.Expression as UnaryExpression;
if (convert != null && convert.NodeType == ExpressionType.Convert) {
paramExpr = convert.Operand as ParameterExpression;
}
}
if (paramExpr != null) {
//
// This is a column of our table, output just the column name
// Need to translate it if that column name is mapped
//
var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name;
return new CompileResult { CommandText = "\"" + columnName + "\"" };
}
else {
object obj = null;
if (mem.Expression != null) {
var r = CompileExpr (mem.Expression, queryArgs);
if (r.Value == null) {
throw new NotSupportedException ("Member access failed to compile expression");
}
if (r.CommandText == "?") {
queryArgs.RemoveAt (queryArgs.Count - 1);
}
obj = r.Value;
}
//
// Get the member value
//
object val = null;
if (mem.Member is PropertyInfo) {
var m = (PropertyInfo)mem.Member;
val = m.GetValue (obj, null);
}
else if (mem.Member is FieldInfo) {
var m = (FieldInfo)mem.Member;
val = m.GetValue (obj);
}
else {
throw new NotSupportedException ("MemberExpr: " + mem.Member.GetType ());
}
//
// Work special magic for enumerables
//
if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable<byte>)) {
var sb = new System.Text.StringBuilder ();
sb.Append ("(");
var head = "";
foreach (var a in (System.Collections.IEnumerable)val) {
queryArgs.Add (a);
sb.Append (head);
sb.Append ("?");
head = ",";
}
sb.Append (")");
return new CompileResult {
CommandText = sb.ToString (),
Value = val
};
}
else {
queryArgs.Add (val);
return new CompileResult {
CommandText = "?",
Value = val
};
}
}
}
throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ());
}
static object ConvertTo (object obj, Type t)
{
Type nut = Nullable.GetUnderlyingType (t);
if (nut != null) {
if (obj == null)
return null;
return Convert.ChangeType (obj, nut);
}
else {
return Convert.ChangeType (obj, t);
}
}
/// <summary>
/// Compiles a BinaryExpression where one of the parameters is null.
/// </summary>
/// <param name="expression">The expression to compile</param>
/// <param name="parameter">The non-null parameter</param>
private string CompileNullBinaryExpression (BinaryExpression expression, CompileResult parameter)
{
if (expression.NodeType == ExpressionType.Equal)
return "(" + parameter.CommandText + " is ?)";
else if (expression.NodeType == ExpressionType.NotEqual)
return "(" + parameter.CommandText + " is not ?)";
else if (expression.NodeType == ExpressionType.GreaterThan
|| expression.NodeType == ExpressionType.GreaterThanOrEqual
|| expression.NodeType == ExpressionType.LessThan
|| expression.NodeType == ExpressionType.LessThanOrEqual)
return "(" + parameter.CommandText + " < ?)"; // always false
else
throw new NotSupportedException ("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString ());
}
string GetSqlName (Expression expr)
{
var n = expr.NodeType;
if (n == ExpressionType.GreaterThan)
return ">";
else if (n == ExpressionType.GreaterThanOrEqual) {
return ">=";
}
else if (n == ExpressionType.LessThan) {
return "<";
}
else if (n == ExpressionType.LessThanOrEqual) {
return "<=";
}
else if (n == ExpressionType.And) {
return "&";
}
else if (n == ExpressionType.AndAlso) {
return "and";
}
else if (n == ExpressionType.Or) {
return "|";
}
else if (n == ExpressionType.OrElse) {
return "or";
}
else if (n == ExpressionType.Equal) {
return "=";
}
else if (n == ExpressionType.NotEqual) {
return "!=";
}
else {
throw new NotSupportedException ("Cannot get SQL for: " + n);
}
}
/// <summary>
/// Execute SELECT COUNT(*) on the query
/// </summary>
public int Count ()
{
return GenerateCommand ("count(*)").ExecuteScalar<int> ();
}
/// <summary>
/// Execute SELECT COUNT(*) on the query with an additional WHERE clause.
/// </summary>
public int Count (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).Count ();
}
public IEnumerator<T> GetEnumerator ()
{
if (!_deferred)
return GenerateCommand ("*").ExecuteQuery<T> ().GetEnumerator ();
return GenerateCommand ("*").ExecuteDeferredQuery<T> ().GetEnumerator ();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
/// <summary>
/// Queries the database and returns the results as a List.
/// </summary>
public List<T> ToList ()
{
return GenerateCommand ("*").ExecuteQuery<T> ();
}
/// <summary>
/// Queries the database and returns the results as an array.
/// </summary>
public T[] ToArray ()
{
return GenerateCommand ("*").ExecuteQuery<T> ().ToArray ();
}
/// <summary>
/// Returns the first element of this query.
/// </summary>
public T First ()
{
var query = Take (1);
return query.ToList ().First ();
}
/// <summary>
/// Returns the first element of this query, or null if no element is found.
/// </summary>
public T FirstOrDefault ()
{
var query = Take (1);
return query.ToList ().FirstOrDefault ();
}
/// <summary>
/// Returns the first element of this query that matches the predicate.
/// </summary>
public T First (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).First ();
}
/// <summary>
/// Returns the first element of this query that matches the predicate, or null
/// if no element is found.
/// </summary>
public T FirstOrDefault (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).FirstOrDefault ();
}
}
public static class SQLite3
{
public enum Result : int
{
OK = 0,
Error = 1,
Internal = 2,
Perm = 3,
Abort = 4,
Busy = 5,
Locked = 6,
NoMem = 7,
ReadOnly = 8,
Interrupt = 9,
IOError = 10,
Corrupt = 11,
NotFound = 12,
Full = 13,
CannotOpen = 14,
LockErr = 15,
Empty = 16,
SchemaChngd = 17,
TooBig = 18,
Constraint = 19,
Mismatch = 20,
Misuse = 21,
NotImplementedLFS = 22,
AccessDenied = 23,
Format = 24,
Range = 25,
NonDBFile = 26,
Notice = 27,
Warning = 28,
Row = 100,
Done = 101
}
public enum ExtendedResult : int
{
IOErrorRead = (Result.IOError | (1 << 8)),
IOErrorShortRead = (Result.IOError | (2 << 8)),
IOErrorWrite = (Result.IOError | (3 << 8)),
IOErrorFsync = (Result.IOError | (4 << 8)),
IOErrorDirFSync = (Result.IOError | (5 << 8)),
IOErrorTruncate = (Result.IOError | (6 << 8)),
IOErrorFStat = (Result.IOError | (7 << 8)),
IOErrorUnlock = (Result.IOError | (8 << 8)),
IOErrorRdlock = (Result.IOError | (9 << 8)),
IOErrorDelete = (Result.IOError | (10 << 8)),
IOErrorBlocked = (Result.IOError | (11 << 8)),
IOErrorNoMem = (Result.IOError | (12 << 8)),
IOErrorAccess = (Result.IOError | (13 << 8)),
IOErrorCheckReservedLock = (Result.IOError | (14 << 8)),
IOErrorLock = (Result.IOError | (15 << 8)),
IOErrorClose = (Result.IOError | (16 << 8)),
IOErrorDirClose = (Result.IOError | (17 << 8)),
IOErrorSHMOpen = (Result.IOError | (18 << 8)),
IOErrorSHMSize = (Result.IOError | (19 << 8)),
IOErrorSHMLock = (Result.IOError | (20 << 8)),
IOErrorSHMMap = (Result.IOError | (21 << 8)),
IOErrorSeek = (Result.IOError | (22 << 8)),
IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)),
IOErrorMMap = (Result.IOError | (24 << 8)),
LockedSharedcache = (Result.Locked | (1 << 8)),
BusyRecovery = (Result.Busy | (1 << 8)),
CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)),
CannotOpenIsDir = (Result.CannotOpen | (2 << 8)),
CannotOpenFullPath = (Result.CannotOpen | (3 << 8)),
CorruptVTab = (Result.Corrupt | (1 << 8)),
ReadonlyRecovery = (Result.ReadOnly | (1 << 8)),
ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)),
ReadonlyRollback = (Result.ReadOnly | (3 << 8)),
AbortRollback = (Result.Abort | (2 << 8)),
ConstraintCheck = (Result.Constraint | (1 << 8)),
ConstraintCommitHook = (Result.Constraint | (2 << 8)),
ConstraintForeignKey = (Result.Constraint | (3 << 8)),
ConstraintFunction = (Result.Constraint | (4 << 8)),
ConstraintNotNull = (Result.Constraint | (5 << 8)),
ConstraintPrimaryKey = (Result.Constraint | (6 << 8)),
ConstraintTrigger = (Result.Constraint | (7 << 8)),
ConstraintUnique = (Result.Constraint | (8 << 8)),
ConstraintVTab = (Result.Constraint | (9 << 8)),
NoticeRecoverWAL = (Result.Notice | (1 << 8)),
NoticeRecoverRollback = (Result.Notice | (2 << 8))
}
public enum ConfigOption : int
{
SingleThread = 1,
MultiThread = 2,
Serialized = 3
}
const string LibraryPath = "sqlite3";
#if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE && !USE_SQLITEPCL_RAW
[DllImport(LibraryPath, EntryPoint = "sqlite3_threadsafe", CallingConvention=CallingConvention.Cdecl)]
public static extern int Threadsafe ();
[DllImport(LibraryPath, EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Open(byte[] filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)]
public static extern Result EnableLoadExtension (IntPtr db, int onoff);
[DllImport(LibraryPath, EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Close (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_close_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Close2(IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Initialize();
[DllImport(LibraryPath, EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Shutdown();
[DllImport(LibraryPath, EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Config (ConfigOption option);
[DllImport(LibraryPath, EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)]
public static extern int SetDirectory (uint directoryType, string directoryPath);
[DllImport(LibraryPath, EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)]
public static extern Result BusyTimeout (IntPtr db, int milliseconds);
[DllImport(LibraryPath, EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)]
public static extern int Changes (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail);
#if NETFX_CORE
[DllImport (LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail);
#endif
public static IntPtr Prepare2 (IntPtr db, string query)
{
IntPtr stmt;
#if NETFX_CORE
byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query);
var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero);
#else
var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero);
#endif
if (r != Result.OK) {
throw SQLiteException.New (r, GetErrmsg (db));
}
return stmt;
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Step (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Reset (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Finalize (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)]
public static extern long LastInsertRowid (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr Errmsg (IntPtr db);
public static string GetErrmsg (IntPtr db)
{
return Marshal.PtrToStringUni (Errmsg (db));
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindNull (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindInt (IntPtr stmt, int index, int val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindInt64 (IntPtr stmt, int index, long val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindDouble (IntPtr stmt, int index, double val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnCount (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnName (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr ColumnName16Internal (IntPtr stmt, int index);
public static string ColumnName16(IntPtr stmt, int index)
{
return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index));
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)]
public static extern ColType ColumnType (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnInt (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)]
public static extern long ColumnInt64 (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)]
public static extern double ColumnDouble (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnText (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnText16 (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnBlob (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnBytes (IntPtr stmt, int index);
public static string ColumnString (IntPtr stmt, int index)
{
return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index));
}
public static byte[] ColumnByteArray (IntPtr stmt, int index)
{
int length = ColumnBytes (stmt, index);
var result = new byte[length];
if (length > 0)
Marshal.Copy (ColumnBlob (stmt, index), result, 0, length);
return result;
}
[DllImport (LibraryPath, EntryPoint = "sqlite3_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern Result GetResult (Sqlite3DatabaseHandle db);
[DllImport (LibraryPath, EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern ExtendedResult ExtendedErrCode (IntPtr db);
[DllImport (LibraryPath, EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)]
public static extern int LibVersionNumber ();
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_init", CallingConvention = CallingConvention.Cdecl)]
public static extern Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, [MarshalAs (UnmanagedType.LPStr)] string destName, Sqlite3DatabaseHandle sourceDb, [MarshalAs (UnmanagedType.LPStr)] string sourceName);
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_step", CallingConvention = CallingConvention.Cdecl)]
public static extern Result BackupStep (Sqlite3BackupHandle backup, int numPages);
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_finish", CallingConvention = CallingConvention.Cdecl)]
public static extern Result BackupFinish (Sqlite3BackupHandle backup);
#else
public static Result Open (string filename, out Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_open (filename, out db);
}
public static Result Open (string filename, out Sqlite3DatabaseHandle db, int flags, string vfsName)
{
#if USE_WP8_NATIVE_SQLITE
return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, vfsName ?? "");
#else
return (Result)Sqlite3.sqlite3_open_v2 (filename, out db, flags, vfsName);
#endif
}
public static Result Close (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_close (db);
}
public static Result Close2 (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_close_v2 (db);
}
public static Result BusyTimeout (Sqlite3DatabaseHandle db, int milliseconds)
{
return (Result)Sqlite3.sqlite3_busy_timeout (db, milliseconds);
}
public static int Changes (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_changes (db);
}
public static Sqlite3Statement Prepare2 (Sqlite3DatabaseHandle db, string query)
{
Sqlite3Statement stmt = default (Sqlite3Statement);
#if USE_WP8_NATIVE_SQLITE || USE_SQLITEPCL_RAW
var r = Sqlite3.sqlite3_prepare_v2 (db, query, out stmt);
#else
stmt = new Sqlite3Statement();
var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0);
#endif
if (r != 0) {
throw SQLiteException.New ((Result)r, GetErrmsg (db));
}
return stmt;
}
public static Result Step (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_step (stmt);
}
public static Result Reset (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_reset (stmt);
}
public static Result Finalize (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_finalize (stmt);
}
public static long LastInsertRowid (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_last_insert_rowid (db);
}
public static string GetErrmsg (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_errmsg (db).utf8_to_string ();
}
public static int BindParameterIndex (Sqlite3Statement stmt, string name)
{
return Sqlite3.sqlite3_bind_parameter_index (stmt, name);
}
public static int BindNull (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_bind_null (stmt, index);
}
public static int BindInt (Sqlite3Statement stmt, int index, int val)
{
return Sqlite3.sqlite3_bind_int (stmt, index, val);
}
public static int BindInt64 (Sqlite3Statement stmt, int index, long val)
{
return Sqlite3.sqlite3_bind_int64 (stmt, index, val);
}
public static int BindDouble (Sqlite3Statement stmt, int index, double val)
{
return Sqlite3.sqlite3_bind_double (stmt, index, val);
}
public static int BindText (Sqlite3Statement stmt, int index, string val, int n, IntPtr free)
{
#if USE_WP8_NATIVE_SQLITE
return Sqlite3.sqlite3_bind_text(stmt, index, val, n);
#elif USE_SQLITEPCL_RAW
return Sqlite3.sqlite3_bind_text (stmt, index, val);
#else
return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null);
#endif
}
public static int BindBlob (Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free)
{
#if USE_WP8_NATIVE_SQLITE
return Sqlite3.sqlite3_bind_blob(stmt, index, val, n);
#elif USE_SQLITEPCL_RAW
return Sqlite3.sqlite3_bind_blob (stmt, index, val);
#else
return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null);
#endif
}
public static int ColumnCount (Sqlite3Statement stmt)
{
return Sqlite3.sqlite3_column_count (stmt);
}
public static string ColumnName (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
}
public static string ColumnName16 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
}
public static ColType ColumnType (Sqlite3Statement stmt, int index)
{
return (ColType)Sqlite3.sqlite3_column_type (stmt, index);
}
public static int ColumnInt (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_int (stmt, index);
}
public static long ColumnInt64 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_int64 (stmt, index);
}
public static double ColumnDouble (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_double (stmt, index);
}
public static string ColumnText (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static string ColumnText16 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static byte[] ColumnBlob (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_blob (stmt, index).ToArray ();
}
public static int ColumnBytes (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_bytes (stmt, index);
}
public static string ColumnString (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static byte[] ColumnByteArray (Sqlite3Statement stmt, int index)
{
int length = ColumnBytes (stmt, index);
if (length > 0) {
return ColumnBlob (stmt, index);
}
return new byte[0];
}
public static Result EnableLoadExtension (Sqlite3DatabaseHandle db, int onoff)
{
return (Result)Sqlite3.sqlite3_enable_load_extension (db, onoff);
}
public static int LibVersionNumber ()
{
return Sqlite3.sqlite3_libversion_number ();
}
public static Result GetResult (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_errcode (db);
}
public static ExtendedResult ExtendedErrCode (Sqlite3DatabaseHandle db)
{
return (ExtendedResult)Sqlite3.sqlite3_extended_errcode (db);
}
public static Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, string destName, Sqlite3DatabaseHandle sourceDb, string sourceName)
{
return Sqlite3.sqlite3_backup_init (destDb, destName, sourceDb, sourceName);
}
public static Result BackupStep (Sqlite3BackupHandle backup, int numPages)
{
return (Result)Sqlite3.sqlite3_backup_step (backup, numPages);
}
public static Result BackupFinish (Sqlite3BackupHandle backup)
{
return (Result)Sqlite3.sqlite3_backup_finish (backup);
}
#endif
public enum ColType : int
{
Integer = 1,
Float = 2,
Text = 3,
Blob = 4,
Null = 5
}
}
}
|
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
// https://stackoverflow.com/a/34384189
namespace PS4Macro.Classes.GlobalHooks
{
public class GlobalKeyboardHookEventArgs : HandledEventArgs
{
public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }
public GlobalKeyboardHookEventArgs(
GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
GlobalKeyboardHook.KeyboardState keyboardState)
{
KeyboardData = keyboardData;
KeyboardState = keyboardState;
}
}
//Based on https://gist.github.com/Stasonix
public class GlobalKeyboardHook : IDisposable
{
public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;
public GlobalKeyboardHook()
{
_windowsHookHandle = IntPtr.Zero;
_user32LibraryHandle = IntPtr.Zero;
_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.
_user32LibraryHandle = LoadLibrary("User32");
if (_user32LibraryHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
if (_windowsHookHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// because we can unhook only in the same thread, not in garbage collector thread
if (_windowsHookHandle != IntPtr.Zero)
{
if (!UnhookWindowsHookEx(_windowsHookHandle))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = IntPtr.Zero;
// ReSharper disable once DelegateSubtraction
_hookProc -= LowLevelKeyboardProc;
}
}
if (_user32LibraryHandle != IntPtr.Zero)
{
if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_user32LibraryHandle = IntPtr.Zero;
}
}
~GlobalKeyboardHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private IntPtr _windowsHookHandle;
private IntPtr _user32LibraryHandle;
private HookProc _hookProc;
delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events are
/// associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">hook type</param>
/// <param name="lpfn">hook procedure</param>
/// <param name="hMod">handle to application instance</param>
/// <param name="dwThreadId">thread identifier</param>
/// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="hhk">handle to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="hHook">handle to current hook</param>
/// <param name="code">hook code passed to hook procedure</param>
/// <param name="wParam">value passed to hook procedure</param>
/// <param name="lParam">value passed to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct LowLevelKeyboardInputEvent
{
/// <summary>
/// A virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualCode;
/// <summary>
/// A hardware scan code for the key.
/// </summary>
public int HardwareScanCode;
/// <summary>
/// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
/// </summary>
public int Flags;
/// <summary>
/// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
/// </summary>
public int TimeStamp;
/// <summary>
/// Additional information associated with the message.
/// </summary>
public IntPtr AdditionalInformation;
}
public const int WH_KEYBOARD_LL = 13;
//const int HC_ACTION = 0;
public enum KeyboardState
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SysKeyDown = 0x0104,
SysKeyUp = 0x0105
}
public const int VkSnapshot = 0x2c;
//const int VkLwin = 0x5b;
//const int VkRwin = 0x5c;
//const int VkTab = 0x09;
//const int VkEscape = 0x18;
//const int VkControl = 0x11;
const int KfAltdown = 0x2000;
public const int LlkhfAltdown = (KfAltdown >> 8);
public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
{
bool fEatKeyStroke = false;
var wparamTyped = wParam.ToInt32();
if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
{
object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;
var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);
EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
handler?.Invoke(this, eventArguments);
fEatKeyStroke = eventArguments.Handled;
}
return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
}
} |
using System; //default
using System.Collections.Generic; //dictionary,list
using System.Linq; //because jon skeet
using NetFwTypeLib; //firewall library
using System.Net.Sockets; //protocol enum
using System.Net; //IPAddress class
namespace msfw
{
/// <summary>
/// Provides a wrapper around the INetFwRule2 class and adds support for "serializing" the
/// rule into the same format as what is stored in the registry for group policy firewall rules
/// </summary>
public class MSFirewallRule
{
public INetFwRule2 rule;
public NET_FW_ACTION_ Action { get { return this.rule.Action; } }
public string ActionName { get { return MSFirewall.getActionName(this.rule.Action); } }
public string ApplicationName { get { return this.rule.ApplicationName; } }
public string AppAndService { get { return this.getAppAndService(); } }
public NET_FW_RULE_DIRECTION_ Direction { get { return this.rule.Direction; } }
public string DirectionName { get { return MSFirewall.getDirectionName(this.rule.Direction); } }
public bool Enabled { get { return this.rule.Enabled; } }
public string LocalAddresses { get { return this.getLocalAddresses(); } }
public string LocalPorts { get { return this.rule.LocalPorts ?? "*"; } }
public string Name { get { return this.rule.Name; } }
public int Profiles { get { return this.rule.Profiles; } }
public int Protocol { get { return this.rule.Protocol; } }
public string ProtocolName { get { return Enum.GetName(typeof(ProtocolType), rule.Protocol) ?? "*"; } }
public string RemoteAddresses { get { return this.getRemoteAddresses(); } }
public string RemotePorts { get { return this.rule.RemotePorts ?? "*"; } }
public string ServiceName { get { return this.rule.serviceName; } }
public bool Extended { get { return this.isExtended(); } }
/// <summary>
/// Constructor: takes in INetFwRule2.</summary>
public MSFirewallRule(INetFwRule2 rule)
{
this.rule = rule;
}
/// <summary>Constructor: Input is a "serialized" rule like one found in
/// "Software\Policies\Microsoft\WindowsFirewall\FirewallRules".</summary>
/// <remarks>See more details in the <see cref="parseRule"/> method</remarks>
public MSFirewallRule(string rulestr)
: this(rulestr, new Dictionary<string, string>())
{
}
/// <summary>
/// Constructor: Input is a "serialized" fw rule string like one found in
/// "Software\Policies\Microsoft\WindowsFirewall\FirewallRules"</summary>
/// <remarks>Allows variable substitution for key/values by providing
/// a dictionary of substitute information.
/// This is necessary since the registry rules store name/description
/// information in separate key/values.
/// See more details in the <see cref="parseRule"/> method</remarks>
public MSFirewallRule(string rulestr, Dictionary<string, string> info)
{
this.rule = this.parseRule(rulestr, info);
}
/// <summary>If rule contains attributes other than basic</summary>
/// <remarks>Basic attribures are:
/// 1. Action (Block, Allow)
/// 2. Direction (In, Out)
/// 3. Local IP Address/Port
/// 4. Remote IP Address/Port
/// 5. Application Name
/// 6. Rule Name</remarks>
private bool isExtended()
{
//basic
bool extended = false;
//if edge is false, then options is false
//rule.EdgeTraversal;
//rule.EdgeTraversalOptions;
if (this.rule.EdgeTraversal)
{
//Console.WriteLine("Edge:TRUE");
extended = true;
}
// "RemoteAccess", "Wireless", "Lan", and "All"
if(rule.InterfaceTypes != "All")
{
//Console.WriteLine("InterfaceTypes not all");
extended = true;
}
if (rule.Interfaces != null)
{
//Console.WriteLine("Interfaces not null");
extended = true;
}
if (rule.IcmpTypesAndCodes != null)
{
// Console.WriteLine("Icmp types and codes not all");
extended = true;
}
return extended;
}
/// <summary>Combines Application Name and Service Name</summary>
private string getAppAndService()
{
var appname = "*";
if (this.rule.ApplicationName != null)
{
appname = this.rule.ApplicationName;
if (this.rule.serviceName != null)
{
appname += ":" + this.rule.serviceName;
}
}
return appname;
}
/// <summary>Returns IP address, removing subnet mask for individual IPs (IPv4)</summary>
private string getLocalAddresses()
{
// TOOD: Support IPv6 LocalAddresses
var laddress = rule.LocalAddresses;
if (laddress.Contains("/255.255.255.255"))
{
laddress = laddress.Replace("/255.255.255.255", "");
}
return laddress ?? "*";
}
/// <summary>Returns IP address, removing subnet mask for individual IPs (IPv4)</summary>
private string getRemoteAddresses()
{
// TOOD: Support IPv6 RemoteAddresses
var raddress = rule.RemoteAddresses;
if (raddress.Contains("/255.255.255.255"))
{
raddress = raddress.Replace("/255.255.255.255", "");
}
return raddress ?? "*";
}
/// <summary>Parses a rule str to make a INetFwRule2</summary>
/// <remarks>This rule string is found in group policy rules and is undocumented,
/// as far as I can tell. I've done my best to document my findings here.
///
/// Field : rule Mapping : Values : Example
///"Action" : rule.Action : Allow,Block : Action=Allow
///"App" : rule.ApplicationName : Text : App=onenote.exe
///"Desc" : rule.Description : Text : Desc=My rule description
///"Dir" : rule.Direction : In,Out : Dir=In
///"Edge" : rule.EdgeTraversal : Bool : Edge=TRUE
///"Defer" : rule.EdgeTraversalOption : App,? : Defer=App
///"Active" : rule.Enabled : Bool : Active=TRUE
///"EmbedCtxt" : rule.Grouping : Text : EmbedCtxt=Core Networking
///"ICMP4","ICMP6" : rule.IcmpTypesAndCodes : :
///????????????????????? : rule.Interfaces : ??? :
///????????????????????? : rule.InterfaceTypes : ??? :
///"LA4","LA6" : rule.LocalAddresses : IP(s) or Enum : LA4=10.10.10.10 or LocalSubnet or ?
///"LPort","LPort2_10" : rule.LocalPorts : Port(s) or Enum : LPort=4500 or ?
///"Name" : rule.Name : Text : Name=My rule name
///"Profile" : rule.Profiles : Domain,Private,Public : Profile=Domain
///"Protocol" : rule.Protocol : ProtocolType : Protocol=6
///"RA4", "RA6" : rule.RemoteAddresses : IP(s) or Enum : RA4=10.10.10.10 or LocalSubnet or ?
///"RPort","RPort2_10" : rule.RemotePorts : Port(s) or Enum : RPort=4500 or ?
///"Svc" : rule.serviceName : Text : Svc=upnphost
///
/// Additional notes on fields:
///
/// All lists are comma-delimited
/// If not present, booleans are FALSE and normally restrictive fields allow all
/// "Action" : required. Will be "Allow" or "Block"
/// "App" : optional. Will be a complete path to an executable. Will be a complete path to svchost.exe if using "Svc" field
/// "Desc" : optional. Variable substitution needed for rules from registry.
/// "Dir" : required. Will be "In" or "Out"
/// "Edge" : optional. Will be "TRUE". Default is "FALSE"
/// "Defer" : optional. See enum NET_FW_EDGE_TRAVERSAL_TYPE_ for values. Only appears if "Edge" is TRUE and only used for DEFER_TO_APP and DEFER_TO_USER
/// "Active" : required. Will be "TRUE" or "FALSE"
/// "EmbedCtxt" : optional. Variable substitution needed for rules from registry.
/// "ICMP4" : optional. If Protocol is "Icmp", then list of allowed ICMP (v4) types and codes
/// "ICMP6" : optional. If Protocol is "IcmpV6", then list of allowed ICMP (v6) types and codes
/// "LA4" : optional. IPv4 Addresses (single, range, or subnet). Not allowed if "ICMP6" is defined.
/// "LA6" : optional. IPv6 Addresses (single, range, or subnet). Not allowed if "ICMP4" is defined.
/// "LPort" : optional. Port or port range.
/// TODO: complete field documentation
/// </remarks>
public INetFwRule2 parseRule(string rulestr, Dictionary<string, string> info)
{
INetFwRule2 rule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
string[] ruleAttribs = rulestr.Split('|');
foreach (string ra in ruleAttribs)
{
var kv = ra.Split('=');
switch (kv[0])
{
case "":
case "v2.10":
//version ignore
break;
case "Action":
kv[1] = kv[1].ToLower();
if (kv[1] == "allow")
{
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
}
else if (kv[1] == "block")
{
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
}
else if (kv[1] == "max")
{
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_MAX;
}
else
{
throw new Exception("parseRule: Unknown action in rule: " + kv[1]);
}
break;
case "Active":
kv[1] = kv[1].ToLower();
if (kv[1] == "true")
{
rule.Enabled = true;
}
else
{
rule.Enabled = false;
}
break;
case "App":
rule.ApplicationName = kv[1];
break;
case "Defer":
kv[1] = kv[1].ToLower();
if (kv[1] == "app")
{
rule.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_APP;
}
else
{
rule.EdgeTraversalOptions = (int)Enum.Parse(typeof(NET_FW_EDGE_TRAVERSAL_TYPE_), kv[1]);
}
break;
case "Desc":
if (info.ContainsKey(kv[1]))
{
rule.Description = info[kv[1]];
}
else
{
rule.Description = kv[1];
}
break;
case "Dir":
kv[1] = kv[1].ToLower();
if (kv[1] == "in")
{
rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
}
else if (kv[1] == "out")
{
rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
}
else if (kv[1] == "max")
{
rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_MAX;
}
else
{
throw new Exception("parseRule: Unknown direction in rule: " + kv[1]);
}
break;
case "Edge":
kv[1] = kv[1].ToLower();
if (kv[1] == "true")
{
rule.EdgeTraversal = true;
}
else
{
rule.EdgeTraversal = false;
}
break;
case "EmbedCtxt":
if (info.ContainsKey(kv[1]))
{
rule.Grouping = info[kv[1]];
}
else
{
rule.Grouping = kv[1];
}
break;
case "ICMP4":
case "ICMP6":
if (rule.IcmpTypesAndCodes == "*")
{
rule.IcmpTypesAndCodes = kv[1];
}
else
{
//Console.WriteLine(rule.IcmpTypesAndCodes + " " + kv[1]);
rule.IcmpTypesAndCodes += "," + kv[1];
}
break;
case "LA4":
case "LA6":
if (rule.LocalAddresses == "*")
{
rule.LocalAddresses = kv[1];
}
else if (!rule.LocalAddresses.Contains(kv[1]))
{
rule.LocalAddresses += "," + kv[1];
}
break;
case "LPort":
if (rule.LocalPorts == "*")
{
//Console.WriteLine("init:" + kv[1]);
rule.LocalPorts = kv[1];
}
else
{
//Console.WriteLine("append: '" + rule.LocalPorts.ToString() + "'" + ":" + kv[1]);
rule.LocalPorts = rule.LocalPorts.ToString() + "," + kv[1];
}
break;
case "LPort2_10":
//todo:IPHTTPS maps to IPHTTPSIn AND IPTLSIn
//warning: unknown if correct; no example yet
rule.LocalPorts = kv[1];
break;
case "Name":
if (info.ContainsKey(kv[1]))
{
rule.Name = info[kv[1]];
}
else
{
rule.Name = kv[1];
}
break;
case "Profile":
if (rule.Profiles == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL)
{
switch (kv[1])
{
case "Domain":
rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN;
break;
case "Private":
rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE;
break;
case "Public":
rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC;
break;
}
}
else
{
switch (kv[1])
{
case "Domain":
rule.Profiles = rule.Profiles | (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN;
break;
case "Private":
rule.Profiles = rule.Profiles | (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE;
break;
case "Public":
rule.Profiles = rule.Profiles | (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC;
break;
}
}
break;
case "Protocol":
rule.Protocol = Int32.Parse(kv[1]);
break;
case "RA4":
case "RA6":
if (rule.RemoteAddresses == "*")
{
rule.RemoteAddresses = kv[1];
}
else if (!rule.RemoteAddresses.Contains(kv[1]))
{
rule.RemoteAddresses += "," + kv[1];
}
//Console.WriteLine(rule.RemoteAddresses + " + " + kv[1]);
//Console.WriteLine(rule.RemoteAddresses);
break;
case "RPort":
if (rule.RemotePorts == "*")
{
//Console.WriteLine("init:" + kv[1]);
rule.RemotePorts = kv[1];
}
else
{
//Console.WriteLine("append: '" + rule.RemotePorts.ToString() + "'" + ":" + kv[1]);
rule.RemotePorts += "," + kv[1];
}
break;
case "RPort2_10":
//does IPHTTPS maps to IPHTTPSOut AND IPTLSOut ????
//warning: unknown if correct; no example yet
rule.RemotePorts = kv[1];
break;
case "Svc":
rule.serviceName = kv[1];
break;
default:
throw new Exception("Uknown firewall rule type:" + kv[0]);
}
}
if (((rule.Profiles & (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN) == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN) &&
((rule.Profiles & (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE) == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE) &&
((rule.Profiles & (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC) == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC)
)
{
rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
}
return rule;
}
/// <summary>Returns the rule as a string using the same format as the group policy rules that are found in the registry</summary>
public override string ToString()
{
//todo: rule.Interfaces
//todo: rule.InterfaceTypes
INetFwRule2 rule = this.rule;
string rs = "v2.10";
var aorder = new List<string> { "Action", "Active", "Dir", "Protocol", "Profile", "ICMP4", "ICMP6", "LPort", "LPort2_10", "RPort", "RPort2_10", "LA4", "LA6", "RA4", "RA6", "App", "Svc", "Name", "Desc", "EmbedCtxt", "Edge", "Defer" };
var attributes = new Dictionary<string, List<string>>();
var strAddresses = new List<string> { "LocalSubnet", "DHCP", "DNS", "WINS", "DefaultGateway" };
IPAddress address;
var curA = "";
//required: if not present then "All"
curA = "Profile";
var fwProfiles = Enum.GetValues(typeof(NET_FW_PROFILE_TYPE2_));
foreach (NET_FW_PROFILE_TYPE2_ fwProfile in fwProfiles)
{
if (((NET_FW_PROFILE_TYPE2_)rule.Profiles & fwProfile) == fwProfile)
{
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + MSFirewall.getProfileName(fwProfile));
}
}
if ((NET_FW_PROFILE_TYPE2_)rule.Profiles == NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL)
{
attributes.Remove(curA);
}
//optional
if (rule.Grouping != null)
{
curA = "EmbedCtxt";
attributes.Add(curA, new List<string> { curA + "=" + rule.Grouping });
}
//required
curA = "Name";
attributes.Add(curA, new List<string> { curA + "=" + rule.Name });
//required
curA = "Action";
attributes.Add(curA, new List<string> { curA + "=" + MSFirewall.getActionName(rule.Action) });
//optional
if (rule.Description != null)
{
curA = "Desc";
attributes.Add(curA, new List<string> { curA + "=" + rule.Description });
}
//required
curA = "Dir";
attributes.Add(curA, new List<string> { curA + "=" + MSFirewall.getDirectionName(rule.Direction) });
if (rule.ApplicationName != null)
{
curA = "App";
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + rule.ApplicationName);
}
if (rule.serviceName != null)
{
curA = "Svc";
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + rule.serviceName);
}
if (rule.LocalPorts != "*" && rule.LocalPorts != null)
{
foreach (string r in rule.LocalPorts.Split(','))
{
if (r == "IPHTTPS")
{
curA = "LPort2_10";
if (rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN)
{
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=IPTLSIn");
attributes[curA].Add(curA + "=IPHTTPSIn");
}
else
{
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=IPTLSOut");
attributes[curA].Add(curA + "=IPHTTPSOut");
}
}
else
{
curA = "LPort";
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + r);
}
}
}
if (rule.LocalAddresses != null && rule.LocalAddresses != "*")
{
var ra = rule.LocalAddresses.Split(',');
foreach (string r in ra)
{
curA = "";
if (strAddresses.Contains(r))
{
curA = "LA4,LA6";
}
else if (IPAddress.TryParse(r, out address))
{
switch (address.AddressFamily)
{
case System.Net.Sockets.AddressFamily.InterNetwork:
curA = "LA4";
break;
case System.Net.Sockets.AddressFamily.InterNetworkV6:
curA = "LA6";
break;
default:
throw new Exception("Unknown remote address: {0}" + r);
}
}
else if (r.Contains(':'))
{
curA = "LA6";
}
else
{
curA = "LA4";
}
if (curA != "")
{
foreach (string a in curA.Split(','))
{
if (!attributes.ContainsKey(a))
attributes.Add(a, new List<string>());
var sub = false;
if (r.Contains('-'))
{
var rtest = r.Split('-');
if (rtest[0] == rtest[1])
{
attributes[a].Add(a + "=" + rtest[0]);
sub = true;
}
}
else if (r.Contains("/255.255.255.255"))
{
var rtest = r.Split('/');
attributes[a].Add(a + "=" + rtest[0]);
sub = true;
}
if (!sub)
{
attributes[a].Add(a + "=" + r);
}
}
}
}
}
if (rule.RemotePorts != "*" && rule.RemotePorts != null)
{
foreach (string r in rule.RemotePorts.Split(','))
{
if (r == "IPHTTPS")
{
curA = "RPort2_10";
if (rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN)
{
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=IPTLSIn");
attributes[curA].Add(curA + "=IPHTTPSIn");
}
else
{
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=IPTLSOut");
attributes[curA].Add(curA + "=IPHTTPSOut");
}
}
else
{
curA = "RPort";
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + r);
}
}
}
//if any, not present
if (rule.RemoteAddresses != null && rule.RemoteAddresses != "*")
{
var ra = rule.RemoteAddresses.Split(',');
foreach (string r in ra)
{
curA = "";
if (strAddresses.Contains(r))
{
curA = "RA4,RA6";
}
else if (IPAddress.TryParse(r, out address))
{
switch (address.AddressFamily)
{
case System.Net.Sockets.AddressFamily.InterNetwork:
curA = "RA4";
break;
case System.Net.Sockets.AddressFamily.InterNetworkV6:
curA = "RA6";
break;
default:
throw new Exception("Unknown remote address: {0}" + r);
}
}
else if (r.Contains(':'))
{
curA = "RA6";
}
else
{
curA = "RA4";
}
if (curA != "")
{
foreach (string a in curA.Split(','))
{
if (!attributes.ContainsKey(a))
attributes.Add(a, new List<string>());
var sub = false;
if (r.Contains('-'))
{
var rtest = r.Split('-');
if (rtest[0] == rtest[1])
{
attributes[a].Add(a + "=" + rtest[0]);
sub = true;
}
}
else if (r.Contains("/255.255.255.255"))
{
var rtest = r.Split('/');
attributes[a].Add(a + "=" + rtest[0]);
sub = true;
}
if (!sub)
{
attributes[a].Add(a + "=" + r);
}
}
}
}
}
//if any, then no setting
if (rule.Protocol != 256) //any
{
curA = "Protocol";
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + rule.Protocol);
}
//required
curA = "Active";
if (rule.Enabled)
attributes.Add(curA, new List<string> { curA + "=TRUE" });
else
attributes.Add(curA, new List<string> { curA + "=FALSE" });
//if not present, then false
if (rule.EdgeTraversal)
{
curA = "Edge";
attributes.Add(curA, new List<string> { curA + "=TRUE" });
}
//if any, then no setting
curA = "Defer";
if (rule.EdgeTraversalOptions > 0)
{
if (rule.EdgeTraversalOptions == (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_APP)
{
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=App");
}
else if (rule.EdgeTraversalOptions == (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_ALLOW)
{
//do nothing because rule.EdgeTraversal should be set to true already
}
else
{
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + rule.EdgeTraversalOptions);
}
}
if (rule.IcmpTypesAndCodes != null)
{
if (rule.Protocol == 1)
{
curA = "ICMP4";
}
else if (rule.Protocol == 58)
{
curA = "ICMP6";
}
if (!attributes.ContainsKey(curA))
attributes.Add(curA, new List<string>());
attributes[curA].Add(curA + "=" + rule.IcmpTypesAndCodes);
}
//ICMPv6 shouldn't have v4 local addresses and vice versa
// TODO: add 41,43,44,59,60 (test first)
if (rule.Protocol == 58 && attributes.ContainsKey("LA4"))
{
attributes.Remove("LA4");
}
else if (rule.Protocol == 1 && attributes.ContainsKey("LA6"))
{
attributes.Remove("LA6");
}
//ICMPv6 shouldn't have v4 remote addresses and vice versa
// TODO: add 41,43,44,59,60 (test first)
if (rule.Protocol == 58 && attributes.ContainsKey("RA4"))
{
attributes.Remove("RA4");
}
else if (rule.Protocol == 1 && attributes.ContainsKey("RA6"))
{
attributes.Remove("RA6");
}
//preserve order of keys
foreach (var a in aorder)
{
if (attributes.ContainsKey(a))
{
rs = rs + "|" + String.Join("|", attributes[a]);
}
}
rs = rs + "|";
return rs;
}
}
} |
// 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.AcceptanceTestsLro
{
using Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for LRORetrysOperations.
/// </summary>
public static partial class LRORetrysOperationsExtensions
{
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Polls
/// return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static ProductInner Put201CreatingSucceeded200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.Put201CreatingSucceeded200Async(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Polls
/// return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ProductInner> Put201CreatingSucceeded200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Put201CreatingSucceeded200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static ProductInner PutAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.PutAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ProductInner> PutAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PutAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains ProvisioningState=’Accepted’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static ProductInner DeleteProvisioning202Accepted200Succeeded(this ILRORetrysOperations operations)
{
return operations.DeleteProvisioning202Accepted200SucceededAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains ProvisioningState=’Accepted’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ProductInner> DeleteProvisioning202Accepted200SucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static LRORetrysDelete202Retry200HeadersInner Delete202Retry200(this ILRORetrysOperations operations)
{
return operations.Delete202Retry200Async().GetAwaiter().GetResult();
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysDelete202Retry200HeadersInner> Delete202Retry200Async(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Delete202Retry200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner DeleteAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations)
{
return operations.DeleteAsyncRelativeRetrySucceededAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner> DeleteAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with
/// a response body after success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static LRORetrysPost202Retry200HeadersInner Post202Retry200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.Post202Retry200Async(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with
/// a response body after success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysPost202Retry200HeadersInner> Post202Retry200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Post202Retry200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static LRORetrysPostAsyncRelativeRetrySucceededHeadersInner PostAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.PostAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner> PostAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Polls
/// return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static ProductInner BeginPut201CreatingSucceeded200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.BeginPut201CreatingSucceeded200Async(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Polls
/// return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ProductInner> BeginPut201CreatingSucceeded200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginPut201CreatingSucceeded200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static ProductInner BeginPutAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.BeginPutAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ProductInner> BeginPutAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains ProvisioningState=’Accepted’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static ProductInner BeginDeleteProvisioning202Accepted200Succeeded(this ILRORetrysOperations operations)
{
return operations.BeginDeleteProvisioning202Accepted200SucceededAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains ProvisioningState=’Accepted’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ProductInner> BeginDeleteProvisioning202Accepted200SucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static LRORetrysDelete202Retry200HeadersInner BeginDelete202Retry200(this ILRORetrysOperations operations)
{
return operations.BeginDelete202Retry200Async().GetAwaiter().GetResult();
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysDelete202Retry200HeadersInner> BeginDelete202Retry200Async(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDelete202Retry200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner BeginDeleteAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations)
{
return operations.BeginDeleteAsyncRelativeRetrySucceededAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner> BeginDeleteAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with
/// a response body after success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static LRORetrysPost202Retry200HeadersInner BeginPost202Retry200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.BeginPost202Retry200Async(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with
/// a response body after success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysPost202Retry200HeadersInner> BeginPost202Retry200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginPost202Retry200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
public static LRORetrysPostAsyncRelativeRetrySucceededHeadersInner BeginPostAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner))
{
return operations.BeginPostAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult();
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner> BeginPostAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Betabit.Lora.Nuget.EventHub.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
} |
//-----------------------------------------------------------------------
// <copyright file="PropertiesFileGenerator.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using SonarQube.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SonarRunner.Shim
{
public static class PropertiesFileGenerator
{
private const string ProjectPropertiesFileName = "sonar-project.properties";
public const string VSBootstrapperPropertyKey = "sonar.visualstudio.enable";
public const string BuildWrapperOutputDirectoryKey = "sonar.cfamily.build-wrapper-output";
#region Public methods
/// <summary>
/// Locates the ProjectInfo.xml files and uses the information in them to generate
/// a sonar-runner properties file
/// </summary>
/// <returns>Information about each of the project info files that was processed, together with
/// the full path to generated file.
/// Note: the path to the generated file will be null if the file could not be generated.</returns>
public static ProjectInfoAnalysisResult GenerateFile(AnalysisConfig config, ILogger logger)
{
return GenerateFile(config, logger, new RoslynV1SarifFixer());
}
public /* for test */ static ProjectInfoAnalysisResult GenerateFile(AnalysisConfig config, ILogger logger, IRoslynV1SarifFixer fixer)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
string fileName = Path.Combine(config.SonarOutputDir, ProjectPropertiesFileName);
logger.LogDebug(Resources.MSG_GeneratingProjectProperties, fileName);
IEnumerable<ProjectInfo> projects = ProjectLoader.LoadFrom(config.SonarOutputDir);
if (projects == null || !projects.Any())
{
logger.LogError(Resources.ERR_NoProjectInfoFilesFound);
return new ProjectInfoAnalysisResult();
}
FixSarifReport(logger, projects, fixer);
PropertiesWriter writer = new PropertiesWriter(config);
ProjectInfoAnalysisResult result = ProcessProjectInfoFiles(projects, writer, logger);
IEnumerable<ProjectInfo> validProjects = result.GetProjectsByStatus(ProjectInfoValidity.Valid);
if (validProjects.Any())
{
// Handle global settings
AnalysisProperties properties = GetAnalysisPropertiesToWrite(config, logger);
writer.WriteGlobalSettings(properties);
string contents = writer.Flush();
result.FullPropertiesFilePath = fileName;
File.WriteAllText(result.FullPropertiesFilePath, contents, Encoding.ASCII);
}
else
{
// if the user tries to build multiple configurations at once there will be duplicate projects
if (result.GetProjectsByStatus(ProjectInfoValidity.DuplicateGuid).Any())
{
logger.LogError(Resources.ERR_NoValidButDuplicateProjects);
}
else
{
logger.LogError(Resources.ERR_NoValidProjectInfoFiles);
}
}
return result;
}
/// <summary>
/// Loads SARIF reports from the given projects and attempts to fix
/// improper escaping from Roslyn V1 (VS 2015 RTM) where appropriate.
/// </summary>
private static void FixSarifReport(ILogger logger, IEnumerable<ProjectInfo> projects, IRoslynV1SarifFixer fixer /* for test */)
{
// attempt to fix invalid project-level SARIF emitted by Roslyn 1.0 (VS 2015 RTM)
foreach (ProjectInfo project in projects)
{
Property reportPathProperty;
bool tryResult = project.TryGetAnalysisSetting(RoslynV1SarifFixer.ReportFilePropertyKey, out reportPathProperty);
if (tryResult)
{
string reportPath = reportPathProperty.Value;
string fixedPath = fixer.LoadAndFixFile(reportPath, logger);
if (!reportPath.Equals(fixedPath)) // only need to alter the property if there was no change
{
// remove the property ahead of changing it
// if the new path is null, the file was unfixable and we should leave the property out
project.AnalysisSettings.Remove(reportPathProperty);
if (fixedPath != null)
{
// otherwise, set the property value (results in no change if the file was already valid)
Property newReportPathProperty = new Property();
newReportPathProperty.Id = RoslynV1SarifFixer.ReportFilePropertyKey;
newReportPathProperty.Value = fixedPath;
project.AnalysisSettings.Add(newReportPathProperty);
}
}
}
}
}
#endregion
#region Private methods
private static ProjectInfoAnalysisResult ProcessProjectInfoFiles(IEnumerable<ProjectInfo> projects, PropertiesWriter writer, ILogger logger)
{
ProjectInfoAnalysisResult result = new ProjectInfoAnalysisResult();
foreach (ProjectInfo projectInfo in projects)
{
ProjectInfoValidity status = ClassifyProject(projectInfo, projects, logger);
if (status == ProjectInfoValidity.Valid)
{
IEnumerable<string> files = GetFilesToAnalyze(projectInfo, logger);
if (files == null || !files.Any())
{
status = ProjectInfoValidity.NoFilesToAnalyze;
}
else
{
string fxCopReport = TryGetFxCopReport(projectInfo, logger);
string vsCoverageReport = TryGetCodeCoverageReport(projectInfo, logger);
writer.WriteSettingsForProject(projectInfo, files, fxCopReport, vsCoverageReport);
}
}
result.Projects.Add(projectInfo, status);
}
return result;
}
private static ProjectInfoValidity ClassifyProject(ProjectInfo projectInfo, IEnumerable<ProjectInfo> projects, ILogger logger)
{
if (projectInfo.IsExcluded)
{
logger.LogInfo(Resources.MSG_ProjectIsExcluded, projectInfo.FullPath);
return ProjectInfoValidity.ExcludeFlagSet;
}
if (!IsProjectGuidValue(projectInfo))
{
logger.LogWarning(Resources.WARN_InvalidProjectGuid, projectInfo.ProjectGuid, projectInfo.FullPath);
return ProjectInfoValidity.InvalidGuid;
}
if (HasDuplicateGuid(projectInfo, projects))
{
logger.LogWarning(Resources.WARN_DuplicateProjectGuid, projectInfo.ProjectGuid, projectInfo.FullPath);
return ProjectInfoValidity.DuplicateGuid;
}
return ProjectInfoValidity.Valid;
}
private static bool IsProjectGuidValue(ProjectInfo project)
{
return project.ProjectGuid != Guid.Empty;
}
private static bool HasDuplicateGuid(ProjectInfo projectInfo, IEnumerable<ProjectInfo> projects)
{
return projects.Count(p => !p.IsExcluded && p.ProjectGuid == projectInfo.ProjectGuid) > 1;
}
/// <summary>
/// Returns all of the valid files that can be analyzed. Logs warnings/info about
/// files that cannot be analyzed.
/// </summary>
private static IEnumerable<string> GetFilesToAnalyze(ProjectInfo projectInfo, ILogger logger)
{
// We're only interested in files that exist and that are under the project root
var result = new List<string>();
var baseDir = projectInfo.GetProjectDirectory();
foreach (string file in projectInfo.GetAllAnalysisFiles())
{
if (File.Exists(file))
{
if (IsInFolder(file, baseDir))
{
result.Add(file);
}
else
{
logger.LogWarning(Resources.WARN_FileIsOutsideProjectDirectory, file, projectInfo.FullPath);
}
}
else
{
logger.LogWarning(Resources.WARN_FileDoesNotExist, file);
}
}
return result;
}
private static bool IsInFolder(string filePath, string folder)
{
string normalizedPath = Path.GetDirectoryName(Path.GetFullPath(filePath));
return normalizedPath.StartsWith(folder, StringComparison.OrdinalIgnoreCase);
}
private static string TryGetFxCopReport(ProjectInfo project, ILogger logger)
{
string fxCopReport = project.TryGetAnalysisFileLocation(AnalysisType.FxCop);
if (fxCopReport != null)
{
if (!File.Exists(fxCopReport))
{
fxCopReport = null;
logger.LogWarning(Resources.WARN_FxCopReportNotFound, fxCopReport);
}
}
return fxCopReport;
}
private static string TryGetCodeCoverageReport(ProjectInfo project, ILogger logger)
{
string vsCoverageReport = project.TryGetAnalysisFileLocation(AnalysisType.VisualStudioCodeCoverage);
if (vsCoverageReport != null)
{
if (!File.Exists(vsCoverageReport))
{
vsCoverageReport = null;
logger.LogWarning(Resources.WARN_CodeCoverageReportNotFound, vsCoverageReport);
}
}
return vsCoverageReport;
}
/// <summary>
/// Returns all of the analysis properties that should
/// be written to the sonar-project properties file
/// </summary>
private static AnalysisProperties GetAnalysisPropertiesToWrite(AnalysisConfig config, ILogger logger)
{
AnalysisProperties properties = new AnalysisProperties();
properties.AddRange(config.GetAnalysisSettings(false).GetAllProperties()
// Strip out any sensitive properties
.Where(p => !p.ContainsSensitiveData()));
// There are some properties we want to override regardless of what the user sets
AddOrSetProperty(VSBootstrapperPropertyKey, "false", properties, logger);
// Special case processing for known properties
RemoveBuildWrapperSettingIfDirectoryEmpty(properties, logger);
return properties;
}
private static void AddOrSetProperty(string key, string value, AnalysisProperties properties, ILogger logger)
{
Property property;
Property.TryGetProperty(key, properties, out property);
if (property == null)
{
logger.LogDebug(Resources.MSG_SettingAnalysisProperty, key, value);
property = new Property() { Id = key, Value = value };
properties.Add(property);
}
else
{
if (string.Equals(property.Value, value, StringComparison.InvariantCulture))
{
logger.LogDebug(Resources.MSG_MandatorySettingIsCorrectlySpecified, key, value);
}
else
{
logger.LogWarning(Resources.WARN_OverridingAnalysisProperty, key, value);
property.Value = value;
}
}
}
/// <summary>
/// Passing in an invalid value for the build wrapper output directory will cause the C++ plugin to
/// fail (invalid = missing or empty directory) so we'll remove invalid settings
/// </summary>
private static void RemoveBuildWrapperSettingIfDirectoryEmpty(AnalysisProperties properties, ILogger logger)
{
// The property is set early in the analysis process before any projects are analysed. We can't
// tell at this point if the directory missing/empty is error or not - it could just be that all
// of the Cpp projects have been excluded from analysis.
// We're assuming that if the build wrapper output was not written due to an error elsewhere then
// that error will have been logged or reported at the point it occurred. Consequently, we;ll
// just write debug output to record what we're doing.
Property directoryProperty;
if (Property.TryGetProperty(BuildWrapperOutputDirectoryKey, properties, out directoryProperty))
{
string path = directoryProperty.Value;
if (!Directory.Exists(path) || IsDirectoryEmpty(path))
{
logger.LogDebug(Resources.MSG_RemovingBuildWrapperAnalysisProperty, BuildWrapperOutputDirectoryKey, path);
properties.Remove(directoryProperty);
}
else
{
logger.LogDebug(Resources.MSG_BuildWrapperPropertyIsValid, BuildWrapperOutputDirectoryKey, path);
}
}
}
private static bool IsDirectoryEmpty(string path)
{
return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length == 0;
}
#endregion
}
} |
/* MIT License
Copyright (c) 2016 JetBrains http://www.jetbrains.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;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
// ReSharper disable once CheckNamespace
namespace FacePalm.Annotations {
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage.
/// </summary>
/// <example><code>
/// [CanBeNull] object Test() => null;
///
/// void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
public sealed class CanBeNullAttribute : Attribute {
}
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>.
/// </summary>
/// <example><code>
/// [NotNull] object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
public sealed class NotNullAttribute : Attribute {
}
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can never be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemNotNullAttribute : Attribute {
}
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemCanBeNullAttribute : Attribute {
}
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form.
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// void ShowError(string message, params object[] args) { /* do something */ }
///
/// void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Delegate)]
public sealed class StringFormatMethodAttribute : Attribute {
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute([NotNull] string formatParameterName) {
FormatParameterName = formatParameterName;
}
[NotNull]
public string FormatParameterName { get; }
}
/// <summary>
/// For a parameter that is expected to be one of the limited set of values.
/// Specify fields of which type should be used as values for this parameter.
/// </summary>
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field,
AllowMultiple = true)]
public sealed class ValueProviderAttribute : Attribute {
public ValueProviderAttribute([NotNull] string name) {
Name = name;
}
[NotNull]
public string Name { get; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>.
/// </summary>
/// <example><code>
/// void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InvokerParameterNameAttribute : Attribute {
}
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method
/// is used to notify that some property value changed.
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
///
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// string _name;
///
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute {
public NotifyPropertyChangedInvocatorAttribute() {
}
public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) {
ParameterName = parameterName;
}
[CanBeNull]
public string ParameterName { get; }
}
/// <summary>
/// Describes dependency between method input and output.
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output
/// means that the methos doesn't return normally (throws or terminates the process).<br/>
/// Value <c>canbenull</c> is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute
/// with rows separated by semicolon. There is no notion of order rows, all rows are checked
/// for applicability and applied per each program state tracked by R# analysis.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("=> true, result: notnull; => false, result: null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class ContractAnnotationAttribute : Attribute {
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) {
}
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) {
Contract = contract;
ForceFullStates = forceFullStates;
}
[NotNull]
public string Contract { get; }
public bool ForceFullStates { get; }
}
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// class Foo {
/// string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All)]
public sealed class LocalizationRequiredAttribute : Attribute {
public LocalizationRequiredAttribute()
: this(true) {
}
public LocalizationRequiredAttribute(bool required) {
Required = required;
}
public bool Required { get; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
///
/// class UsesNoEquality {
/// void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute {
}
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// class ComponentAttribute : Attribute { }
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute {
public BaseTypeRequiredAttribute([NotNull] Type baseType) {
BaseType = baseType;
}
[NotNull]
public Type BaseType { get; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections).
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public sealed class UsedImplicitlyAttribute : Attribute {
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) {
}
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) {
}
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) {
}
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) {
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; }
public ImplicitUseTargetFlags TargetFlags { get; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes
/// as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)]
public sealed class MeansImplicitUseAttribute : Attribute {
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) {
}
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) {
}
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) {
}
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) {
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly]
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags {
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used.</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member.</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type.</summary>
InstantiatedNoFixedConstructorSignature = 8
}
/// <summary>
/// Specify what is considered used implicitly when marked
/// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>.
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags {
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used.</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used.</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used.
/// </summary>
[MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)]
public sealed class PublicAPIAttribute : Attribute {
public PublicAPIAttribute() {
}
public PublicAPIAttribute([NotNull] string comment) {
Comment = comment;
}
[CanBeNull]
public string Comment { get; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack.
/// If the parameter is a delegate, indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InstantHandleAttribute : Attribute {
}
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>.
/// </summary>
/// <example><code>
/// [Pure] int Multiply(int x, int y) => x * y;
///
/// void M() {
/// Multiply(123, 42); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class PureAttribute : Attribute {
}
/// <summary>
/// Indicates that the return value of method invocation must be used.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class MustUseReturnValueAttribute : Attribute {
public MustUseReturnValueAttribute() {
}
public MustUseReturnValueAttribute([NotNull] string justification) {
Justification = justification;
}
[CanBeNull]
public string Justification { get; }
}
/// <summary>
/// Indicates the type member or parameter of some type, that should be used instead of all other ways
/// to get the value that type. This annotation is useful when you have some "context" value evaluated
/// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one.
/// </summary>
/// <example><code>
/// class Foo {
/// [ProvidesContext] IBarService _barService = ...;
///
/// void ProcessNode(INode node) {
/// DoSomething(node, node.GetGlobalServices().Bar);
/// // ^ Warning: use value of '_barService' field
/// }
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct |
AttributeTargets.GenericParameter)]
public sealed class ProvidesContextAttribute : Attribute {
}
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~).
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class PathReferenceAttribute : Attribute {
public PathReferenceAttribute() {
}
public PathReferenceAttribute([NotNull] [PathReference] string basePath) {
BasePath = basePath;
}
[CanBeNull]
public string BasePath { get; }
}
/// <summary>
/// An extension method marked with this attribute is processed by ReSharper code completion
/// as a 'Source Template'. When extension method is completed over some expression, it's source code
/// is automatically expanded like a template at call site.
/// </summary>
/// <remarks>
/// Template method body can contain valid source code and/or special comments starting with '$'.
/// Text inside these comments is added as source code when the template is applied. Template parameters
/// can be used either as additional method parameters or as identifiers wrapped in two '$' signs.
/// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters.
/// </remarks>
/// <example>
/// In this example, the 'forEach' method is a source template available over all values
/// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block:
/// <code>
/// [SourceTemplate]
/// public static void forEach<T>(this IEnumerable<T> xs) {
/// foreach (var x in xs) {
/// //$ $END$
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SourceTemplateAttribute : Attribute {
}
/// <summary>
/// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>.
/// </summary>
/// <remarks>
/// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression
/// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target
/// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently
/// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1.
/// </remarks>
/// <example>
/// Applying the attribute on a source template method:
/// <code>
/// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")]
/// public static void forEach<T>(this IEnumerable<T> collection) {
/// foreach (var item in collection) {
/// //$ $END$
/// }
/// }
/// </code>
/// Applying the attribute on a template method parameter:
/// <code>
/// [SourceTemplate]
/// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) {
/// /*$ var $x$Id = "$newguid$" + x.ToString();
/// x.DoSomething($x$Id); */
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)]
public sealed class MacroAttribute : Attribute {
/// <summary>
/// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see>
/// parameter when the template is expanded.
/// </summary>
[CanBeNull]
public string Expression { get; set; }
/// <summary>
/// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed.
/// </summary>
/// <remarks>
/// If the target parameter is used several times in the template, only one occurrence becomes editable;
/// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence,
/// use values >= 0. To make the parameter non-editable when the template is expanded, use -1.
/// </remarks>>
public int Editable { get; set; }
/// <summary>
/// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the
/// <see cref="MacroAttribute"/> is applied on a template method.
/// </summary>
[CanBeNull]
public string Target { get; set; }
}
[AttributeUsage(
AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute {
public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) {
Format = format;
}
[NotNull]
public string Format { get; }
}
[AttributeUsage(
AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute {
public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) {
Format = format;
}
[NotNull]
public string Format { get; }
}
[AttributeUsage(
AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute {
public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) {
Format = format;
}
[NotNull]
public string Format { get; }
}
[AttributeUsage(
AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute {
public AspMvcMasterLocationFormatAttribute([NotNull] string format) {
Format = format;
}
[NotNull]
public string Format { get; }
}
[AttributeUsage(
AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute {
public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) {
Format = format;
}
[NotNull]
public string Format { get; }
}
[AttributeUsage(
AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute {
public AspMvcViewLocationFormatAttribute([NotNull] string format) {
Format = format;
}
[NotNull]
public string Format { get; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute {
public AspMvcActionAttribute() {
}
public AspMvcActionAttribute([NotNull] string anonymousProperty) {
AnonymousProperty = anonymousProperty;
}
[CanBeNull]
public string AnonymousProperty { get; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : Attribute {
public AspMvcAreaAttribute() {
}
public AspMvcAreaAttribute([NotNull] string anonymousProperty) {
AnonymousProperty = anonymousProperty;
}
[CanBeNull]
public string AnonymousProperty { get; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is
/// an MVC controller. If applied to a method, the MVC controller name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute {
public AspMvcControllerAttribute() {
}
public AspMvcControllerAttribute([NotNull] string anonymousProperty) {
AnonymousProperty = anonymousProperty;
}
[CanBeNull]
public string AnonymousProperty { get; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC
/// partial view. If applied to a method, the MVC partial view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSuppressViewErrorAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component name.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcViewComponentAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component view. If applied to a method, the MVC view component view name is default.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewComponentViewAttribute : Attribute {
}
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name.
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class HtmlElementAttributesAttribute : Attribute {
public HtmlElementAttributesAttribute() {
}
public HtmlElementAttributesAttribute([NotNull] string name) {
Name = name;
}
[CanBeNull]
public string Name { get; }
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class HtmlAttributeValueAttribute : Attribute {
public HtmlAttributeValueAttribute([NotNull] string name) {
Name = name;
}
[NotNull]
public string Name { get; }
}
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class RazorSectionAttribute : Attribute {
}
/// <summary>
/// Indicates how method, constructor invocation or property access
/// over collection type affects content of the collection.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)]
public sealed class CollectionAccessAttribute : Attribute {
public CollectionAccessAttribute(CollectionAccessType collectionAccessType) {
CollectionAccessType = collectionAccessType;
}
public CollectionAccessType CollectionAccessType { get; }
}
[Flags]
public enum CollectionAccessType {
/// <summary>Method does not use or modify content of the collection.</summary>
None = 0,
/// <summary>Method only reads content of the collection but does not modify it.</summary>
Read = 1,
/// <summary>Method can change content of the collection but does not add new elements.</summary>
ModifyExistingContent = 2,
/// <summary>Method can add new elements to the collection.</summary>
UpdatedContent = ModifyExistingContent | 4
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if
/// one of the conditions is satisfied. To set the condition, mark one of the parameters with
/// <see cref="AssertionConditionAttribute"/> attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class AssertionMethodAttribute : Attribute {
}
/// <summary>
/// Indicates the condition parameter of the assertion method. The method itself should be
/// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of
/// the attribute is the assertion type.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AssertionConditionAttribute : Attribute {
public AssertionConditionAttribute(AssertionConditionType conditionType) {
ConditionType = conditionType;
}
public AssertionConditionType ConditionType { get; }
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisfies the condition,
/// then the execution continues. Otherwise, execution is assumed to be halted.
/// </summary>
public enum AssertionConditionType {
/// <summary>Marked parameter should be evaluated to true.</summary>
IS_TRUE = 0,
/// <summary>Marked parameter should be evaluated to false.</summary>
IS_FALSE = 1,
/// <summary>Marked parameter should be evaluated to null value.</summary>
IS_NULL = 2,
/// <summary>Marked parameter should be evaluated to not null value.</summary>
IS_NOT_NULL = 3
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception.
/// </summary>
[Obsolete("Use [ContractAnnotation('=> halt')] instead")]
[AttributeUsage(AttributeTargets.Method)]
public sealed class TerminatesProgramAttribute : Attribute {
}
/// <summary>
/// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select,
/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters
/// of delegate type by analyzing LINQ method chains.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class LinqTunnelAttribute : Attribute {
}
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class NoEnumerationAttribute : Attribute {
}
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RegexPatternAttribute : Attribute {
}
/// <summary>
/// Prevents the Member Reordering feature from tossing members of the marked class.
/// </summary>
/// <remarks>
/// The attribute must be mentioned in your member reordering patterns
/// </remarks>
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)]
public sealed class NoReorderAttribute : Attribute {
}
/// <summary>
/// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated
/// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class XamlItemsControlAttribute : Attribute {
}
/// <summary>
/// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that
/// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will
/// enable the <c>DataContext</c> type resolve for XAML bindings for such properties.
/// </summary>
/// <remarks>
/// Property should have the tree ancestor of the <c>ItemsControl</c> type or
/// marked with the <see cref="XamlItemsControlAttribute"/> attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public sealed class XamlItemBindingOfItemsControlAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspChildControlTypeAttribute : Attribute {
public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) {
TagName = tagName;
ControlType = controlType;
}
[NotNull]
public string TagName { get; }
[NotNull]
public Type ControlType { get; }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldsAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspMethodPropertyAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspRequiredAttributeAttribute : Attribute {
public AspRequiredAttributeAttribute([NotNull] string attribute) {
Attribute = attribute;
}
[NotNull]
public string Attribute { get; }
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspTypePropertyAttribute : Attribute {
public AspTypePropertyAttribute(bool createConstructorReferences) {
CreateConstructorReferences = createConstructorReferences;
}
public bool CreateConstructorReferences { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorImportNamespaceAttribute : Attribute {
public RazorImportNamespaceAttribute([NotNull] string name) {
Name = name;
}
[NotNull]
public string Name { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorInjectionAttribute : Attribute {
public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) {
Type = type;
FieldName = fieldName;
}
[NotNull]
public string Type { get; }
[NotNull]
public string FieldName { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorDirectiveAttribute : Attribute {
public RazorDirectiveAttribute([NotNull] string directive) {
Directive = directive;
}
[NotNull]
public string Directive { get; }
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorHelperCommonAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class RazorLayoutAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteLiteralMethodAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteMethodAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RazorWriteMethodParameterAttribute : Attribute {
}
} |
using System.Collections.Generic;
using BEPUphysics.Constraints.SolverGroups;
using BEPUphysics.Constraints.TwoEntity.Motors;
using BEPUphysics.Entities.Prefabs;
using BEPUutilities;
using BEPUphysics.Entities;
using BEPUphysics.CollisionRuleManagement;
using Microsoft.Xna.Framework.Input;
using System;
using BEPUphysics.BroadPhaseEntries;
namespace BEPUphysicsDemos.Demos
{
/// <summary>
/// A robot with multiple individually controllable legs qwops around.
/// </summary>
/// <remarks>
/// This demo type is initially excluded from the main list in the DemosGame.
/// To access it while playing the demos, add an entry to the demoTypes array for this demo.
/// </remarks>
public class SpiderDemo : StandardDemo
{
private List<RevoluteJoint> legJoints;
/// <summary>
/// Constructs a new demo.
/// </summary>
/// <param name="game">Game owning this demo.</param>
public SpiderDemo(DemosGame game)
: base(game)
{
game.Camera.Position = new Vector3(0, 2, 15);
Space.Add(new Box(new Vector3(0, -5, 0), 20, 1, 20));
BuildBot(new Vector3(0, 3, 0), out legJoints);
//x and y, in terms of heightmaps, refer to their local x and y coordinates. In world space, they correspond to x and z.
//Setup the heights of the terrain.
int xLength = 180;
int zLength = 180;
float xSpacing = 8f;
float zSpacing = 8f;
var heights = new float[xLength, zLength];
for (int i = 0; i < xLength; i++)
{
for (int j = 0; j < zLength; j++)
{
float x = i - xLength / 2;
float z = j - zLength / 2;
//heights[i,j] = (float)(x * y / 1000f);
heights[i, j] = (float)(10 * (Math.Sin(x / 8) + Math.Sin(z / 8)));
//heights[i,j] = 3 * (float)Math.Sin(x * y / 100f);
//heights[i,j] = (x * x * x * y - y * y * y * x) / 1000f;
}
}
//Create the terrain.
var terrain = new Terrain(heights, new AffineTransform(
new Vector3(xSpacing, 1, zSpacing),
Quaternion.Identity,
new Vector3(-xLength * xSpacing / 2, -10, -zLength * zSpacing / 2)));
//terrain.Thickness = 5; //Uncomment this and shoot some things at the bottom of the terrain! They'll be sucked up through the ground.
Space.Add(terrain);
game.ModelDrawer.Add(terrain);
}
void BuildBot(Vector3 position, out List<RevoluteJoint> legJoints)
{
var body = new Box(position + new Vector3(0, 2.5f, 0), 2, 3, 2, 30);
Space.Add(body);
legJoints = new List<RevoluteJoint>();
//Plop four legs on the spider.
BuildLeg(body, new RigidTransform(body.Position + new Vector3(-.8f, -1, -.8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4 * 3)), legJoints);
BuildLeg(body, new RigidTransform(body.Position + new Vector3(-.8f, -1, .8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4 * 5)), legJoints);
BuildLeg(body, new RigidTransform(body.Position + new Vector3(.8f, -1, -.8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4)), legJoints);
BuildLeg(body, new RigidTransform(body.Position + new Vector3(.8f, -1, .8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4 * 7)), legJoints);
}
void BuildLeg(Entity body, RigidTransform legTransform, List<RevoluteJoint> legJoints)
{
//Build the leg in local space.
var upperLeg = new Box(new Vector3(.75f, 0, 0), 1.5f, .6f, .6f, 7);
var lowerLeg = new Box(new Vector3(1.2f, -.75f, 0), .6f, 1.5f, .6f, 7);
//Increase the feetfriction to make walking easier.
lowerLeg.Material.KineticFriction = 3;
lowerLeg.Material.StaticFriction = 3;
Space.Add(upperLeg);
Space.Add(lowerLeg);
//Pull the leg entities into world space.
upperLeg.WorldTransform *= legTransform.Matrix;
lowerLeg.WorldTransform *= legTransform.Matrix;
//Don't let the leg pieces interact with each other.
CollisionRules.AddRule(upperLeg, body, CollisionRule.NoBroadPhase);
CollisionRules.AddRule(upperLeg, lowerLeg, CollisionRule.NoBroadPhase);
//Connect the body to the upper leg.
var bodyToUpper = new RevoluteJoint(body, upperLeg, legTransform.Position, legTransform.OrientationMatrix.Forward);
//Both the motor and limit need to be activated for this leg.
bodyToUpper.Limit.IsActive = true;
//While the angular joint doesn't need any extra configuration, the limit does in order to ensure that its interpretation of angles matches ours.
bodyToUpper.Limit.LocalTestAxis = Vector3.Left;
bodyToUpper.Limit.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Left);
bodyToUpper.Limit.MinimumAngle = -MathHelper.PiOver4;
bodyToUpper.Limit.MaximumAngle = MathHelper.PiOver4;
//Similarly, the motor needs configuration.
bodyToUpper.Motor.IsActive = true;
bodyToUpper.Motor.LocalTestAxis = Vector3.Left;
bodyToUpper.Motor.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Left);
bodyToUpper.Motor.Settings.Mode = MotorMode.Servomechanism;
//Weaken the spring to prevent it from launching too much.
bodyToUpper.Motor.Settings.Servo.SpringSettings.Stiffness *= .01f;
bodyToUpper.Motor.Settings.Servo.SpringSettings.Damping *= .01f;
Space.Add(bodyToUpper);
//Connect the upper leg to the lower leg.
var upperToLower = new RevoluteJoint(upperLeg, lowerLeg, legTransform.Position - legTransform.OrientationMatrix.Left * 1.2f, legTransform.OrientationMatrix.Forward);
//Both the motor and limit need to be activated for this leg.
upperToLower.Limit.IsActive = true;
//While the angular joint doesn't need any extra configuration, the limit does in order to ensure that its interpretation of angles matches ours.
upperToLower.Limit.LocalTestAxis = Vector3.Down;
upperToLower.Limit.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Down);
upperToLower.Limit.MinimumAngle = -MathHelper.PiOver4;
upperToLower.Limit.MaximumAngle = MathHelper.PiOver4;
//Similarly, the motor needs configuration.
upperToLower.Motor.IsActive = true;
upperToLower.Motor.LocalTestAxis = Vector3.Down;
upperToLower.Motor.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Down);
upperToLower.Motor.Settings.Mode = MotorMode.Servomechanism;
//Weaken the spring to prevent it from launching too much.
upperToLower.Motor.Settings.Servo.SpringSettings.Stiffness *= .01f;
upperToLower.Motor.Settings.Servo.SpringSettings.Damping *= .01f;
Space.Add(upperToLower);
legJoints.Add(upperToLower);
legJoints.Add(bodyToUpper);
}
/// <summary>
/// Gets the name of the simulation.
/// </summary>
public override string Name
{
get { return "QWOPbot"; }
}
public override void DrawUI()
{
base.DrawUI();
Game.DataTextDrawer.Draw("QWRT to retract, OPKL to extend. Good luck!", new Microsoft.Xna.Framework.Vector2(50, 50));
}
public override void Update(float dt)
{
//Extend the legs!
if (Game.KeyboardInput.IsKeyDown(Keys.Q))
{
Extend(legJoints[0], dt);
Extend(legJoints[1], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.W))
{
Extend(legJoints[2], dt);
Extend(legJoints[3], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.R))
{
Extend(legJoints[4], dt);
Extend(legJoints[5], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.T))
{
Extend(legJoints[6], dt);
Extend(legJoints[7], dt);
}
//Retract the legs!
if (Game.KeyboardInput.IsKeyDown(Keys.O))
{
Retract(legJoints[0], dt);
Retract(legJoints[1], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.P))
{
Retract(legJoints[2], dt);
Retract(legJoints[3], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.K))
{
Retract(legJoints[4], dt);
Retract(legJoints[5], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.L))
{
Retract(legJoints[6], dt);
Retract(legJoints[7], dt);
}
base.Update(dt);
}
void Extend(RevoluteJoint joint, float dt)
{
float extensionSpeed = 2;
joint.Motor.Settings.Servo.Goal = MathHelper.Clamp(joint.Motor.Settings.Servo.Goal + extensionSpeed * dt, joint.Limit.MinimumAngle, joint.Limit.MaximumAngle);
}
void Retract(RevoluteJoint joint, float dt)
{
float retractionSpeed = 2;
joint.Motor.Settings.Servo.Goal = MathHelper.Clamp(joint.Motor.Settings.Servo.Goal - retractionSpeed * dt, joint.Limit.MinimumAngle, joint.Limit.MaximumAngle);
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.MultiCluster;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime
{
/// <summary>
/// Interface for system management functions of silos,
/// exposed as a grain for receiving remote requests / commands.
/// </summary>
public interface IManagementGrain : IGrainWithIntegerKey, IVersionManager
{
/// <summary>
/// Get the list of silo hosts and statuses currently known about in this cluster.
/// </summary>
/// <param name="onlyActive">Whether data on just current active silos should be returned,
/// or by default data for all current and previous silo instances [including those in Joining or Dead status].</param>
/// <returns></returns>
Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false);
/// <summary>
/// Get the list of silo hosts and membership information currently known about in this cluster.
/// </summary>
/// <param name="onlyActive">Whether data on just current active silos should be returned,
/// or by default data for all current and previous silo instances [including those in Joining or Dead status].</param>
/// <returns></returns>
Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false);
/// <summary>
/// Set the current log level for system runtime components.
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <param name="traceLevel">New log level to use.</param>
/// <returns>Completion promise for this operation.</returns>
Task SetSystemLogLevel(SiloAddress[] hostsIds, int traceLevel);
/// <summary>
/// Set the current log level for application grains.
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <param name="traceLevel">New log level to use.</param>
/// <returns>Completion promise for this operation.</returns>
Task SetAppLogLevel(SiloAddress[] hostsIds, int traceLevel);
/// <summary>
/// Set the current log level for a particular Logger, by name (with prefix matching).
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <param name="logName">Name of the Logger (with prefix matching) to change.</param>
/// <param name="traceLevel">New log level to use.</param>
/// <returns>Completion promise for this operation.</returns>
Task SetLogLevel(SiloAddress[] hostsIds, string logName, int traceLevel);
/// <summary>
/// Perform a run of the .NET garbage collector in the specified silos.
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <returns>Completion promise for this operation.</returns>
Task ForceGarbageCollection(SiloAddress[] hostsIds);
/// <summary>Perform a run of the Orleans activation collecter in the specified silos.</summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <param name="ageLimit">Maximum idle time of activations to be collected.</param>
/// <returns>Completion promise for this operation.</returns>
Task ForceActivationCollection(SiloAddress[] hostsIds, TimeSpan ageLimit);
Task ForceActivationCollection(TimeSpan ageLimit);
/// <summary>Perform a run of the silo statistics collector in the specified silos.</summary>
/// <param name="siloAddresses">List of silos this command is to be sent to.</param>
/// <returns>Completion promise for this operation.</returns>
Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses);
/// <summary>
/// Return the most recent silo runtime statistics information for the specified silos.
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <returns>Completion promise for this operation.</returns>
Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] hostsIds);
/// <summary>
/// Return the most recent grain statistics information, amalgomated across silos.
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <returns>Completion promise for this operation.</returns>
Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds);
/// <summary>
/// Return the most recent grain statistics information, amalgomated across all silos.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics();
/// <summary>
/// Returns the most recent detailed grain statistics information, amalgomated across silos for the specified types.
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <param name="types">Array of grain types to filter the results with</param>
/// <returns></returns>
Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null,SiloAddress[] hostsIds=null);
Task<int> GetGrainActivationCount(GrainReference grainReference);
/// <summary>
/// Return the total count of all current grain activations across all silos.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
///
Task<int> GetTotalActivationCount();
/// <summary>
/// Execute a control command on the specified providers on all silos in the cluster.
/// Commands are sent to all known providers on each silo which match both the <c>providerTypeFullName</c> AND <c>providerName</c> parameters.
/// </summary>
/// <remarks>
/// Providers must implement the <c>Orleans.Providers.IControllable</c>
/// interface in order to receive these control channel commands.
/// </remarks>
/// <param name="providerTypeFullName">Class full name for the provider type to send this command to.</param>
/// <param name="providerName">Provider name to send this command to.</param>
/// <param name="command">An id / serial number of this command.
/// This is an opaque value to the Orleans runtime - the control protocol semantics are decided between the sender and provider.</param>
/// <param name="arg">An opaque command argument.
/// This is an opaque value to the Orleans runtime - the control protocol semantics are decided between the sender and provider.</param>
/// <returns>Completion promise for this operation.</returns>
Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg = null);
/// <summary>
/// Update the configuration information dynamically. Only a subset of configuration information
/// can be updated - will throw an error (and make no config changes) if you specify attributes
/// or elements that cannot be changed. The configuration format is XML, in the same format
/// as the OrleansConfiguration.xml file. The allowed elements and attributes are:
/// <pre>
/// <OrleansConfiguration>
/// <Globals>
/// <Messaging ResponseTimeout="?"/>
/// <Caching CacheSize="?"/>
/// <Activation CollectionInterval="?" CollectionAmount="?" CollectionTotalMemoryLimit="?" CollectionActivationLimit="?"/>
/// <Liveness ProbeTimeout="?" TableRefreshTimeout="?" NumMissedProbesLimit="?"/>
/// </Globals>
/// <Defaults>
/// <LoadShedding Enabled="?" LoadLimit="?"/>
/// <Tracing DefaultTraceLevel="?" PropagateActivityId="?">
/// <TraceLevelOverride LogPrefix="?" TraceLevel="?"/>
/// </Tracing>
/// </Defaults>
/// </OrleansConfiguration>
/// </pre>
/// </summary>
/// <param name="hostIds">Silos to update, or null for all silos</param>
/// <param name="configuration">XML elements and attributes to update</param>
/// <param name="tracing">Tracing level settings</param>
/// <returns></returns>
Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing);
/// <summary>
/// Update the stream providers dynamically. The stream providers in the listed silos will be
/// updated based on the differences between its loaded stream providers and the list of providers
/// in the streamProviderConfigurations: If a provider in the configuration object already exists
/// in the silo, it will be kept as is; if a provider in the configuration object does not exist
/// in the silo, it will be loaded and started; if a provider that exists in silo but is not in
/// the configuration object, it will be stopped and removed from the silo.
/// </summary>
/// <param name="hostIds">Silos to update, or null for all silos</param>
/// <param name="streamProviderConfigurations">stream provider configurations that carries target stream providers</param>
/// <returns></returns>
Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations);
/// <summary>
/// Returns an array of all the active grain types in the system
/// </summary>
/// <param name="hostsIds">List of silos this command is to be sent to.</param>
/// <returns></returns>
Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null);
#region MultiCluster Management
/// <summary>
/// Get the current list of multicluster gateways.
/// </summary>
/// <returns>A list of the currently known gateways</returns>
Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways();
/// <summary>
/// Get the current multicluster configuration.
/// </summary>
/// <returns>The current multicluster configuration, or null if there is none</returns>
Task<MultiClusterConfiguration> GetMultiClusterConfiguration();
/// <summary>
/// Contact all silos in all clusters and return silos that do not have the latest multi-cluster configuration.
/// If some clusters and/or silos cannot be reached, an exception is thrown.
/// </summary>
/// <returns>A list of silo addresses of silos that do not have the latest configuration</returns>
Task<List<SiloAddress>> FindLaggingSilos();
/// <summary>
/// Configure the active multi-cluster, by injecting a multicluster configuration.
/// </summary>
/// <param name="clusters">the clusters that should be part of the active configuration</param>
/// <param name="comment">a comment to store alongside the configuration</param>
/// <param name="checkForLaggingSilosFirst">if true, checks that all clusters are reachable and up-to-date before injecting the new configuration</param>
/// <returns> The task completes once information has propagated to the gossip channels</returns>
Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true);
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using Bender;
using Bender.Collections;
using Bender.Extensions;
using Bender.Reflection;
using NUnit.Framework;
using Should;
using Tests.Collections.Implementations;
namespace Tests.Serializer.Json
{
[TestFixture]
public class ArrayTests
{
// Simple types
private static readonly Guid RandomGuid = Guid.NewGuid();
private static readonly object[] SimpleArrayTypes = TestCases.Create()
.AddTypeAndValues<string>("1")
.AddTypeAndValues<Uri>(new Uri("http://www.xkcd.com"))
.AddTypeAndValues<UriFormat>(UriFormat.UriEscaped)
.AddTypeAndValues<UriFormat?>(UriFormat.UriEscaped)
.AddTypeAndValues<DateTime>(DateTime.Today).AddTypeAndValues<DateTime?>(DateTime.Today)
.AddTypeAndValues<TimeSpan>(TimeSpan.MaxValue).AddTypeAndValues<TimeSpan?>(TimeSpan.MaxValue)
.AddTypeAndValues<Guid>(RandomGuid).AddTypeAndValues<Guid?>(RandomGuid)
.AddTypeAndValues<Boolean>(true).AddTypeAndValues<Boolean?>(true)
.AddTypeAndValues<Byte>(5).AddTypeAndValues<Byte?>(55)
.AddTypeAndValues<SByte>(6).AddTypeAndValues<SByte?>(66)
.AddTypeAndValues<Int16>(7).AddTypeAndValues<Int16?>(77)
.AddTypeAndValues<UInt16>(8).AddTypeAndValues<UInt16?>(88)
.AddTypeAndValues<Int32>(9).AddTypeAndValues<Int32?>(99)
.AddTypeAndValues<UInt32>(10).AddTypeAndValues<UInt32?>(110)
.AddTypeAndValues<Int64>(11).AddTypeAndValues<Int64?>(111)
.AddTypeAndValues<UInt64>(12).AddTypeAndValues<UInt64?>(120)
.AddTypeAndValues<IntPtr>(new IntPtr(13)).AddTypeAndValues<IntPtr?>(new IntPtr(130))
.AddTypeAndValues<UIntPtr>(new UIntPtr(14)).AddTypeAndValues<UIntPtr?>(new UIntPtr(140))
.AddTypeAndValues<Char>('a').AddTypeAndValues<Char?>('b')
.AddTypeAndValues<Double>(15).AddTypeAndValues<Double?>(150)
.AddTypeAndValues<Single>(16).AddTypeAndValues<Single?>(160)
.AddTypeAndValues<Decimal>(17).AddTypeAndValues<Decimal?>(170)
.All;
[Test]
[TestCaseSource(nameof(SimpleArrayTypes))]
public void should_serialize_typed_array_items(Type type, object value)
{
var list = type.MakeGenericListType().CreateInstance().As<IList>();
list.Add(value);
Serialize.Json(list).ShouldEqual("[{0}]".ToFormat(
type.IsNumeric() || type.IsBoolean()
? value.ToString().ToLower()
: "\"" + value.ToString().Replace("/", "\\/") + "\""));
}
// Complex types
public class ComplexType
{
public string Property {get; set; }
}
private static readonly ComplexType ComplexTypeInstance = new ComplexType { Property = "hai" };
private static readonly object[] ComplexTypeArrays = TestCases.Create()
.AddTypeAndValues(new List<ComplexType> { ComplexTypeInstance })
.AddTypeAndValues<IEnumerable<ComplexType>>(new List<ComplexType> { ComplexTypeInstance })
.AddTypeAndValues<IList<ComplexType>>(new List<ComplexType> { ComplexTypeInstance })
.AddTypeAndValues(new GenericListImpl<ComplexType> { ComplexTypeInstance })
.AddTypeAndValues<ComplexType[]>(new[] { ComplexTypeInstance })
.AddTypeAndValues(new ArrayList { ComplexTypeInstance })
.AddTypeAndValues<IEnumerable>(new ArrayList { ComplexTypeInstance })
.AddTypeAndValues(new EnumerableImpl(ComplexTypeInstance))
.AddTypeAndValues(new GenericEnumerableImpl<ComplexType>(ComplexTypeInstance))
.All;
[Test]
[TestCaseSource(nameof(ComplexTypeArrays))]
public void should_serialize_list_of_complex_type(Type type, object list)
{
Serialize.Json(list, type).ShouldEqual("[{\"Property\":\"hai\"}]");
}
// Array types
private static readonly object[] ComplexTypeArrayOfArrays = TestCases.Create()
.AddTypeAndValues(new List<IList<ComplexType>> { new List<ComplexType> { ComplexTypeInstance } })
.AddTypeAndValues<IEnumerable<IList<ComplexType>>>(new List<IList<ComplexType>> { new List<ComplexType> { ComplexTypeInstance } })
.AddTypeAndValues<IList<IList<ComplexType>>>(new List<IList<ComplexType>> { new List<ComplexType> { ComplexTypeInstance } })
.AddTypeAndValues(new GenericListImpl<IList<ComplexType>> { new List<ComplexType> { ComplexTypeInstance } })
.AddTypeAndValues<IList<ComplexType>[]>(new[] { new List<ComplexType> { ComplexTypeInstance } })
.AddTypeAndValues(new ArrayList { new ArrayList { ComplexTypeInstance } })
.AddTypeAndValues<IEnumerable>(new ArrayList { new ArrayList { ComplexTypeInstance } })
.AddTypeAndValues(new EnumerableImpl((object)new ArrayList { ComplexTypeInstance }))
.AddTypeAndValues(new GenericEnumerableImpl<IList<ComplexType>>(new List<ComplexType> { ComplexTypeInstance}))
.All;
[Test]
[TestCaseSource(nameof(ComplexTypeArrayOfArrays))]
public void should_serialize_array_of_arrays(Type type, object list)
{
Serialize.Json(list, type).ShouldEqual("[[{\"Property\":\"hai\"}]]");
}
// Dictionary types
private static readonly object[] ComplexTypeDictionaries = TestCases.Create()
.AddTypeAndValues<Hashtable[]>(new[] { new Hashtable
{ { "item", ComplexTypeInstance } } })
.AddTypeAndValues<Dictionary<string, ComplexType>[]>(new[] { new Dictionary<string, ComplexType>
{ { "item", ComplexTypeInstance } } })
.AddTypeAndValues<IEnumerable<Dictionary<string, ComplexType>>>(new List<Dictionary<string, ComplexType>>
{ new Dictionary<string, ComplexType> { { "item", ComplexTypeInstance } } })
.AddTypeAndValues(new List<Dictionary<string, ComplexType>> { new Dictionary<string, ComplexType>
{ { "item", ComplexTypeInstance } } })
.AddTypeAndValues<IList<Dictionary<string, ComplexType>>>(new List<Dictionary<string, ComplexType>>
{ new Dictionary<string, ComplexType> { { "item", ComplexTypeInstance } } })
.AddTypeAndValues(new GenericListImpl<Dictionary<string, ComplexType>>
{ new Dictionary<string, ComplexType> { { "item", ComplexTypeInstance } } })
.All;
[Test]
[TestCaseSource(nameof(ComplexTypeDictionaries))]
public void should_serialize_array_of_dictionary(Type type, object list)
{
Serialize.Json(list, type).ShouldEqual("[{\"item\":{\"Property\":\"hai\"}}]");
}
// Array member
public class Model
{
public ArrayList NonGenericArray { get; set; }
public IEnumerable EnumerableInterface { get; set; }
public EnumerableImpl EnumerableImpl { get; set; }
public GenericEnumerableImpl<ComplexType> ComplexEnumerableImpl { get; set; }
public ComplexType[] ComplexArray { get; set; }
public IEnumerable<ComplexType> ComplexEnumerableInterface { get; set; }
public List<ComplexType> ComplexList { get; set; }
public IList<ComplexType> ComplexListInterface { get; set; }
public GenericListImpl<ComplexType> ComplexListImpl { get; set; }
}
private static readonly object[] ComplexArrayMembers = TestCases.Create()
.Add("ComplexArray", new Model { ComplexArray = new ComplexType[] { ComplexTypeInstance } })
.Add("ComplexEnumerableInterface", new Model { ComplexEnumerableInterface = new List<ComplexType> { ComplexTypeInstance } })
.Add("ComplexList", new Model { ComplexList = new List<ComplexType> { ComplexTypeInstance } })
.Add("ComplexListInterface", new Model { ComplexListInterface = new ComplexType[] { ComplexTypeInstance } })
.Add("ComplexListImpl", new Model { ComplexListImpl = new GenericListImpl<ComplexType> { ComplexTypeInstance } })
.Add("NonGenericArray", new Model { NonGenericArray = new ArrayList { ComplexTypeInstance } })
.Add("EnumerableInterface", new Model { EnumerableInterface = new ArrayList { ComplexTypeInstance } })
.Add("EnumerableImpl", new Model { EnumerableImpl = new EnumerableImpl(ComplexTypeInstance) })
.Add("ComplexEnumerableImpl", new Model { ComplexEnumerableImpl = new GenericEnumerableImpl<ComplexType>(ComplexTypeInstance) })
.All;
[Test]
[TestCaseSource(nameof(ComplexArrayMembers))]
public void should_serialize_member_array_of_complex_type(string name, Model model)
{
Serialize.Json(model).ShouldEqual("{{\"{0}\":[{{\"Property\":\"hai\"}}]}}".ToFormat(name));
}
// Actual vs specified type
public class ActualType : ISpecifiedType
{
public string Actual { get; set; }
public string Specified { get; set; }
}
public interface ISpecifiedType
{
string Specified { get; set; }
}
[Test]
public void should_serialize_specified_type_by_default()
{
Serialize.Json(new List<ActualType> { new ActualType
{ Actual = "oh", Specified = "hai" } }, typeof(List<ISpecifiedType>))
.ShouldEqual("[{\"Specified\":\"hai\"}]");
}
[Test]
public void should_serialize_actual_type_when_configured()
{
Serialize.Json(new List<ActualType> { new ActualType
{ Actual = "oh", Specified = "hai" } }, typeof(List<ISpecifiedType>),
x => x.Serialization(y => y.UseActualType()))
.ShouldEqual("[{\"Actual\":\"oh\",\"Specified\":\"hai\"}]");
}
public class MemberSpecifiedType
{
public List<ISpecifiedType> Specified { get; set; }
}
[Test]
public void should_serialize_member_specified_type_by_default()
{
Serialize.Json(new MemberSpecifiedType { Specified = new List<ISpecifiedType>
{ new ActualType { Actual = "oh", Specified = "hai" } } },
typeof(MemberSpecifiedType))
.ShouldEqual("{\"Specified\":[{\"Specified\":\"hai\"}]}");
}
[Test]
public void should_serialize_member_actual_type_when_configured()
{
Serialize.Json(new MemberSpecifiedType { Specified = new List<ISpecifiedType>
{ new ActualType { Actual = "oh", Specified = "hai" } } },
typeof(MemberSpecifiedType),
x => x.Serialization(y => y.UseActualType()))
.ShouldEqual("{\"Specified\":[{\"Actual\":\"oh\",\"Specified\":\"hai\"}]}");
}
// Enumerable vs object handling
public class EnumerableMember
{
public EnumerableImplementation EnumerableImpl { get; set; }
}
public class EnumerableImplementation : GenericListImpl<string>
{
public string Property { get; set; }
public string Field;
}
[Test]
public void should_not_treat_enumerable_root_as_object_by_default()
{
Serialize.Json(new EnumerableImplementation { "oh", "hai" })
.ShouldEqual("[\"oh\",\"hai\"]");
}
[Test]
public void should_treat_enumerable_root_as_object_when_configured()
{
Serialize.Json(new EnumerableImplementation { Property = "oh", Field = "hai" },
x => x.TreatEnumerableImplsAsObjects().IncludePublicFields())
.ShouldEqual("{\"Property\":\"oh\",\"Field\":\"hai\"}");
}
[Test]
public void should_not_treat_enumerable_member_as_object_by_default()
{
Serialize.Json(new EnumerableMember { EnumerableImpl = new EnumerableImplementation { "oh", "hai" } })
.ShouldEqual("{\"EnumerableImpl\":[\"oh\",\"hai\"]}");
}
[Test]
public void should_treat_enumerable_member_as_object_when_configured()
{
Serialize.Json(new EnumerableMember { EnumerableImpl = new EnumerableImplementation { Property = "oh", Field = "hai" } },
x => x.TreatEnumerableImplsAsObjects().IncludePublicFields())
.ShouldEqual("{\"EnumerableImpl\":{\"Property\":\"oh\",\"Field\":\"hai\"}}");
}
[Test]
public void should_not_treat_enumerable_array_item_as_object_by_default()
{
Serialize.Json(new List<EnumerableImplementation> { new EnumerableImplementation { "oh", "hai" }})
.ShouldEqual("[[\"oh\",\"hai\"]]");
}
[Test]
public void should_treat_enumerable_array_item_as_object_when_configured()
{
Serialize.Json(new List<EnumerableImplementation> { new EnumerableImplementation { Property = "oh", Field = "hai" }},
x => x.TreatEnumerableImplsAsObjects().IncludePublicFields())
.ShouldEqual("[{\"Property\":\"oh\",\"Field\":\"hai\"}]");
}
[Test]
public void should_not_treat_enumerable_dictionary_entry_as_object_by_default()
{
Serialize.Json(new Dictionary<string, EnumerableImplementation> { { "item",
new EnumerableImplementation { "oh", "hai" } } })
.ShouldEqual("{\"item\":[\"oh\",\"hai\"]}");
}
[Test]
public void should_treat_enumerable_dictionary_entry_as_object_when_configured()
{
Serialize.Json(new Dictionary<string, EnumerableImplementation> { { "item",
new EnumerableImplementation { Property = "oh", Field = "hai" } } },
x => x.TreatEnumerableImplsAsObjects().IncludePublicFields())
.ShouldEqual("{\"item\":{\"Property\":\"oh\",\"Field\":\"hai\"}}");
}
// Type filtering
[Test]
public void should_not_include_types_when_does_not_match()
{
Serialize.Json<IList<ComplexType>>(new List<ComplexType> { new ComplexType() },
x => x.IncludeTypesWhen((t, o) => t.Name == "ComplexType2"))
.ShouldEqual("[]");
}
[Test]
public void should_include_types_when_matches()
{
Serialize.Json<IList<ComplexType>>(new List<ComplexType> { new ComplexType() },
x => x.IncludeTypesWhen((t, o) => t.Name == "ComplexType"))
.ShouldEqual("[{}]");
}
[Test]
public void should_filter_types()
{
Serialize.Json<IList<ComplexType>>(new List<ComplexType> { ComplexTypeInstance },
x => x.ExcludeType<ComplexType>())
.ShouldEqual("[]");
}
[Test]
public void should_exclude_types_when()
{
Serialize.Json<IList<ComplexType>>(new List<ComplexType> { ComplexTypeInstance },
x => x.ExcludeTypesWhen((t, o) => t.Name == "ComplexType"))
.ShouldEqual("[]");
}
// Circular references
public class CircularReference
{
public CircularReferenceNode Value { get; set; }
}
public class CircularReferenceNode
{
public string Value1 { get; set; }
public List<CircularReference> Value2 { get; set; }
}
[Test]
public void should_not_allow_circular_references()
{
var graph = new CircularReference { Value = new CircularReferenceNode { Value1 = "hai" } };
graph.Value.Value2 = new List<CircularReference> { graph };
Serialize.Json(graph).ShouldEqual("{\"Value\":{\"Value1\":\"hai\",\"Value2\":[]}}");
}
}
}
|
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
// ORIGINAL HEADER FROM C++ source which was converted to C# by Ted Dunsford 2/24/2010
/******************************************************************************
* $Id: hfatype.cpp, v 1.11 2006/05/07 04:04:03 fwarmerdam Exp $
*
* Project: Erdas Imagine (.img) Translator
* Purpose: Implementation of the HFAType class, for managing one type
* defined in the HFA data dictionary. Managed by HFADictionary.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1999, Intergraph Corporation
*
* 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.
******************************************************************************
*
* $Log: hfatype.cpp, v $
* Revision 1.11 2006/05/07 04:04:03 fwarmerdam
* fixed serious multithreading issue with ExtractInstValue (bug 1132)
*
* Revision 1.10 2005/05/13 02:45:16 fwarmerdam
* fixed GetInstCount() error return
*
* Revision 1.9 2005/05/10 00:55:30 fwarmerdam
* Added GetInstCount method
*
* Revision 1.8 2004/01/26 18:28:51 warmerda
* added error recover after corrupt/unrecognised entries - bug 411
*
* Revision 1.7 2003/04/22 19:40:36 warmerda
* fixed email address
*
* Revision 1.6 2003/02/21 15:40:58 dron
* Added support for writing large (>4 GB) Erdas Imagine files.
*
* Revision 1.5 2001/07/18 04:51:57 warmerda
* added CPL_CVSID
*
* Revision 1.4 2000/12/29 16:37:32 warmerda
* Use GUInt32 for all file offsets
*
* Revision 1.3 2000/09/29 21:42:38 warmerda
* preliminary write support implemented
*
* Revision 1.2 1999/01/22 17:36:47 warmerda
* Added GetInstBytes(), track unknown sizes properly
*
* Revision 1.1 1999/01/04 22:52:10 warmerda
* New
*
*/
using System.Collections.Generic;
using System.IO;
namespace DotSpatial.Data
{
/// <summary>
/// HfaType
/// </summary>
public class HfaType
{
#region Properties
/// <summary>
/// Gets or sets the number of fields.
/// </summary>
public int FieldCount { get; set; }
/// <summary>
/// Gets or sets the list of fields
/// </summary>
public List<HfaField> Fields { get; set; }
/// <summary>
/// Gets or sets the number of bytes.
/// </summary>
public int NumBytes { get; set; }
/// <summary>
/// Gets or sets the type name.
/// </summary>
public string TypeName { get; set; }
#endregion
#region Methods
/// <summary>
/// Completes the defenition of this type based on the existing dictionary.
/// </summary>
/// <param name="dictionary">Dictionary used for completion.</param>
public void CompleteDefn(HfaDictionary dictionary)
{
// This may already be done, if an earlier object required this
// object (as a field), and forced and early computation of the size
if (NumBytes != 0) return;
// Complete each fo the fields, totaling up the sizes. This
// isn't really accurate for objects with variable sized
// subobjects.
foreach (HfaField field in Fields)
{
field.CompleteDefn(dictionary);
if (field.NumBytes < 0 || NumBytes == -1)
{
NumBytes = -1;
}
else
{
NumBytes += field.NumBytes;
}
}
}
/// <summary>
/// This function writes content to the file for this entire type by writing
/// the type name and number of bytes, followed by cycling through and writing each
/// of the fields.
/// </summary>
/// <param name="stream">Stream to write to.</param>
public void Dump(Stream stream)
{
StreamWriter sw = new StreamWriter(stream);
sw.Write("HFAType " + TypeName + "/" + NumBytes + "\n");
foreach (HfaField field in Fields)
{
field.Dump(stream);
}
}
/// <summary>
/// Triggers a dump on all the fields of this type.
/// </summary>
/// <param name="fpOut">The output stream.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The offset to start from.</param>
/// <param name="dataSize">The data size.</param>
/// <param name="pszPrefix">The prefix.</param>
public void DumpInstValue(Stream fpOut, byte[] data, long dataOffset, int dataSize, string pszPrefix)
{
foreach (HfaField field in Fields)
{
field.DumpInstValue(fpOut, data, dataOffset, dataSize, pszPrefix);
int nInstBytes = field.GetInstBytes(data, dataOffset);
dataOffset += nInstBytes;
dataSize -= nInstBytes;
}
}
/// <summary>
/// Extracts the value form the byte array.
/// </summary>
/// <param name="fieldPath">The field path.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The offset to start from.</param>
/// <param name="dataSize">The data size.</param>
/// <param name="reqType">The req type.</param>
/// <param name="reqReturn">The req return.</param>
/// <returns>True, if the value could be extracted.</returns>
public bool ExtractInstValue(string fieldPath, byte[] data, long dataOffset, int dataSize, char reqType, out object reqReturn)
{
reqReturn = null;
int arrayIndex, byteOffset, extraOffset;
string remainder;
HfaField field = ParseFieldPath(fieldPath, data, dataOffset, out remainder, out arrayIndex, out byteOffset);
return field != null && field.ExtractInstValue(remainder, arrayIndex, data, dataOffset + byteOffset, dataSize - byteOffset, reqType, out reqReturn, out extraOffset);
}
/// <summary>
/// Gets the number of bytes for this type by adding up the byte contribution from each of its fields.
/// </summary>
/// <param name="data">The array of bytes to scan.</param>
/// <param name="dataOffset">The integer index in the array where scanning should begin.</param>
/// <returns>The integer count.</returns>
public int GetInstBytes(byte[] data, long dataOffset)
{
if (NumBytes >= 0)
{
return NumBytes;
}
int nTotal = 0;
foreach (HfaField field in Fields)
{
nTotal += field.GetInstBytes(data, dataOffset + nTotal);
}
return nTotal;
}
/// <summary>
/// Attempts to find the specified field in the field path and extracts the count of the specified field.
/// </summary>
/// <param name="fieldPath">The field path.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The data offset.</param>
/// <param name="dataSize">The data size.</param>
/// <returns>The count for a particular instance of a field.</returns>
public int GetInstCount(string fieldPath, byte[] data, long dataOffset, int dataSize)
{
int arrayIndex, byteOffset;
string remainder;
HfaField field = ParseFieldPath(fieldPath, data, dataOffset, out remainder, out arrayIndex, out byteOffset);
if (field != null) return field.GetInstCount(data, dataOffset + byteOffset);
return -1;
}
/// <summary>
/// Originally Initialize
/// </summary>
/// <param name="input">The input string that contains content for this type</param>
/// <returns>The remaining string content, unless this fails in which case this may return null</returns>
public string Intialize(string input)
{
if (!input.Contains("{")) return null;
string partialInput = input.SkipTo("{");
while (partialInput != null && partialInput[0] != '}')
{
HfaField fld = new HfaField();
// If the initialize fails, the return string is null.
partialInput = fld.Initialize(partialInput);
if (partialInput == null) continue;
if (Fields == null) Fields = new List<HfaField>();
Fields.Add(fld);
FieldCount++;
}
// If we have run out of content, we can't complete the type.
if (partialInput == null) return null;
// Get the name
int start = 0;
TypeName = partialInput.ExtractTo(ref start, ",");
return partialInput.Substring(start, partialInput.Length - start);
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="fieldPath">The field path.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The data offset.</param>
/// <param name="dataSize">The data size.</param>
/// <param name="reqType">The req type.</param>
/// <param name="value">The value.</param>
public void SetInstValue(string fieldPath, byte[] data, long dataOffset, int dataSize, char reqType, object value)
{
int arrayIndex, byteOffset;
string remainder;
HfaField field = ParseFieldPath(fieldPath, data, dataOffset, out remainder, out arrayIndex, out byteOffset);
field.SetInstValue(remainder, arrayIndex, data, dataOffset + byteOffset, dataSize - byteOffset, reqType, value);
}
private HfaField ParseFieldPath(string fieldPath, byte[] data, long dataOffset, out string remainder, out int arrayIndex, out int byteOffset)
{
arrayIndex = 0;
string name;
remainder = null;
if (fieldPath.Contains("["))
{
// In the array case we have the format: name[2].subname
// so only read up to the [ for the name but we also need to read the integer after that bracket.
string arrayVal;
name = fieldPath.ExtractTo("[", out arrayVal);
arrayIndex = arrayVal.ExtractInteger();
// Finally, we still need the subname after the period, but we can ignore the return value and just use the remainder.
fieldPath.ExtractTo(".", out remainder);
}
else if (fieldPath.Contains("."))
{
// This is separating name.subname into two separate parts, even if there are many further sub-divisions of the name.
name = fieldPath.ExtractTo(".", out remainder);
}
else
{
name = fieldPath;
}
// Find the field within this type, if possible
byteOffset = 0;
foreach (HfaField field in Fields)
{
if (field.FieldName == name)
{
return field;
}
byteOffset += field.GetInstBytes(data, dataOffset + byteOffset);
}
return null;
}
#endregion
}
} |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using XSerializer.Encryption;
namespace XSerializer
{
internal static class SerializationExtensions
{
internal const string ReadOnlyDictionary = "System.Collections.ObjectModel.ReadOnlyDictionary`2, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
internal const string IReadOnlyDictionary = "System.Collections.Generic.IReadOnlyDictionary`2, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
internal const string IReadOnlyCollection = "System.Collections.Generic.IReadOnlyCollection`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
internal const string IReadOnlyList = "System.Collections.Generic.IReadOnlyList`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
private static readonly Type[] _readOnlyCollections = new[] { Type.GetType(IReadOnlyCollection), Type.GetType(IReadOnlyList), typeof(ReadOnlyCollection<>) }.Where(t => t != null).ToArray();
private static readonly ConcurrentDictionary<Tuple<Type, Type>, Func<object, object>> _convertFuncs = new ConcurrentDictionary<Tuple<Type, Type>, Func<object, object>>();
private static readonly Dictionary<Type, string> _typeToXsdTypeMap = new Dictionary<Type, string>();
private static readonly Dictionary<string, Type> _xsdTypeToTypeMap = new Dictionary<string, Type>();
private static readonly ConcurrentDictionary<int, Type> _xsdTypeToTypeCache = new ConcurrentDictionary<int, Type>();
static SerializationExtensions()
{
_typeToXsdTypeMap.Add(typeof(bool), "xsd:boolean");
_typeToXsdTypeMap.Add(typeof(byte), "xsd:unsignedByte");
_typeToXsdTypeMap.Add(typeof(sbyte), "xsd:byte");
_typeToXsdTypeMap.Add(typeof(short), "xsd:short");
_typeToXsdTypeMap.Add(typeof(ushort), "xsd:unsignedShort");
_typeToXsdTypeMap.Add(typeof(int), "xsd:int");
_typeToXsdTypeMap.Add(typeof(uint), "xsd:unsignedInt");
_typeToXsdTypeMap.Add(typeof(long), "xsd:long");
_typeToXsdTypeMap.Add(typeof(ulong), "xsd:unsignedLong");
_typeToXsdTypeMap.Add(typeof(float), "xsd:float");
_typeToXsdTypeMap.Add(typeof(double), "xsd:double");
_typeToXsdTypeMap.Add(typeof(decimal), "xsd:decimal");
_typeToXsdTypeMap.Add(typeof(DateTime), "xsd:dateTime");
_typeToXsdTypeMap.Add(typeof(string), "xsd:string");
foreach (var typeToXsdType in _typeToXsdTypeMap)
{
_xsdTypeToTypeMap.Add(typeToXsdType.Value, typeToXsdType.Key);
}
}
public static string SerializeObject(
this IXmlSerializerInternal serializer,
object instance,
Encoding encoding,
Formatting formatting,
ISerializeOptions options)
{
options = options.WithNewSerializationState();
var sb = new StringBuilder();
using (var stringWriter = new StringWriterWithEncoding(sb, encoding ?? Encoding.UTF8))
{
using (var xmlWriter = new XSerializerXmlTextWriter(stringWriter, options))
{
xmlWriter.Formatting = formatting;
serializer.SerializeObject(xmlWriter, instance, options);
}
}
return sb.ToString();
}
public static void SerializeObject(
this IXmlSerializerInternal serializer,
Stream stream,
object instance,
Encoding encoding,
Formatting formatting,
ISerializeOptions options)
{
options = options.WithNewSerializationState();
StreamWriter streamWriter = null;
try
{
streamWriter = new StreamWriter(stream, encoding ?? Encoding.UTF8);
var xmlWriter = new XSerializerXmlTextWriter(streamWriter, options)
{
Formatting = formatting
};
serializer.SerializeObject(xmlWriter, instance, options);
xmlWriter.Flush();
}
finally
{
if (streamWriter != null)
{
streamWriter.Flush();
}
}
}
public static void SerializeObject(
this IXmlSerializerInternal serializer,
TextWriter writer,
object instance,
Formatting formatting,
ISerializeOptions options)
{
options = options.WithNewSerializationState();
var xmlWriter = new XSerializerXmlTextWriter(writer, options)
{
Formatting = formatting
};
serializer.SerializeObject(xmlWriter, instance, options);
xmlWriter.Flush();
}
public static object DeserializeObject(this IXmlSerializerInternal serializer, string xml, ISerializeOptions options)
{
options = options.WithNewSerializationState();
using (var stringReader = new StringReader(xml))
{
using (var xmlReader = new XmlTextReader(stringReader))
{
using (var reader = new XSerializerXmlReader(xmlReader, options.GetEncryptionMechanism(), options.EncryptKey, options.SerializationState))
{
return serializer.DeserializeObject(reader, options);
}
}
}
}
public static object DeserializeObject(this IXmlSerializerInternal serializer, Stream stream, ISerializeOptions options)
{
options = options.WithNewSerializationState();
var xmlReader = new XmlTextReader(stream);
var reader = new XSerializerXmlReader(xmlReader, options.GetEncryptionMechanism(), options.EncryptKey, options.SerializationState);
return serializer.DeserializeObject(reader, options);
}
public static object DeserializeObject(this IXmlSerializerInternal serializer, TextReader textReader, ISerializeOptions options)
{
options = options.WithNewSerializationState();
var xmlReader = new XmlTextReader(textReader);
var reader = new XSerializerXmlReader(xmlReader, options.GetEncryptionMechanism(), options.EncryptKey, options.SerializationState);
return serializer.DeserializeObject(reader, options);
}
private static ISerializeOptions WithNewSerializationState(this ISerializeOptions serializeOptions)
{
return new SerializeOptions
{
EncryptionMechanism = serializeOptions.EncryptionMechanism,
EncryptKey = serializeOptions.EncryptKey,
Namespaces = serializeOptions.Namespaces,
SerializationState = new SerializationState(),
ShouldAlwaysEmitTypes = serializeOptions.ShouldAlwaysEmitTypes,
ShouldEmitNil = serializeOptions.ShouldEmitNil,
ShouldEncrypt = serializeOptions.ShouldEncrypt,
ShouldRedact = serializeOptions.ShouldRedact,
ShouldIgnoreCaseForEnum = serializeOptions.ShouldIgnoreCaseForEnum,
ShouldSerializeCharAsInt = serializeOptions.ShouldSerializeCharAsInt
};
}
private class SerializeOptions : ISerializeOptions
{
public XmlSerializerNamespaces Namespaces { get; set; }
public bool ShouldAlwaysEmitTypes { get; set; }
public bool ShouldRedact { get; set; }
public bool ShouldEncrypt { get; set; }
public bool ShouldEmitNil { get; set; }
public IEncryptionMechanism EncryptionMechanism { get; set; }
public object EncryptKey { get; set; }
public SerializationState SerializationState { get; set; }
public bool ShouldIgnoreCaseForEnum { get; set; }
public bool ShouldSerializeCharAsInt { get; set; }
}
/// <summary>
/// Maybe sets the <see cref="XSerializerXmlTextWriter.IsEncryptionEnabled"/> property of
/// <paramref name="writer"/> to true. Returns true if the value was changed to true, false
/// if it was not changed to true.
/// </summary>
internal static bool MaybeSetIsEncryptionEnabledToTrue(this XSerializerXmlTextWriter writer, EncryptAttribute encryptAttribute, ISerializeOptions options)
{
if (options.ShouldEncrypt && encryptAttribute != null && !writer.IsEncryptionEnabled)
{
writer.IsEncryptionEnabled = true;
return true;
}
return false;
}
/// <summary>
/// Maybe sets the <see cref="XSerializerXmlTextWriter.IsEncryptionEnabled"/> property of
/// <paramref name="reader"/> to true. Returns true if the value was changed to true, false
/// if it was not changed to true.
/// </summary>
internal static bool MaybeSetIsDecryptionEnabledToTrue(this XSerializerXmlReader reader,
EncryptAttribute encryptAttribute, ISerializeOptions options)
{
if (options.ShouldEncrypt && encryptAttribute != null && !reader.IsDecryptionEnabled)
{
reader.IsDecryptionEnabled = true;
return true;
}
return false;
}
internal static bool HasDefaultConstructor(this Type type)
{
return type.GetConstructor(Type.EmptyTypes) != null;
}
public static bool IsSerializable(this PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters)
{
if (property.DeclaringType.IsAnonymous())
{
return true;
}
if (Attribute.IsDefined(property, typeof(XmlIgnoreAttribute)))
{
return false;
}
var isSerializable = property.GetIndexParameters().Length == 0 && (property.IsReadWriteProperty() || property.IsSerializableReadOnlyProperty(constructorParameters));
return isSerializable;
}
public static bool IsJsonSerializable(this PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters)
{
if (property.DeclaringType.IsAnonymous())
{
return true;
}
if (Attribute.IsDefined(property, typeof(JsonIgnoreAttribute))
|| Attribute.GetCustomAttributes(property).Any(attribute =>
attribute.GetType().FullName == "Newtonsoft.Json.JsonIgnoreAttribute"))
{
return false;
}
var isSerializable = property.GetIndexParameters().Length == 0 && (property.IsReadWriteProperty() || property.IsJsonSerializableReadOnlyProperty(constructorParameters));
return isSerializable;
}
internal static string GetName(this PropertyInfo property)
{
var jsonPropertyAttribute = (JsonPropertyAttribute)Attribute.GetCustomAttribute(property, typeof(JsonPropertyAttribute));
if (jsonPropertyAttribute != null && !string.IsNullOrEmpty(jsonPropertyAttribute.Name))
{
return jsonPropertyAttribute.Name;
}
var newtonsoftJsonPropertyAttribute =
Attribute.GetCustomAttributes(property).FirstOrDefault(attribute =>
attribute.GetType().FullName == "Newtonsoft.Json.JsonPropertyAttribute");
if (newtonsoftJsonPropertyAttribute != null)
{
var propertyNameProperty = newtonsoftJsonPropertyAttribute.GetType().GetProperty("PropertyName");
if (propertyNameProperty != null
&& propertyNameProperty.PropertyType == typeof(string))
{
var propertyName = (string)propertyNameProperty.GetValue(newtonsoftJsonPropertyAttribute, new object[0]);
if (!string.IsNullOrEmpty(propertyName))
{
return propertyName;
}
}
}
return property.Name;
}
internal static bool IsReadWriteProperty(this PropertyInfo property)
{
var isReadWriteProperty = property.HasPublicGetter() && property.HasPublicSetter();
return isReadWriteProperty;
}
internal static bool IsSerializableReadOnlyProperty(this PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters = null)
{
return
property.IsReadOnlyProperty()
&&
!IsConditionalProperty(property, constructorParameters)
&&
(
((constructorParameters ?? Enumerable.Empty<ParameterInfo>()).Any(p => p.Name.ToLower() == property.Name.ToLower() && p.ParameterType == property.PropertyType))
||
(property.PropertyType.IsAnyKindOfDictionary() && property.PropertyType != typeof(ExpandoObject))
||
(property.PropertyType.IsAssignableToGenericIEnumerable() && property.PropertyType.HasAddMethodOfType(property.PropertyType.GetGenericIEnumerableType().GetGenericArguments()[0]))
||
(property.PropertyType.IsAssignableToNonGenericIEnumerable() && property.PropertyType.HasAddMethod())
||
(property.PropertyType.IsReadOnlyCollection())
||
(property.PropertyType.IsArray && property.PropertyType.GetArrayRank() == 1)
||
(property.PropertyType.IsReadOnlyDictionary())
); // TODO: add additional serializable types?
}
internal static bool IsJsonSerializableReadOnlyProperty(this PropertyInfo propertyInfo, IEnumerable<ParameterInfo> constructorParameters = null)
{
if (!propertyInfo.IsReadOnlyProperty())
{
return false;
}
if (constructorParameters != null && constructorParameters.Any(p => string.Equals(p.Name, propertyInfo.Name, StringComparison.OrdinalIgnoreCase)))
{
return true;
}
if (typeof(IDictionary).IsAssignableFrom(propertyInfo.PropertyType)
|| propertyInfo.PropertyType.IsAssignableToGenericIDictionary())
{
return true;
}
if (propertyInfo.PropertyType.IsArray)
{
return false;
}
if (typeof(IList).IsAssignableFrom(propertyInfo.PropertyType)
|| propertyInfo.PropertyType.IsAssignableToGenericICollection())
{
return true;
}
return false;
}
internal static object ConvertIfNecessary(this object instance, Type targetType)
{
if (instance == null)
{
return null;
}
var instanceType = instance.GetType();
if (targetType.IsAssignableFrom(instanceType))
{
return instance;
}
var convertFunc =
_convertFuncs.GetOrAdd(
Tuple.Create(instanceType, targetType),
tuple => CreateConvertFunc(tuple.Item1, tuple.Item2));
return convertFunc(instance);
}
private static Func<object, object> CreateConvertFunc(Type instanceType, Type targetType)
{
if (instanceType.IsGenericType && instanceType.GetGenericTypeDefinition() == typeof(List<>))
{
if (targetType.IsArray)
{
return CreateToArrayFunc(targetType.GetElementType());
}
if (targetType.IsReadOnlyCollection())
{
var collectionType = targetType.GetReadOnlyCollectionType();
return CreateAsReadOnlyFunc(collectionType.GetGenericArguments()[0]);
}
}
// Oh well, we were gonna throw anyway. Just let it happen...
return x => x;
}
private static Func<object, object> CreateToArrayFunc(Type itemType)
{
var toArrayMethod =
typeof(Enumerable)
.GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(itemType);
var sourceParameter = Expression.Parameter(typeof(object), "source");
var lambda =
Expression.Lambda<Func<object, object>>(
Expression.Call(
toArrayMethod,
Expression.Convert(sourceParameter, typeof(IEnumerable<>).MakeGenericType(itemType))),
sourceParameter);
return lambda.Compile();
}
private static Func<object, object> CreateAsReadOnlyFunc(Type itemType)
{
var listType = typeof (List<>).MakeGenericType(itemType);
var asReadOnlyMethod = listType.GetMethod("AsReadOnly", BindingFlags.Instance | BindingFlags.Public);
var instanceParameter = Expression.Parameter(typeof(object), "instance");
var lambda =
Expression.Lambda<Func<object, object>>(
Expression.Call(
Expression.Convert(instanceParameter, listType),
asReadOnlyMethod),
instanceParameter);
return lambda.Compile();
}
internal static bool IsReadOnlyCollection(this Type type)
{
var openGenerics = GetOpenGenerics(type);
foreach (var openGeneric in openGenerics)
{
if (openGeneric == typeof(ReadOnlyCollection<>))
{
return true;
}
switch (openGeneric.AssemblyQualifiedName)
{
case IReadOnlyCollection:
case IReadOnlyList:
return true;
}
}
return false;
}
internal static Type GetReadOnlyCollectionType(this Type type)
{
if (IsReadOnlyCollectionType(type))
{
return type;
}
var interfaceType = type.GetInterfaces().FirstOrDefault(IsReadOnlyCollectionType);
if (interfaceType != null)
{
return interfaceType;
}
do
{
type = type.BaseType;
if (type == null)
{
return null;
}
if (IsReadOnlyCollectionType(type))
{
return type;
}
} while (true);
}
private static bool IsReadOnlyCollectionType(Type i)
{
if (i.IsGenericType)
{
var genericTypeDefinition = i.GetGenericTypeDefinition();
if (_readOnlyCollections.Any(readOnlyCollectionType => genericTypeDefinition == readOnlyCollectionType))
{
return true;
}
}
return false;
}
internal static bool IsReadOnlyDictionary(this Type type)
{
var openGenerics = GetOpenGenerics(type);
foreach (var openGeneric in openGenerics)
{
switch (openGeneric.AssemblyQualifiedName)
{
case IReadOnlyDictionary:
case ReadOnlyDictionary:
return true;
}
}
return false;
}
internal static Type GetIReadOnlyDictionaryInterface(this Type type)
{
var iReadOnlyDictionaryType = Type.GetType(IReadOnlyDictionary);
if (type.IsGenericType && type.GetGenericTypeDefinition() == iReadOnlyDictionaryType)
{
return type;
}
return
type.GetInterfaces()
.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == iReadOnlyDictionaryType);
}
private static IEnumerable<Type> GetOpenGenerics(Type type)
{
if (type.IsGenericType)
{
yield return type.GetGenericTypeDefinition();
}
foreach (var interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType)
{
yield return interfaceType;
}
}
while (true)
{
type = type.BaseType;
if (type == null)
{
yield break;
}
if (type.IsGenericType)
{
yield return type.GetGenericTypeDefinition();
}
}
}
private static bool IsConditionalProperty(PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters)
{
if (property.Name.EndsWith("Specified"))
{
var otherPropertyName = property.Name.Substring(0, property.Name.LastIndexOf("Specified"));
return property.DeclaringType.GetProperties().Any(p => p.Name == otherPropertyName);
}
return false;
}
internal static bool HasAddMethodOfType(this Type type, Type addMethodType)
{
return type.GetMethod("Add", new[] { addMethodType }) != null;
}
internal static bool HasAddMethod(this Type type)
{
return type.GetMethods().Any(m => m.Name == "Add" && m.GetParameters().Length == 1);
}
internal static bool IsAnyKindOfDictionary(this Type type)
{
return type.IsAssignableToNonGenericIDictionary() || type.IsAssignableToGenericIDictionary();
}
internal static bool IsReadOnlyProperty(this PropertyInfo property)
{
var canCallGetter = property.HasPublicGetter();
var canCallSetter = property.HasPublicSetter();
return canCallGetter && !canCallSetter;
}
internal static bool IsAssignableToNonGenericIDictionary(this Type type)
{
var isAssignableToIDictionary = typeof(IDictionary).IsAssignableFrom(type);
return isAssignableToIDictionary;
}
internal static bool IsGenericIDictionary(this Type type)
{
return type.IsInterface
&& type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IDictionary<,>);
}
internal static bool IsAssignableToGenericIDictionary(this Type type)
{
var isAssignableToGenericIDictionary =
(type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
|| type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>));
return isAssignableToGenericIDictionary;
}
internal static bool IsAssignableToGenericIDictionaryWithKeyOrValueOfTypeObject(this Type type)
{
var isAssignableToGenericIDictionary = type.IsAssignableToGenericIDictionary();
if (!isAssignableToGenericIDictionary)
{
return false;
}
Type iDictionaryType;
if (type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
iDictionaryType = type;
}
else
{
iDictionaryType = type.GetInterfaces().Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>));
}
return iDictionaryType.GetGenericArguments()[0] == typeof(object) || iDictionaryType.GetGenericArguments()[1] == typeof(object);
}
internal static bool IsAssignableToGenericIDictionaryOfStringToAnything(this Type type)
{
if (type.IsAssignableToGenericIDictionary())
{
var dictionaryType = type.GetGenericIDictionaryType();
var args = dictionaryType.GetGenericArguments();
return args[0] == typeof(string);
}
return false;
}
internal static bool IsAssignableToNonGenericIEnumerable(this Type type)
{
var isAssignableToIEnumerable = typeof(IEnumerable).IsAssignableFrom(type);
return isAssignableToIEnumerable;
}
internal static bool IsGenericIEnumerable(this Type type)
{
return type.IsInterface
&& type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}
internal static bool IsAssignableToGenericIEnumerable(this Type type)
{
var isAssignableToGenericIEnumerable =
type.IsGenericIEnumerable()
|| type.GetInterfaces().Any(i => i.IsGenericIEnumerable());
return isAssignableToGenericIEnumerable;
}
internal static bool IsAssignableToGenericIEnumerableOfTypeObject(this Type type)
{
var isAssignableToGenericIEnumerable = type.IsAssignableToGenericIEnumerable();
if (!isAssignableToGenericIEnumerable)
{
return false;
}
var iEnumerableType =
type.IsGenericIEnumerable()
? type
: type.GetInterfaces().Single(i => i.IsGenericIEnumerable());
return iEnumerableType.GetGenericArguments()[0] == typeof(object);
}
internal static bool IsGenericICollection(this Type type)
{
return type.IsInterface
&& type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(ICollection<>);
}
internal static bool IsAssignableToGenericICollection(this Type type)
{
var isAssignableToGenericICollection =
type.IsGenericICollection()
|| type.GetInterfaces().Any(i => i.IsGenericICollection());
return isAssignableToGenericICollection;
}
internal static Type GetGenericIDictionaryType(this Type type)
{
if (type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
return type;
}
return type.GetInterfaces().First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>));
}
internal static Type GetGenericIEnumerableType(this Type type)
{
if (type.IsGenericIEnumerable())
{
return type;
}
return type.GetInterfaces().First(i => i.IsGenericIEnumerable());
}
internal static Type GetGenericICollectionType(this Type type)
{
if (type.IsGenericICollection())
{
return type;
}
return type.GetInterfaces().First(i => i.IsGenericICollection());
}
private static bool HasPublicGetter(this PropertyInfo property)
{
if (!property.CanRead)
{
return false;
}
var getMethod = property.GetGetMethod();
return getMethod != null && getMethod.IsPublic;
}
private static bool HasPublicSetter(this PropertyInfo property)
{
if (!property.CanWrite)
{
return false;
}
var setMethod = property.GetSetMethod();
return setMethod != null && setMethod.IsPublic;
}
internal static bool ReadIfNeeded(this XSerializerXmlReader reader, bool shouldRead)
{
if (shouldRead)
{
return reader.Read();
}
return true;
}
internal static bool IsNil(this XSerializerXmlReader reader)
{
var nilFound = false;
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == "nil" && reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema-instance")
{
nilFound = true;
break;
}
}
reader.MoveToElement();
return nilFound;
}
internal static void WriteNilAttribute(this XmlWriter writer)
{
writer.WriteAttributeString("xsi", "nil", null, "true");
}
internal static bool IsPrimitiveLike(this Type type)
{
return
type.IsPrimitive
|| type.IsEnum
|| type == typeof(string)
|| type == typeof(decimal)
|| type == typeof(DateTime)
|| type == typeof(Guid)
|| type == typeof(TimeSpan)
|| type == typeof(DateTimeOffset);
}
internal static bool IsNullablePrimitiveLike(this Type type)
{
return
type.IsNullableType()
&& type.GetGenericArguments()[0].IsPrimitiveLike();
}
internal static bool IsNullableType(this Type type)
{
return type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
internal static bool IsReferenceType(this Type type)
{
return !type.IsValueType;
}
internal static object GetUninitializedObject(this Type type)
{
return FormatterServices.GetUninitializedObject(type);
}
public static bool IsAnonymous(this object instance)
{
if (instance == null)
{
return false;
}
return instance.GetType().IsAnonymous();
}
public static bool IsAnonymous(this Type type)
{
return
type.Namespace == null
&& type.IsClass
&& type.IsNotPublic
&& type.IsSealed
&& type.DeclaringType == null
&& type.BaseType == typeof(object)
&& (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase))
&& type.Name.Contains("AnonymousType")
&& Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute));
}
public static string GetElementName(this Type type)
{
if (type.IsGenericType)
{
return type.Name.Substring(0, type.Name.IndexOf("`")) + "Of" + string.Join("_", type.GetGenericArguments().Select(x => x.GetElementName()));
}
if (type.IsArray)
{
return "ArrayOf" + type.GetElementType().Name;
}
return type.Name;
}
public static string GetXsdType(this Type type)
{
string xsdType;
if (_typeToXsdTypeMap.TryGetValue(type, out xsdType))
{
return xsdType;
}
return type.Name;
}
public static Type GetXsdType<T>(this XSerializerXmlReader reader, Type[] extraTypes)
{
string typeName = null;
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == "type" && reader.LookupNamespace(reader.Prefix) == "http://www.w3.org/2001/XMLSchema-instance")
{
typeName = reader.Value;
break;
}
}
reader.MoveToElement();
if (typeName == null)
{
return null;
}
Type typeFromXsdType;
if (_xsdTypeToTypeMap.TryGetValue(typeName, out typeFromXsdType))
{
return typeFromXsdType;
}
return _xsdTypeToTypeCache.GetOrAdd(
CreateTypeCacheKey<T>(typeName),
_ =>
{
Type type = null;
//// try REAL hard to get the type. (holy crap, this is UUUUUGLY!!!!)
if (extraTypes != null)
{
var matchingExtraTypes = extraTypes.Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matchingExtraTypes.Count == 1)
{
type = matchingExtraTypes[0];
}
}
if (type == null)
{
var typeNameWithPossibleNamespace = typeName;
if (!typeName.Contains('.'))
{
typeNameWithPossibleNamespace = typeof(T).Namespace + "." + typeName;
}
var checkPossibleNamespace = typeName != typeNameWithPossibleNamespace;
type = Type.GetType(typeName);
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = checkPossibleNamespace ? Type.GetType(typeNameWithPossibleNamespace) : null;
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = typeof(T).Assembly.GetType(typeName);
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = checkPossibleNamespace ? typeof(T).Assembly.GetType(typeNameWithPossibleNamespace) : null;
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
var matches = typeof(T).Assembly.GetTypes().Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matches.Count == 1)
{
type = matches.Single();
}
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
type = entryAssembly.GetType(typeName);
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = checkPossibleNamespace ? entryAssembly.GetType(typeNameWithPossibleNamespace) : null;
type = typeof(T).IsAssignableFrom(type) ? type : null;
}
if (type == null)
{
matches = entryAssembly.GetTypes().Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matches.Count == 1)
{
type = matches.Single();
}
}
}
if (type == null)
{
matches = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a =>
{
try
{
return a.GetTypes();
}
catch
{
return Enumerable.Empty<Type>();
}
}).Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matches.Count == 1)
{
type = matches.Single();
}
else if (matches.Count > 1)
{
throw new SerializationException(string.Format("More than one type matches '{0}'. Consider decorating your type with the XmlIncludeAttribute, or pass in the type into the serializer as an extra type.", typeName));
}
}
}
}
}
}
}
if (type == null)
{
throw new SerializationException(string.Format("No suitable type matches '{0}'. Consider decorating your type with the XmlIncludeAttribute, or pass in the type into the serializer as an extra type.", typeName));
}
return type;
});
}
private static int CreateTypeCacheKey<T>(string typeName)
{
unchecked
{
var key = typeof(T).GetHashCode();
key = (key * 397) ^ typeName.GetHashCode();
return key;
}
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MonogameDraw
{
public enum LINECAP
{
NONE,
SQUARE,
CIRCLE
};
public class Renderer
{
private GraphicsDevice gd;
private BasicEffect effect;
private Matrix orthographic;
private static VertexPosition[] drawRectangleVertices = new[] {
new VertexPosition(new Vector3(-0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(0.5f, 0.5f, 0)),
new VertexPosition(new Vector3(-0.5f, 0.5f, 0)),
new VertexPosition(new Vector3(-0.5f, -0.5f, 0))
};
private static VertexPosition[] fillRectangleVertices = new[] {
new VertexPosition(new Vector3(-0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(-0.5f, 0.5f, 0)),
new VertexPosition(new Vector3(0.5f, 0.5f, 0))
};
private static Dictionary<int, VertexPosition[]> filledNgons = new Dictionary<int, VertexPosition[]>();
private static Dictionary<int, VertexPosition[]> drawnNgons = new Dictionary<int, VertexPosition[]>();
private const int NGON_CACHE_SIZE = 25;
public Renderer(GraphicsDevice gd)
{
this.gd = gd;
effect = new BasicEffect(gd);
orthographic = Matrix.CreateOrthographicOffCenter(0, gd.Viewport.Width, gd.Viewport.Height, 0, 0, 1);
}
~Renderer()
{
effect.Dispose();
}
private void Draw(PrimitiveType primitiveType, VertexPosition[] vertexPositions, int primitiveCount, Color color, Matrix worldMatrix)
{
effect.World = worldMatrix;
effect.DiffuseColor = color.ToVector3();
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
gd.DrawUserPrimitives(primitiveType, vertexPositions, 0, primitiveCount);
}
}
public void FillNgon(float x, float y, float rx, float ry, int sides, Color color, double angle = 0, double offsetAngle = 0)
{
if (rx <= 0 || ry <= 0 || sides < 3) return;
VertexPosition[] vertexPositions;
if (filledNgons.ContainsKey(sides))
{
vertexPositions = filledNgons[sides];
}
else
{
Vector3[] vertices = new Vector3[sides];
double nextAngle = MathHelper.TwoPi / sides;
for (int i = 0; i < sides; i++)
{
double currX = Math.Cos(nextAngle * i + offsetAngle - MathHelper.PiOver2);
double currY = Math.Sin(nextAngle * i + offsetAngle - MathHelper.PiOver2);
vertices[i] = new Vector3((float)currX, (float)currY, 0);
}
vertexPositions = new VertexPosition[sides];
vertexPositions[0] = new VertexPosition(vertices[0]);
for (int i = 0; i < sides / 2; i++)
{
vertexPositions[i * 2 + 1] = new VertexPosition(vertices[i + 1]);
if (i * 2 + 2 != sides)
vertexPositions[i * 2 + 2] = new VertexPosition(vertices[sides - i - 1]);
}
if (filledNgons.Count > NGON_CACHE_SIZE) filledNgons.Remove(filledNgons.Keys.First());
filledNgons.Add(sides, vertexPositions);
}
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(rx, ry, 1);
Draw(PrimitiveType.TriangleStrip, vertexPositions, sides - 2, color, scale * rotation * translation * orthographic);
}
public void FillRect(float x, float y, float width, float height, Color color, double angle = 0)
{
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(width, height, 1);
Draw(PrimitiveType.TriangleStrip, fillRectangleVertices, 2, color, scale * rotation * translation * orthographic);
}
public void FillSquare(float x, float y, float length, Color color, double angle = 0)
{
FillRect(x, y, length, length, color, angle);
}
public void FillCircle(float x, float y, float radius, Color color, float quality = 1f)
{
FillEllipse(x, y, radius, radius, color, quality);
}
public void FillEllipse(float x, float y, float rx, float ry, Color color, float quality = 1f)
{
int sides = Math.Max((int)(quality * (rx + ry) / 3f + 3), 8);
FillNgon(x, y, rx, ry, sides, color);
}
public void StrokeLine(float ax, float ay, float bx, float by, Color color, int thickness = 1, LINECAP linecap = LINECAP.NONE)
{
if (thickness == 1)
{
VertexPosition[] vertexPositions = new[]
{
new VertexPosition(new Vector3(ax, ay, 0)),
new VertexPosition(new Vector3(bx, by, 0))
};
Draw(PrimitiveType.LineStrip, vertexPositions, 1, color, orthographic);
}
else
{
double angle = Math.Atan2(by - ay, bx - ax);
float xDelta = (float)(Math.Cos(angle + MathHelper.PiOver2) * thickness / 2);
float yDelta = (float)(Math.Sin(angle + MathHelper.PiOver2) * thickness / 2);
VertexPosition[] vertexPositions = new[]
{
new VertexPosition(new Vector3(ax + xDelta, ay + yDelta, 0)),
new VertexPosition(new Vector3(ax - xDelta, ay - yDelta, 0)),
new VertexPosition(new Vector3(bx + xDelta, by + yDelta, 0)),
new VertexPosition(new Vector3(bx - xDelta, by - yDelta, 0))
};
if (thickness > 2)
{
switch (linecap)
{
case LINECAP.CIRCLE:
FillCircle(ax, ay, thickness / 2, color);
FillCircle(bx, by, thickness / 2, color);
break;
case LINECAP.SQUARE:
FillSquare(ax, ay, thickness, color, angle);
FillSquare(bx, by, thickness, color, angle);
break;
}
}
Draw(PrimitiveType.TriangleStrip, vertexPositions, 2, color, orthographic);
}
}
public void StrokePath(List<Vector2> points, Color color, int thickness = 1, LINECAP linecap = LINECAP.NONE)
{
if (points.Count < 2) return;
if (thickness == 1)
{
VertexPosition[] vertexPositions = new VertexPosition[points.Count];
for (int i = 0; i < points.Count; i++)
{
vertexPositions[i] = new VertexPosition(new Vector3(points[i].X, points[i].Y, 0));
}
Draw(PrimitiveType.LineStrip, vertexPositions, points.Count - 1, color, orthographic);
}
else
{
if (points.Count == 2)
{
StrokeLine(points[0].X, points[0].Y, points[1].X, points[2].Y, color, thickness);
return;
}
VertexPosition[] vertexPositions = new VertexPosition[points.Count * 4 - 4];
double angle = 0;
for (int i = 0; i < points.Count - 1; i++)
{
Vector2 point = points[i];
Vector2 nextPoint = points[i + 1];
angle = Math.Atan2(nextPoint.Y - point.Y, nextPoint.X - point.X);
float xDelta = (float)(Math.Cos(angle + MathHelper.PiOver2) * thickness / 2);
float yDelta = (float)(Math.Sin(angle + MathHelper.PiOver2) * thickness / 2);
vertexPositions[4 * i] = new VertexPosition(new Vector3(point.X + xDelta, point.Y + yDelta, 0));
vertexPositions[4 * i + 1] = new VertexPosition(new Vector3(point.X - xDelta, point.Y - yDelta, 0));
vertexPositions[4 * i + 2] = new VertexPosition(new Vector3(nextPoint.X + xDelta, nextPoint.Y + yDelta, 0));
vertexPositions[4 * i + 3] = new VertexPosition(new Vector3(nextPoint.X - xDelta, nextPoint.Y - yDelta, 0));
switch(linecap)
{
case LINECAP.CIRCLE:
FillCircle(points[i].X, points[i].Y, thickness / 2, color);
break;
case LINECAP.SQUARE:
if(i == 0) FillSquare(points[i].X, points[i].Y, thickness, color, angle);
break;
}
}
switch (linecap)
{
case LINECAP.CIRCLE:
FillCircle(points[points.Count - 1].X, points[points.Count - 1].Y, thickness / 2, color);
break;
case LINECAP.SQUARE:
FillSquare(points[points.Count - 1].X, points[points.Count - 1].Y, thickness, color, angle);
break;
}
Draw(PrimitiveType.TriangleStrip, vertexPositions, points.Count * 4 - 6, color, orthographic);
}
}
public void StrokeLoop(List<Vector2> points, Color color, int thickness = 1)
{
if (points.Count < 2) return;
if (thickness == 1)
{
points.Add(points[0]);
StrokePath(points, color, thickness);
}
else
{
if (points.Count == 2)
{
StrokeLine(points[0].X, points[0].Y, points[1].X, points[2].Y, color, thickness);
return;
}
points.Add(points[0]);
VertexPosition[] vertexPositions = new VertexPosition[points.Count * 4 - 2];
for (int i = 0; i < points.Count - 1; i++)
{
Vector2 point = points[i];
Vector2 nextPoint = points[i + 1];
double angle = Math.Atan2(nextPoint.Y - point.Y, nextPoint.X - point.X);
float xDelta = (float)(Math.Cos(angle + MathHelper.PiOver2) * thickness / 2);
float yDelta = (float)(Math.Sin(angle + MathHelper.PiOver2) * thickness / 2);
vertexPositions[4 * i] = new VertexPosition(new Vector3(point.X + xDelta, point.Y + yDelta, 0));
vertexPositions[4 * i + 1] = new VertexPosition(new Vector3(point.X - xDelta, point.Y - yDelta, 0));
vertexPositions[4 * i + 2] = new VertexPosition(new Vector3(nextPoint.X + xDelta, nextPoint.Y + yDelta, 0));
vertexPositions[4 * i + 3] = new VertexPosition(new Vector3(nextPoint.X - xDelta, nextPoint.Y - yDelta, 0));
}
vertexPositions[vertexPositions.Length - 2] = vertexPositions[0];
vertexPositions[vertexPositions.Length - 1] = vertexPositions[1];
Draw(PrimitiveType.TriangleStrip, vertexPositions, points.Count * 4 - 4, color, orthographic);
}
}
public void StrokeNgon(float x, float y, float rx, float ry, int sides, Color color, double angle = 0, double offsetAngle = 0)
{
if (rx <= 0 || ry <= 0 || sides < 3) return;
VertexPosition[] vertexPositions;
if (drawnNgons.ContainsKey(sides))
{
vertexPositions = drawnNgons[sides];
}
else
{
vertexPositions = new VertexPosition[sides + 1];
double nextAngle = MathHelper.TwoPi / sides;
for (int i = 0; i < sides; i++)
{
double currX = Math.Cos(nextAngle * i + offsetAngle - MathHelper.PiOver2);
double currY = Math.Sin(nextAngle * i + offsetAngle - MathHelper.PiOver2);
vertexPositions[i] = new VertexPosition(new Vector3((float)currX, (float)currY, 0));
}
vertexPositions[vertexPositions.Length - 1] = vertexPositions[0];
if (drawnNgons.Count > NGON_CACHE_SIZE) drawnNgons.Remove(drawnNgons.Keys.First());
drawnNgons.Add(sides, vertexPositions);
}
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(rx, ry, 1);
Draw(PrimitiveType.LineStrip, vertexPositions, sides, color, scale * rotation * translation * orthographic);
}
public void StrokeCircle(float x, float y, float radius, Color color, float qualityFactor = 1f)
{
StrokeEllipse(x, y, radius, radius, color, qualityFactor);
}
public void StrokeEllipse(float x, float y, float rx, float ry, Color color, float qualityFactor = 1f)
{
int quality = Math.Max((int)(qualityFactor * ((rx + ry) / 3f + 3)), 8);
StrokeNgon(x, y, rx, ry, quality, color);
}
public void StrokeRect(float x, float y, float width, float height, Color color, double angle = 0)
{
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(width, height, 1);
Draw(PrimitiveType.LineStrip, drawRectangleVertices, 4, color, scale * rotation * translation * orthographic);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Formatting;
using System.Text.RegularExpressions;
namespace AnalyzeThis.ReadonlyField
{
internal class ReadonlyFieldRule : FixableAnalysisRule
{
public static readonly string Id = "AT001";
private readonly string fixTitle = "Set with constructor parameter";
public ReadonlyFieldRule()
: base(
diagnosticId: Id,
title: "Readonly fields must be assigned.",
messageFormat: "Readonly field(s) not assigned in constructor: {0}.",
category: "TODO",
severity: DiagnosticSeverity.Error,
description: "Readonly fields which are not assigned on declaration must be assigned in every non-chained constructor."
)
{
}
public override void Register(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ConstructorDeclaration);
}
public override void RegisterCodeFix(CodeFixContext context, Diagnostic diagnostic)
{
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: fixTitle,
createChangedDocument: c => AddConstructorParameterAndAssignAsync(context.Document, diagnostic.Location, c),
equivalenceKey: fixTitle
),
diagnostic);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var constructorNode = context.Node as ConstructorDeclarationSyntax;
IEnumerable<string> unsetReadonlyFieldNames = GetUnassignedReadonlyFields(constructorNode)
.Select(declaration => declaration.GetIdentifierText());
if (unsetReadonlyFieldNames.Any())
{
var diagnostic = Diagnostic.Create(this.Descriptor, constructorNode.GetLocation(), string.Join(", ", unsetReadonlyFieldNames));
context.ReportDiagnostic(diagnostic);
}
}
private static IEnumerable<FieldDeclarationSyntax> GetUnassignedReadonlyFields(ConstructorDeclarationSyntax constructorNode)
{
// Ignore chained 'this' constructors
if (constructorNode.Initializer?.Kind() == SyntaxKind.ThisConstructorInitializer)
{
return Enumerable.Empty<FieldDeclarationSyntax>();
}
var classNode = constructorNode.Parent as ClassDeclarationSyntax;
var assignedFields = (constructorNode.Body?.DescendantNodes() ?? Enumerable.Empty<SyntaxNode>())
.WhereIs<SyntaxNode, AssignmentExpressionSyntax>()
.Select(x =>
{
return x;
})
.Select(assignment => assignment.Left)
.WhereIs<ExpressionSyntax, MemberAccessExpressionSyntax>()
.Select(memberAccess => memberAccess.Name.Identifier.ValueText)
.ToImmutableHashSet();
var unsetReadonlyFields = classNode.Members
.WhereIs<SyntaxNode, FieldDeclarationSyntax>() // Fields
.Where(fieldNode => fieldNode.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) // Readonly
.Where(fieldNode => fieldNode.Declaration.Variables.First().Initializer == null) // Not initialized inline
.Where(fieldNode => !assignedFields.Contains(fieldNode.GetIdentifierText())); // Not assigned in constructor
return unsetReadonlyFields;
}
private string GetLocalIdentifierName(string originalName)
{
return Regex.Replace(originalName, "^[A-Z]", match => match.Value.ToLower());
}
private async Task<Document> AddConstructorParameterAndAssignAsync(
Document document,
Location location,
CancellationToken cancellationToken
)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var constructorNode = root.FindNode(location.SourceSpan) as ConstructorDeclarationSyntax;
var existingParameters = constructorNode.ParameterList
.Parameters
.ToDictionary(parameter => parameter.Identifier.ValueText, StringComparer.OrdinalIgnoreCase);
var unassignedFields = GetUnassignedReadonlyFields(constructorNode);
var newParameters = unassignedFields
.Where(field => !existingParameters.ContainsKey(field.GetIdentifierText()))
.Select(field =>
SyntaxFactory.Parameter(
SyntaxFactory
.Identifier(this.GetLocalIdentifierName(field.GetIdentifierText()))
)
.WithType(field.Declaration.Type)
);
var newStatements = unassignedFields.Select(field =>
{
ParameterSyntax existingParameter;
string assignmentRight;
// Find existing parameter with same name (ignoring case)
if (existingParameters.TryGetValue(field.GetIdentifierText(), out existingParameter))
{
// Use it if type is the same
if (existingParameter.Type.ProperEquals(field.Declaration.Type))
{
assignmentRight = existingParameter.Identifier.ValueText;
}
// Abort if type is different
else
{
return null;
}
}
// Otherwise use adjusted field name
else
{
assignmentRight = this.GetLocalIdentifierName(field.GetIdentifierText());
}
return SyntaxFactory.ExpressionStatement(
SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ThisExpression(),
SyntaxFactory.IdentifierName(field.GetIdentifierText())
),
SyntaxFactory.IdentifierName(assignmentRight)
)
);
})
.Where(statement => statement != null);
var updatedMethod = constructorNode
.AddParameterListParameters(newParameters.ToArray())
.AddBodyStatements(newStatements.ToArray());
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken);
var updatedSyntaxTree = root.ReplaceNode(constructorNode, updatedMethod);
updatedSyntaxTree = Formatter.Format(updatedSyntaxTree, new AdhocWorkspace());
return document.WithSyntaxRoot(updatedSyntaxTree);
}
}
}
|
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SData.Internal;
namespace SData.Compiler
{
internal static class CSEX
{
internal static readonly string[] SchemaNamespaceAttributeNameParts = new string[] { "SchemaNamespaceAttribute", "SData" };
internal static readonly string[] __CompilerSchemaNamespaceAttributeNameParts = new string[] { "__CompilerSchemaNamespaceAttribute", "SData" };
internal static readonly string[] SchemaClassAttributeNameParts = new string[] { "SchemaClassAttribute", "SData" };
internal static readonly string[] SchemaPropertyAttributeNameParts = new string[] { "SchemaPropertyAttribute", "SData" };
internal static readonly string[] IgnoreCaseStringNameParts = new string[] { "IgnoreCaseString", "SData" };
internal static readonly string[] BinaryNameParts = new string[] { "Binary", "SData" };
internal static int MapNamespaces(NamespaceInfoMap nsInfoMap, IAssemblySymbol assSymbol, bool isRef)
{
var count = 0;
foreach (AttributeData attData in assSymbol.GetAttributes())
{
if (attData.AttributeClass.FullNameEquals(isRef ? __CompilerSchemaNamespaceAttributeNameParts : SchemaNamespaceAttributeNameParts))
{
var ctorArgs = attData.ConstructorArguments;
string uri = null, dottedString = null;
var ctorArgsLength = ctorArgs.Length;
if (ctorArgsLength >= 2)
{
uri = ctorArgs[0].Value as string;
if (uri != null)
{
dottedString = ctorArgs[1].Value as string;
}
}
if (dottedString == null)
{
if (isRef)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Invalid__CompilerSchemaNamespaceAttribute,
assSymbol.Identity.Name), default(TextSpan));
}
else
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaNamespaceAttribute),
GetTextSpan(attData));
}
}
NamespaceInfo nsInfo;
if (!nsInfoMap.TryGetValue(uri, out nsInfo))
{
if (isRef)
{
continue;
}
else
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaNamespaceAttributeUri, uri),
GetTextSpan(attData));
}
}
if (nsInfo.DottedName != null)
{
if (isRef)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Duplicate__CompilerSchemaNamespaceAttributeUri,
uri, assSymbol.Identity.Name), default(TextSpan));
}
else
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.DuplicateSchemaNamespaceAttributeUri, uri),
GetTextSpan(attData));
}
}
CSDottedName dottedName;
if (!CSDottedName.TryParse(dottedString, out dottedName))
{
if (isRef)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Invalid__CompilerSchemaNamespaceAttributeNamespaceName,
dottedString, assSymbol.Identity.Name), default(TextSpan));
}
else
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaNamespaceAttributeNamespaceName, dottedString),
GetTextSpan(attData));
}
}
nsInfo.DottedName = dottedName;
nsInfo.IsRef = isRef;
++count;
if (isRef)
{
if (ctorArgsLength >= 4)
{
var ca2 = ctorArgs[2];
var ca3 = ctorArgs[3];
nsInfo.SetRefData(ca2.IsNull ? null : ca2.Values.Select(i => i.Value as string),
ca3.IsNull ? null : ca3.Values.Select(i => i.Value as string));
}
else
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Invalid__CompilerSchemaNamespaceAttribute,
assSymbol.Identity.Name), default(TextSpan));
}
}
}
}
return count;
}
internal static string GetFirstArgumentAsString(AttributeData attData)
{
var ctorArgs = attData.ConstructorArguments;
if (ctorArgs.Length > 0)
{
return ctorArgs[0].Value as string;
}
return null;
}
internal static void MapGlobalTypes(NamespaceInfoMap nsInfoMap, INamespaceSymbol nsSymbol)
{
if (!nsSymbol.IsGlobalNamespace)
{
foreach (var nsInfo in nsInfoMap.Values)
{
if (nsSymbol.FullNameEquals(nsInfo.DottedName.NameParts))
{
var typeSymbolList = nsSymbol.GetMembers().OfType<INamedTypeSymbol>().Where(i => i.TypeKind == Microsoft.CodeAnalysis.TypeKind.Class).ToList();
for (var i = 0; i < typeSymbolList.Count;)
{
var typeSymbol = typeSymbolList[i];
var clsAttData = typeSymbol.GetAttributeData(SchemaClassAttributeNameParts);
if (clsAttData != null)
{
if (typeSymbol.IsGenericType)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.SchemaClassCannotBeGeneric), GetTextSpan(typeSymbol));
}
if (typeSymbol.IsStatic)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.SchemaClassCannotBeStatic), GetTextSpan(typeSymbol));
}
var clsName = GetFirstArgumentAsString(clsAttData);
if (clsName == null)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaClassAttribute), GetTextSpan(clsAttData));
}
var clsInfo = nsInfo.TryGetGlobalType<ClassTypeInfo>(clsName);
if (clsInfo == null)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaClassAttributeName, clsName), GetTextSpan(clsAttData));
}
if (clsInfo.Symbol != null)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.DuplicateSchemaClassAttributeName, clsName), GetTextSpan(clsAttData));
}
if (!clsInfo.IsAbstract)
{
if (typeSymbol.IsAbstract)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.NonAbstractSchemaClassRequired),
GetTextSpan(typeSymbol));
}
if (!typeSymbol.HasParameterlessConstructor())
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.ParameterlessConstructorRequired),
GetTextSpan(typeSymbol));
}
}
clsInfo.Symbol = typeSymbol;
typeSymbolList.RemoveAt(i);
continue;
}
++i;
}
foreach (var typeSymbol in typeSymbolList)
{
if (!typeSymbol.IsGenericType)
{
var clsName = typeSymbol.Name;
var clsInfo = nsInfo.TryGetGlobalType<ClassTypeInfo>(clsName);
if (clsInfo != null)
{
if (clsInfo.Symbol == null)
{
if (typeSymbol.IsStatic)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.SchemaClassCannotBeStatic), GetTextSpan(typeSymbol));
}
if (!clsInfo.IsAbstract)
{
if (typeSymbol.IsAbstract)
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.NonAbstractSchemaClassRequired),
GetTextSpan(typeSymbol));
}
if (!typeSymbol.HasParameterlessConstructor())
{
CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.ParameterlessConstructorRequired),
GetTextSpan(typeSymbol));
}
}
clsInfo.Symbol = typeSymbol;
}
}
}
}
}
}
}
foreach (var subNsSymbol in nsSymbol.GetNamespaceMembers())
{
MapGlobalTypes(nsInfoMap, subNsSymbol);
}
}
#region
internal static TextSpan GetTextSpan(AttributeData attData)
{
if (attData != null)
{
return GetTextSpan(attData.ApplicationSyntaxReference);
}
return default(TextSpan);
}
internal static TextSpan GetTextSpan(SyntaxReference sr)
{
if (sr != null)
{
return GetTextSpan(sr.GetSyntax().GetLocation());
}
return default(TextSpan);
}
internal static TextSpan GetTextSpan(ISymbol symbol)
{
if (symbol != null)
{
var locations = symbol.Locations;
if (locations.Length > 0)
{
return GetTextSpan(locations[0]);
}
}
return default(TextSpan);
}
internal static TextSpan GetTextSpan(Location location)
{
if (location != null && location.IsInSource)
{
var csLineSpan = location.GetLineSpan();
if (csLineSpan.IsValid)
{
var csTextSpan = location.SourceSpan;
return new TextSpan(csLineSpan.Path, csTextSpan.Start, csTextSpan.Length,
ToTextPosition(csLineSpan.StartLinePosition), ToTextPosition(csLineSpan.EndLinePosition));
}
}
return default(TextSpan);
}
private static TextPosition ToTextPosition(this LinePosition csPosition)
{
return new TextPosition(csPosition.Line + 1, csPosition.Character + 1);
}
#endregion
internal static bool IsAtomType(TypeKind typeKind, ITypeSymbol typeSymbol)
{
switch (typeKind)
{
case TypeKind.String:
return typeSymbol.SpecialType == SpecialType.System_String;
case TypeKind.IgnoreCaseString:
return typeSymbol.FullNameEquals(IgnoreCaseStringNameParts);
case TypeKind.Char:
return typeSymbol.SpecialType == SpecialType.System_Char;
case TypeKind.Decimal:
return typeSymbol.SpecialType == SpecialType.System_Decimal;
case TypeKind.Int64:
return typeSymbol.SpecialType == SpecialType.System_Int64;
case TypeKind.Int32:
return typeSymbol.SpecialType == SpecialType.System_Int32;
case TypeKind.Int16:
return typeSymbol.SpecialType == SpecialType.System_Int16;
case TypeKind.SByte:
return typeSymbol.SpecialType == SpecialType.System_SByte;
case TypeKind.UInt64:
return typeSymbol.SpecialType == SpecialType.System_UInt64;
case TypeKind.UInt32:
return typeSymbol.SpecialType == SpecialType.System_UInt32;
case TypeKind.UInt16:
return typeSymbol.SpecialType == SpecialType.System_UInt16;
case TypeKind.Byte:
return typeSymbol.SpecialType == SpecialType.System_Byte;
case TypeKind.Double:
return typeSymbol.SpecialType == SpecialType.System_Double;
case TypeKind.Single:
return typeSymbol.SpecialType == SpecialType.System_Single;
case TypeKind.Boolean:
return typeSymbol.SpecialType == SpecialType.System_Boolean;
case TypeKind.Binary:
return typeSymbol.FullNameEquals(BinaryNameParts);
case TypeKind.Guid:
return typeSymbol.FullNameEquals(CS.GuidNameParts);
case TypeKind.TimeSpan:
return typeSymbol.FullNameEquals(CS.TimeSpanNameParts);
case TypeKind.DateTimeOffset:
return typeSymbol.FullNameEquals(CS.DateTimeOffsetNameParts);
default:
throw new ArgumentException("Invalid type kind: " + typeKind.ToString());
}
}
internal static ExpressionSyntax AtomValueLiteral(TypeKind typeKind, object value)
{
switch (typeKind)
{
case TypeKind.String:
return CS.Literal((string)value);
case TypeKind.IgnoreCaseString:
return Literal((IgnoreCaseString)value);
case TypeKind.Char:
return CS.Literal((char)value);
case TypeKind.Decimal:
return CS.Literal((decimal)value);
case TypeKind.Int64:
return CS.Literal((long)value);
case TypeKind.Int32:
return CS.Literal((int)value);
case TypeKind.Int16:
return CS.Literal((short)value);
case TypeKind.SByte:
return CS.Literal((sbyte)value);
case TypeKind.UInt64:
return CS.Literal((ulong)value);
case TypeKind.UInt32:
return CS.Literal((uint)value);
case TypeKind.UInt16:
return CS.Literal((ushort)value);
case TypeKind.Byte:
return CS.Literal((byte)value);
case TypeKind.Double:
return CS.Literal((double)value);
case TypeKind.Single:
return CS.Literal((float)value);
case TypeKind.Boolean:
return CS.Literal((bool)value);
case TypeKind.Binary:
return Literal((Binary)value);
case TypeKind.Guid:
return CS.Literal((Guid)value); ;
case TypeKind.TimeSpan:
return CS.Literal((TimeSpan)value); ;
case TypeKind.DateTimeOffset:
return CS.Literal((DateTimeOffset)value); ;
default:
throw new ArgumentException("Invalid type kind: " + typeKind.ToString());
}
}
internal static string ToValidId(string s)
{
if (string.IsNullOrEmpty(s))
{
return s;
}
var sb = StringBuilderBuffer.Acquire();
foreach (var ch in s)
{
if (SyntaxFacts.IsIdentifierPartCharacter(ch))
{
sb.Append(ch);
}
else
{
sb.Append('_');
}
}
return sb.ToStringAndRelease();
}
internal static string SDataProgramName(string assName)
{
return "SData_" + ToValidId(assName);
}
internal static AliasQualifiedNameSyntax SDataName
{
get { return CS.GlobalAliasQualifiedName("SData"); }
}
internal static QualifiedNameSyntax __CompilerSchemaNamespaceAttributeName
{
get { return CS.QualifiedName(SDataName, "__CompilerSchemaNamespaceAttribute"); }
}
internal static MemberAccessExpressionSyntax ProgramMdExpr
{
get { return CS.MemberAccessExpr(SDataName, "ProgramMd"); }
}
internal static QualifiedNameSyntax GlobalTypeMdName
{
get { return CS.QualifiedName(SDataName, "GlobalTypeMd"); }
}
internal static ArrayTypeSyntax GlobalTypeMdArrayType
{
get { return CS.OneDimArrayType(GlobalTypeMdName); }
}
internal static QualifiedNameSyntax EnumTypeMdName
{
get { return CS.QualifiedName(SDataName, "EnumTypeMd"); }
}
internal static QualifiedNameSyntax ClassTypeMdName
{
get { return CS.QualifiedName(SDataName, "ClassTypeMd"); }
}
internal static QualifiedNameSyntax PropertyMdName
{
get { return CS.QualifiedName(SDataName, "PropertyMd"); }
}
internal static QualifiedNameSyntax KeyMdName
{
get { return CS.QualifiedName(SDataName, "KeyMd"); }
}
internal static ArrayTypeSyntax KeyMdArrayType
{
get { return CS.OneDimArrayType(KeyMdName); }
}
internal static QualifiedNameSyntax NullableTypeMdName
{
get { return CS.QualifiedName(SDataName, "NullableTypeMd"); }
}
internal static QualifiedNameSyntax GlobalTypeRefMdName
{
get { return CS.QualifiedName(SDataName, "GlobalTypeRefMd"); }
}
internal static QualifiedNameSyntax CollectionTypeMdName
{
get { return CS.QualifiedName(SDataName, "CollectionTypeMd"); }
}
internal static ExpressionSyntax Literal(TypeKind value)
{
return CS.MemberAccessExpr(CS.MemberAccessExpr(SDataName, "TypeKind"), value.ToString());
}
internal static QualifiedNameSyntax FullNameName
{
get { return CS.QualifiedName(SDataName, "FullName"); }
}
internal static ExpressionSyntax Literal(FullName value)
{
return CS.NewObjExpr(FullNameName, CS.Literal(value.Uri), CS.Literal(value.Name));
}
internal static QualifiedNameSyntax IgnoreCaseStringName
{
get { return CS.QualifiedName(SDataName, "IgnoreCaseString"); }
}
internal static ExpressionSyntax Literal(IgnoreCaseString value)
{
return CS.NewObjExpr(IgnoreCaseStringName, CS.Literal(value.Value), CS.Literal(value.IsReadOnly));
}
internal static QualifiedNameSyntax BinaryName
{
get { return CS.QualifiedName(SDataName, "Binary"); }
}
internal static ExpressionSyntax Literal(Binary value)
{
return CS.NewObjExpr(BinaryName, CS.Literal(value.ToBytes()), CS.Literal(value.IsReadOnly));
}
internal static QualifiedNameSyntax LoadingContextName
{
get { return CS.QualifiedName(SDataName, "LoadingContext"); }
}
internal static MemberAccessExpressionSyntax SerializerExpr
{
get { return CS.MemberAccessExpr(SDataName, "Serializer"); }
}
internal static MemberAccessExpressionSyntax ExtensionsExpr
{
get { return CS.MemberAccessExpr(SDataName, "Extensions"); }
}
internal static MemberAccessExpressionSyntax AtomTypeMdExpr
{
get { return CS.MemberAccessExpr(SDataName, "AtomTypeMd"); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inference.Interpreter;
using Inference.Interpreter.LISP;
using Inference.Interpreter.Scheme;
using Inference.Parser;
using NUnit.Framework;
namespace Inference.Tests.Interpreter.Scheme
{
#region InferenceAssert
public static class InferenceAssert
{
public static void ThrowsWithLineAndColumnNumbers<T>(TestDelegate code, int expectedLine, int expectedColumn)
where T : ExceptionWithLineAndColumnNumbers
{
bool thrown = false;
int actualLine = -1;
int actualColumn = -1;
// To catch only exceptions whose types exactly match T, we could catch (Exception ex), and then:
// if (ex.GetType().Equals(typeof(T)) { ... }
// Maybe we could put this in a function called ThrowsExactWithLineAndColumnNumbers<T>()
try
{
code();
}
catch (T ex) // Note that this will also catch exceptions of classes derived from T.
{
thrown = true;
actualLine = ex.Line;
actualColumn = ex.Column;
}
catch
{
}
Assert.IsTrue(thrown);
Assert.AreEqual(expectedLine, actualLine);
Assert.AreEqual(expectedColumn, actualColumn);
}
}
#endregion
[TestFixture]
public class Parser_Fixture
{
private readonly ITokenizer tokenizer;
private readonly IParser parser;
private readonly SchemeGlobalInfo globalInfo;
public Parser_Fixture()
{
tokenizer = TokenizerFactory.Create(GrammarSelector.Scheme);
parser = ParserFactory.Create(ParserSelector.SLR1, GrammarSelector.Scheme);
globalInfo = new SchemeGlobalInfo(tokenizer, parser);
}
[SetUp]
public void SetUp()
{
globalInfo.Clear();
globalInfo.LoadPresets();
}
private object GetParseResult(string input)
{
var parseResult = parser.Parse(tokenizer.Tokenize(input));
Assert.IsNotNull(parseResult);
//Assert.AreEqual(input, parseResult.ToString()); // This fails on multi-line or whitespace-formatted input.
return parseResult;
}
private ISExpression EvaluateToISExpression(string input)
{
var expr = GetParseResult(input) as IExpression<ISExpression>;
Assert.IsNotNull(expr);
var sexpr = expr.Evaluate(globalInfo.GlobalEnvironment, globalInfo);
Assert.IsNotNull(sexpr);
return sexpr;
}
private string Evaluate(string input)
{
return EvaluateToISExpression(input).ToString();
}
[Test]
public void RecognizeTest()
{
parser.Recognize(tokenizer.Tokenize("+"));
parser.Recognize(tokenizer.Tokenize("(lambda (x) (+ x 1))"));
parser.Recognize(tokenizer.Tokenize("(primop? +)"));
parser.Recognize(tokenizer.Tokenize("(closure? (lambda (x) (+ x 1)))"));
}
[Test]
public void PrimOpTest1()
{
var input = "+";
var parseResult = GetParseResult(input);
Assert.IsNotNull(parseResult);
Assert.AreEqual("PrimOp", parseResult.GetType().Name);
var sexpr = EvaluateToISExpression(input);
Assert.IsTrue(sexpr.IsPrimOp());
Assert.IsTrue(sexpr is PrimOp);
var primOp = sexpr as PrimOp;
Assert.AreEqual(input, primOp.OperatorName.Value);
}
[Test]
public void PrimOpTest2()
{
EvaluateToISExpression("(set add +)");
var sexpr = EvaluateToISExpression("(add 2 3)");
Assert.AreEqual("5", sexpr.ToString());
}
[Test]
public void ClosureTest1()
{
var input = "(lambda (x) (+ x 1))";
var sexpr = EvaluateToISExpression(input);
Assert.IsTrue(sexpr.IsClosure());
Assert.IsTrue(sexpr is Closure);
}
[Test]
public void ClosureTest2()
{
EvaluateToISExpression("(set increment (lambda (x) (+ x 1)))");
var sexpr = EvaluateToISExpression("(increment 13)");
Assert.AreEqual("14", sexpr.ToString());
}
[Test]
public void ClosureTest3()
{
EvaluateToISExpression("(set add (lambda (x) (lambda (y) (+ x y))))");
var sexpr = EvaluateToISExpression("((add 8) 13)");
Assert.AreEqual("21", sexpr.ToString());
}
[Test]
public void LetTest()
{
Assert.AreEqual("(12 5)", Evaluate("(let ((m (* 3 4)) (n (+ 2 3))) (list m n))"));
}
[Test]
public void LetStarTest()
{
Assert.AreEqual("25", Evaluate("(let* ((x (+ 2 3)) (y (* x x))) y)"));
}
[Test]
public void LetStarNonRecursiveTest() // 2014/02/17 : Derived from Kamin page 126.
{
// Assert that let* is not a clone of letrec.
Assert.Throws<EvaluationException>(() => Evaluate(@"
(let*
((countones (lambda (l)
(if (null? l) 0
(if (= (car l) 1) (+ 1 (countones (cdr l)))
(countones (cdr l)))))))
(countones '(1 2 3 1 0 1 1 5)))"));
}
[Test]
public void LetRecTest() // From Kamin page 126.
{
Assert.AreEqual("4", Evaluate(@"
(letrec
((countones (lambda (l)
(if (null? l) 0
(if (= (car l) 1) (+ 1 (countones (cdr l)))
(countones (cdr l)))))))
(countones '(1 2 3 1 0 1 1 5)))"));
}
[Test]
public void CondTest()
{
Evaluate("(set condtest (lambda (n) (cond ((= n 1) 'First) ((= n 2) 'Second) ((= n 3) 'Third) ('T 'Other))))");
Assert.AreEqual("Other", Evaluate("(condtest 0)"));
Assert.AreEqual("First", Evaluate("(condtest 1)"));
Assert.AreEqual("Second", Evaluate("(condtest 2)"));
Assert.AreEqual("Third", Evaluate("(condtest 3)"));
Assert.AreEqual("Other", Evaluate("(condtest 4)"));
}
[Test]
public void CallCCTest() // From Kamin page 128.
{
Evaluate(@"
(set gcd* (lambda (l)
(call/cc (lambda (exit)
(letrec ((gcd*-aux (lambda (l)
(if (= (car l) 1) (exit 1)
(if (null? (cdr l)) (car l)
(gcd (car l) (gcd*-aux (cdr l))))))))
(gcd*-aux l))))))");
Assert.AreEqual("3", Evaluate("(gcd* '(9 27 81 60))"));
Assert.AreEqual("1", Evaluate("(gcd* '(101 202 103))"));
Assert.AreEqual("1", Evaluate("(gcd* '(9 27 1 81 60))"));
Assert.AreEqual("1", Evaluate("(gcd* '(9 27 81 60 1 NotANumber))"));
}
[Test]
public void ListTest()
{
Assert.AreEqual("()", Evaluate("(list)"));
Assert.AreEqual("(1)", Evaluate("(list 1)"));
Assert.AreEqual("(1 2 3)", Evaluate("(list 1 2 3)"));
Assert.AreEqual("(1 + T)", Evaluate("(list 1 + 'T)"));
}
[Test]
public void StaticScopeTest() // See page 135 of Kamin, or pages 128-137 for more context about static vs. dynamic scope.
{
Evaluate("(set add (lambda (x) (lambda (y) (+ x y))))");
Evaluate("(set add1 (add 1))");
Evaluate("(set f (lambda (x) (add1 x)))");
Assert.AreEqual("6", Evaluate("(f 5)")); // Assert that our Scheme uses static scope, as Scheme should.
}
[Test]
public void GlobalVsLocalVariableTest()
{
Evaluate("(set a 1)");
Evaluate("(set afunc (lambda () a))");
Evaluate("(set func2 (lambda (a) (afunc)))");
Assert.AreEqual("1", Evaluate("(func2 0)"));
}
[Test]
public void PrimOpAndClosurePredTest()
{
Evaluate("(set add +)");
Evaluate("(set add1 (lambda (x) (+ x 1)))");
Assert.AreEqual("T", Evaluate("(primop? +)"));
Assert.AreEqual("T", Evaluate("(primop? add)"));
Assert.AreEqual("()", Evaluate("(primop? add1)"));
Assert.AreEqual("()", Evaluate("(closure? +)"));
Assert.AreEqual("()", Evaluate("(closure? add)"));
Assert.AreEqual("T", Evaluate("(closure? add1)"));
Assert.AreEqual("T", Evaluate("(primop? list)"));
// Just for fun:
Assert.AreEqual("T", Evaluate("(primop? primop?)"));
Assert.AreEqual("T", Evaluate("(primop? closure?)"));
Assert.AreEqual("()", Evaluate("(closure? primop?)"));
Assert.AreEqual("()", Evaluate("(closure? closure?)"));
}
[Test]
public void StreamsTest() // See Kamin pages 176-178 : "SASL vs. Scheme"
{
// This Scheme code uses zero-argument closures to mimic SASL thunks.
// If s is a stream, (car s) is a number, and ((cadr s)) is a stream.
Evaluate(@"
(set add-streams (lambda (s1 s2)
(list (+ (car s1) (car s2)) (lambda () (add-streams ((cadr s1)) ((cadr s2)))))
))");
Evaluate(@"
(set stream-first-n (lambda (n s)
(if (= n 0) '()
(cons (car s) (stream-first-n (- n 1) ((cadr s)))))
))");
Evaluate("(set powers-of-2 (list 1 (lambda () (add-streams powers-of-2 powers-of-2))))");
Evaluate("(set fibonacci (list 0 (lambda () (list 1 (lambda () (add-streams fibonacci ((cadr fibonacci))))))))");
Assert.AreEqual("(1 2 4 8 16)", Evaluate("(stream-first-n 5 powers-of-2)"));
Assert.AreEqual("(0 1 1 2 3 5 8 13)", Evaluate("(stream-first-n 8 fibonacci)"));
}
[Test]
public void RplacaRplacdTest() // See page 55
{
Evaluate("(set x '(a b c))");
Evaluate("(set y x)");
Evaluate("(rplaca y 'd)");
Assert.AreEqual("(d b c)", Evaluate("y"));
Assert.AreEqual("(d b c)", Evaluate("x"));
Evaluate("(rplacd y 'e)");
Assert.AreEqual("(d . e)", Evaluate("y"));
Assert.AreEqual("(d . e)", Evaluate("x"));
}
[Test]
public void MacroTest() // From pages 56-57, and Exercise 12, from pages 62-63 (in the LISP chapter)
{
Evaluate("(set <= (lambda (x y) (or (< x y) (= x y))))");
Evaluate(@"
(define-macro for (indexvar lower upper body)
(list 'begin
(list 'set indexvar lower)
(list 'while
(list '<= indexvar upper)
(list 'begin body
(list 'set indexvar (list '+ indexvar 1))))))");
Evaluate("(set sum 0)");
Evaluate("(for x 1 10 (set sum (+ sum x)))");
Assert.AreEqual("55", Evaluate("sum"));
}
[Test]
public void RandomTest()
{
const int maxValue = 100;
var x = int.Parse(Evaluate(string.Format("(random {0})", maxValue)));
Assert.IsTrue(x >= 0);
Assert.IsTrue(x < maxValue);
}
[Test]
public void SetsTest() // See pages 104-105
{
globalInfo.LoadPreset("set");
Assert.AreEqual("(a b)", Evaluate("(set s1 (addelt 'a (addelt 'b nullset)))"));
Assert.AreEqual("T", Evaluate("(member? 'a s1)"));
Assert.AreEqual("()", Evaluate("(member? 'c s1)"));
Assert.AreEqual("(b c)", Evaluate("(set s2 (addelt 'b (addelt 'c nullset)))"));
Assert.AreEqual("(c a b)", Evaluate("(set s3 (union s1 s2))"));
}
private void DefineTermRewritingSystem() // See section 4.4 on pages 116-122
{
globalInfo.LoadPreset("set"); // For "member?"
//globalInfo.LoadPreset("compose");
// Functions from Figure 4.2 (on page 120)
Evaluate("(set fun-mod (lambda (f x y) (lambda (z) (if (= x z) y (f z)))))");
Evaluate("(set variable? (lambda (x) (member? x '(X Y))))");
Evaluate("(set empty-subst (lambda (x) 'unbound))");
Evaluate(@"
(set mk-subst-fun
(lambda (lhs e sigma)
(if (variable? lhs)
(if (= (sigma lhs) 'unbound)
(fun-mod sigma lhs e)
(if (equal (sigma lhs) e) sigma 'nomatch))
(if (atom? lhs)
(if (= lhs e) sigma 'nomatch)
(if (atom? e) 'nomatch
(if (= (car lhs) (car e))
(mk-subst-fun* (cdr lhs) (cdr e) sigma)
'nomatch))))))");
Evaluate(@"
(set mk-subst-fun*
(lambda (lhs-lis exp-lis sigma)
(if (null? lhs-lis) sigma
(begin
(set car-match
(mk-subst-fun (car lhs-lis) (car exp-lis) sigma))
(if (= car-match 'nomatch) 'nomatch
(mk-subst-fun* (cdr lhs-lis) (cdr exp-lis) car-match))))))");
Evaluate(@"
(set extend-to-pat
(lambda (sigma)
(lambda (p)
(if (variable? p) (if (= (sigma p) 'unbound) p (sigma p))
(if (atom? p) p
(cons (car p)
(mapcar (extend-to-pat sigma) (cdr p))))))))");
// Function from Figure 4.3 (on page 121)
Evaluate(@"
(set mk-toplvl-rw-fn
(lambda (rule)
(lambda (e)
(begin
(set induced-subst (mk-subst-fun (car rule) e empty-subst))
(if (= induced-subst 'nomatch) '()
((extend-to-pat induced-subst) (cadr rule)))))))");
// Functions from Figure 4.4 (on page 122)
Evaluate(@"
(set apply-inside-exp
(lambda (f)
(lambda (e)
(begin
(set newe (f e))
(if newe newe
(if (atom? e) '()
(begin
(set newargs ((apply-inside-exp* f) (cdr e)))
(if newargs (cons (car e) newargs) '()))))))))");
Evaluate(@"
(set apply-inside-exp*
(lambda (f)
(lambda (l)
(if (null? l) '()
(begin
(set newfirstarg ((apply-inside-exp f) (car l)))
(if newfirstarg
(cons newfirstarg (cdr l))
(begin
(set newrestofargs ((apply-inside-exp* f) (cdr l)))
(if newrestofargs
(cons (car l) newrestofargs) '()))))))))");
Evaluate("(set mk-rw-fn (compose mk-toplvl-rw-fn apply-inside-exp))");
// Functions from Figure 4.4 (on page 122)
Evaluate("(set failure (lambda (e) '()))");
Evaluate(@"
(set compose-rewrites (lambda (f g)
(lambda (x)
((lambda (fx) (if fx fx (g x))) (f x)))))");
Evaluate("(set mk-rw-fn* (combine mk-rw-fn compose-rewrites failure))");
Evaluate(@"
(set repeat-fn
(lambda (f)
(lambda (e)
(begin
(set tmp (f e))
(if tmp ((repeat-fn f) tmp) e)))))");
Evaluate("(set compile-trs (compose mk-rw-fn* repeat-fn))");
// Differentiation: from page 116
Evaluate(@"
(set diff-rules '(
((Dx x) 1)
((Dx c) 0)
((Dx (+ X Y)) (+ (Dx X) (Dx Y)))
((Dx (- X Y)) (- (Dx X) (Dx Y)))
((Dx (* X Y)) (+ (* Y (Dx X)) (* X (Dx Y))))
((Dx (/ X Y)) (/ (- (* Y (Dx X)) (* X (Dx Y))) (* Y Y)))))");
Evaluate("(set differentiate (compile-trs diff-rules))");
}
[Test]
public void TermRewritingSystemsTest() // See section 4.4 on pages 116-122
{
DefineTermRewritingSystem();
Assert.AreEqual("(+ 1 0)", Evaluate("(differentiate '(Dx (+ x c)))"));
}
[Test]
public void Exercise1Test() // Exercise 1 on pages 148-149.
{
// Exercise 1a) : cdr*
Evaluate("(set cdr* (mapc cdr))");
Assert.AreEqual("((b c) (e) ())", Evaluate("(cdr* '((a b c) (d e) (f)))"));
// Exercise 1b) : max*
Evaluate("(set max (lambda (x y) (if (> x y) x y)))");
Evaluate("(set max* (combine id max 0))");
Assert.AreEqual("10", Evaluate("(max* '(1 5 10 3 7 2 8))"));
// Exercise 1c) : append (although we will call it append2 here)
Evaluate("(set append2 (lambda (l1 l2) ((combine id cons l2) l1)))");
Assert.AreEqual("(a b c d e f g)", Evaluate("(append2 '(a b c) '(d e f g))"));
// Exercise 1d) : addtoend
Evaluate("(set addtoend (lambda (x l) ((combine id cons (list x)) l)))");
Assert.AreEqual("(b c d a)", Evaluate("(addtoend 'a '(b c d))"));
// Exercise 1e) : reverse (although we will call it reverse2 here)
Evaluate("(set reverse2 (combine id addtoend '()))");
Assert.AreEqual("(g f e d c b a)", Evaluate("(reverse2 '(a b c d e f g))"));
// Exercise 1f) : insertion-sort
Evaluate(@"
(set insert (lambda (x l)
(cond
((null? l) (list x))
((<= x (car l)) (cons x l))
('T (cons (car l) (insert x (cdr l)))))))");
Evaluate("(set insertion-sort (combine id insert '()))");
Assert.AreEqual("(1 2 3 4 5 6 7)", Evaluate("(insertion-sort '(3 7 4 1 2 6 5))"));
// Exercise 1g) : mkpairsfn
Evaluate("(set mkpairsfn (lambda (x) (mapc (lambda (l) (cons x l)))))");
Assert.AreEqual("((a) (a b c) (a d) (a (e f)))",
Evaluate("((mkpairsfn 'a) '(() (b c) (d) ((e f))))"));
}
[Test]
public void Exercise2Test() // Exercise 2 on page 149 : lex-order*
{
Evaluate(@"
(set lex-order* (lambda (cmp)
(lambda (l1 l2)
(cond
((null? l1) (not (null? l2)))
((null? l2) '())
((cmp (car l1) (car l2)) 'T)
((cmp (car l2) (car l1)) '())
('T ((lex-order* cmp) (cdr l1) (cdr l2)))))))");
Evaluate("(set alpha-order (lex-order* <))");
Assert.AreEqual("T", Evaluate("(alpha-order '(4 15 7) '(4 15 7 5))"));
Assert.AreEqual("()", Evaluate("(alpha-order '(4 15 7) '(4 15 6 6))"));
}
[Test]
public void Exercise3Test() // Exercise 3 on page 149 : Sets implemented using characteristic functions
{
Evaluate("(set nullset (lambda (x) '()))");
Evaluate("(set member? (lambda (x s) (s x)))");
// mk-set-ops : See pages 106-107
Evaluate(@"
(set mk-set-ops (lambda (eqfun)
(cons (lambda (x s) (if (member? x s) s (lambda (y) (or (eqfun x y) (member? y s))))) ; addelt
'())))");
Evaluate("(set addelt (car (mk-set-ops =)))");
Evaluate(@"
(set union (lambda (s1 s2)
(lambda (x) (or (member? x s1) (member? x s2)))))");
Evaluate(@"
(set inter (lambda (s1 s2)
(lambda (x) (and (member? x s1) (member? x s2)))))");
Evaluate(@"
(set diff (lambda (s1 s2)
(lambda (x) (and (member? x s1) (not (member? x s2))))))");
Evaluate("(set s1 (addelt 'a (addelt 'b nullset)))");
Assert.AreEqual("T", Evaluate("(member? 'a s1)"));
Assert.AreEqual("T", Evaluate("(member? 'b s1)"));
Assert.AreEqual("()", Evaluate("(member? 'c s1)"));
Evaluate("(set s2 (addelt 'b (addelt 'c nullset)))");
Evaluate("(set s3 (union s1 s2))");
Assert.AreEqual("T", Evaluate("(member? 'a s3)"));
Assert.AreEqual("T", Evaluate("(member? 'b s3)"));
Assert.AreEqual("T", Evaluate("(member? 'c s3)"));
Assert.AreEqual("()", Evaluate("(member? 'd s3)"));
Evaluate("(set s4 (inter s1 s2))");
Assert.AreEqual("()", Evaluate("(member? 'a s4)"));
Assert.AreEqual("T", Evaluate("(member? 'b s4)"));
Assert.AreEqual("()", Evaluate("(member? 'c s4)"));
Evaluate("(set s5 (diff s1 s2))");
Assert.AreEqual("T", Evaluate("(member? 'a s5)"));
Assert.AreEqual("()", Evaluate("(member? 'b s5)"));
Assert.AreEqual("()", Evaluate("(member? 'c s5)"));
}
[Test]
public void Exercise4Test() // Exercise 4 on page 149 : Optimizing gcd* and gcds (from pages 108-109)
{
// Part 1
Evaluate("(set gcd* (lambda (l) (gcd*-aux l id)))");
Evaluate(@"
(set gcd*-aux (lambda (l f)
(if (= (car l) 1) 1
(if (null? (cdr l)) (f (car l))
(gcd*-aux (cdr l)
(lambda (n)
(let ((gcd-value (gcd (car l) n)))
(if (= gcd-value 1) 1 (f gcd-value)))))))))");
Assert.AreEqual("7", Evaluate("(gcd* '(14 49 98))"));
Assert.AreEqual("1", Evaluate("(gcd* '(3 5 7 9 11))"));
Assert.AreEqual("1", Evaluate("(gcd* '(NotANumber 3 5))")); // The gcd is calculated from the arguments from right to left.
// Part 2
Evaluate("(set gcds (lambda (s) (gcds-aux s id)))");
Evaluate(@"
(set gcds-aux (lambda (s f)
(if (number? s) (if (= s 1) 1 (f s))
(if (null? (cdr s))
(gcds-aux (car s) f)
(gcds-aux (car s)
(lambda (n) (gcds-aux (cdr s)
(lambda (p)
(let ((gcd-value (gcd n p)))
(if (= gcd-value 1) 1 (f (gcd n p))))))))))))");
Assert.AreEqual("7", Evaluate("(gcds '((14 (49 98)) 56 ((84 105 21) 91 77)))"));
Assert.AreEqual("1", Evaluate("(gcds '((3 5) 7 (9 11)))"));
//Assert.AreEqual("1", Evaluate("(gcds '((NotANumber 3) 5))")); // gcds only accepts S-expressions of numbers and pairs (lists), not symbols.
}
[Test]
public void Exercise5aTest() // Exercise 5a on pages 150-151; TermRewritingSystems
{
DefineTermRewritingSystem();
// Old code; from the text.
//Evaluate("(set mk-rw-fn* (combine mk-rw-fn compose-rewrites failure))");
// New code.
Evaluate("(set mk-toplvl-rw-fn* (combine mk-toplvl-rw-fn compose-rewrites failure))"); // Apply any of the rules at the top level of an expression.
Evaluate("(set mk-rw-fn* (compose mk-toplvl-rw-fn* apply-inside-exp))"); // Extend the above to operate inside expressions.
Assert.AreEqual("(+ 1 0)", Evaluate("(differentiate '(Dx (+ x c)))"));
}
[Test]
public void Exercise5bTest() // Exercise 5b on pages 150-151; TermRewritingSystems; modifications to apply-inside-exp
{
DefineTermRewritingSystem();
// The next two functions are new or rewritten.
Evaluate(@"
(set apply-func
(lambda (f)
(lambda (x)
(let ((result ((apply-inside-exp f) x)))
(if result result x)))))");
Evaluate(@"
(set apply-inside-exp*
(lambda (f)
(lambda (l)
(let ((result (mapcar (apply-func f) l)))
(if (equal result l) '() result)))))");
Assert.AreEqual("(+ 1 0)", Evaluate("(differentiate '(Dx (+ x c)))"));
}
[Test]
public void LetMacroTest() // Part of exercise 15 on page 152.
{
Evaluate("(set list-of-cars (lambda (l) (mapcar car l)))");
Evaluate("(set list-of-cadrs (lambda (l) (mapcar cadr l)))");
Evaluate(@"
(define-macro letm (declarations body)
(cons
(list 'lambda (list-of-cars declarations) body)
(list-of-cadrs declarations)))");
Assert.AreEqual("(12 5)", Evaluate("(letm ((m (* 3 4)) (n (+ 2 3))) (list m n))"));
}
[Test]
public void LetStarMacroTest() // Part of exercise 15 on page 152.
{
Evaluate(@"
(set build-expr
(lambda (declarations body)
(if (null? declarations) body
(list
(list 'lambda
(list (car (car declarations)))
(build-expr (cdr declarations) body))
(cadr (car declarations))))))");
Evaluate("(define-macro let*m (declarations body) (build-expr declarations body))");
Assert.AreEqual("25", Evaluate("(let*m ((x (+ 2 3)) (y (* x x))) y)"));
}
[Test]
public void LetRecMacroTest() // Part of exercise 15 on page 152.
{
Evaluate(@"
(set build-let-declaration
(lambda (declaration)
(list (car declaration) 0)))");
Evaluate(@"
(set build-set-statement
(lambda (declaration)
(cons 'set declaration)))");
Evaluate(@"
(define-macro letrecm (declarations body)
(list 'let (mapcar build-let-declaration declarations)
(cons 'begin
(append
(mapcar build-set-statement declarations)
(list body)))))");
/*
Assert.AreEqual("4", Evaluate(@"
(letrecm
((countones (lambda (l)
(if (null? l) 0
(if (= (car l) 1) (+ 1 (countones (cdr l)))
(countones (cdr l)))))))
(countones (quote (1 2 3 1 0 1 1 5))))"));
*/
Assert.AreEqual("4", Evaluate(@"
(letrecm
((countones (lambda (l)
(if (null? l) 0
(if (= (car l) 1) (+ 1 (countones (cdr l)))
(countones (cdr l)))))))
(countones '(1 2 3 1 0 1 1 5)))"));
}
[Test]
public void EvalInSchemeTest() // From section 4.5, on pages 123-124. Also part of exercise 17 on page 152.
{
globalInfo.LoadPreset("assoc");
globalInfo.LoadPreset("select");
Evaluate("(set caddr (lambda (l) (cadr (cdr l))))");
Evaluate("(set cadddr (lambda (l) (caddr (cdr l))))");
// Functions adapted from page 48
Evaluate(@"
(set apply-binary-op (lambda (f x y)
(cond
((= f 'cons) (cons x y))
((= f '+) (+ x y))
((= f '-) (- x y))
((= f '*) (* x y))
((= f '/) (/ x y))
((= f '<) (< x y))
((= f '>) (> x y))
((= f '=) (= x y))
('T 'binary-op-error!))))");
Evaluate(@"
(set apply-unary-op (lambda (f x)
(cond
((= f 'car) (car x))
((= f 'cdr) (cdr x))
((= f 'number?) (number? x))
((= f 'list?) (list? x))
((= f 'symbol?) (symbol? x))
((= f 'null?) (null? x))
((= f 'closure?) (is-closure? x))
((= f 'primop?) (is-primop? x))
('T 'unary-op-error!)
; ('T f)
)))");
// From page 123
Evaluate("(set formals (lambda (lamexp) (cadr lamexp)))");
Evaluate("(set body (lambda (lamexp) (caddr lamexp)))");
Evaluate("(set funpart (lambda (clo) (cadr clo)))");
Evaluate("(set envpart (lambda (clo) (caddr clo)))");
// begin
Evaluate(@"
(set do-begin (lambda (expr-list rho)
(if (null? (cdr expr-list))
(eval (car expr-list) rho)
(begin
(eval (car expr-list) rho)
(do-begin (cdr expr-list) rho)))))");
// let
Evaluate("(set construct-let-var-list (mapc car))");
Evaluate("(set construct-let-expr-list (mapc cadr))");
Evaluate(@"
(set do-let (lambda (var-expr-list expr rho)
(eval
(cons
(list 'lambda (construct-let-var-list var-expr-list) expr)
(construct-let-expr-list var-expr-list))
rho)))");
// let*
Evaluate(@"
(set construct-let* (lambda (var-expr-list expr)
(if (null? var-expr-list) expr
(list
(list
'lambda
(list (caar var-expr-list))
(construct-let* (cdr var-expr-list) expr))
(cadar var-expr-list)))))");
Evaluate(@"
(set do-let* (lambda (var-expr-list expr rho)
(eval (construct-let* var-expr-list expr) rho)))");
// letrec
Evaluate(@"
(set construct-letrec-let-body (lambda (var-expr-list)
(if (null? var-expr-list) '()
(cons
(list (caar var-expr-list) 0)
(construct-letrec-let-body (cdr var-expr-list))))))");
Evaluate(@"
(set construct-letrec-begin-body (lambda (var-expr-list expr)
(if (null? var-expr-list) (list expr)
(cons
(cons 'set (car var-expr-list))
(construct-letrec-begin-body (cdr var-expr-list) expr)))))");
Evaluate(@"
(set construct-letrec (lambda (var-expr-list expr)
(list 'let (construct-letrec-let-body var-expr-list)
(cons 'begin (construct-letrec-begin-body var-expr-list expr)))))");
Evaluate(@"
(set do-letrec (lambda (var-expr-list expr rho)
(eval (construct-letrec var-expr-list expr) rho)))");
// cond
Evaluate(@"
(set do-cond (lambda (expr-pair-list rho)
(if (null? expr-pair-list) '()
(if (eval (caar expr-pair-list) rho)
(eval (cadar expr-pair-list) rho)
(do-cond (cdr expr-pair-list) rho)))))");
// Functions from Figure 4.6 on page 124
Evaluate(@"
(set eval (lambda (expr env)
(cond
((number? expr) expr)
((symbol? expr)
(if (assoc-contains-key expr env)
(assoc expr env)
(assoc expr global-environment)))
((= (car expr) 'quote) (cadr expr))
((= (car expr) 'if)
(if (null? (eval (cadr expr) env))
(eval (cadddr expr) env)
(eval (caddr expr) env)))
((= (car expr) 'begin) (do-begin (cdr expr) env)) ; Exercise 6a) on page 61
((= (car expr) 'print) ; Exercise 6a) on page 61
(print (eval (cadr expr) env)))
((= (car expr) 'set)
(let ((evaluated-expression (eval (caddr expr) env)))
(if (assoc-contains-key (cadr expr) env)
(begin
(rplac-assoc (cadr expr) evaluated-expression env)
evaluated-expression)
(begin
(set global-environment (mkassoc (cadr expr) evaluated-expression global-environment))
evaluated-expression))))
((= (car expr) 'let) (do-let (cadr expr) (caddr expr) env))
((= (car expr) 'let*) (do-let* (cadr expr) (caddr expr) env))
((= (car expr) 'letrec) (do-letrec (cadr expr) (caddr expr) env))
((= (car expr) 'cond) (do-cond (cdr expr) env))
((= (car expr) 'lambda) (list 'closure expr env))
((= (car expr) 'list) (evallist (cdr expr) env))
('T (apply (evallist expr env) env))
)))");
Evaluate(@"
(set evallist (lambda (el rho)
(if (null? el) '()
(cons
(eval (car el) rho)
(evallist (cdr el) rho)))))");
Evaluate(@"
(set mkassoc* (lambda (keys values al)
(if (null? keys) al
(mkassoc* (cdr keys) (cdr values)
(mkassoc (car keys) (car values) al)))))");
Evaluate(@"
(set apply (lambda (el env)
(if (is-closure? (car el))
(apply-closure (car el) (cdr el))
(apply-value-op (car el) (cdr el)))))");
Evaluate(@"
(set apply-closure (lambda (clo args)
(eval (body (funpart clo))
(mkassoc* (formals (funpart clo)) args (envpart clo)))))");
Evaluate(@"
(set apply-value-op (lambda (primop args)
(if (= (length args) 1)
(apply-unary-op (cadr primop) (car args))
(apply-binary-op (cadr primop) (car args) (cadr args)))))");
Evaluate("(set is-closure? (lambda (f) (= (car f) 'closure)))");
Evaluate("(set is-primop? (lambda (f) (= (car f) 'primop)))");
Evaluate(@"
(set valueops '(
(+ (primop +))
(- (primop -))
(cons (primop cons))
(* (primop *))
(/ (primop /))
(< (primop <))
(> (primop >))
(= (primop =))
(cdr (primop cdr))
(car (primop car))
(number? (primop number?))
(list? (primop list?))
(symbol? (primop symbol?))
(null? (primop null?))
(closure? (primop closure?))
(primop? (primop primop?))))");
// Functions adapted from Figure 2.8
Evaluate(@"
(set r-e-p-loop (lambda (inputs)
(begin
(set global-environment '())
(r-e-p-loop* inputs))))");
Evaluate(@"
(set r-e-p-loop* (lambda (inputs)
(if (null? inputs) '()
(process-expr (car inputs) (cdr inputs)))))");
Evaluate(@"
(set process-expr (lambda (e inputs)
(cons (eval e valueops) ; print value of expression
(r-e-p-loop* inputs))))");
Assert.AreEqual("5", Evaluate("(eval '(+ 2 3) valueops)"));
// Test from page 123
Evaluate("(set E (mkassoc 'double (eval '(lambda (a) (+ a a)) valueops) valueops))");
Assert.AreEqual("8", Evaluate("(eval '(double 4) E)"));
// select test
Assert.AreEqual("(12 16 18)", Evaluate("(select '(1 3 4) '(10 12 14 16 18 20))"));
// Test of "set" to ensure that we have completed the exercise.
Assert.AreEqual("(8 () T)", Evaluate(@"
(select '(1 2 3) (r-e-p-loop '( ; We use 'select' because we don't want to test the value of the closure 'double'.
(set double (lambda (a) (+ a a)))
(double 4)
(primop? double)
(closure? double)
)))"));
// letrec test: from Kamin page 126.
/*
Assert.AreEqual("(4)", Evaluate(@"
(r-e-p-loop '(
(letrec ; Try a letrec wth two bindings
(
(countzeroes (lambda (l)
(if (null? l) 0
(if (= (car l) 0) (+ 1 (countzeroes (cdr l)))
(countzeroes (cdr l))))))
(countones (lambda (l)
(if (null? l) 0
(if (= (car l) 1) (+ 1 (countones (cdr l)))
(countones (cdr l))))))
)
(countones (quote (1 2 3 1 0 1 1 5))))
))"));
*/
Assert.AreEqual("(4)", Evaluate(@"
(r-e-p-loop (list
(list 'letrec ; Try a letrec wth two bindings
'(
(countzeroes (lambda (l)
(if (null? l) 0
(if (= (car l) 0) (+ 1 (countzeroes (cdr l)))
(countzeroes (cdr l))))))
(countones (lambda (l)
(if (null? l) 0
(if (= (car l) 1) (+ 1 (countones (cdr l)))
(countones (cdr l))))))
)
(list 'countones (list 'quote '(1 2 3 1 0 1 1 5))))
))"));
// Test of letrec (see exercise 6 on page 150)
#if DEAD_CODE
Assert.AreEqual("(15 120 54)", Evaluate(@"
(select '(1 2 3) (r-e-p-loop '(
(set eval-ex6 (lambda (e)
(letrec
((combine (lambda (f sum zero) (lambda (l) (if (null? l) zero (sum (f (car l)) ((combine f sum zero) (cdr l)))))))
(id (lambda (x) x))
(+/ (combine id + 0))
(*/ (combine id * 1))
(ev (lambda (expr)
(if (number? expr) expr
(if (= (car expr) (quote +))
(+/ (evlis (cdr expr)))
(*/ (evlis (cdr expr)))))))
(mapcar (lambda (f l) (if (null? l) l (cons (f (car l)) (mapcar f (cdr l))))))
(curry (lambda (f) (lambda (x) (lambda (y) (f x y)))))
(mapc (curry mapcar))
(evlis (mapc ev))
)
(ev e))))
(eval-ex6 (quote (+ 1 2 3 4 5)))
(eval-ex6 (quote (* 1 2 3 4 5)))
(eval-ex6 (quote (* (+ 1 2 3) (+ 4 5))))
)))"));
#else
Assert.AreEqual("(15 120 54)", Evaluate(@"
(select '(1 2 3) (r-e-p-loop (list
(list 'set 'eval-ex6 (list 'lambda '(e)
(list 'letrec
(list
'(combine (lambda (f sum zero) (lambda (l) (if (null? l) zero (sum (f (car l)) ((combine f sum zero) (cdr l)))))))
'(id (lambda (x) x))
'(+/ (combine id + 0))
'(*/ (combine id * 1))
(list 'ev (list 'lambda '(expr)
(list 'if '(number? expr) 'expr
(list 'if (list '= '(car expr) (list 'quote '+))
'(+/ (evlis (cdr expr)))
'(*/ (evlis (cdr expr)))))))
'(mapcar (lambda (f l) (if (null? l) l (cons (f (car l)) (mapcar f (cdr l))))))
'(curry (lambda (f) (lambda (x) (lambda (y) (f x y)))))
'(mapc (curry mapcar))
'(evlis (mapc ev))
)
'(ev e))))
(list 'eval-ex6 (list 'quote '(+ 1 2 3 4 5)))
(list 'eval-ex6 (list 'quote '(* 1 2 3 4 5)))
(list 'eval-ex6 (list 'quote '(* (+ 1 2 3) (+ 4 5))))
)))"));
#endif
// Note: If you get an error saying that car's argument is null, it is probably because you forgot to declare something
// (e.g. a function like id or mapc).
// "list" tests.
Assert.AreEqual("((2 3 5 7) (1 2 3 5))", Evaluate(@"
(r-e-p-loop '(
(list 2 3 5 7)
(list (+ 0 1) (+ 1 1) (+ 1 2) (+ 2 3))
))"));
// Test of the "set" implementation that uses rplac-assoc.
Assert.AreEqual("(14)", Evaluate(@"
(select '(1) (r-e-p-loop '(
(set f (lambda (n)
(let ((g (lambda ()
(begin
(set n (+ n 1))
0))))
(begin
(g)
n))))
(f 13)
)))"));
// Test of the "let" implementation that uses lambda.
Assert.AreEqual("(60)", Evaluate(@"
(r-e-p-loop '(
(let ((a 2) (b 3) (c 5) (d (+ 3 4)))
(* (+ a b) (+ c d)))
))"));
// Test of the "let*" implementation that uses nested lambda expressions.
Assert.AreEqual("(24)", Evaluate(@"
(r-e-p-loop '(
(let* ((a 1) (b (* a 2)) (c (* b 3)) (d (* c 4)))
d)
))"));
}
[Test]
public void APLEvalTest()
{
globalInfo.LoadPreset("assoc");
globalInfo.LoadPreset("select");
globalInfo.LoadPreset("flatten");
//globalInfo.LoadPreset("compose");
Evaluate("(set cddr (compose cdr cdr))");
Evaluate("(set caddr (compose cdr cadr))");
Evaluate("(set cadddr (compose cdr caddr))");
Evaluate(@"
(set get-type (lambda (x)
(cond
((number? x) 'scalar)
((null? x) 'vector)
((number? (car x)) 'vector)
('T 'matrix))))");
Evaluate("(set s1 7)");
Evaluate("(set v1 '(2 3 5 7))");
Evaluate("(set m1 '((3 4) 1 2 3 4 5 6 7 8 9 10 11 12))");
Assert.AreEqual("scalar", Evaluate("(get-type s1)"));
Assert.AreEqual("vector", Evaluate("(get-type '())"));
Assert.AreEqual("vector", Evaluate("(get-type v1)"));
Assert.AreEqual("matrix", Evaluate("(get-type m1)"));
Evaluate(@"
(set shape (lambda (x)
(let ((type (get-type x)))
(cond
((= type 'scalar) '())
((= type 'vector) (list (length x)))
('T (car x))))))");
Assert.AreEqual("()", Evaluate("(shape s1)"));
Assert.AreEqual("(4)", Evaluate("(shape v1)"));
Assert.AreEqual("(3 4)", Evaluate("(shape m1)"));
Evaluate(@"
(set to-vector (lambda (x)
(let ((type (get-type x)))
(cond
((= type 'scalar) (list x))
((= type 'vector) x)
('T (cdr x))))))");
Assert.AreEqual("(7)", Evaluate("(to-vector s1)"));
Assert.AreEqual("(2 3 5 7)", Evaluate("(to-vector v1)"));
Assert.AreEqual("(1 2 3 4 5 6 7 8 9 10 11 12)", Evaluate("(to-vector m1)"));
Evaluate(@"
(set get-first-scalar (lambda (x)
(let ((type (get-type x)))
(cond
((= type 'scalar) x)
((= type 'vector) (car x))
('T (cadr x))))))");
Assert.AreEqual("7", Evaluate("(get-first-scalar 7)"));
Assert.AreEqual("13", Evaluate("(get-first-scalar '(13 14 15))"));
Assert.AreEqual("9", Evaluate("(get-first-scalar '((2 2) 9 3 5 7))"));
Evaluate("(set +/ (combine id + 0))");
Evaluate("(set -/ (combine id - 0))");
Evaluate("(set */ (combine id * 1))");
Evaluate("(set // (combine id / 1))");
Evaluate("(set to-scalar-if-possible (lambda (x) (if (= (*/ (shape x)) 1) (get-first-scalar x) x)))");
Assert.AreEqual("13", Evaluate("(to-scalar-if-possible 13)"));
Assert.AreEqual("7", Evaluate("(to-scalar-if-possible '(7))"));
Assert.AreEqual("(8 9)", Evaluate("(to-scalar-if-possible '(8 9))"));
Assert.AreEqual("20", Evaluate("(to-scalar-if-possible '((1 1) 20))"));
Assert.AreEqual("((2 2) 1 0 0 1)", Evaluate("(to-scalar-if-possible '((2 2) 1 0 0 1))"));
Evaluate(@"
(set get-matrix-rows (lambda (m)
(letrec ((get-matrix-rows* (lambda (r c l)
(if (= r 0) '()
(cons (take c l) (get-matrix-rows* (- r 1) c (skip c l)))))))
(get-matrix-rows* (caar m) (cadar m) (cdr m)))))");
Assert.AreEqual("((1 2 3 4) (5 6 7 8) (9 10 11 12))", Evaluate("(get-matrix-rows m1)"));
Evaluate("(set max-of-pair (lambda (x y) (if (> x y) x y)))");
Evaluate("(set max/ (lambda (l) ((combine id max-of-pair (car l)) (cdr l))))");
Evaluate("(set apl-and (lambda (x y) (if (and (<> x 0) (<> y 0)) 1 0)))");
Evaluate("(set apl-or (lambda (x y) (if (or (<> x 0) (<> y 0)) 1 0)))");
Evaluate("(set and/ (combine id apl-and 1))");
Evaluate("(set or/ (combine id apl-or 0))");
Evaluate(@"
(set m-to-n (lambda (m n)
(if (> m n) '()
(cons m (m-to-n (+1 m) n)))))");
Evaluate(@"
(set repeat (lambda (n l)
(letrec ((repeat* (lambda (n l l-original)
(cond
((= n 0) '())
((null? l) (repeat* n l-original l-original))
('T (cons (car l) (repeat* (- n 1) (cdr l) l-original)))))))
(repeat* n l l))))");
Evaluate(@"
(set restruct (lambda (desired-shape src-data)
(let* ((length-of-desired-shape (length desired-shape))
(src-vector (to-vector src-data))
(dst-vector (repeat (*/ desired-shape) src-vector)))
(cond
((= length-of-desired-shape 0) 'restruct-to-scalar-error)
((= length-of-desired-shape 1) dst-vector)
('T (cons desired-shape dst-vector))))))");
Evaluate(@"
(set trans (lambda (matrix)
(letrec ((get-column (lambda (n l) (mapcar ((curry nth) n) l)))
(get-data (lambda (n num-cols l)
(if (< n num-cols)
(append (get-column n l) (get-data (+1 n) num-cols l))
'())))
(new-shape (list (cadar matrix) (caar matrix))))
(cons new-shape (get-data 0 (cadar matrix) (get-matrix-rows matrix))))))");
Evaluate(@"
(set [] (lambda (x y)
(let ((type-of-x (get-type x))
(type-of-y (get-type y))
(vector-y (to-vector y))
(nth*-reversed-args (lambda (l n) (nth (- n 1) l))))
(cond
((= type-of-x 'scalar) '[]-x-scalar-error)
((= type-of-y 'matrix) '[]-x-matrix-error)
((= type-of-x 'vector) (mapcar ((curry nth*-reversed-args) x) vector-y))
('T (restruct
(list (length vector-y) (cadar x))
(flatten (mapcar ((curry nth*-reversed-args) (get-matrix-rows x)) vector-y))))))))");
// Binary operators to implement:
// - compress
Evaluate(@"
(set compress (lambda (x y)
(letrec ((type-of-x (get-type x))
(type-of-y (get-type y))
(is-logical (lambda (v)
(if (null? v) 'T
(if (or (= (car v) 0) (= (car v) 1))
(is-logical (cdr v))
'()))))
(compress* (lambda (logv l)
(if (or (null? logv) (null? l)) '()
(if (= (car logv) 0)
(compress* (cdr logv) (cdr l))
(cons (car l) (compress* (cdr logv) (cdr l))))))))
(cond
((<> type-of-x 'vector) 'compress-x-not-vector-error)
((not (is-logical x)) 'compress-vector-not-logical-error)
((= type-of-y 'scalar) 'compress-y-scalar-error)
((= type-of-y 'vector) (compress* x y))
('T (restruct
(list (+/ x) (cadar y))
(flatten (compress* x (get-matrix-rows y)))))))))");
Evaluate(@"
(set apply-binary-op (lambda (f x y)
(letrec ((combine2 (lambda (f l1 l2)
(if (or (null? l1) (null? l2)) '()
(cons (f (car l1) (car l2)) (combine2 f (cdr l1) (cdr l2))))))
(apply-scalar-scalar (lambda (f x y) (f x y)))
(apply-scalar-vector (lambda (f x y) (mapcar (lambda (z) (f x z)) y)))
(apply-scalar-matrix (lambda (f x y) (cons (car y) (mapcar (lambda (z) (f x z)) (cdr y)))))
(apply-vector-scalar (lambda (f x y) (mapcar (lambda (z) (f z y)) x)))
(apply-vector-vector (lambda (f x y)
(if (= (length x) (length y))
(combine2 f x y)
'binary-op-vector-shape-mismatch)))
(apply-matrix-scalar (lambda (f x y) (cons (car x) (mapcar (lambda (z) (f z y)) (cdr x)))))
(apply-matrix-matrix (lambda (f x y)
(if (equal (car x) (car y))
(cons (car x) (combine2 f (cdr x) (cdr y)))
'binary-op-matrix-shape-mismatch)))
(apply-binary-op* (lambda (f x y)
(begin
(set x (to-scalar-if-possible x))
(set y (to-scalar-if-possible y))
(let ((type-of-x (get-type x))
(type-of-y (get-type y)))
(cond
((= type-of-x 'scalar)
(cond
((= type-of-y 'scalar) (apply-scalar-scalar f x y))
((= type-of-y 'vector) (apply-scalar-vector f x y))
('T (apply-scalar-matrix f x y))))
((= type-of-x 'vector)
(cond
((= type-of-y 'scalar) (apply-vector-scalar f x y))
((= type-of-y 'vector) (apply-vector-vector f x y))
('T 'binary-op-vector-matrix-error)))
((= type-of-x 'matrix)
(cond
((= type-of-y 'scalar) (apply-matrix-scalar f x y))
((= type-of-y 'vector) 'binary-op-matrix-vector-error)
('T (apply-matrix-matrix f x y)))))))))
(apl< (lambda (x y) (if (< x y) 1 0)))
(apl> (lambda (x y) (if (> x y) 1 0)))
(apl= (lambda (x y) (if (= x y) 1 0))))
(cond
((= f '+) (apply-binary-op* + x y))
((= f '-) (apply-binary-op* - x y))
((= f '*) (apply-binary-op* * x y))
((= f '/) (apply-binary-op* / x y))
((= f '<) (apply-binary-op* apl< x y))
((= f '>) (apply-binary-op* apl> x y))
((= f '=) (apply-binary-op* apl= x y))
((= f 'max) (apply-binary-op* max-of-pair x y))
((= f 'and) (apply-binary-op* apl-and x y))
((= f 'or) (apply-binary-op* apl-or x y))
((= f 'restruct) (restruct x y))
((= f 'cat) (append (to-vector x) (to-vector y)))
((= f '[]) ([] x y))
((= f 'compress) (compress x y))
('T 'binary-op-error!)
))))");
Evaluate(@"
(set apply-unary-op (lambda (f x)
(let* ((type-of-x (get-type x))
(apply-reduction-op (lambda (f x)
(cond
((= type-of-x 'scalar) 'scalar-reduction-error)
((= type-of-x 'vector) (f x))
('T (mapcar f (get-matrix-rows x)))))))
(cond
((= f '+/) (apply-reduction-op +/ x))
((= f '-/) (apply-reduction-op -/ x))
((= f '*/) (apply-reduction-op */ x))
((= f '//) (apply-reduction-op // x))
((= f 'max/) (apply-reduction-op max/ x))
((= f 'and/) (apply-reduction-op and/ x))
((= f 'or/) (apply-reduction-op or/ x))
((= f 'shape) (shape x))
((= f 'indx) (m-to-n 1 x))
((= f 'ravel) (to-vector x))
((= f 'trans) (trans x))
('T 'unary-op-error!)
; ('T f)
))))");
// begin
Evaluate(@"
(set do-begin (lambda (expr-list rho fundefs)
(if (null? (cdr expr-list))
(eval (car expr-list) rho fundefs)
(begin
(eval (car expr-list) rho fundefs)
(do-begin (cdr expr-list) rho fundefs)))))");
Evaluate(@"
(set eval (lambda (expr rho fundefs)
(cond
((number? expr) expr)
((symbol? expr)
(if (assoc-contains-key expr rho)
(assoc expr rho)
(assoc expr global-environment)))
((= (car expr) 'quote) (cadr expr))
((= (car expr) 'if)
(if (= 0 (get-first-scalar (eval (cadr expr) rho fundefs)))
(eval (cadddr expr) rho fundefs)
(eval (caddr expr) rho fundefs)))
((= (car expr) 'begin) (do-begin (cdr expr) rho fundefs)) ; Exercise 6a) on page 61
((= (car expr) 'print) ; Exercise 6a) on page 61
(print (eval (cadr expr) rho fundefs)))
((= (car expr) 'set)
(let ((evaluated-expression (eval (caddr expr) rho fundefs)))
(if (assoc-contains-key (cadr expr) rho)
(begin
(rplac-assoc (cadr expr) evaluated-expression rho)
evaluated-expression)
(begin
(set global-environment (mkassoc (cadr expr) evaluated-expression global-environment))
evaluated-expression))))
((userfun? (car expr) fundefs)
(apply-userfun
(assoc (car expr) fundefs)
(evallist (cdr expr) rho fundefs)
fundefs))
((= (length expr) 2)
(apply-unary-op (car expr) (eval (cadr expr) rho fundefs)))
('T (apply-binary-op (car expr)
(eval (cadr expr) rho fundefs)
(eval (caddr expr) rho fundefs))))))");
Evaluate("(set userfun? (lambda (f fundefs) (assoc-contains-key f fundefs)))");
Evaluate(@"
(set apply-userfun (lambda (fundef args fundefs)
(eval (cadr fundef) ; body of function
(mkassoc* (car fundef) args '()) ; local env
fundefs)))");
Evaluate(@"
(set evallist (lambda (el rho fundefs)
(if (null? el) '()
(cons (eval (car el) rho fundefs)
(evallist (cdr el) rho fundefs)))))");
Evaluate(@"
(set mkassoc* (lambda (keys values al)
(if (null? keys) al
(mkassoc* (cdr keys) (cdr values)
(mkassoc (car keys) (car values) al)))))");
Evaluate(@"
(set r-e-p-loop (lambda (inputs)
(begin
(set global-environment '())
(r-e-p-loop* inputs '()))))");
Evaluate(@"
(set r-e-p-loop* (lambda (inputs fundefs)
(cond
((null? inputs) '()) ; session done
((atom? (car inputs)) ; input is variable or number
(process-expr (car inputs) (cdr inputs) fundefs))
((= (caar inputs) 'define) ; input is function definition
(process-def (car inputs) (cdr inputs) fundefs))
('T (process-expr (car inputs) (cdr inputs) fundefs)))))");
Evaluate(@"
(set process-def (lambda (e inputs fundefs)
(cons (cadr e) ; echo function name
(r-e-p-loop* inputs
(mkassoc (cadr e) (cddr e) fundefs)))))");
Evaluate(@"
(set process-expr (lambda (e inputs fundefs)
(cons (eval e '() fundefs) ; print value of expression
(r-e-p-loop* inputs fundefs))))");
// indx test
Assert.AreEqual("((1 2 3 4 5 6 7 8))", Evaluate(@"
(r-e-p-loop '(
(indx 8)
))"));
// max/ test
/*
Assert.AreEqual("(8 (10 9 12))", Evaluate(@"
(r-e-p-loop '(
(max/ (quote (2 4 6 8 1 3 5 7)))
(max/ (quote ((3 4) 8 4 10 1 9 2 5 7 3 11 6 12)))
))"));
*/
Assert.AreEqual("(8 (10 9 12))", Evaluate(@"
(r-e-p-loop (list
(list 'max/ (list 'quote '(2 4 6 8 1 3 5 7)))
(list 'max/ (list 'quote '((3 4) 8 4 10 1 9 2 5 7 3 11 6 12)))
))"));
// restruct test
/*
Assert.AreEqual("((8 9 8 9 8 9 8) ((4 4) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1))", Evaluate(@"
(r-e-p-loop '(
(restruct (quote (7)) (quote (8 9)))
(restruct (quote (4 4)) (quote (1 0 0 0 0)))
))"));
*/
Assert.AreEqual("((8 9 8 9 8 9 8) ((4 4) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1))", Evaluate(@"
(r-e-p-loop (list
(list 'restruct (list 'quote '(7)) (list 'quote '(8 9)))
(list 'restruct (list 'quote '(4 4)) (list 'quote '(1 0 0 0 0)))
))"));
// trans test
/*
Assert.AreEqual("(((4 3) 1 5 9 2 6 10 3 7 11 4 8 12))", Evaluate(@"
(select '(1) (r-e-p-loop '(
(set m1 (restruct (quote (3 4)) (indx 12)))
(trans m1)
)))"));
*/
Assert.AreEqual("(((4 3) 1 5 9 2 6 10 3 7 11 4 8 12))", Evaluate(@"
(select '(1) (r-e-p-loop (list
(list 'set 'm1 (list 'restruct (list 'quote '(3 4)) '(indx 12)))
'(trans m1)
)))"));
// [] test
/*
Assert.AreEqual("((5) (7 8 9 0) ((1 4) 5 6 7 8) ((2 4) 9 10 11 12 1 2 3 4))", Evaluate(@"
(select '(2 3 4 5) (r-e-p-loop '(
(set v1 (quote (8 6 7 5 3 0 9)))
(set m1 (restruct (quote (3 4)) (indx 12)))
([] v1 4)
([] v1 (quote (3 1 7 6)))
([] m1 2)
([] m1 (quote (3 1)))
)))"));
*/
Assert.AreEqual("((5) (7 8 9 0) ((1 4) 5 6 7 8) ((2 4) 9 10 11 12 1 2 3 4))", Evaluate(@"
(select '(2 3 4 5) (r-e-p-loop (list
(list 'set 'v1 (list 'quote '(8 6 7 5 3 0 9)))
(list 'set 'm1 (list 'restruct (list 'quote '(3 4)) '(indx 12)))
'([] v1 4)
(list '[] 'v1 (list 'quote '(3 1 7 6)))
'([] m1 2)
(list '[] 'm1 (list 'quote '(3 1)))
)))"));
// compress test
/*
Assert.AreEqual("((8 7 5 0) ((2 4) 5 6 7 8 13 14 15 16))", Evaluate(@"
(select '(2 3) (r-e-p-loop '(
(set v1 (quote (8 6 7 5 3 0 9)))
(set m1 (restruct (quote (4 4)) (indx 16)))
(compress (quote (1 0 1 1 0 1 0)) v1)
(compress (quote (0 1 0 1)) m1)
)))"));
*/
Assert.AreEqual("((8 7 5 0) ((2 4) 5 6 7 8 13 14 15 16))", Evaluate(@"
(select '(2 3) (r-e-p-loop (list
(list 'set 'v1 (list 'quote '(8 6 7 5 3 0 9)))
(list 'set 'm1 (list 'restruct (list 'quote '(4 4)) '(indx 16)))
(list 'compress (list 'quote '(1 0 1 1 0 1 0)) 'v1)
(list 'compress (list 'quote '(0 1 0 1)) 'm1)
)))"));
// primes<= test (see pages 74-75)
Assert.AreEqual("(((4 7) 0 1 1 1 1 1 1 0 0 2 2 2 2 2 0 1 0 3 3 3 3 0 0 1 0 4 4 4) (2 3 5 7))", Evaluate(@"
(select '(2 4) (r-e-p-loop '(
(define mod (m n) (- m (* n (/ m n))))
(define mod-outer-probe (v1 v2)
(mod (trans (restruct (cat (shape v2) (shape v1)) v1))
(restruct (cat (shape v1) (shape v2)) v2)))
(mod-outer-probe (indx 4) (indx 7))
; Perhaps we could implement 'let', and then use (let ((s (indx n))) ...)
(define primes<= (n) (compress (= 2 (+/ (= 0 (mod-outer-probe (set s (indx n)) s)))) s))
(primes<= 7)
)))"));
// +\ ("+-scan") test (see page 74). This tests the "if" construct.
/*
Assert.AreEqual("(0)", Evaluate(@"
(select '(0) (r-e-p-loop '(
(= (shape (quote (1 3 5 7))) 0)
)))"));
*/
Assert.AreEqual("(0)", Evaluate(@"
(select '(0) (r-e-p-loop (list
(list '= (list 'shape (list 'quote '(1 3 5 7))) 0)
)))"));
/*
Assert.AreEqual("(0)", Evaluate(@"
(select '(1) (r-e-p-loop '(
(define foo (v) (if (= (shape v) 0) 1 0))
(foo (quote (1 3 5 7)))
)))"));
*/
Assert.AreEqual("(0)", Evaluate(@"
(select '(1) (r-e-p-loop (list
'(define foo (v) (if (= (shape v) 0) 1 0))
(list 'foo (list 'quote '(1 3 5 7)))
)))"));
/*
Assert.AreEqual("((1 4 9 16))", Evaluate(@"
(select '(2) (r-e-p-loop '(
(define dropend (v) ([] v (indx (- (shape v) 1))))
(define +\ (v)
(if (= (shape v) 0) v
(cat (+\ (dropend v)) (+/ v))))
(+\ (quote (1 3 5 7)))
)))"));
*/
Assert.AreEqual("((1 4 9 16))", Evaluate(@"
(select '(2) (r-e-p-loop (list
'(define dropend (v) ([] v (indx (- (shape v) 1))))
'(define +\ (v)
(if (= (shape v) 0) v
(cat (+\ (dropend v)) (+/ v))))
(list '+\ (list 'quote '(1 3 5 7)))
)))"));
}
[Test]
public void MacroApostrophesToQuoteKeywordsTest()
{
// Note that these expressions are parsed, but not evaluated.
Assert.AreEqual("(lambda (foo) (quote bar))", MacroDefinition.ObjectToString_ApostrophesToQuoteKeywords(GetParseResult("(lambda (foo) 'bar)")));
Assert.AreEqual("(foo (quote bar) (quote baz))", MacroDefinition.ObjectToString_ApostrophesToQuoteKeywords(GetParseResult("(foo 'bar 'baz)")));
Assert.AreEqual("((lambda (foo) (quote bar)) (quote baz))", MacroDefinition.ObjectToString_ApostrophesToQuoteKeywords(GetParseResult("((lambda (foo) 'bar) 'baz)")));
Assert.AreEqual("(letrec ((foo (quote bar))) (quote baz))", MacroDefinition.ObjectToString_ApostrophesToQuoteKeywords(GetParseResult("(letrec ((foo 'bar)) 'baz)")));
Assert.AreEqual("(call/cc (lambda (foo) (foo (quote bar))))", MacroDefinition.ObjectToString_ApostrophesToQuoteKeywords(GetParseResult("(call/cc (lambda (foo) (foo 'bar)))")));
}
[Test]
public void ComposeListTest() // 2013/11/30
{
Evaluate("(set compose-list (combine id compose id))");
Evaluate("(set cadaddr (compose-list (list cdr cdr car cdr car)))");
Assert.AreEqual("10", Evaluate("(cadaddr '((1 2 3 4) (5 6 7 8) (9 10 11 12) (13 14 15 16)))"));
// 2013/12/02
Evaluate("(set compose-list-reverse (combine id (reverse2args compose) id))");
Evaluate("(set cadaddr (compose-list-reverse (list car cdr car cdr cdr)))"); // The functions are applied from right to left.
Assert.AreEqual("10", Evaluate("(cadaddr '((1 2 3 4) (5 6 7 8) (9 10 11 12) (13 14 15 16)))"));
Evaluate("(set sumplus3 (compose2args + (compose-list (list +1 +1 +1))))");
Assert.AreEqual("18", Evaluate("(sumplus3 7 8)"));
}
[Test]
public void GeneralFindTest() // 2013/12/03
{
Evaluate(@"
(set general-find (lambda (pred result zero)
(letrec
((loop
(lambda (l)
(cond
((null? l) zero)
((pred (car l)) (result (car l)))
('T (loop (cdr l)))
)
)
))
loop
)
))");
Evaluate(@"
(set original-find (lambda (pred lis)
(
(general-find
pred
(lambda (x) 'T)
'()
)
lis
)
))");
Evaluate("(set original-contains (lambda (x l) (original-find ((curry =) x) l)))");
Assert.AreEqual("T", Evaluate("(original-contains 5 '(2 3 5 7))"));
Assert.AreEqual("()", Evaluate("(original-contains 4 '(2 3 5 7))"));
Evaluate(@"
(set alist-alt (lambda (x alist)
(
(general-find
(compose car ((curry =) x))
cadr
'()
)
alist
)
))");
Evaluate("(set sample-alist '((2 11) (3 13) (5 19) (7 19)))");
Assert.AreEqual("13", Evaluate("(alist-alt 3 sample-alist)"));
Assert.AreEqual("()", Evaluate("(alist-alt 4 sample-alist)"));
}
[Test]
public void SyntaxExceptionTest() // 2013/12/12
{
InferenceAssert.ThrowsWithLineAndColumnNumbers<SyntaxException>(() => Evaluate("(if 'T 7 13 'SyntaxError)"), 1, 13);
}
[Test]
public void EvaluationExceptionTest() // 2013/12/12
{
InferenceAssert.ThrowsWithLineAndColumnNumbers<EvaluationException>(() => Evaluate("(car 7)"), 1, 2);
}
[Test]
public void StringLessThanTest() // 2013/12/14
{
Assert.AreEqual("T", Evaluate("(primop? string<)"));
Assert.AreEqual("()", Evaluate("(string< \"a\" \"a\")"));
Assert.AreEqual("T", Evaluate("(string< \"a\" \"b\")"));
Assert.AreEqual("()", Evaluate("(string< \"b\" \"a\")"));
Assert.AreEqual("T", Evaluate("(string< \"abac\" \"abacus\")"));
Assert.AreEqual("T", Evaluate("(string< \"abacab\" \"abacus\")"));
}
[Test]
public void StringSortTest() // 2013/12/14
{
globalInfo.LoadPreset("sort");
// 1) Insertion sort.
Assert.AreEqual("(a ab abacab abacus abbot abbreviate abcess baa)",
Evaluate("((insertion-sort string<) '(\"abbreviate\" \"abacab\" \"abbot\" \"a\" \"baa\" \"abcess\" \"ab\" \"abacus\"))"));
// 2) Quicksort.
Assert.AreEqual("(a ab abacab abacus abbot abbreviate abcess baa)",
Evaluate("((quicksort string<) '(\"abbreviate\" \"abacab\" \"abbot\" \"a\" \"baa\" \"abcess\" \"ab\" \"abacus\"))"));
// 3) Merge sort.
Assert.AreEqual("(a ab abacab abacus abbot abbreviate abcess baa)",
Evaluate("((merge-sort string<) '(\"abbreviate\" \"abacab\" \"abbot\" \"a\" \"baa\" \"abcess\" \"ab\" \"abacus\"))"));
}
[Test]
public void RepeatListTest() // 2014/02/15. This might be useful in "restruct" in our Scheme APL interpreter.
{
Evaluate(@"
(set repeat-list (lambda (n master)
(letrec
((loop (lambda (n lm)
(if (<= n lm)
(take n master) ; Verify the order of take's args
(append master (loop (- n lm) lm))
)
)))
(loop n (length master))
)
))");
Assert.AreEqual("(2 3 5 7 2 3 5 7 2 3 5)", Evaluate("(repeat-list 11 '(2 3 5 7))"));
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using NUnit.Framework;
namespace Azure.AI.TextAnalytics.Tests
{
[ClientTestFixture(
TextAnalyticsClientOptions.ServiceVersion.V3_1,
TextAnalyticsClientOptions.ServiceVersion.V3_2_Preview_2)]
public class AnalyzeOperationTests : TextAnalyticsClientLiveTestBase
{
public AnalyzeOperationTests(bool isAsync, TextAnalyticsClientOptions.ServiceVersion serviceVersion)
: base(isAsync, serviceVersion)
{
}
private static List<string> batchConvenienceDocuments = new List<string>
{
"Elon Musk is the CEO of SpaceX and Tesla.",
"Tesla stock is up by 400% this year."
};
private static List<TextDocumentInput> batchDocuments = new List<TextDocumentInput>
{
new TextDocumentInput("1", "Elon Musk is the CEO of SpaceX and Tesla.")
{
Language = "en",
},
new TextDocumentInput("2", "Tesla stock is up by 400% this year.")
{
Language = "en",
}
};
[RecordedTest]
public async Task AnalyzeOperationWithAADTest()
{
TextAnalyticsClient client = GetClient(useTokenCredential: true);
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() },
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchDocuments, batchActions);
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<ExtractKeyPhrasesActionResult> keyPhrasesActionsResults = resultCollection.ExtractKeyPhrasesResults;
Assert.IsNotNull(keyPhrasesActionsResults);
Assert.AreEqual(2, keyPhrasesActionsResults.FirstOrDefault().DocumentsResults.Count);
}
[RecordedTest]
[ServiceVersion(Min = TextAnalyticsClientOptions.ServiceVersion.V3_2_Preview_2)]
public async Task AnalyzeOperationTest()
{
TextAnalyticsClient client = GetClient();
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() },
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchConvenienceDocuments, batchActions, "en");
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<RecognizeEntitiesActionResult> entitiesActionsResults = resultCollection.RecognizeEntitiesResults;
IReadOnlyCollection<ExtractKeyPhrasesActionResult> keyPhrasesActionsResults = resultCollection.ExtractKeyPhrasesResults;
IReadOnlyCollection<RecognizePiiEntitiesActionResult> piiActionsResults = resultCollection.RecognizePiiEntitiesResults;
IReadOnlyCollection<RecognizeLinkedEntitiesActionResult> entityLinkingActionsResults = resultCollection.RecognizeLinkedEntitiesResults;
IReadOnlyCollection<AnalyzeSentimentActionResult> analyzeSentimentActionsResults = resultCollection.AnalyzeSentimentResults;
IReadOnlyCollection<ExtractSummaryActionResult> extractSummaryActionsResults = resultCollection.ExtractSummaryResults;
IReadOnlyCollection<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = resultCollection.RecognizeCustomEntitiesResults;
IReadOnlyCollection<SingleCategoryClassifyActionResult> singleCategoryClassifyResults = resultCollection.SingleCategoryClassifyResults;
IReadOnlyCollection<MultiCategoryClassifyActionResult> multiCategoryClassifyResults = resultCollection.MultiCategoryClassifyResults;
Assert.IsNotNull(keyPhrasesActionsResults);
Assert.IsNotNull(entitiesActionsResults);
Assert.IsNotNull(piiActionsResults);
Assert.IsNotNull(entityLinkingActionsResults);
Assert.IsNotNull(analyzeSentimentActionsResults);
Assert.IsNotNull(extractSummaryActionsResults);
Assert.IsNotNull(singleCategoryClassifyResults);
Assert.IsNotNull(multiCategoryClassifyResults);
Assert.IsNotNull(recognizeCustomEntitiesActionResults);
var keyPhrasesListId1 = new List<string> { "CEO", "SpaceX", "Elon Musk", "Tesla" };
var keyPhrasesListId2 = new List<string> { "Tesla stock" };
ExtractKeyPhrasesResultCollection keyPhrasesDocumentsResults = keyPhrasesActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(2, keyPhrasesDocumentsResults.Count);
foreach (string keyphrase in keyPhrasesDocumentsResults[0].KeyPhrases)
{
Assert.IsTrue(keyPhrasesListId1.Contains(keyphrase));
}
foreach (string keyphrase in keyPhrasesDocumentsResults[1].KeyPhrases)
{
Assert.IsTrue(keyPhrasesListId2.Contains(keyphrase));
}
}
[RecordedTest]
public async Task AnalyzeOperationWithLanguageTest()
{
TextAnalyticsClient client = GetClient();
var batchDocuments = new List<TextDocumentInput>
{
new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
{
Language = "en",
},
new TextDocumentInput("2", "Mi perro y mi gato tienen que ir al veterinario.")
{
Language = "es",
}
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() },
DisplayName = "AnalyzeOperationWithLanguageTest"
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchDocuments, batchActions);
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<ExtractKeyPhrasesActionResult> keyPhrasesActionsResults = resultCollection.ExtractKeyPhrasesResults;
Assert.IsNotNull(keyPhrasesActionsResults);
ExtractKeyPhrasesResultCollection keyPhrasesDocumentsResults = keyPhrasesActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(2, keyPhrasesDocumentsResults.Count);
Assert.AreEqual("AnalyzeOperationWithLanguageTest", operation.DisplayName);
var keyPhrasesListId1 = new List<string> { "Bill Gates", "Paul Allen", "Microsoft" };
var keyPhrasesListId2 = new List<string> { "Mi", "gato", "perro", "veterinario" };
foreach (string keyphrase in keyPhrasesDocumentsResults[0].KeyPhrases)
{
Assert.IsTrue(keyPhrasesListId1.Contains(keyphrase));
}
foreach (string keyphrase in keyPhrasesDocumentsResults[1].KeyPhrases)
{
Assert.IsTrue(keyPhrasesListId2.Contains(keyphrase));
}
}
[RecordedTest]
public async Task AnalyzeOperationWithMultipleActions()
{
TextAnalyticsClient client = GetClient();
var batchDocuments = new List<TextDocumentInput>
{
new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
{
Language = "en",
},
new TextDocumentInput("2", "Mi perro y mi gato tienen que ir al veterinario.")
{
Language = "es",
}
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() },
RecognizeEntitiesActions = new List<RecognizeEntitiesAction>() { new RecognizeEntitiesAction() },
RecognizePiiEntitiesActions = new List<RecognizePiiEntitiesAction>() { new RecognizePiiEntitiesAction() },
RecognizeLinkedEntitiesActions = new List<RecognizeLinkedEntitiesAction>() { new RecognizeLinkedEntitiesAction() },
AnalyzeSentimentActions = new List<AnalyzeSentimentAction>() { new AnalyzeSentimentAction() },
DisplayName = "AnalyzeOperationWithMultipleTasks"
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchDocuments, batchActions);
Assert.AreEqual(0, operation.ActionsFailed);
Assert.AreEqual(0, operation.ActionsSucceeded);
Assert.AreEqual(0, operation.ActionsInProgress);
Assert.AreEqual(0, operation.ActionsTotal);
await operation.WaitForCompletionAsync();
Assert.AreEqual(0, operation.ActionsFailed);
Assert.AreEqual(5, operation.ActionsSucceeded);
Assert.AreEqual(0, operation.ActionsInProgress);
Assert.AreEqual(5, operation.ActionsTotal);
Assert.AreNotEqual(new DateTimeOffset(), operation.CreatedOn);
Assert.AreNotEqual(new DateTimeOffset(), operation.LastModified);
Assert.AreNotEqual(new DateTimeOffset(), operation.ExpiresOn);
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<RecognizeEntitiesActionResult> entitiesActionsResults = resultCollection.RecognizeEntitiesResults;
IReadOnlyCollection<ExtractKeyPhrasesActionResult> keyPhrasesActionsResults = resultCollection.ExtractKeyPhrasesResults;
IReadOnlyCollection<RecognizePiiEntitiesActionResult> piiActionsResults = resultCollection.RecognizePiiEntitiesResults;
IReadOnlyCollection<RecognizeLinkedEntitiesActionResult> entityLinkingActionsResults = resultCollection.RecognizeLinkedEntitiesResults;
IReadOnlyCollection<AnalyzeSentimentActionResult> analyzeSentimentActionsResults = resultCollection.AnalyzeSentimentResults;
Assert.IsNotNull(keyPhrasesActionsResults);
Assert.IsNotNull(entitiesActionsResults);
Assert.IsNotNull(piiActionsResults);
Assert.IsNotNull(entityLinkingActionsResults);
Assert.IsNotNull(analyzeSentimentActionsResults);
Assert.AreEqual("AnalyzeOperationWithMultipleTasks", operation.DisplayName);
// Keyphrases
ExtractKeyPhrasesResultCollection keyPhrasesDocumentsResults = keyPhrasesActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(2, keyPhrasesDocumentsResults.Count);
var keyPhrasesListId1 = new List<string> { "Bill Gates", "Paul Allen", "Microsoft" };
var keyPhrasesListId2 = new List<string> { "Mi", "gato", "perro", "veterinario" };
foreach (string keyphrase in keyPhrasesDocumentsResults[0].KeyPhrases)
{
Assert.IsTrue(keyPhrasesListId1.Contains(keyphrase));
}
foreach (string keyphrase in keyPhrasesDocumentsResults[1].KeyPhrases)
{
Assert.IsTrue(keyPhrasesListId2.Contains(keyphrase));
}
// Entities
RecognizeEntitiesResultCollection entitiesDocumentsResults = entitiesActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(2, entitiesDocumentsResults.Count);
Assert.AreEqual(3, entitiesDocumentsResults[0].Entities.Count);
var entitiesList = new List<string> { "Bill Gates", "Microsoft", "Paul Allen" };
foreach (CategorizedEntity entity in entitiesDocumentsResults[0].Entities)
{
Assert.IsTrue(entitiesList.Contains(entity.Text));
Assert.IsNotNull(entity.Category);
Assert.IsNotNull(entity.Offset);
Assert.IsNotNull(entity.ConfidenceScore);
}
// PII
RecognizePiiEntitiesResultCollection piiDocumentsResults = piiActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(2, piiDocumentsResults.Count);
Assert.AreEqual(3, piiDocumentsResults[0].Entities.Count);
Assert.IsNotNull(piiDocumentsResults[0].Id);
Assert.IsNotNull(piiDocumentsResults[0].Entities);
Assert.IsNotNull(piiDocumentsResults[0].Error);
// Entity Linking
RecognizeLinkedEntitiesResultCollection entityLinkingDocumentsResults = entityLinkingActionsResults.FirstOrDefault().DocumentsResults;
// Disable because of bug https://github.com/Azure/azure-sdk-for-net/issues/22648
//Assert.AreEqual(2, entityLinkingDocumentsResults.Count);
Assert.AreEqual(3, entityLinkingDocumentsResults[0].Entities.Count);
Assert.IsNotNull(entityLinkingDocumentsResults[0].Id);
Assert.IsNotNull(entityLinkingDocumentsResults[0].Entities);
Assert.IsNotNull(entityLinkingDocumentsResults[0].Error);
foreach (LinkedEntity entity in entityLinkingDocumentsResults[0].Entities)
{
if (entity.Name == "Bill Gates")
{
Assert.AreEqual("Bill Gates", entity.DataSourceEntityId);
Assert.AreEqual("Wikipedia", entity.DataSource);
}
if (entity.Name == "Microsoft")
{
Assert.AreEqual("Microsoft", entity.DataSourceEntityId);
Assert.AreEqual("Wikipedia", entity.DataSource);
}
}
// Analyze sentiment
AnalyzeSentimentResultCollection analyzeSentimentDocumentsResults = analyzeSentimentActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(2, analyzeSentimentDocumentsResults.Count);
Assert.AreEqual(TextSentiment.Neutral, analyzeSentimentDocumentsResults[0].DocumentSentiment.Sentiment);
Assert.AreEqual(TextSentiment.Neutral, analyzeSentimentDocumentsResults[1].DocumentSentiment.Sentiment);
}
[Ignore("issue: results in an internal server error | bug link: https://dev.azure.com/msazure/Cognitive%20Services/_workitems/edit/12413250")]
public async Task AnalyzeOperationWithMultipleActionsOfSameType()
{
TextAnalyticsClient client = GetClient();
var batchDocuments = new List<TextDocumentInput>
{
new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
{
Language = "en",
},
new TextDocumentInput("2", "Mi perro y mi gato tienen que ir al veterinario.")
{
Language = "es",
}
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>()
{
new ExtractKeyPhrasesAction()
{ ActionName = "DisableServaiceLogsTrue", DisableServiceLogs = true },
new ExtractKeyPhrasesAction()
{ ActionName = "DisableServiceLogsFalse"},
},
RecognizeEntitiesActions = new List<RecognizeEntitiesAction>()
{
new RecognizeEntitiesAction()
{ ActionName = "DisableServiceLogsTrue", DisableServiceLogs = true },
new RecognizeEntitiesAction()
{ ActionName = "DisableServiceLogsFalse" },
},
RecognizePiiEntitiesActions = new List<RecognizePiiEntitiesAction>()
{
new RecognizePiiEntitiesAction()
{ ActionName = "DisableServiceLogsTrue", DisableServiceLogs = true },
new RecognizePiiEntitiesAction()
{ ActionName = "DisableServiceLogsFalse" },
},
RecognizeLinkedEntitiesActions = new List<RecognizeLinkedEntitiesAction>()
{
new RecognizeLinkedEntitiesAction()
{ ActionName = "DisableServiceLogsTrue", DisableServiceLogs = true },
new RecognizeLinkedEntitiesAction()
{ ActionName = "DisableServiceLogsFalse" },
},
AnalyzeSentimentActions = new List<AnalyzeSentimentAction>()
{
new AnalyzeSentimentAction()
{ ActionName = "DisableServiceLogsTrue", DisableServiceLogs = true },
new AnalyzeSentimentAction()
{ ActionName = "DisableServiceLogsFalse" },
},
RecognizeCustomEntitiesActions = new List<RecognizeCustomEntitiesAction>()
{
new RecognizeCustomEntitiesAction(TestEnvironment.RecognizeCustomEntitiesProjectName, TestEnvironment.RecognizeCustomEntitiesDeploymentName)
{ ActionName = "DisableServiceLogsTrue", DisableServiceLogs = true },
new RecognizeCustomEntitiesAction(TestEnvironment.RecognizeCustomEntitiesProjectName, TestEnvironment.RecognizeCustomEntitiesDeploymentName)
{ ActionName = "DisableServiceLogsFalse" },
},
SingleCategoryClassifyActions = new List<SingleCategoryClassifyAction>()
{
new SingleCategoryClassifyAction(TestEnvironment.SingleClassificationProjectName, TestEnvironment.SingleClassificationDeploymentName)
{ ActionName = "DisableServiceLogsTrue", DisableServiceLogs = true },
new SingleCategoryClassifyAction(TestEnvironment.SingleClassificationProjectName, TestEnvironment.SingleClassificationDeploymentName)
{ ActionName = "DisableServiceLogsFalse" },
},
MultiCategoryClassifyActions = new List<MultiCategoryClassifyAction>()
{
new MultiCategoryClassifyAction(TestEnvironment.MultiClassificationProjectName, TestEnvironment.MultiClassificationDeploymentName)
{ ActionName = "DisableServiceLogsTrue", DisableServiceLogs = true },
new MultiCategoryClassifyAction(TestEnvironment.MultiClassificationProjectName, TestEnvironment.MultiClassificationDeploymentName)
{ ActionName = "DisableServiceLogsFalse"},
},
DisplayName = "AnalyzeOperationWithMultipleTasksOfSameType"
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchDocuments, batchActions);
Assert.AreEqual(0, operation.ActionsFailed);
Assert.AreEqual(0, operation.ActionsSucceeded);
Assert.AreEqual(0, operation.ActionsInProgress);
Assert.AreEqual(0, operation.ActionsTotal);
await operation.WaitForCompletionAsync();
Assert.AreEqual(0, operation.ActionsFailed);
Assert.AreEqual(16, operation.ActionsSucceeded);
Assert.AreEqual(0, operation.ActionsInProgress);
Assert.AreEqual(16, operation.ActionsTotal);
Assert.AreNotEqual(new DateTimeOffset(), operation.CreatedOn);
Assert.AreNotEqual(new DateTimeOffset(), operation.LastModified);
Assert.AreNotEqual(new DateTimeOffset(), operation.ExpiresOn);
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<RecognizeEntitiesActionResult> entitiesActionsResults = resultCollection.RecognizeEntitiesResults;
IReadOnlyCollection<ExtractKeyPhrasesActionResult> keyPhrasesActionsResults = resultCollection.ExtractKeyPhrasesResults;
IReadOnlyCollection<RecognizePiiEntitiesActionResult> piiActionsResults = resultCollection.RecognizePiiEntitiesResults;
IReadOnlyCollection<RecognizeLinkedEntitiesActionResult> entityLinkingActionsResults = resultCollection.RecognizeLinkedEntitiesResults;
IReadOnlyCollection<AnalyzeSentimentActionResult> analyzeSentimentActionsResults = resultCollection.AnalyzeSentimentResults;
IReadOnlyCollection<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesResults = resultCollection.RecognizeCustomEntitiesResults;
IReadOnlyCollection<SingleCategoryClassifyActionResult> singleCategoryClassifyResults = resultCollection.SingleCategoryClassifyResults;
IReadOnlyCollection<MultiCategoryClassifyActionResult> multiCategoryClassifyResults = resultCollection.MultiCategoryClassifyResults;
Assert.IsNotNull(keyPhrasesActionsResults);
Assert.IsNotNull(entitiesActionsResults);
Assert.IsNotNull(piiActionsResults);
Assert.IsNotNull(entityLinkingActionsResults);
Assert.IsNotNull(analyzeSentimentActionsResults);
Assert.IsNotNull(recognizeCustomEntitiesResults);
Assert.IsNotNull(singleCategoryClassifyResults);
Assert.IsNotNull(multiCategoryClassifyResults);
Assert.AreEqual("AnalyzeOperationWithMultipleTasks", operation.DisplayName);
}
[RecordedTest]
public async Task AnalyzeOperationWithPagination()
{
TextAnalyticsClient client = GetClient();
List<string> documents = new();
for (int i = 0; i < 23; i++)
{
documents.Add("Elon Musk is the CEO of SpaceX and Tesla.");
}
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() },
DisplayName = "AnalyzeOperationWithPagination",
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(documents, batchActions);
Assert.IsFalse(operation.HasCompleted);
Assert.IsFalse(operation.HasValue);
Assert.ThrowsAsync<InvalidOperationException>(async () => await Task.Run(() => operation.Value));
Assert.ThrowsAsync<InvalidOperationException>(async () => await Task.Run(() => operation.GetValuesAsync()));
await operation.WaitForCompletionAsync();
Assert.IsTrue(operation.HasCompleted);
Assert.IsTrue(operation.HasValue);
// try async
//There most be 2 pages as service limit is 20 documents per page
List<AnalyzeActionsResult> asyncPages = operation.Value.ToEnumerableAsync().Result;
Assert.AreEqual(2, asyncPages.Count);
// First page should have 20 results
Assert.AreEqual(20, asyncPages[0].ExtractKeyPhrasesResults.FirstOrDefault().DocumentsResults.Count);
// Second page should have remaining 3 results
Assert.AreEqual(3, asyncPages[1].ExtractKeyPhrasesResults.FirstOrDefault().DocumentsResults.Count);
// try sync
//There most be 2 pages as service limit is 20 documents per page
List<AnalyzeActionsResult> pages = operation.GetValues().AsEnumerable().ToList();
Assert.AreEqual(2, pages.Count);
// First page should have 20 results
Assert.AreEqual(20, pages[0].ExtractKeyPhrasesResults.FirstOrDefault().DocumentsResults.Count);
// Second page should have remaining 3 results
Assert.AreEqual(3, pages[1].ExtractKeyPhrasesResults.FirstOrDefault().DocumentsResults.Count);
}
[RecordedTest]
public void AnalyzeOperationWithErrorTest()
{
TextAnalyticsClient client = GetClient();
var documents = new List<string>
{
"Subject is taking 100mg of ibuprofen twice daily"
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>()
{
new ExtractKeyPhrasesAction()
{
ModelVersion = "InvalidVersion"
}
},
DisplayName = "AnalyzeOperationBatchWithErrorTest",
};
RequestFailedException ex = Assert.ThrowsAsync<RequestFailedException>(async () => await client.StartAnalyzeActionsAsync(documents, batchActions));
Assert.AreEqual(TextAnalyticsErrorCode.InvalidParameterValue, ex.ErrorCode);
}
[RecordedTest]
public async Task AnalyzeOperationWithErrorsInDocumentTest()
{
TextAnalyticsClient client = GetClient();
var documents = new List<string>
{
"Subject is taking 100mg of ibuprofen twice daily",
"",
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>()
{
new ExtractKeyPhrasesAction()
}
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(documents, batchActions, "en");
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
//Key phrases
List<ExtractKeyPhrasesActionResult> keyPhrasesActions = resultCollection.ExtractKeyPhrasesResults.ToList();
Assert.AreEqual(1, keyPhrasesActions.Count);
ExtractKeyPhrasesResultCollection documentsResults = keyPhrasesActions[0].DocumentsResults;
Assert.IsFalse(documentsResults[0].HasError);
Assert.IsTrue(documentsResults[1].HasError);
Assert.AreEqual(TextAnalyticsErrorCode.InvalidDocument, documentsResults[1].Error.ErrorCode.ToString());
}
[RecordedTest]
public async Task AnalyzeOperationWithPHIDomain()
{
TextAnalyticsClient client = GetClient();
var documents = new List<string>
{
"A patient with medical id 12345678 whose phone number is 800-102-1100 is going under heart surgery",
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
RecognizePiiEntitiesActions = new List<RecognizePiiEntitiesAction>() { new RecognizePiiEntitiesAction() { DomainFilter = PiiEntityDomain.ProtectedHealthInformation } },
DisplayName = "AnalyzeOperationWithPHIDomain",
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(documents, batchActions, "en");
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<RecognizePiiEntitiesActionResult> piiActionsResults = resultCollection.RecognizePiiEntitiesResults;
Assert.IsNotNull(piiActionsResults);
RecognizePiiEntitiesResultCollection piiDocumentsResults = piiActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(1, piiDocumentsResults.Count);
Assert.IsNotEmpty(piiDocumentsResults[0].Entities.RedactedText);
Assert.IsFalse(piiDocumentsResults[0].HasError);
Assert.AreEqual(2, piiDocumentsResults[0].Entities.Count);
}
[RecordedTest]
public async Task AnalyzeOperationWithPiiCategories()
{
TextAnalyticsClient client = GetClient();
var documents = new List<string>
{
"A developer with SSN 859-98-0987 whose phone number is 800-102-1100 is building tools with our APIs. They work at Microsoft.",
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
RecognizePiiEntitiesActions = new List<RecognizePiiEntitiesAction>() { new RecognizePiiEntitiesAction() { CategoriesFilter = { PiiEntityCategory.USSocialSecurityNumber } } },
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(documents, batchActions, "en");
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<RecognizePiiEntitiesActionResult> piiActionsResults = resultCollection.RecognizePiiEntitiesResults;
Assert.IsNotNull(piiActionsResults);
RecognizePiiEntitiesResultCollection piiDocumentsResults = piiActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(1, piiDocumentsResults.Count);
Assert.IsNotEmpty(piiDocumentsResults[0].Entities.RedactedText);
Assert.IsFalse(piiDocumentsResults[0].HasError);
Assert.AreEqual(1, piiDocumentsResults[0].Entities.Count);
Assert.AreEqual(PiiEntityCategory.USSocialSecurityNumber, piiDocumentsResults[0].Entities.FirstOrDefault().Category);
}
[RecordedTest]
public async Task AnalyzeOperationWithStatisticsTest()
{
TextAnalyticsClient client = GetClient();
var batchDocuments = new List<TextDocumentInput>
{
new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
{
Language = "en",
},
new TextDocumentInput("2", "Mi perro y mi gato tienen que ir al veterinario.")
{
Language = "es",
},
new TextDocumentInput("3", "")
{
Language = "es",
}
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() },
DisplayName = "AnalyzeOperationTest",
};
AnalyzeActionsOptions options = new AnalyzeActionsOptions()
{
IncludeStatistics = true
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchDocuments, batchActions, options);
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
ExtractKeyPhrasesResultCollection documentsResults = resultCollection.ExtractKeyPhrasesResults.ElementAt(0).DocumentsResults;
Assert.IsNotNull(documentsResults);
Assert.AreEqual(3, documentsResults.Count);
Assert.AreEqual(3, documentsResults.Statistics.DocumentCount);
Assert.AreEqual(2, documentsResults.Statistics.TransactionCount);
Assert.AreEqual(2, documentsResults.Statistics.ValidDocumentCount);
Assert.AreEqual(1, documentsResults.Statistics.InvalidDocumentCount);
Assert.AreEqual(51, documentsResults[0].Statistics.CharacterCount);
Assert.AreEqual(1, documentsResults[0].Statistics.TransactionCount);
}
[RecordedTest]
public async Task AnalyzeOperationAllActionsAndDisableServiceLogs()
{
TextAnalyticsClient client = GetClient();
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() { DisableServiceLogs = true } },
RecognizeEntitiesActions = new List<RecognizeEntitiesAction>() { new RecognizeEntitiesAction() { DisableServiceLogs = true } },
RecognizePiiEntitiesActions = new List<RecognizePiiEntitiesAction>() { new RecognizePiiEntitiesAction() { DisableServiceLogs = false } },
RecognizeLinkedEntitiesActions = new List<RecognizeLinkedEntitiesAction>() { new RecognizeLinkedEntitiesAction() { DisableServiceLogs = true } },
AnalyzeSentimentActions = new List<AnalyzeSentimentAction>() { new AnalyzeSentimentAction() { DisableServiceLogs = true } }
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchConvenienceDocuments, batchActions);
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<ExtractKeyPhrasesActionResult> keyPhrasesActionsResults = resultCollection.ExtractKeyPhrasesResults;
IReadOnlyCollection<RecognizeEntitiesActionResult> entitiesActionsResults = resultCollection.RecognizeEntitiesResults;
IReadOnlyCollection<RecognizePiiEntitiesActionResult> piiActionsResults = resultCollection.RecognizePiiEntitiesResults;
IReadOnlyCollection<RecognizeLinkedEntitiesActionResult> entityLinkingActionsResults = resultCollection.RecognizeLinkedEntitiesResults;
IReadOnlyCollection<AnalyzeSentimentActionResult> analyzeSentimentActionsResults = resultCollection.AnalyzeSentimentResults;
Assert.IsNotNull(keyPhrasesActionsResults);
Assert.AreEqual(2, keyPhrasesActionsResults.FirstOrDefault().DocumentsResults.Count);
Assert.IsNotNull(entitiesActionsResults);
Assert.AreEqual(2, entitiesActionsResults.FirstOrDefault().DocumentsResults.Count);
Assert.IsNotNull(piiActionsResults);
Assert.AreEqual(2, piiActionsResults.FirstOrDefault().DocumentsResults.Count);
Assert.IsNotNull(entityLinkingActionsResults);
Assert.AreEqual(2, entityLinkingActionsResults.FirstOrDefault().DocumentsResults.Count);
Assert.IsNotNull(analyzeSentimentActionsResults);
Assert.AreEqual(2, analyzeSentimentActionsResults.FirstOrDefault().DocumentsResults.Count);
}
[RecordedTest]
public async Task AnalyzeOperationAnalyzeSentimentWithOpinionMining()
{
TextAnalyticsClient client = GetClient();
var documents = new List<string>
{
"The park was clean and pretty. The bathrooms and restaurant were not clean.",
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
AnalyzeSentimentActions = new List<AnalyzeSentimentAction>() { new AnalyzeSentimentAction() { IncludeOpinionMining = true } },
DisplayName = "AnalyzeOperationWithOpinionMining",
};
AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(documents, batchActions);
await operation.WaitForCompletionAsync();
//Take the first page
AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
IReadOnlyCollection<AnalyzeSentimentActionResult> analyzeSentimentActionsResults = resultCollection.AnalyzeSentimentResults;
Assert.IsNotNull(analyzeSentimentActionsResults);
AnalyzeSentimentResultCollection analyzeSentimentDocumentsResults = analyzeSentimentActionsResults.FirstOrDefault().DocumentsResults;
Assert.AreEqual(1, analyzeSentimentDocumentsResults.Count);
Assert.AreEqual(TextSentiment.Mixed, analyzeSentimentDocumentsResults[0].DocumentSentiment.Sentiment);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Build.Framework
{
public delegate void AnyEventHandler(object sender, Microsoft.Build.Framework.BuildEventArgs e);
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct BuildEngineResult
{
private object _dummy;
private int _dummyPrimitive;
public BuildEngineResult(bool result, System.Collections.Generic.List<System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.ITaskItem[]>> targetOutputsPerProject) { throw null; }
public bool Result { get { throw null; } }
public System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.ITaskItem[]>> TargetOutputsPerProject { get { throw null; } }
}
public partial class BuildErrorEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildErrorEventArgs() { }
public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { }
public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, string helpLink, System.DateTime eventTimestamp, params object[] messageArgs) { }
public string Code { get { throw null; } }
public int ColumnNumber { get { throw null; } }
public int EndColumnNumber { get { throw null; } }
public int EndLineNumber { get { throw null; } }
public string File { get { throw null; } }
public string HelpLink { get { throw null; } }
public int LineNumber { get { throw null; } }
public string ProjectFile { get { throw null; } set { } }
public string Subcategory { get { throw null; } }
}
public delegate void BuildErrorEventHandler(object sender, Microsoft.Build.Framework.BuildErrorEventArgs e);
public abstract partial class BuildEventArgs : System.EventArgs
{
protected BuildEventArgs() { }
protected BuildEventArgs(string message, string helpKeyword, string senderName) { }
protected BuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public Microsoft.Build.Framework.BuildEventContext BuildEventContext { get { throw null; } set { } }
public string HelpKeyword { get { throw null; } }
public virtual string Message { get { throw null; } protected set { } }
protected internal string RawMessage { get { throw null; } set { } }
protected internal System.DateTime RawTimestamp { get { throw null; } set { } }
public string SenderName { get { throw null; } }
public int ThreadId { get { throw null; } }
public System.DateTime Timestamp { get { throw null; } }
}
public partial class BuildEventContext
{
public const int InvalidEvaluationId = -1;
public const int InvalidNodeId = -2;
public const int InvalidProjectContextId = -2;
public const int InvalidProjectInstanceId = -1;
public const int InvalidSubmissionId = -1;
public const int InvalidTargetId = -1;
public const int InvalidTaskId = -1;
public BuildEventContext(int nodeId, int targetId, int projectContextId, int taskId) { }
public BuildEventContext(int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId) { }
public BuildEventContext(int submissionId, int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId) { }
public BuildEventContext(int submissionId, int nodeId, int evaluationId, int projectInstanceId, int projectContextId, int targetId, int taskId) { }
public long BuildRequestId { get { throw null; } }
public int EvaluationId { get { throw null; } }
public static Microsoft.Build.Framework.BuildEventContext Invalid { get { throw null; } }
public int NodeId { get { throw null; } }
public int ProjectContextId { get { throw null; } }
public int ProjectInstanceId { get { throw null; } }
public int SubmissionId { get { throw null; } }
public int TargetId { get { throw null; } }
public int TaskId { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Microsoft.Build.Framework.BuildEventContext left, Microsoft.Build.Framework.BuildEventContext right) { throw null; }
public static bool operator !=(Microsoft.Build.Framework.BuildEventContext left, Microsoft.Build.Framework.BuildEventContext right) { throw null; }
public override string ToString() { throw null; }
}
public partial class BuildFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected BuildFinishedEventArgs() { }
public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded) { }
public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded, System.DateTime eventTimestamp) { }
public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded, System.DateTime eventTimestamp, params object[] messageArgs) { }
public bool Succeeded { get { throw null; } }
}
public delegate void BuildFinishedEventHandler(object sender, Microsoft.Build.Framework.BuildFinishedEventArgs e);
public partial class BuildMessageEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildMessageEventArgs() { }
public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance) { }
public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { }
public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp, params object[] messageArgs) { }
public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance) { }
public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { }
public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp, params object[] messageArgs) { }
public string Code { get { throw null; } }
public int ColumnNumber { get { throw null; } }
public int EndColumnNumber { get { throw null; } }
public int EndLineNumber { get { throw null; } }
public string File { get { throw null; } }
public Microsoft.Build.Framework.MessageImportance Importance { get { throw null; } }
public int LineNumber { get { throw null; } }
public string ProjectFile { get { throw null; } set { } }
public string Subcategory { get { throw null; } }
}
public delegate void BuildMessageEventHandler(object sender, Microsoft.Build.Framework.BuildMessageEventArgs e);
public partial class BuildStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected BuildStartedEventArgs() { }
public BuildStartedEventArgs(string message, string helpKeyword) { }
public BuildStartedEventArgs(string message, string helpKeyword, System.Collections.Generic.IDictionary<string, string> environmentOfBuild) { }
public BuildStartedEventArgs(string message, string helpKeyword, System.DateTime eventTimestamp) { }
public BuildStartedEventArgs(string message, string helpKeyword, System.DateTime eventTimestamp, params object[] messageArgs) { }
public System.Collections.Generic.IDictionary<string, string> BuildEnvironment { get { throw null; } }
}
public delegate void BuildStartedEventHandler(object sender, Microsoft.Build.Framework.BuildStartedEventArgs e);
public abstract partial class BuildStatusEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildStatusEventArgs() { }
protected BuildStatusEventArgs(string message, string helpKeyword, string senderName) { }
protected BuildStatusEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
protected BuildStatusEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
}
public delegate void BuildStatusEventHandler(object sender, Microsoft.Build.Framework.BuildStatusEventArgs e);
public partial class BuildWarningEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected BuildWarningEventArgs() { }
public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { }
public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, string helpLink, System.DateTime eventTimestamp, params object[] messageArgs) { }
public string Code { get { throw null; } }
public int ColumnNumber { get { throw null; } }
public int EndColumnNumber { get { throw null; } }
public int EndLineNumber { get { throw null; } }
public string File { get { throw null; } }
public string HelpLink { get { throw null; } }
public int LineNumber { get { throw null; } }
public string ProjectFile { get { throw null; } set { } }
public string Subcategory { get { throw null; } }
}
public delegate void BuildWarningEventHandler(object sender, Microsoft.Build.Framework.BuildWarningEventArgs e);
public partial class CriticalBuildMessageEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
protected CriticalBuildMessageEventArgs() { }
public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { }
public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
}
public abstract partial class CustomBuildEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs
{
protected CustomBuildEventArgs() { }
protected CustomBuildEventArgs(string message, string helpKeyword, string senderName) { }
protected CustomBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { }
protected CustomBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
}
public delegate void CustomBuildEventHandler(object sender, Microsoft.Build.Framework.CustomBuildEventArgs e);
public abstract partial class EngineServices
{
public const int Version1 = 1;
protected EngineServices() { }
public virtual bool IsTaskInputLoggingEnabled { get { throw null; } }
public virtual int Version { get { throw null; } }
public virtual bool LogsMessagesOfImportance(Microsoft.Build.Framework.MessageImportance importance) { throw null; }
}
public partial class EnvironmentVariableReadEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public EnvironmentVariableReadEventArgs() { }
public EnvironmentVariableReadEventArgs(string environmentVariableName, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { }
public string EnvironmentVariableName { get { throw null; } set { } }
}
public partial class ExternalProjectFinishedEventArgs : Microsoft.Build.Framework.CustomBuildEventArgs
{
protected ExternalProjectFinishedEventArgs() { }
public ExternalProjectFinishedEventArgs(string message, string helpKeyword, string senderName, string projectFile, bool succeeded) { }
public ExternalProjectFinishedEventArgs(string message, string helpKeyword, string senderName, string projectFile, bool succeeded, System.DateTime eventTimestamp) { }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
}
public partial class ExternalProjectStartedEventArgs : Microsoft.Build.Framework.CustomBuildEventArgs
{
protected ExternalProjectStartedEventArgs() { }
public ExternalProjectStartedEventArgs(string message, string helpKeyword, string senderName, string projectFile, string targetNames) { }
public ExternalProjectStartedEventArgs(string message, string helpKeyword, string senderName, string projectFile, string targetNames, System.DateTime eventTimestamp) { }
public string ProjectFile { get { throw null; } }
public string TargetNames { get { throw null; } }
}
public partial interface IBuildEngine
{
int ColumnNumberOfTaskNode { get; }
bool ContinueOnError { get; }
int LineNumberOfTaskNode { get; }
string ProjectFileOfTaskNode { get; }
bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs);
void LogCustomEvent(Microsoft.Build.Framework.CustomBuildEventArgs e);
void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e);
void LogMessageEvent(Microsoft.Build.Framework.BuildMessageEventArgs e);
void LogWarningEvent(Microsoft.Build.Framework.BuildWarningEventArgs e);
}
public partial interface IBuildEngine10 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6, Microsoft.Build.Framework.IBuildEngine7, Microsoft.Build.Framework.IBuildEngine8, Microsoft.Build.Framework.IBuildEngine9
{
Microsoft.Build.Framework.EngineServices EngineServices { get; }
}
public partial interface IBuildEngine2 : Microsoft.Build.Framework.IBuildEngine
{
bool IsRunningMultipleNodes { get; }
bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs, string toolsVersion);
bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion);
}
public partial interface IBuildEngine3 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2
{
Microsoft.Build.Framework.BuildEngineResult BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.Generic.IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs);
void Reacquire();
void Yield();
}
public partial interface IBuildEngine4 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3
{
object GetRegisteredTaskObject(object key, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime);
void RegisterTaskObject(object key, object obj, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection);
object UnregisterTaskObject(object key, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime);
}
public partial interface IBuildEngine5 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4
{
void LogTelemetry(string eventName, System.Collections.Generic.IDictionary<string, string> properties);
}
public partial interface IBuildEngine6 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5
{
System.Collections.Generic.IReadOnlyDictionary<string, string> GetGlobalProperties();
}
public partial interface IBuildEngine7 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6
{
bool AllowFailureWithoutError { get; set; }
}
public partial interface IBuildEngine8 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6, Microsoft.Build.Framework.IBuildEngine7
{
bool ShouldTreatWarningAsError(string warningCode);
}
public partial interface IBuildEngine9 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6, Microsoft.Build.Framework.IBuildEngine7, Microsoft.Build.Framework.IBuildEngine8
{
void ReleaseCores(int coresToRelease);
int RequestCores(int requestedCores);
}
public partial interface ICancelableTask : Microsoft.Build.Framework.ITask
{
void Cancel();
}
public partial interface IEventRedirector
{
void ForwardEvent(Microsoft.Build.Framework.BuildEventArgs buildEvent);
}
public partial interface IEventSource
{
event Microsoft.Build.Framework.AnyEventHandler AnyEventRaised;
event Microsoft.Build.Framework.BuildFinishedEventHandler BuildFinished;
event Microsoft.Build.Framework.BuildStartedEventHandler BuildStarted;
event Microsoft.Build.Framework.CustomBuildEventHandler CustomEventRaised;
event Microsoft.Build.Framework.BuildErrorEventHandler ErrorRaised;
event Microsoft.Build.Framework.BuildMessageEventHandler MessageRaised;
event Microsoft.Build.Framework.ProjectFinishedEventHandler ProjectFinished;
event Microsoft.Build.Framework.ProjectStartedEventHandler ProjectStarted;
event Microsoft.Build.Framework.BuildStatusEventHandler StatusEventRaised;
event Microsoft.Build.Framework.TargetFinishedEventHandler TargetFinished;
event Microsoft.Build.Framework.TargetStartedEventHandler TargetStarted;
event Microsoft.Build.Framework.TaskFinishedEventHandler TaskFinished;
event Microsoft.Build.Framework.TaskStartedEventHandler TaskStarted;
event Microsoft.Build.Framework.BuildWarningEventHandler WarningRaised;
}
public partial interface IEventSource2 : Microsoft.Build.Framework.IEventSource
{
event Microsoft.Build.Framework.TelemetryEventHandler TelemetryLogged;
}
public partial interface IEventSource3 : Microsoft.Build.Framework.IEventSource, Microsoft.Build.Framework.IEventSource2
{
void IncludeEvaluationMetaprojects();
void IncludeEvaluationProfiles();
void IncludeTaskInputs();
}
public partial interface IEventSource4 : Microsoft.Build.Framework.IEventSource, Microsoft.Build.Framework.IEventSource2, Microsoft.Build.Framework.IEventSource3
{
void IncludeEvaluationPropertiesAndItems();
}
public partial interface IForwardingLogger : Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger
{
Microsoft.Build.Framework.IEventRedirector BuildEventRedirector { get; set; }
int NodeId { get; set; }
}
public partial interface IGeneratedTask : Microsoft.Build.Framework.ITask
{
object GetPropertyValue(Microsoft.Build.Framework.TaskPropertyInfo property);
void SetPropertyValue(Microsoft.Build.Framework.TaskPropertyInfo property, object value);
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial interface ILogger
{
string Parameters { get; set; }
Microsoft.Build.Framework.LoggerVerbosity Verbosity { get; set; }
void Initialize(Microsoft.Build.Framework.IEventSource eventSource);
void Shutdown();
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial interface INodeLogger : Microsoft.Build.Framework.ILogger
{
void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount);
}
public partial interface IProjectElement
{
string ElementName { get; }
string OuterElement { get; }
}
public partial interface ITask
{
Microsoft.Build.Framework.IBuildEngine BuildEngine { get; set; }
Microsoft.Build.Framework.ITaskHost HostObject { get; set; }
bool Execute();
}
public partial interface ITaskFactory
{
string FactoryName { get; }
System.Type TaskType { get; }
void CleanupTask(Microsoft.Build.Framework.ITask task);
Microsoft.Build.Framework.ITask CreateTask(Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost);
Microsoft.Build.Framework.TaskPropertyInfo[] GetTaskParameters();
bool Initialize(string taskName, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.TaskPropertyInfo> parameterGroup, string taskBody, Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost);
}
public partial interface ITaskFactory2 : Microsoft.Build.Framework.ITaskFactory
{
Microsoft.Build.Framework.ITask CreateTask(Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost, System.Collections.Generic.IDictionary<string, string> taskIdentityParameters);
bool Initialize(string taskName, System.Collections.Generic.IDictionary<string, string> factoryIdentityParameters, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.TaskPropertyInfo> parameterGroup, string taskBody, Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost);
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
[System.Runtime.InteropServices.GuidAttribute("9049A481-D0E9-414f-8F92-D4F67A0359A6")]
[System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public partial interface ITaskHost
{
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
[System.Runtime.InteropServices.GuidAttribute("8661674F-2148-4F71-A92A-49875511C528")]
public partial interface ITaskItem
{
string ItemSpec { get; set; }
int MetadataCount { get; }
System.Collections.ICollection MetadataNames { get; }
System.Collections.IDictionary CloneCustomMetadata();
void CopyMetadataTo(Microsoft.Build.Framework.ITaskItem destinationItem);
string GetMetadata(string metadataName);
void RemoveMetadata(string metadataName);
void SetMetadata(string metadataName, string metadataValue);
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
[System.Runtime.InteropServices.GuidAttribute("ac6d5a59-f877-461b-88e3-b2f06fce0cb9")]
public partial interface ITaskItem2 : Microsoft.Build.Framework.ITaskItem
{
string EvaluatedIncludeEscaped { get; set; }
System.Collections.IDictionary CloneCustomMetadataEscaped();
string GetMetadataValueEscaped(string metadataName);
void SetMetadataValueLiteral(string metadataName, string metadataValue);
}
public partial class LazyFormattedBuildEventArgs : Microsoft.Build.Framework.BuildEventArgs
{
[System.NonSerializedAttribute]
protected object locker;
protected LazyFormattedBuildEventArgs() { }
public LazyFormattedBuildEventArgs(string message, string helpKeyword, string senderName) { }
public LazyFormattedBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { }
public override string Message { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public sealed partial class LoadInSeparateAppDomainAttribute : System.Attribute
{
public LoadInSeparateAppDomainAttribute() { }
}
public partial class LoggerException : System.Exception
{
public LoggerException() { }
protected LoggerException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public LoggerException(string message) { }
public LoggerException(string message, System.Exception innerException) { }
public LoggerException(string message, System.Exception innerException, string errorCode, string helpKeyword) { }
public string ErrorCode { get { throw null; } }
public string HelpKeyword { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public enum LoggerVerbosity
{
Quiet = 0,
Minimal = 1,
Normal = 2,
Detailed = 3,
Diagnostic = 4,
}
public enum MessageImportance
{
High = 0,
Normal = 1,
Low = 2,
}
public partial class MetaprojectGeneratedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public string metaprojectXml;
public MetaprojectGeneratedEventArgs(string metaprojectXml, string metaprojectPath, string message) { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)]
public sealed partial class OutputAttribute : System.Attribute
{
public OutputAttribute() { }
}
public sealed partial class ProjectEvaluationFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
public ProjectEvaluationFinishedEventArgs() { }
public ProjectEvaluationFinishedEventArgs(string message, params object[] messageArgs) { }
public System.Collections.IEnumerable GlobalProperties { get { throw null; } set { } }
public System.Collections.IEnumerable Items { get { throw null; } set { } }
public Microsoft.Build.Framework.Profiler.ProfilerResult? ProfilerResult { get { throw null; } set { } }
public string ProjectFile { get { throw null; } set { } }
public System.Collections.IEnumerable Properties { get { throw null; } set { } }
}
public partial class ProjectEvaluationStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
public ProjectEvaluationStartedEventArgs() { }
public ProjectEvaluationStartedEventArgs(string message, params object[] messageArgs) { }
public string ProjectFile { get { throw null; } set { } }
}
public partial class ProjectFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected ProjectFinishedEventArgs() { }
public ProjectFinishedEventArgs(string message, string helpKeyword, string projectFile, bool succeeded) { }
public ProjectFinishedEventArgs(string message, string helpKeyword, string projectFile, bool succeeded, System.DateTime eventTimestamp) { }
public override string Message { get { throw null; } }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
}
public delegate void ProjectFinishedEventHandler(object sender, Microsoft.Build.Framework.ProjectFinishedEventArgs e);
public partial class ProjectImportedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public ProjectImportedEventArgs() { }
public ProjectImportedEventArgs(int lineNumber, int columnNumber, string message, params object[] messageArgs) { }
public string ImportedProjectFile { get { throw null; } set { } }
public bool ImportIgnored { get { throw null; } set { } }
public string UnexpandedProject { get { throw null; } set { } }
}
public partial class ProjectStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
public const int InvalidProjectId = -1;
protected ProjectStartedEventArgs() { }
public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext) { }
public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext, System.Collections.Generic.IDictionary<string, string> globalProperties, string toolsVersion) { }
public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext, System.DateTime eventTimestamp) { }
public ProjectStartedEventArgs(string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items) { }
public ProjectStartedEventArgs(string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, System.DateTime eventTimestamp) { }
public System.Collections.Generic.IDictionary<string, string> GlobalProperties { get { throw null; } }
public System.Collections.IEnumerable Items { get { throw null; } }
public override string Message { get { throw null; } }
public Microsoft.Build.Framework.BuildEventContext ParentProjectBuildEventContext { get { throw null; } }
public string ProjectFile { get { throw null; } }
public int ProjectId { get { throw null; } }
public System.Collections.IEnumerable Properties { get { throw null; } }
public string TargetNames { get { throw null; } }
public string ToolsVersion { get { throw null; } }
}
public delegate void ProjectStartedEventHandler(object sender, Microsoft.Build.Framework.ProjectStartedEventArgs e);
public partial class PropertyInitialValueSetEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public PropertyInitialValueSetEventArgs() { }
public PropertyInitialValueSetEventArgs(string propertyName, string propertyValue, string propertySource, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { }
public string PropertyName { get { throw null; } set { } }
public string PropertySource { get { throw null; } set { } }
public string PropertyValue { get { throw null; } set { } }
}
public partial class PropertyReassignmentEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public PropertyReassignmentEventArgs() { }
public PropertyReassignmentEventArgs(string propertyName, string previousValue, string newValue, string location, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { }
public string Location { get { throw null; } set { } }
public override string Message { get { throw null; } }
public string NewValue { get { throw null; } set { } }
public string PreviousValue { get { throw null; } set { } }
public string PropertyName { get { throw null; } set { } }
}
public enum RegisteredTaskObjectLifetime
{
Build = 0,
AppDomain = 1,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)]
public sealed partial class RequiredAttribute : System.Attribute
{
public RequiredAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
public sealed partial class RequiredRuntimeAttribute : System.Attribute
{
public RequiredRuntimeAttribute(string runtimeVersion) { }
public string RuntimeVersion { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
public sealed partial class RunInMTAAttribute : System.Attribute
{
public RunInMTAAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
public sealed partial class RunInSTAAttribute : System.Attribute
{
public RunInSTAAttribute() { }
}
public abstract partial class SdkLogger
{
protected SdkLogger() { }
public abstract void LogMessage(string message, Microsoft.Build.Framework.MessageImportance messageImportance = Microsoft.Build.Framework.MessageImportance.Low);
}
public sealed partial class SdkReference : System.IEquatable<Microsoft.Build.Framework.SdkReference>
{
public SdkReference(string name, string version, string minimumVersion) { }
public string MinimumVersion { get { throw null; } }
public string Name { get { throw null; } }
public string Version { get { throw null; } }
public bool Equals(Microsoft.Build.Framework.SdkReference other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string sdk, out Microsoft.Build.Framework.SdkReference sdkReference) { throw null; }
}
public abstract partial class SdkResolver
{
protected SdkResolver() { }
public abstract string Name { get; }
public abstract int Priority { get; }
public abstract Microsoft.Build.Framework.SdkResult Resolve(Microsoft.Build.Framework.SdkReference sdkReference, Microsoft.Build.Framework.SdkResolverContext resolverContext, Microsoft.Build.Framework.SdkResultFactory factory);
}
public abstract partial class SdkResolverContext
{
protected SdkResolverContext() { }
public virtual bool Interactive { get { throw null; } protected set { } }
public virtual bool IsRunningInVisualStudio { get { throw null; } protected set { } }
public virtual Microsoft.Build.Framework.SdkLogger Logger { get { throw null; } protected set { } }
public virtual System.Version MSBuildVersion { get { throw null; } protected set { } }
public virtual string ProjectFilePath { get { throw null; } protected set { } }
public virtual string SolutionFilePath { get { throw null; } protected set { } }
public virtual object State { get { throw null; } set { } }
}
public abstract partial class SdkResult
{
protected SdkResult() { }
public virtual System.Collections.Generic.IList<string> AdditionalPaths { get { throw null; } set { } }
public virtual System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.SdkResultItem> ItemsToAdd { get { throw null; } protected set { } }
public virtual string Path { get { throw null; } protected set { } }
public virtual System.Collections.Generic.IDictionary<string, string> PropertiesToAdd { get { throw null; } protected set { } }
public virtual Microsoft.Build.Framework.SdkReference SdkReference { get { throw null; } protected set { } }
public virtual bool Success { get { throw null; } protected set { } }
public virtual string Version { get { throw null; } protected set { } }
}
public abstract partial class SdkResultFactory
{
protected SdkResultFactory() { }
public abstract Microsoft.Build.Framework.SdkResult IndicateFailure(System.Collections.Generic.IEnumerable<string> errors, System.Collections.Generic.IEnumerable<string> warnings = null);
public virtual Microsoft.Build.Framework.SdkResult IndicateSuccess(System.Collections.Generic.IEnumerable<string> paths, string version, System.Collections.Generic.IDictionary<string, string> propertiesToAdd = null, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.SdkResultItem> itemsToAdd = null, System.Collections.Generic.IEnumerable<string> warnings = null) { throw null; }
public virtual Microsoft.Build.Framework.SdkResult IndicateSuccess(string path, string version, System.Collections.Generic.IDictionary<string, string> propertiesToAdd, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.SdkResultItem> itemsToAdd, System.Collections.Generic.IEnumerable<string> warnings = null) { throw null; }
public abstract Microsoft.Build.Framework.SdkResult IndicateSuccess(string path, string version, System.Collections.Generic.IEnumerable<string> warnings = null);
}
public partial class SdkResultItem
{
public SdkResultItem() { }
public SdkResultItem(string itemSpec, System.Collections.Generic.Dictionary<string, string> metadata) { }
public string ItemSpec { get { throw null; } set { } }
public System.Collections.Generic.Dictionary<string, string> Metadata { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
public enum TargetBuiltReason
{
None = 0,
BeforeTargets = 1,
DependsOn = 2,
AfterTargets = 3,
}
public partial class TargetFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TargetFinishedEventArgs() { }
public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded) { }
public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded, System.Collections.IEnumerable targetOutputs) { }
public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded, System.DateTime eventTimestamp, System.Collections.IEnumerable targetOutputs) { }
public override string Message { get { throw null; } }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
public string TargetFile { get { throw null; } }
public string TargetName { get { throw null; } }
public System.Collections.IEnumerable TargetOutputs { get { throw null; } set { } }
}
public delegate void TargetFinishedEventHandler(object sender, Microsoft.Build.Framework.TargetFinishedEventArgs e);
public partial class TargetSkippedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public TargetSkippedEventArgs() { }
public TargetSkippedEventArgs(string message, params object[] messageArgs) { }
public Microsoft.Build.Framework.TargetBuiltReason BuildReason { get { throw null; } set { } }
public string Condition { get { throw null; } set { } }
public string EvaluatedCondition { get { throw null; } set { } }
public override string Message { get { throw null; } }
public Microsoft.Build.Framework.BuildEventContext OriginalBuildEventContext { get { throw null; } set { } }
public bool OriginallySucceeded { get { throw null; } set { } }
public string ParentTarget { get { throw null; } set { } }
public Microsoft.Build.Framework.TargetSkipReason SkipReason { get { throw null; } set { } }
public string TargetFile { get { throw null; } set { } }
public string TargetName { get { throw null; } set { } }
}
public enum TargetSkipReason
{
None = 0,
PreviouslyBuiltSuccessfully = 1,
PreviouslyBuiltUnsuccessfully = 2,
OutputsUpToDate = 3,
ConditionWasFalse = 4,
}
public partial class TargetStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TargetStartedEventArgs() { }
public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile) { }
public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, string parentTarget, Microsoft.Build.Framework.TargetBuiltReason buildReason, System.DateTime eventTimestamp) { }
public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, string parentTarget, System.DateTime eventTimestamp) { }
public Microsoft.Build.Framework.TargetBuiltReason BuildReason { get { throw null; } }
public override string Message { get { throw null; } }
public string ParentTarget { get { throw null; } }
public string ProjectFile { get { throw null; } }
public string TargetFile { get { throw null; } }
public string TargetName { get { throw null; } }
}
public delegate void TargetStartedEventHandler(object sender, Microsoft.Build.Framework.TargetStartedEventArgs e);
public partial class TaskCommandLineEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
protected TaskCommandLineEventArgs() { }
public TaskCommandLineEventArgs(string commandLine, string taskName, Microsoft.Build.Framework.MessageImportance importance) { }
public TaskCommandLineEventArgs(string commandLine, string taskName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { }
public string CommandLine { get { throw null; } }
public string TaskName { get { throw null; } }
}
public partial class TaskFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TaskFinishedEventArgs() { }
public TaskFinishedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, bool succeeded) { }
public TaskFinishedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, bool succeeded, System.DateTime eventTimestamp) { }
public override string Message { get { throw null; } }
public string ProjectFile { get { throw null; } }
public bool Succeeded { get { throw null; } }
public string TaskFile { get { throw null; } }
public string TaskName { get { throw null; } }
}
public delegate void TaskFinishedEventHandler(object sender, Microsoft.Build.Framework.TaskFinishedEventArgs e);
public partial class TaskParameterEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public TaskParameterEventArgs(Microsoft.Build.Framework.TaskParameterMessageKind kind, string itemType, System.Collections.IList items, bool logItemMetadata, System.DateTime eventTimestamp) { }
public System.Collections.IList Items { get { throw null; } }
public string ItemType { get { throw null; } }
public Microsoft.Build.Framework.TaskParameterMessageKind Kind { get { throw null; } }
public bool LogItemMetadata { get { throw null; } }
public override string Message { get { throw null; } }
}
public enum TaskParameterMessageKind
{
TaskInput = 0,
TaskOutput = 1,
AddItem = 2,
RemoveItem = 3,
SkippedTargetInputs = 4,
SkippedTargetOutputs = 5,
}
public partial class TaskPropertyInfo
{
public TaskPropertyInfo(string name, System.Type typeOfParameter, bool output, bool required) { }
public bool Log { get { throw null; } set { } }
public bool LogItemMetadata { get { throw null; } set { } }
public string Name { get { throw null; } }
public bool Output { get { throw null; } }
public System.Type PropertyType { get { throw null; } }
public bool Required { get { throw null; } }
}
public partial class TaskStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs
{
protected TaskStartedEventArgs() { }
public TaskStartedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName) { }
public TaskStartedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, System.DateTime eventTimestamp) { }
public int ColumnNumber { get { throw null; } }
public int LineNumber { get { throw null; } }
public override string Message { get { throw null; } }
public string ProjectFile { get { throw null; } }
public string TaskFile { get { throw null; } }
public string TaskName { get { throw null; } }
}
public delegate void TaskStartedEventHandler(object sender, Microsoft.Build.Framework.TaskStartedEventArgs e);
public sealed partial class TelemetryEventArgs : Microsoft.Build.Framework.BuildEventArgs
{
public TelemetryEventArgs() { }
public string EventName { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Properties { get { throw null; } set { } }
}
public delegate void TelemetryEventHandler(object sender, Microsoft.Build.Framework.TelemetryEventArgs e);
public partial class UninitializedPropertyReadEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs
{
public UninitializedPropertyReadEventArgs() { }
public UninitializedPropertyReadEventArgs(string propertyName, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { }
public string PropertyName { get { throw null; } set { } }
}
}
namespace Microsoft.Build.Framework.Profiler
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct EvaluationLocation
{
private object _dummy;
private int _dummyPrimitive;
public EvaluationLocation(Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, int? line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null; }
public EvaluationLocation(long id, long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, int? line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null; }
public EvaluationLocation(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, int? line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null; }
public string ElementDescription { get { throw null; } }
public string ElementName { get { throw null; } }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation EmptyLocation { get { throw null; } }
public Microsoft.Build.Framework.Profiler.EvaluationPass EvaluationPass { get { throw null; } }
public string EvaluationPassDescription { get { throw null; } }
public string File { get { throw null; } }
public long Id { get { throw null; } }
public bool IsEvaluationPass { get { throw null; } }
public Microsoft.Build.Framework.Profiler.EvaluationLocationKind Kind { get { throw null; } }
public int? Line { get { throw null; } }
public long? ParentId { get { throw null; } }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForAggregatedGlob() { throw null; }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForCondition(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, int? line, string condition) { throw null; }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForGlob(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, int? line, string globDescription) { throw null; }
public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForProject(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, int? line, Microsoft.Build.Framework.IProjectElement element) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithEvaluationPass(Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string passDescription = null) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFile(string file) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFileLineAndCondition(string file, int? line, string condition) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFileLineAndElement(string file, int? line, Microsoft.Build.Framework.IProjectElement element) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithGlob(string globDescription) { throw null; }
public Microsoft.Build.Framework.Profiler.EvaluationLocation WithParentId(long? parentId) { throw null; }
}
public enum EvaluationLocationKind : byte
{
Element = (byte)0,
Condition = (byte)1,
Glob = (byte)2,
}
public enum EvaluationPass : byte
{
TotalEvaluation = (byte)0,
TotalGlobbing = (byte)1,
InitialProperties = (byte)2,
Properties = (byte)3,
ItemDefinitionGroups = (byte)4,
Items = (byte)5,
LazyItems = (byte)6,
UsingTasks = (byte)7,
Targets = (byte)8,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ProfiledLocation
{
private int _dummyPrimitive;
public ProfiledLocation(System.TimeSpan inclusiveTime, System.TimeSpan exclusiveTime, int numberOfHits) { throw null; }
public System.TimeSpan ExclusiveTime { get { throw null; } }
public System.TimeSpan InclusiveTime { get { throw null; } }
public int NumberOfHits { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ProfilerResult
{
private object _dummy;
public ProfilerResult(System.Collections.Generic.IDictionary<Microsoft.Build.Framework.Profiler.EvaluationLocation, Microsoft.Build.Framework.Profiler.ProfiledLocation> profiledLocations) { throw null; }
public System.Collections.Generic.IReadOnlyDictionary<Microsoft.Build.Framework.Profiler.EvaluationLocation, Microsoft.Build.Framework.Profiler.ProfiledLocation> ProfiledLocations { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using FilesToDatabaseImporter.Annotations;
using FilesToDatabaseImporter.Helpers;
using FilesToDatabaseImporter.Interfaces;
namespace FilesToDatabaseImporter.ViewModels
{
public class SqlServerViewModel : INotifyPropertyChanged, IDataErrorInfo
{
private string _datasource;
public string Datasource
{
get { return _datasource; }
set
{
if (value == _datasource) return;
_datasource = value;
DatabaseHelper.SqlConnectionStringBuilder.DataSource = _datasource;
OnPropertyChanged();
}
}
private string _username;
public string Username
{
get { return _username; }
set
{
if (value == _username) return;
_username = value;
if (!IntegratedSecurity)
{
DatabaseHelper.SqlConnectionStringBuilder.UserID = _username;
}
else
{
DatabaseHelper.SqlConnectionStringBuilder.UserID = null;
}
OnPropertyChanged();
}
}
private string _password;
public string Password
{
get { return _password; }
set
{
if (value == _password) return;
_password = value;
if (!IntegratedSecurity)
{
DatabaseHelper.SqlConnectionStringBuilder.Password = _password;
}
else
{
DatabaseHelper.SqlConnectionStringBuilder.Password = null;
}
OnPropertyChanged();
}
}
private string _database;
public string Database
{
get { return _database; }
set
{
if (value == _database) return;
_database = value;
DatabaseHelper.SqlConnectionStringBuilder.InitialCatalog = _database;
OnPropertyChanged();
}
}
private string _table;
public string Table
{
get { return _table; }
set
{
if (value == _table) return;
_table = value;
DatabaseHelper.SetTable(_table);
OnPropertyChanged();
}
}
private bool _integratedSecurity;
public bool IntegratedSecurity
{
get { return _integratedSecurity; }
set
{
if (value.Equals(_integratedSecurity)) return;
_integratedSecurity = value;
DatabaseHelper.SqlConnectionStringBuilder.IntegratedSecurity = _integratedSecurity;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Username"));
PropertyChanged(this, new PropertyChangedEventArgs("Password"));
}
OnPropertyChanged();
}
}
private IDatabaseHelper _databaseHelper;
public IDatabaseHelper DatabaseHelper
{
get { return _databaseHelper; }
set { _databaseHelper = value; }
}
public SqlServerViewModel(IDatabaseHelper databaseHelper = null)
{
_databaseHelper = databaseHelper;
IntegratedSecurity = true;
Database = "FilesToDatabaseImporter";
Table = "Imports";
}
public SqlServerViewModel() : this(new DatabaseHelper())
{
}
#region IDataErrorInfo
private bool _canSave;
public bool CanSave
{
get { return _canSave; }
set
{
if (value.Equals(_canSave)) return;
_canSave = value;
OnPropertyChanged();
}
}
private readonly Dictionary<string, string> _errors = new Dictionary<string, string>();
string IDataErrorInfo.this[string propertyName]
{
get
{
var error = "";
if (propertyName == "Datasource")
{
if (string.IsNullOrEmpty(Datasource))
{
error = "Datasource is mandatory";
}
}
if (propertyName == "Database")
{
if (string.IsNullOrEmpty(Database))
{
error = "Database is mandatory";
}
}
if (propertyName == "Username")
{
if (string.IsNullOrEmpty(Username) && !IntegratedSecurity)
{
error = "Username is mandatory when SQL Authentication is used";
}
}
if (propertyName == "Password")
{
if (string.IsNullOrEmpty(Password) && !IntegratedSecurity)
{
error = "Password is mandatory when SQL Authentication is used";
}
}
if (propertyName == "Table")
{
if (string.IsNullOrEmpty(Table))
{
error = "Table is mandatory";
}
}
if (_errors.ContainsKey(propertyName) && string.IsNullOrEmpty(error))
{
_errors.Remove(propertyName);
}
if (!_errors.ContainsKey(propertyName) && !string.IsNullOrEmpty(error))
{
_errors[propertyName] = error;
}
CanSave = !_errors.Any();
return error;
}
}
public string Error
{
get { throw new NotImplementedException(); }
}
#endregion
#region INPC
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
|
/****************************************************************************
Copyright (c) 2013-2015 scutgame.com
http://www.scutgame.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.Data;
using ZyGames.Framework.Common;
using ZyGames.Framework.Game.Service;
using ZyGames.Tianjiexing.Lang;
using ZyGames.Tianjiexing.Model;
using ZyGames.Tianjiexing.BLL.Combat;
using ZyGames.Tianjiexing.BLL.Base;
using ZyGames.Tianjiexing.Model.Config;
namespace ZyGames.Tianjiexing.BLL.Action
{
/// <summary>
/// 6103_公会Boss战欲火重生接口
/// </summary>
public class Action6103 : BaseAction
{
private const int GoldNum = 5;
private const int MaxNum = 5;
private int Ops;
private double _reliveInspirePercent;
private int _activeId;
public Action6103(ZyGames.Framework.Game.Contract.HttpGet httpGet)
: base(ActionIDDefine.Cst_Action6103, httpGet)
{
}
public override void BuildPacket()
{
PushIntoStack((_reliveInspirePercent * 100).ToInt());
}
public override bool GetUrlElement()
{
if (httpGet.GetInt("Ops", ref Ops, 1, 2)
&& httpGet.GetInt("ActiveId", ref _activeId))
{
return true;
}
return false;
}
public override bool TakeAction()
{
if (!string.IsNullOrEmpty(ContextUser.MercenariesID))
{
if (CombatHelper.GuildBossKill(ContextUser.MercenariesID))
{
ErrorCode = LanguageManager.GetLang().ErrorCode;
ErrorInfo = LanguageManager.GetLang().St5405_BossKilled;
return false;
}
GuildBossCombat bossCombat = new GuildBossCombat(ContextUser.MercenariesID);
UserGuild guild = bossCombat.UserGuild;
if (guild != null)
{
if (!VipHelper.GetVipOpenFun(ContextUser.VipLv, ExpandType.BossChongSheng))
{
ErrorCode = LanguageManager.GetLang().ErrorCode;
ErrorInfo = LanguageManager.GetLang().St_VipNotEnoughNotFuntion;
return false;
}
CombatStatus combatStatus = guild.CombatStatus;
if (combatStatus != CombatStatus.Wait && combatStatus != CombatStatus.Combat)
{
ErrorCode = LanguageManager.GetLang().ErrorCode;
ErrorInfo = LanguageManager.GetLang().St5402_CombatNoStart;
return false;
}
ErrorCode = Ops;
BossUser bossUser = bossCombat.GetCombatUser(Uid);
if (bossUser != null && !bossUser.IsRelive)
{
ErrorCode = LanguageManager.GetLang().ErrorCode;
ErrorInfo = LanguageManager.GetLang().St5403_IsLive;
return false;
}
if (bossUser != null && bossUser.ReliveNum >= MaxNum)
{
ErrorCode = LanguageManager.GetLang().ErrorCode;
ErrorInfo = LanguageManager.GetLang().St5403_IsReLiveMaxNum;
return false;
}
int goldNum = GoldNum * (bossUser.ReliveNum + 1);
if (Ops == 1)
{
ErrorInfo = string.Format(LanguageManager.GetLang().St5403_CombatGoldTip, goldNum);
}
else if (Ops == 2)
{
if (ContextUser.GoldNum < goldNum)
{
ErrorCode = LanguageManager.GetLang().ErrorCode;
ErrorInfo = LanguageManager.GetLang().St_GoldNotEnough;
return false;
}
if (bossUser != null && bossUser.IsRelive)
{
if (bossUser.IsRelive)
{
ContextUser.UseGold = MathUtils.Addition(ContextUser.UseGold, goldNum, int.MaxValue);
//ContextUser.Update();
bossUser.IsRelive = false;
bossUser.ReliveBeginDate = DateTime.MinValue;
bossUser.ReliveInspirePercent = MathUtils.Addition(bossUser.ReliveInspirePercent, CountryCombat.InspireIncrease, 1);
_reliveInspirePercent = bossUser.ReliveInspirePercent;
bossUser.ReliveNum++;
}
}
}
}
}
return true;
}
}
} |
//===============================================================================
// TinyIoC
//
// An easy to use, hassle free, Inversion of Control Container for small projects
// and beginners alike.
//
// https://github.com/grumpydev/TinyIoC
//===============================================================================
// Copyright © Steven Robbins. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
#region Preprocessor Directives
// Uncomment this line if you want the container to automatically
// register the TinyMessenger messenger/event aggregator
//#define TINYMESSENGER
// PCL profile supports System.Linq.Expressions
// PCL profile does not support compiling expressions (due to restriction in MonoTouch)
// PCL profile does not support getting all assemblies from the AppDomain object
// PCL profile supports GetConstructors on unbound generic types
// PCL profile supports GetParameters on open generics
// PCL profile supports resolving open generics
// MonoTouch does not support compiled exceptions due to the restriction on Reflection.Emit
// (http://docs.xamarin.com/guides/ios/advanced_topics/limitations#No_Dynamic_Code_Generation)
// Note: This restriction is not enforced on the emulator (at the moment), but on the device.
// Note: Comment out the next line to compile a version that can be used with MonoTouch.
#define COMPILED_EXPRESSIONS
#if MONO_TOUCH
#undef COMPILED_EXPRESSIONS
#endif
#endregion
namespace TinyIoC
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
using System.Threading;
#region SafeDictionary
public class SafeDictionary<TKey, TValue> : IDisposable
{
private readonly object _Padlock = new object();
private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
set
{
lock (_Padlock)
{
TValue current;
if (_Dictionary.TryGetValue(key, out current))
{
var disposable = current as IDisposable;
if (disposable != null)
disposable.Dispose();
}
_Dictionary[key] = value;
}
}
}
public bool TryGetValue(TKey key, out TValue value)
{
lock (_Padlock)
{
return _Dictionary.TryGetValue(key, out value);
}
}
public bool Remove(TKey key)
{
lock (_Padlock)
{
return _Dictionary.Remove(key);
}
}
public void Clear()
{
lock (_Padlock)
{
_Dictionary.Clear();
}
}
public IEnumerable<TKey> Keys
{
get
{
return _Dictionary.Keys;
}
}
#region IDisposable Members
public void Dispose()
{
lock (_Padlock)
{
var disposableItems = from item in _Dictionary.Values
where item is IDisposable
select item as IDisposable;
foreach (var item in disposableItems)
{
item.Dispose();
}
}
GC.SuppressFinalize(this);
}
#endregion
}
#endregion
#region Extensions
public static class AssemblyExtensions
{
public static Type[] SafeGetTypes(this Assembly assembly)
{
Type[] assemblies;
try
{
assemblies = assembly.GetTypes();
}
catch (System.IO.FileNotFoundException)
{
assemblies = new Type[] { };
}
catch (NotSupportedException)
{
assemblies = new Type[] { };
}
catch (ReflectionTypeLoadException e)
{
assemblies = e.Types.Where(t => t != null).ToArray();
}
return assemblies;
}
}
public static class TypeExtensions
{
private static SafeDictionary<GenericMethodCacheKey, MethodInfo> _genericMethodCache;
static TypeExtensions()
{
_genericMethodCache = new SafeDictionary<GenericMethodCacheKey, MethodInfo>();
}
/// <summary>
/// Gets a generic method from a type given the method name, binding flags, generic types and parameter types
/// </summary>
/// <param name="sourceType">Source type</param>
/// <param name="bindingFlags">Binding flags</param>
/// <param name="methodName">Name of the method</param>
/// <param name="genericTypes">Generic types to use to make the method generic</param>
/// <param name="parameterTypes">Method parameters</param>
/// <returns>MethodInfo or null if no matches found</returns>
/// <exception cref="System.Reflection.AmbiguousMatchException"/>
/// <exception cref="System.ArgumentException"/>
public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)
{
MethodInfo method;
var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes);
// Shouldn't need any additional locking
// we don't care if we do the method info generation
// more than once before it gets cached.
if (!_genericMethodCache.TryGetValue(cacheKey, out method))
{
method = GetMethod(sourceType, bindingFlags, methodName, genericTypes, parameterTypes);
_genericMethodCache[cacheKey] = method;
}
return method;
}
private static MethodInfo GetMethod(Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)
{
var methods =
sourceType.GetMethods(bindingFlags).Where(
mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where(
mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length).
Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(
mi => mi.MakeGenericMethod(genericTypes)).Where(
mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList();
if (methods.Count > 1)
{
throw new AmbiguousMatchException();
}
return methods.FirstOrDefault();
}
private sealed class GenericMethodCacheKey
{
private readonly Type _sourceType;
private readonly string _methodName;
private readonly Type[] _genericTypes;
private readonly Type[] _parameterTypes;
private readonly int _hashCode;
public GenericMethodCacheKey(Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes)
{
_sourceType = sourceType;
_methodName = methodName;
_genericTypes = genericTypes;
_parameterTypes = parameterTypes;
_hashCode = GenerateHashCode();
}
public override bool Equals(object obj)
{
var cacheKey = obj as GenericMethodCacheKey;
if (cacheKey == null)
return false;
if (_sourceType != cacheKey._sourceType)
return false;
if (!String.Equals(_methodName, cacheKey._methodName, StringComparison.Ordinal))
return false;
if (_genericTypes.Length != cacheKey._genericTypes.Length)
return false;
if (_parameterTypes.Length != cacheKey._parameterTypes.Length)
return false;
for (int i = 0; i < _genericTypes.Length; ++i)
{
if (_genericTypes[i] != cacheKey._genericTypes[i])
return false;
}
for (int i = 0; i < _parameterTypes.Length; ++i)
{
if (_parameterTypes[i] != cacheKey._parameterTypes[i])
return false;
}
return true;
}
public override int GetHashCode()
{
return _hashCode;
}
private int GenerateHashCode()
{
unchecked
{
var result = _sourceType.GetHashCode();
result = (result * 397) ^ _methodName.GetHashCode();
for (int i = 0; i < _genericTypes.Length; ++i)
{
result = (result * 397) ^ _genericTypes[i].GetHashCode();
}
for (int i = 0; i < _parameterTypes.Length; ++i)
{
result = (result * 397) ^ _parameterTypes[i].GetHashCode();
}
return result;
}
}
}
}
#endregion
#region TinyIoC Exception Types
public class TinyIoCResolutionException : Exception
{
private const string ERROR_TEXT = "Unable to resolve type: {0}";
public TinyIoCResolutionException(Type type)
: base(String.Format(ERROR_TEXT, type.FullName))
{
}
public TinyIoCResolutionException(Type type, Exception innerException)
: base(String.Format(ERROR_TEXT, type.FullName), innerException)
{
}
}
public class TinyIoCRegistrationTypeException : Exception
{
private const string REGISTER_ERROR_TEXT = "Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}.";
public TinyIoCRegistrationTypeException(Type type, string factory)
: base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory))
{
}
public TinyIoCRegistrationTypeException(Type type, string factory, Exception innerException)
: base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory), innerException)
{
}
}
public class TinyIoCRegistrationException : Exception
{
private const string CONVERT_ERROR_TEXT = "Cannot convert current registration of {0} to {1}";
private const string GENERIC_CONSTRAINT_ERROR_TEXT = "Type {1} is not valid for a registration of type {0}";
public TinyIoCRegistrationException(Type type, string method)
: base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method))
{
}
public TinyIoCRegistrationException(Type type, string method, Exception innerException)
: base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method), innerException)
{
}
public TinyIoCRegistrationException(Type registerType, Type implementationType)
: base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName))
{
}
public TinyIoCRegistrationException(Type registerType, Type implementationType, Exception innerException)
: base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName), innerException)
{
}
}
public class TinyIoCWeakReferenceException : Exception
{
private const string ERROR_TEXT = "Unable to instantiate {0} - referenced object has been reclaimed";
public TinyIoCWeakReferenceException(Type type)
: base(String.Format(ERROR_TEXT, type.FullName))
{
}
public TinyIoCWeakReferenceException(Type type, Exception innerException)
: base(String.Format(ERROR_TEXT, type.FullName), innerException)
{
}
}
public class TinyIoCConstructorResolutionException : Exception
{
private const string ERROR_TEXT = "Unable to resolve constructor for {0} using provided Expression.";
public TinyIoCConstructorResolutionException(Type type)
: base(String.Format(ERROR_TEXT, type.FullName))
{
}
public TinyIoCConstructorResolutionException(Type type, Exception innerException)
: base(String.Format(ERROR_TEXT, type.FullName), innerException)
{
}
public TinyIoCConstructorResolutionException(string message, Exception innerException)
: base(message, innerException)
{
}
public TinyIoCConstructorResolutionException(string message)
: base(message)
{
}
}
public class TinyIoCAutoRegistrationException : Exception
{
private const string ERROR_TEXT = "Duplicate implementation of type {0} found ({1}).";
public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types)
: base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)))
{
}
public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types, Exception innerException)
: base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)), innerException)
{
}
private static string GetTypesString(IEnumerable<Type> types)
{
var typeNames = from type in types
select type.FullName;
return string.Join(",", typeNames.ToArray());
}
}
#endregion
#region Public Setup / Settings Classes
/// <summary>
/// Name/Value pairs for specifying "user" parameters when resolving
/// </summary>
public sealed class NamedParameterOverloads : Dictionary<string, object>
{
public static NamedParameterOverloads FromIDictionary(IDictionary<string, object> data)
{
return data as NamedParameterOverloads ?? new NamedParameterOverloads(data);
}
public NamedParameterOverloads()
{
}
public NamedParameterOverloads(IDictionary<string, object> data)
: base(data)
{
}
private static readonly NamedParameterOverloads _Default = new NamedParameterOverloads();
public static NamedParameterOverloads Default
{
get
{
return _Default;
}
}
}
public enum UnregisteredResolutionActions
{
/// <summary>
/// Attempt to resolve type, even if the type isn't registered.
///
/// Registered types/options will always take precedence.
/// </summary>
AttemptResolve,
/// <summary>
/// Fail resolution if type not explicitly registered
/// </summary>
Fail,
/// <summary>
/// Attempt to resolve unregistered type if requested type is generic
/// and no registration exists for the specific generic parameters used.
///
/// Registered types/options will always take precedence.
/// </summary>
GenericsOnly
}
public enum NamedResolutionFailureActions
{
AttemptUnnamedResolution,
Fail
}
/// <summary>
/// Resolution settings
/// </summary>
public sealed class ResolveOptions
{
private static readonly ResolveOptions _Default = new ResolveOptions();
private static readonly ResolveOptions _FailUnregisteredAndNameNotFound = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };
private static readonly ResolveOptions _FailUnregisteredOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.AttemptUnnamedResolution, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };
private static readonly ResolveOptions _FailNameNotFoundOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve };
private UnregisteredResolutionActions _UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve;
public UnregisteredResolutionActions UnregisteredResolutionAction
{
get { return _UnregisteredResolutionAction; }
set { _UnregisteredResolutionAction = value; }
}
private NamedResolutionFailureActions _NamedResolutionFailureAction = NamedResolutionFailureActions.Fail;
public NamedResolutionFailureActions NamedResolutionFailureAction
{
get { return _NamedResolutionFailureAction; }
set { _NamedResolutionFailureAction = value; }
}
/// <summary>
/// Gets the default options (attempt resolution of unregistered types, fail on named resolution if name not found)
/// </summary>
public static ResolveOptions Default
{
get
{
return _Default;
}
}
/// <summary>
/// Preconfigured option for attempting resolution of unregistered types and failing on named resolution if name not found
/// </summary>
public static ResolveOptions FailNameNotFoundOnly
{
get
{
return _FailNameNotFoundOnly;
}
}
/// <summary>
/// Preconfigured option for failing on resolving unregistered types and on named resolution if name not found
/// </summary>
public static ResolveOptions FailUnregisteredAndNameNotFound
{
get
{
return _FailUnregisteredAndNameNotFound;
}
}
/// <summary>
/// Preconfigured option for failing on resolving unregistered types, but attempting unnamed resolution if name not found
/// </summary>
public static ResolveOptions FailUnregisteredOnly
{
get
{
return _FailUnregisteredOnly;
}
}
}
#endregion
public sealed partial class TinyIoCContainer : IDisposable
{
private sealed class MethodAccessException : Exception
{
}
#region "Fluent" API
/// <summary>
/// Registration options for "fluent" API
/// </summary>
public sealed class RegisterOptions
{
private TinyIoCContainer _Container;
private TypeRegistration _Registration;
public RegisterOptions(TinyIoCContainer container, TypeRegistration registration)
{
_Container = container;
_Registration = registration;
}
/// <summary>
/// Make registration a singleton (single instance) if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions AsSingleton()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "singleton");
return _Container.AddUpdateRegistration(_Registration, currentFactory.SingletonVariant);
}
/// <summary>
/// Make registration multi-instance if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions AsMultiInstance()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "multi-instance");
return _Container.AddUpdateRegistration(_Registration, currentFactory.MultiInstanceVariant);
}
/// <summary>
/// Make registration hold a weak reference if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions WithWeakReference()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "weak reference");
return _Container.AddUpdateRegistration(_Registration, currentFactory.WeakReferenceVariant);
}
/// <summary>
/// Make registration hold a strong reference if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions WithStrongReference()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "strong reference");
return _Container.AddUpdateRegistration(_Registration, currentFactory.StrongReferenceVariant);
}
public RegisterOptions UsingConstructor<RegisterType>(Expression<Func<RegisterType>> constructor)
{
var lambda = constructor as LambdaExpression;
if (lambda == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
var newExpression = lambda.Body as NewExpression;
if (newExpression == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
var constructorInfo = newExpression.Constructor;
if (constructorInfo == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
currentFactory.SetConstructor(constructorInfo);
return this;
}
/// <summary>
/// Switches to a custom lifetime manager factory if possible.
///
/// Usually used for RegisterOptions "To*" extension methods such as the ASP.Net per-request one.
/// </summary>
/// <param name="instance">RegisterOptions instance</param>
/// <param name="lifetimeProvider">Custom lifetime manager</param>
/// <param name="errorString">Error string to display if switch fails</param>
/// <returns>RegisterOptions</returns>
public static RegisterOptions ToCustomLifetimeManager(RegisterOptions instance, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)
{
if (instance == null)
throw new ArgumentNullException("instance", "instance is null.");
if (lifetimeProvider == null)
throw new ArgumentNullException("lifetimeProvider", "lifetimeProvider is null.");
if (String.IsNullOrEmpty(errorString))
throw new ArgumentException("errorString is null or empty.", "errorString");
var currentFactory = instance._Container.GetCurrentFactory(instance._Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(instance._Registration.Type, errorString);
return instance._Container.AddUpdateRegistration(instance._Registration, currentFactory.GetCustomObjectLifetimeVariant(lifetimeProvider, errorString));
}
}
/// <summary>
/// Registration options for "fluent" API when registering multiple implementations
/// </summary>
public sealed class MultiRegisterOptions
{
private IEnumerable<RegisterOptions> _RegisterOptions;
/// <summary>
/// Initializes a new instance of the MultiRegisterOptions class.
/// </summary>
/// <param name="registerOptions">Registration options</param>
public MultiRegisterOptions(IEnumerable<RegisterOptions> registerOptions)
{
_RegisterOptions = registerOptions;
}
/// <summary>
/// Make registration a singleton (single instance) if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public MultiRegisterOptions AsSingleton()
{
_RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsSingleton());
return this;
}
/// <summary>
/// Make registration multi-instance if possible
/// </summary>
/// <returns>MultiRegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public MultiRegisterOptions AsMultiInstance()
{
_RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance());
return this;
}
private IEnumerable<RegisterOptions> ExecuteOnAllRegisterOptions(Func<RegisterOptions, RegisterOptions> action)
{
var newRegisterOptions = new List<RegisterOptions>();
foreach (var registerOption in _RegisterOptions)
{
newRegisterOptions.Add(action(registerOption));
}
return newRegisterOptions;
}
}
#endregion
#region Public API
#region Child Containers
public TinyIoCContainer GetChildContainer()
{
return new TinyIoCContainer(this);
}
#endregion
#region Registration
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
///
/// If more than one class implements an interface then only one implementation will be registered
/// although no error will be thrown.
/// </summary>
public void AutoRegister()
{
AutoRegisterInternal(new Assembly[] {this.GetType().Assembly()}, true, null);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
/// Types will only be registered if they pass the supplied registration predicate.
///
/// If more than one class implements an interface then only one implementation will be registered
/// although no error will be thrown.
/// </summary>
/// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param>
public void AutoRegister(Func<Type, bool> registrationPredicate)
{
AutoRegisterInternal(new Assembly[] { this.GetType().Assembly()}, true, registrationPredicate);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
/// </summary>
/// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param>
/// <exception cref="TinyIoCAutoRegistrationException"/>
public void AutoRegister(bool ignoreDuplicateImplementations)
{
AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, null);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
/// Types will only be registered if they pass the supplied registration predicate.
/// </summary>
/// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param>
/// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param>
/// <exception cref="TinyIoCAutoRegistrationException"/>
public void AutoRegister(bool ignoreDuplicateImplementations, Func<Type, bool> registrationPredicate)
{
AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, registrationPredicate);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
///
/// If more than one class implements an interface then only one implementation will be registered
/// although no error will be thrown.
/// </summary>
/// <param name="assemblies">Assemblies to process</param>
public void AutoRegister(IEnumerable<Assembly> assemblies)
{
AutoRegisterInternal(assemblies, true, null);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
/// Types will only be registered if they pass the supplied registration predicate.
///
/// If more than one class implements an interface then only one implementation will be registered
/// although no error will be thrown.
/// </summary>
/// <param name="assemblies">Assemblies to process</param>
/// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param>
public void AutoRegister(IEnumerable<Assembly> assemblies, Func<Type, bool> registrationPredicate)
{
AutoRegisterInternal(assemblies, true, registrationPredicate);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
/// </summary>
/// <param name="assemblies">Assemblies to process</param>
/// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param>
/// <exception cref="TinyIoCAutoRegistrationException"/>
public void AutoRegister(IEnumerable<Assembly> assemblies, bool ignoreDuplicateImplementations)
{
AutoRegisterInternal(assemblies, ignoreDuplicateImplementations, null);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
/// Types will only be registered if they pass the supplied registration predicate.
/// </summary>
/// <param name="assemblies">Assemblies to process</param>
/// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param>
/// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param>
/// <exception cref="TinyIoCAutoRegistrationException"/>
public void AutoRegister(IEnumerable<Assembly> assemblies, bool ignoreDuplicateImplementations, Func<Type, bool> registrationPredicate)
{
AutoRegisterInternal(assemblies, ignoreDuplicateImplementations, registrationPredicate);
}
/// <summary>
/// Creates/replaces a container class registration with default options.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType)
{
return RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerType));
}
/// <summary>
/// Creates/replaces a named container class registration with default options.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, string name)
{
return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType));
}
/// <summary>
/// Creates/replaces a container class registration with a given implementation and default options.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type to instantiate that implements RegisterType</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type registerImplementation)
{
return this.RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerImplementation));
}
/// <summary>
/// Creates/replaces a named container class registration with a given implementation and default options.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type to instantiate that implements RegisterType</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type registerImplementation, string name)
{
return this.RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation));
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="instance">Instance of RegisterType to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, object instance)
{
return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerType, instance));
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="instance">Instance of RegisterType to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, object instance, string name)
{
return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerType, instance));
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type of instance to register that implements RegisterType</param>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type registerImplementation, object instance)
{
return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerImplementation, instance));
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type of instance to register that implements RegisterType</param>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type registerImplementation, object instance, string name)
{
return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerImplementation, instance));
}
/// <summary>
/// Creates/replaces a container class registration with a user specified factory
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory)
{
return RegisterInternal(registerType, string.Empty, new DelegateFactory(registerType, factory));
}
/// <summary>
/// Creates/replaces a container class registration with a user specified factory
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType</param>
/// <param name="name">Name of registation</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory, string name)
{
return RegisterInternal(registerType, name, new DelegateFactory(registerType, factory));
}
/// <summary>
/// Creates/replaces a container class registration with default options.
/// </summary>
/// <typeparam name="RegisterImplementation">Type to register</typeparam>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>()
where RegisterType : class
{
return this.Register(typeof(RegisterType));
}
/// <summary>
/// Creates/replaces a named container class registration with default options.
/// </summary>
/// <typeparam name="RegisterImplementation">Type to register</typeparam>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(string name)
where RegisterType : class
{
return this.Register(typeof(RegisterType), name);
}
/// <summary>
/// Creates/replaces a container class registration with a given implementation and default options.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type to instantiate that implements RegisterType</typeparam>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>()
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return this.Register(typeof(RegisterType), typeof(RegisterImplementation));
}
/// <summary>
/// Creates/replaces a named container class registration with a given implementation and default options.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type to instantiate that implements RegisterType</typeparam>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>(string name)
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return this.Register(typeof(RegisterType), typeof(RegisterImplementation), name);
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <param name="instance">Instance of RegisterType to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(RegisterType instance)
where RegisterType : class
{
return this.Register(typeof(RegisterType), instance);
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <param name="instance">Instance of RegisterType to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(RegisterType instance, string name)
where RegisterType : class
{
return this.Register(typeof(RegisterType), instance, name);
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type of instance to register that implements RegisterType</typeparam>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance)
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance);
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type of instance to register that implements RegisterType</typeparam>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance, string name)
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance, name);
}
/// <summary>
/// Creates/replaces a container class registration with a user specified factory
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory)
where RegisterType : class
{
if (factory == null)
{
throw new ArgumentNullException("factory");
}
return this.Register(typeof(RegisterType), (c, o) => factory(c, o));
}
/// <summary>
/// Creates/replaces a named container class registration with a user specified factory
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType</param>
/// <param name="name">Name of registation</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory, string name)
where RegisterType : class
{
if (factory == null)
{
throw new ArgumentNullException("factory");
}
return this.Register(typeof(RegisterType), (c, o) => factory(c, o), name);
}
/// <summary>
/// Register multiple implementations of a type.
///
/// Internally this registers each implementation using the full name of the class as its registration name.
/// </summary>
/// <typeparam name="RegisterType">Type that each implementation implements</typeparam>
/// <param name="implementationTypes">Types that implement RegisterType</param>
/// <returns>MultiRegisterOptions for the fluent API</returns>
public MultiRegisterOptions RegisterMultiple<RegisterType>(IEnumerable<Type> implementationTypes)
{
return RegisterMultiple(typeof(RegisterType), implementationTypes);
}
/// <summary>
/// Register multiple implementations of a type.
///
/// Internally this registers each implementation using the full name of the class as its registration name.
/// </summary>
/// <param name="registrationType">Type that each implementation implements</param>
/// <param name="implementationTypes">Types that implement RegisterType</param>
/// <returns>MultiRegisterOptions for the fluent API</returns>
public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable<Type> implementationTypes)
{
if (implementationTypes == null)
throw new ArgumentNullException("types", "types is null.");
foreach (var type in implementationTypes)
if (!registrationType.IsAssignableFrom(type))
throw new ArgumentException(String.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName));
if (implementationTypes.Count() != implementationTypes.Distinct().Count())
{
var queryForDuplicatedTypes = from i in implementationTypes
group i by i
into j
where j.Count() > 1
select j.Key.FullName;
var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray());
var multipleRegMessage = string.Format("types: The same implementation type cannot be specified multiple times for {0}\n\n{1}", registrationType.FullName, fullNamesOfDuplicatedTypes);
throw new ArgumentException(multipleRegMessage);
}
var registerOptions = new List<RegisterOptions>();
foreach (var type in implementationTypes)
{
registerOptions.Add(Register(registrationType, type, type.FullName));
}
return new MultiRegisterOptions(registerOptions);
}
#endregion
#region Resolution
/// <summary>
/// Attempts to resolve a type using default options.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType)
{
return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default);
}
/// <summary>
/// Attempts to resolve a type using specified options.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, ResolveOptions options)
{
return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options);
}
/// <summary>
/// Attempts to resolve a type using default options and the supplied name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, string name)
{
return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default);
}
/// <summary>
/// Attempts to resolve a type using supplied options and name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, string name, ResolveOptions options)
{
return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options);
}
/// <summary>
/// Attempts to resolve a type using default options and the supplied constructor parameters.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, NamedParameterOverloads parameters)
{
return ResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default);
}
/// <summary>
/// Attempts to resolve a type using specified options and the supplied constructor parameters.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options)
{
return ResolveInternal(new TypeRegistration(resolveType), parameters, options);
}
/// <summary>
/// Attempts to resolve a type using default options and the supplied constructor parameters and name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="name">Name of registration</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters)
{
return ResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default);
}
/// <summary>
/// Attempts to resolve a named type using specified options and the supplied constructor parameters.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options)
{
return ResolveInternal(new TypeRegistration(resolveType, name), parameters, options);
}
/// <summary>
/// Attempts to resolve a type using default options.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>()
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType));
}
/// <summary>
/// Attempts to resolve a type using specified options.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>(ResolveOptions options)
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType), options);
}
/// <summary>
/// Attempts to resolve a type using default options and the supplied name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>(string name)
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType), name);
}
/// <summary>
/// Attempts to resolve a type using supplied options and name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>(string name, ResolveOptions options)
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType), name, options);
}
/// <summary>
/// Attempts to resolve a type using default options and the supplied constructor parameters.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="parameters">User specified constructor parameters</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>(NamedParameterOverloads parameters)
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType), parameters);
}
/// <summary>
/// Attempts to resolve a type using specified options and the supplied constructor parameters.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options)
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType), parameters, options);
}
/// <summary>
/// Attempts to resolve a type using default options and the supplied constructor parameters and name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="name">Name of registration</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>(string name, NamedParameterOverloads parameters)
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType), name, parameters);
}
/// <summary>
/// Attempts to resolve a named type using specified options and the supplied constructor parameters.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public ResolveType Resolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options)
where ResolveType : class
{
return (ResolveType)Resolve(typeof(ResolveType), name, parameters, options);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with default options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve(Type resolveType)
{
return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default);
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with default options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
private bool CanResolve(Type resolveType, string name)
{
return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with the specified options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve(Type resolveType, ResolveOptions options)
{
return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options);
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with the specified options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve(Type resolveType, string name, ResolveOptions options)
{
return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve(Type resolveType, NamedParameterOverloads parameters)
{
return CanResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default);
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters)
{
return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options)
{
return CanResolveInternal(new TypeRegistration(resolveType), parameters, options);
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options)
{
return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, options);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with default options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>()
where ResolveType : class
{
return CanResolve(typeof(ResolveType));
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with default options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>(string name)
where ResolveType : class
{
return CanResolve(typeof(ResolveType), name);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with the specified options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>(ResolveOptions options)
where ResolveType : class
{
return CanResolve(typeof(ResolveType), options);
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with the specified options.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>(string name, ResolveOptions options)
where ResolveType : class
{
return CanResolve(typeof(ResolveType), name, options);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>(NamedParameterOverloads parameters)
where ResolveType : class
{
return CanResolve(typeof(ResolveType), parameters);
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>(string name, NamedParameterOverloads parameters)
where ResolveType : class
{
return CanResolve(typeof(ResolveType), name, parameters);
}
/// <summary>
/// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options)
where ResolveType : class
{
return CanResolve(typeof(ResolveType), parameters, options);
}
/// <summary>
/// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
///
/// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User supplied named parameter overloads</param>
/// <param name="options">Resolution options</param>
/// <returns>Bool indicating whether the type can be resolved</returns>
public bool CanResolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options)
where ResolveType : class
{
return CanResolve(typeof(ResolveType), name, parameters, options);
}
/// <summary>
/// Attemps to resolve a type using the default options
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the given options
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, ResolveOptions options, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the default options and given name
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, string name, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, name);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the given options and name
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, string name, ResolveOptions options, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, name, options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the default options and supplied constructor parameters
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, parameters);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the default options and supplied name and constructor parameters
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, name, parameters);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the supplied options and constructor parameters
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, parameters, options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the supplied name, options and constructor parameters
/// </summary>
/// <param name="ResolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, name, parameters, options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the default options
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>();
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the given options
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(ResolveOptions options, out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>(options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the default options and given name
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(string name, out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>(name);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the given options and name
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(string name, ResolveOptions options, out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>(name, options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the default options and supplied constructor parameters
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(NamedParameterOverloads parameters, out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>(parameters);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the default options and supplied name and constructor parameters
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(string name, NamedParameterOverloads parameters, out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>(name, parameters);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the supplied options and constructor parameters
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>(parameters, options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Attemps to resolve a type using the supplied name, options and constructor parameters
/// </summary>
/// <typeparam name="ResolveType">Type to resolve</typeparam>
/// <param name="name">Name of registration</param>
/// <param name="parameters">User specified constructor parameters</param>
/// <param name="options">Resolution options</param>
/// <param name="resolvedType">Resolved type or default if resolve fails</param>
/// <returns>True if resolved sucessfully, false otherwise</returns>
public bool TryResolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType)
where ResolveType : class
{
try
{
resolvedType = Resolve<ResolveType>(name, parameters, options);
return true;
}
catch (TinyIoCResolutionException)
{
resolvedType = default(ResolveType);
return false;
}
}
/// <summary>
/// Returns all registrations of a type
/// </summary>
/// <param name="ResolveType">Type to resolveAll</param>
/// <param name="includeUnnamed">Whether to include un-named (default) registrations</param>
/// <returns>IEnumerable</returns>
public IEnumerable<object> ResolveAll(Type resolveType, bool includeUnnamed)
{
return ResolveAllInternal(resolveType, includeUnnamed);
}
/// <summary>
/// Returns all registrations of a type, both named and unnamed
/// </summary>
/// <param name="ResolveType">Type to resolveAll</param>
/// <returns>IEnumerable</returns>
public IEnumerable<object> ResolveAll(Type resolveType)
{
return ResolveAll(resolveType, false);
}
/// <summary>
/// Returns all registrations of a type
/// </summary>
/// <typeparam name="ResolveType">Type to resolveAll</typeparam>
/// <param name="includeUnnamed">Whether to include un-named (default) registrations</param>
/// <returns>IEnumerable</returns>
public IEnumerable<ResolveType> ResolveAll<ResolveType>(bool includeUnnamed)
where ResolveType : class
{
return this.ResolveAll(typeof(ResolveType), includeUnnamed).Cast<ResolveType>();
}
/// <summary>
/// Returns all registrations of a type, both named and unnamed
/// </summary>
/// <typeparam name="ResolveType">Type to resolveAll</typeparam>
/// <param name="includeUnnamed">Whether to include un-named (default) registrations</param>
/// <returns>IEnumerable</returns>
public IEnumerable<ResolveType> ResolveAll<ResolveType>()
where ResolveType : class
{
return ResolveAll<ResolveType>(true);
}
/// <summary>
/// Attempts to resolve all public property dependencies on the given object.
/// </summary>
/// <param name="input">Object to "build up"</param>
public void BuildUp(object input)
{
BuildUpInternal(input, ResolveOptions.Default);
}
/// <summary>
/// Attempts to resolve all public property dependencies on the given object using the given resolve options.
/// </summary>
/// <param name="input">Object to "build up"</param>
/// <param name="resolveOptions">Resolve options to use</param>
public void BuildUp(object input, ResolveOptions resolveOptions)
{
BuildUpInternal(input, resolveOptions);
}
#endregion
#endregion
#region Object Factories
/// <summary>
/// Provides custom lifetime management for ASP.Net per-request lifetimes etc.
/// </summary>
public interface ITinyIoCObjectLifetimeProvider
{
/// <summary>
/// Gets the stored object if it exists, or null if not
/// </summary>
/// <returns>Object instance or null</returns>
object GetObject();
/// <summary>
/// Store the object
/// </summary>
/// <param name="value">Object to store</param>
void SetObject(object value);
/// <summary>
/// Release the object
/// </summary>
void ReleaseObject();
}
private abstract class ObjectFactoryBase
{
/// <summary>
/// Whether to assume this factory sucessfully constructs its objects
///
/// Generally set to true for delegate style factories as CanResolve cannot delve
/// into the delegates they contain.
/// </summary>
public virtual bool AssumeConstruction { get { return false; } }
/// <summary>
/// The type the factory instantiates
/// </summary>
public abstract Type CreatesType { get; }
/// <summary>
/// Constructor to use, if specified
/// </summary>
public ConstructorInfo Constructor { get; protected set; }
/// <summary>
/// Create the type
/// </summary>
/// <param name="requestedType">Type user requested to be resolved</param>
/// <param name="container">Container that requested the creation</param>
/// <param name="parameters">Any user parameters passed</param>
/// <param name="options"></param>
/// <returns></returns>
public abstract object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options);
public virtual ObjectFactoryBase SingletonVariant
{
get
{
throw new TinyIoCRegistrationException(this.GetType(), "singleton");
}
}
public virtual ObjectFactoryBase MultiInstanceVariant
{
get
{
throw new TinyIoCRegistrationException(this.GetType(), "multi-instance");
}
}
public virtual ObjectFactoryBase StrongReferenceVariant
{
get
{
throw new TinyIoCRegistrationException(this.GetType(), "strong reference");
}
}
public virtual ObjectFactoryBase WeakReferenceVariant
{
get
{
throw new TinyIoCRegistrationException(this.GetType(), "weak reference");
}
}
public virtual ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)
{
throw new TinyIoCRegistrationException(this.GetType(), errorString);
}
public virtual void SetConstructor(ConstructorInfo constructor)
{
Constructor = constructor;
}
public virtual ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child)
{
return this;
}
}
/// <summary>
/// IObjectFactory that creates new instances of types for each resolution
/// </summary>
private class MultiInstanceFactory : ObjectFactoryBase
{
private readonly Type registerType;
private readonly Type registerImplementation;
public override Type CreatesType { get { return this.registerImplementation; } }
public MultiInstanceFactory(Type registerType, Type registerImplementation)
{
if (registerImplementation.IsAbstract() || registerImplementation.IsInterface())
throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory");
if (!IsValidAssignment(registerType, registerImplementation))
throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory");
this.registerType = registerType;
this.registerImplementation = registerImplementation;
}
public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
{
try
{
return container.ConstructType(requestedType, this.registerImplementation, Constructor, parameters, options);
}
catch (TinyIoCResolutionException ex)
{
throw new TinyIoCResolutionException(this.registerType, ex);
}
}
public override ObjectFactoryBase SingletonVariant
{
get
{
return new SingletonFactory(this.registerType, this.registerImplementation);
}
}
public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)
{
return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString);
}
public override ObjectFactoryBase MultiInstanceVariant
{
get
{
return this;
}
}
}
/// <summary>
/// IObjectFactory that invokes a specified delegate to construct the object
/// </summary>
private class DelegateFactory : ObjectFactoryBase
{
private readonly Type registerType;
private Func<TinyIoCContainer, NamedParameterOverloads, object> _factory;
public override bool AssumeConstruction { get { return true; } }
public override Type CreatesType { get { return this.registerType; } }
public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
{
try
{
return _factory.Invoke(container, parameters);
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(this.registerType, ex);
}
}
public DelegateFactory( Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory)
{
if (factory == null)
throw new ArgumentNullException("factory");
_factory = factory;
this.registerType = registerType;
}
public override ObjectFactoryBase WeakReferenceVariant
{
get
{
return new WeakDelegateFactory(this.registerType, _factory);
}
}
public override ObjectFactoryBase StrongReferenceVariant
{
get
{
return this;
}
}
public override void SetConstructor(ConstructorInfo constructor)
{
throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for delegate factory registrations");
}
}
/// <summary>
/// IObjectFactory that invokes a specified delegate to construct the object
/// Holds the delegate using a weak reference
/// </summary>
private class WeakDelegateFactory : ObjectFactoryBase
{
private readonly Type registerType;
private WeakReference _factory;
public override bool AssumeConstruction { get { return true; } }
public override Type CreatesType { get { return this.registerType; } }
public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
{
var factory = _factory.Target as Func<TinyIoCContainer, NamedParameterOverloads, object>;
if (factory == null)
throw new TinyIoCWeakReferenceException(this.registerType);
try
{
return factory.Invoke(container, parameters);
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(this.registerType, ex);
}
}
public WeakDelegateFactory(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory)
{
if (factory == null)
throw new ArgumentNullException("factory");
_factory = new WeakReference(factory);
this.registerType = registerType;
}
public override ObjectFactoryBase StrongReferenceVariant
{
get
{
var factory = _factory.Target as Func<TinyIoCContainer, NamedParameterOverloads, object>;
if (factory == null)
throw new TinyIoCWeakReferenceException(this.registerType);
return new DelegateFactory(this.registerType, factory);
}
}
public override ObjectFactoryBase WeakReferenceVariant
{
get
{
return this;
}
}
public override void SetConstructor(ConstructorInfo constructor)
{
throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for delegate factory registrations");
}
}
/// <summary>
/// Stores an particular instance to return for a type
/// </summary>
private class InstanceFactory : ObjectFactoryBase, IDisposable
{
private readonly Type registerType;
private readonly Type registerImplementation;
private object _instance;
public override bool AssumeConstruction { get { return true; } }
public InstanceFactory(Type registerType, Type registerImplementation, object instance)
{
if (!IsValidAssignment(registerType, registerImplementation))
throw new TinyIoCRegistrationTypeException(registerImplementation, "InstanceFactory");
this.registerType = registerType;
this.registerImplementation = registerImplementation;
_instance = instance;
}
public override Type CreatesType
{
get { return this.registerImplementation; }
}
public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
{
return _instance;
}
public override ObjectFactoryBase MultiInstanceVariant
{
get { return new MultiInstanceFactory(this.registerType, this.registerImplementation); }
}
public override ObjectFactoryBase WeakReferenceVariant
{
get
{
return new WeakInstanceFactory(this.registerType, this.registerImplementation, this._instance);
}
}
public override ObjectFactoryBase StrongReferenceVariant
{
get
{
return this;
}
}
public override void SetConstructor(ConstructorInfo constructor)
{
throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for instance factory registrations");
}
public void Dispose()
{
var disposable = _instance as IDisposable;
if (disposable != null)
disposable.Dispose();
}
}
/// <summary>
/// Stores an particular instance to return for a type
///
/// Stores the instance with a weak reference
/// </summary>
private class WeakInstanceFactory : ObjectFactoryBase, IDisposable
{
private readonly Type registerType;
private readonly Type registerImplementation;
private readonly WeakReference _instance;
public WeakInstanceFactory(Type registerType, Type registerImplementation, object instance)
{
if (!IsValidAssignment(registerType, registerImplementation))
throw new TinyIoCRegistrationTypeException(registerImplementation, "WeakInstanceFactory");
this.registerType = registerType;
this.registerImplementation = registerImplementation;
_instance = new WeakReference(instance);
}
public override Type CreatesType
{
get { return this.registerImplementation; }
}
public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
{
var instance = _instance.Target;
if (instance == null)
throw new TinyIoCWeakReferenceException(this.registerType);
return instance;
}
public override ObjectFactoryBase MultiInstanceVariant
{
get
{
return new MultiInstanceFactory(this.registerType, this.registerImplementation);
}
}
public override ObjectFactoryBase WeakReferenceVariant
{
get
{
return this;
}
}
public override ObjectFactoryBase StrongReferenceVariant
{
get
{
var instance = _instance.Target;
if (instance == null)
throw new TinyIoCWeakReferenceException(this.registerType);
return new InstanceFactory(this.registerType, this.registerImplementation, instance);
}
}
public override void SetConstructor(ConstructorInfo constructor)
{
throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for instance factory registrations");
}
public void Dispose()
{
var disposable = _instance.Target as IDisposable;
if (disposable != null)
disposable.Dispose();
}
}
/// <summary>
/// A factory that lazy instantiates a type and always returns the same instance
/// </summary>
private class SingletonFactory : ObjectFactoryBase, IDisposable
{
private readonly Type registerType;
private readonly Type registerImplementation;
private readonly object SingletonLock = new object();
private object _Current;
public SingletonFactory(Type registerType, Type registerImplementation)
{
if (registerImplementation.IsAbstract() || registerImplementation.IsInterface())
throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory");
if (!IsValidAssignment(registerType, registerImplementation))
throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory");
this.registerType = registerType;
this.registerImplementation = registerImplementation;
}
public override Type CreatesType
{
get { return this.registerImplementation; }
}
public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
{
if (parameters.Count != 0)
throw new ArgumentException("Cannot specify parameters for singleton types");
lock (SingletonLock)
if (_Current == null)
_Current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options);
return _Current;
}
public override ObjectFactoryBase SingletonVariant
{
get
{
return this;
}
}
public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)
{
return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString);
}
public override ObjectFactoryBase MultiInstanceVariant
{
get
{
return new MultiInstanceFactory(this.registerType, this.registerImplementation);
}
}
public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child)
{
// We make sure that the singleton is constructed before the child container takes the factory.
// Otherwise the results would vary depending on whether or not the parent container had resolved
// the type before the child container does.
GetObject(type, parent, NamedParameterOverloads.Default, ResolveOptions.Default);
return this;
}
public void Dispose()
{
if (this._Current == null)
return;
var disposable = this._Current as IDisposable;
if (disposable != null)
disposable.Dispose();
}
}
/// <summary>
/// A factory that offloads lifetime to an external lifetime provider
/// </summary>
private class CustomObjectLifetimeFactory : ObjectFactoryBase, IDisposable
{
private readonly object SingletonLock = new object();
private readonly Type registerType;
private readonly Type registerImplementation;
private readonly ITinyIoCObjectLifetimeProvider _LifetimeProvider;
public CustomObjectLifetimeFactory(Type registerType, Type registerImplementation, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorMessage)
{
if (lifetimeProvider == null)
throw new ArgumentNullException("lifetimeProvider", "lifetimeProvider is null.");
if (!IsValidAssignment(registerType, registerImplementation))
throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory");
if (registerImplementation.IsAbstract() || registerImplementation.IsInterface())
throw new TinyIoCRegistrationTypeException(registerImplementation, errorMessage);
this.registerType = registerType;
this.registerImplementation = registerImplementation;
_LifetimeProvider = lifetimeProvider;
}
public override Type CreatesType
{
get { return this.registerImplementation; }
}
public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
{
object current;
lock (SingletonLock)
{
current = _LifetimeProvider.GetObject();
if (current == null)
{
current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options);
_LifetimeProvider.SetObject(current);
}
}
return current;
}
public override ObjectFactoryBase SingletonVariant
{
get
{
_LifetimeProvider.ReleaseObject();
return new SingletonFactory(this.registerType, this.registerImplementation);
}
}
public override ObjectFactoryBase MultiInstanceVariant
{
get
{
_LifetimeProvider.ReleaseObject();
return new MultiInstanceFactory(this.registerType, this.registerImplementation);
}
}
public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)
{
_LifetimeProvider.ReleaseObject();
return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString);
}
public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child)
{
// We make sure that the singleton is constructed before the child container takes the factory.
// Otherwise the results would vary depending on whether or not the parent container had resolved
// the type before the child container does.
GetObject(type, parent, NamedParameterOverloads.Default, ResolveOptions.Default);
return this;
}
public void Dispose()
{
_LifetimeProvider.ReleaseObject();
}
}
#endregion
#region Singleton Container
private static readonly TinyIoCContainer _Current = new TinyIoCContainer();
static TinyIoCContainer()
{
}
/// <summary>
/// Lazy created Singleton instance of the container for simple scenarios
/// </summary>
public static TinyIoCContainer Current
{
get
{
return _Current;
}
}
#endregion
#region Type Registrations
public sealed class TypeRegistration
{
private int _hashCode;
public Type Type { get; private set; }
public string Name { get; private set; }
public TypeRegistration(Type type)
: this(type, string.Empty)
{
}
public TypeRegistration(Type type, string name)
{
Type = type;
Name = name;
_hashCode = String.Concat(Type.FullName, "|", Name).GetHashCode();
}
public override bool Equals(object obj)
{
var typeRegistration = obj as TypeRegistration;
if (typeRegistration == null)
return false;
if (Type != typeRegistration.Type)
return false;
if (String.Compare(Name, typeRegistration.Name, StringComparison.Ordinal) != 0)
return false;
return true;
}
public override int GetHashCode()
{
return _hashCode;
}
}
private readonly SafeDictionary<TypeRegistration, ObjectFactoryBase> _RegisteredTypes;
#if COMPILED_EXPRESSIONS
private delegate object ObjectConstructor(params object[] parameters);
private static readonly SafeDictionary<ConstructorInfo, ObjectConstructor> _ObjectConstructorCache = new SafeDictionary<ConstructorInfo, ObjectConstructor>();
#endif
#endregion
#region Constructors
public TinyIoCContainer()
{
_RegisteredTypes = new SafeDictionary<TypeRegistration, ObjectFactoryBase>();
RegisterDefaultTypes();
}
TinyIoCContainer _Parent;
private TinyIoCContainer(TinyIoCContainer parent)
: this()
{
_Parent = parent;
}
#endregion
#region Internal Methods
private readonly object _AutoRegisterLock = new object();
private void AutoRegisterInternal(IEnumerable<Assembly> assemblies, bool ignoreDuplicateImplementations, Func<Type, bool> registrationPredicate)
{
lock (_AutoRegisterLock)
{
var types = assemblies.SelectMany(a => a.SafeGetTypes()).Where(t => !IsIgnoredType(t, registrationPredicate)).ToList();
var concreteTypes = from type in types
where (type.IsClass() == true) && (type.IsAbstract() == false) && (type != this.GetType() && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition()))
select type;
foreach (var type in concreteTypes)
{
try
{
RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, type));
}
catch (MethodAccessException)
{
// Ignore methods we can't access - added for Silverlight
}
}
var abstractInterfaceTypes = from type in types
where ((type.IsInterface() == true || type.IsAbstract() == true) && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition()))
select type;
foreach (var type in abstractInterfaceTypes)
{
var implementations = from implementationType in concreteTypes
where implementationType.GetInterfaces().Contains(type) || implementationType.BaseType() == type
select implementationType;
if (!ignoreDuplicateImplementations && implementations.Count() > 1)
throw new TinyIoCAutoRegistrationException(type, implementations);
var firstImplementation = implementations.FirstOrDefault();
if (firstImplementation != null)
{
try
{
RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, firstImplementation));
}
catch (MethodAccessException)
{
// Ignore methods we can't access - added for Silverlight
}
}
}
}
}
private bool IsIgnoredAssembly(Assembly assembly)
{
// TODO - find a better way to remove "system" assemblies from the auto registration
var ignoreChecks = new List<Func<Assembly, bool>>()
{
asm => asm.FullName.StartsWith("Microsoft.", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("System.", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("System,", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("mscorlib,", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.Ordinal),
};
foreach (var check in ignoreChecks)
{
if (check(assembly))
return true;
}
return false;
}
private bool IsIgnoredType(Type type, Func<Type, bool> registrationPredicate)
{
// TODO - find a better way to remove "system" types from the auto registration
var ignoreChecks = new List<Func<Type, bool>>()
{
t => t.FullName.StartsWith("System.", StringComparison.Ordinal),
t => t.FullName.StartsWith("Microsoft.", StringComparison.Ordinal),
t => t.IsPrimitive(),
t => (t.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Length == 0) && !(t.IsInterface() || t.IsAbstract()),
};
if (registrationPredicate != null)
{
ignoreChecks.Add(t => !registrationPredicate(t));
}
foreach (var check in ignoreChecks)
{
if (check(type))
return true;
}
return false;
}
private void RegisterDefaultTypes()
{
Register<TinyIoCContainer>(this);
#if TINYMESSENGER
// Only register the TinyMessenger singleton if we are the root container
if (_Parent == null)
Register<TinyMessenger.ITinyMessengerHub, TinyMessenger.TinyMessengerHub>();
#endif
}
private ObjectFactoryBase GetCurrentFactory(TypeRegistration registration)
{
ObjectFactoryBase current = null;
_RegisteredTypes.TryGetValue(registration, out current);
return current;
}
private RegisterOptions RegisterInternal(Type registerType, string name, ObjectFactoryBase factory)
{
var typeRegistration = new TypeRegistration(registerType, name);
return AddUpdateRegistration(typeRegistration, factory);
}
private RegisterOptions AddUpdateRegistration(TypeRegistration typeRegistration, ObjectFactoryBase factory)
{
_RegisteredTypes[typeRegistration] = factory;
return new RegisterOptions(this, typeRegistration);
}
private void RemoveRegistration(TypeRegistration typeRegistration)
{
_RegisteredTypes.Remove(typeRegistration);
}
private ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation)
{
if (registerType.IsInterface() || registerType.IsAbstract())
return new SingletonFactory(registerType, registerImplementation);
return new MultiInstanceFactory(registerType, registerImplementation);
}
private bool CanResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options)
{
if (parameters == null)
throw new ArgumentNullException("parameters");
Type checkType = registration.Type;
string name = registration.Name;
ObjectFactoryBase factory;
if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType, name), out factory))
{
if (factory.AssumeConstruction)
return true;
if (factory.Constructor == null)
return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false;
else
return CanConstruct(factory.Constructor, parameters, options);
}
// Fail if requesting named resolution and settings set to fail if unresolved
// Or bubble up if we have a parent
if (!String.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.Fail)
return (_Parent != null) ? _Parent.CanResolveInternal(registration, parameters, options) : false;
// Attemped unnamed fallback container resolution if relevant and requested
if (!String.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.AttemptUnnamedResolution)
{
if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType), out factory))
{
if (factory.AssumeConstruction)
return true;
return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false;
}
}
// Check if type is an automatic lazy factory request
if (IsAutomaticLazyFactoryRequest(checkType))
return true;
// Check if type is an IEnumerable<ResolveType>
if (IsIEnumerableRequest(registration.Type))
return true;
// Attempt unregistered construction if possible and requested
// If we cant', bubble if we have a parent
if ((options.UnregisteredResolutionAction == UnregisteredResolutionActions.AttemptResolve) || (checkType.IsGenericType() && options.UnregisteredResolutionAction == UnregisteredResolutionActions.GenericsOnly))
return (GetBestConstructor(checkType, parameters, options) != null) ? true : (_Parent != null) ? _Parent.CanResolveInternal(registration, parameters, options) : false;
// Bubble resolution up the container tree if we have a parent
if (_Parent != null)
return _Parent.CanResolveInternal(registration, parameters, options);
return false;
}
private bool IsIEnumerableRequest(Type type)
{
if (!type.IsGenericType())
return false;
Type genericType = type.GetGenericTypeDefinition();
if (genericType == typeof(IEnumerable<>))
return true;
return false;
}
private bool IsAutomaticLazyFactoryRequest(Type type)
{
if (!type.IsGenericType())
return false;
Type genericType = type.GetGenericTypeDefinition();
// Just a func
if (genericType == typeof(Func<>))
return true;
// 2 parameter func with string as first parameter (name)
if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string)))
return true;
// 3 parameter func with string as first parameter (name) and IDictionary<string, object> as second (parameters)
if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary<String, object>)))
return true;
return false;
}
private ObjectFactoryBase GetParentObjectFactory(TypeRegistration registration)
{
if (_Parent == null)
return null;
ObjectFactoryBase factory;
if (_Parent._RegisteredTypes.TryGetValue(registration, out factory))
{
return factory.GetFactoryForChildContainer(registration.Type, _Parent, this);
}
return _Parent.GetParentObjectFactory(registration);
}
private object ResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options)
{
ObjectFactoryBase factory;
// Attempt container resolution
if (_RegisteredTypes.TryGetValue(registration, out factory))
{
try
{
return factory.GetObject(registration.Type, this, parameters, options);
}
catch (TinyIoCResolutionException)
{
throw;
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(registration.Type, ex);
}
}
// Attempt container resolution of open generic
if (registration.Type.IsGenericType())
{
var openTypeRegistration = new TypeRegistration(registration.Type.GetGenericTypeDefinition(),
registration.Name);
if (_RegisteredTypes.TryGetValue(openTypeRegistration, out factory))
{
try
{
return factory.GetObject(registration.Type, this, parameters, options);
}
catch (TinyIoCResolutionException)
{
throw;
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(registration.Type, ex);
}
}
}
// Attempt to get a factory from parent if we can
var bubbledObjectFactory = GetParentObjectFactory(registration);
if (bubbledObjectFactory != null)
{
try
{
return bubbledObjectFactory.GetObject(registration.Type, this, parameters, options);
}
catch (TinyIoCResolutionException)
{
throw;
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(registration.Type, ex);
}
}
// Fail if requesting named resolution and settings set to fail if unresolved
if (!String.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.Fail)
throw new TinyIoCResolutionException(registration.Type);
// Attemped unnamed fallback container resolution if relevant and requested
if (!String.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.AttemptUnnamedResolution)
{
if (_RegisteredTypes.TryGetValue(new TypeRegistration(registration.Type, string.Empty), out factory))
{
try
{
return factory.GetObject(registration.Type, this, parameters, options);
}
catch (TinyIoCResolutionException)
{
throw;
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(registration.Type, ex);
}
}
}
#if COMPILED_EXPRESSIONS
// Attempt to construct an automatic lazy factory if possible
if (IsAutomaticLazyFactoryRequest(registration.Type))
return GetLazyAutomaticFactoryRequest(registration.Type);
#endif
if (IsIEnumerableRequest(registration.Type))
return GetIEnumerableRequest(registration.Type);
// Attempt unregistered construction if possible and requested
if ((options.UnregisteredResolutionAction == UnregisteredResolutionActions.AttemptResolve) || (registration.Type.IsGenericType() && options.UnregisteredResolutionAction == UnregisteredResolutionActions.GenericsOnly))
{
if (!registration.Type.IsAbstract() && !registration.Type.IsInterface())
return ConstructType(null, registration.Type, parameters, options);
}
// Unable to resolve - throw
throw new TinyIoCResolutionException(registration.Type);
}
#if COMPILED_EXPRESSIONS
private object GetLazyAutomaticFactoryRequest(Type type)
{
if (!type.IsGenericType())
return null;
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
// Just a func
if (genericType == typeof(Func<>))
{
Type returnType = genericArguments[0];
MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { });
resolveMethod = resolveMethod.MakeGenericMethod(returnType);
var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod);
var resolveLambda = Expression.Lambda(resolveCall).Compile();
return resolveLambda;
}
// 2 parameter func with string as first parameter (name)
if ((genericType == typeof(Func<,>)) && (genericArguments[0] == typeof(string)))
{
Type returnType = genericArguments[1];
MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(String) });
resolveMethod = resolveMethod.MakeGenericMethod(returnType);
ParameterExpression[] resolveParameters = new ParameterExpression[] { Expression.Parameter(typeof(String), "name") };
var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod, resolveParameters);
var resolveLambda = Expression.Lambda(resolveCall, resolveParameters).Compile();
return resolveLambda;
}
// 3 parameter func with string as first parameter (name) and IDictionary<string, object> as second (parameters)
if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary<string, object>)))
{
Type returnType = genericArguments[2];
var name = Expression.Parameter(typeof(string), "name");
var parameters = Expression.Parameter(typeof(IDictionary<string, object>), "parameters");
MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(String), typeof(NamedParameterOverloads) });
resolveMethod = resolveMethod.MakeGenericMethod(returnType);
var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod, name, Expression.Call(typeof(NamedParameterOverloads), "FromIDictionary", null, parameters));
var resolveLambda = Expression.Lambda(resolveCall, name, parameters).Compile();
return resolveLambda;
}
throw new TinyIoCResolutionException(type);
}
#endif
private object GetIEnumerableRequest(Type type)
{
var genericResolveAllMethod = this.GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, "ResolveAll", type.GetGenericArguments(), new[] { typeof(bool) });
return genericResolveAllMethod.Invoke(this, new object[] { false });
}
private bool CanConstruct(ConstructorInfo ctor, NamedParameterOverloads parameters, ResolveOptions options)
{
if (parameters == null)
throw new ArgumentNullException("parameters");
foreach (var parameter in ctor.GetParameters())
{
if (string.IsNullOrEmpty(parameter.Name))
return false;
var isParameterOverload = parameters.ContainsKey(parameter.Name);
if (parameter.ParameterType.IsPrimitive() && !isParameterOverload)
return false;
if (!isParameterOverload && !CanResolveInternal(new TypeRegistration(parameter.ParameterType), NamedParameterOverloads.Default, options))
return false;
}
return true;
}
private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads parameters, ResolveOptions options)
{
if (parameters == null)
throw new ArgumentNullException("parameters");
if (type.IsValueType())
return null;
// Get constructors in reverse order based on the number of parameters
// i.e. be as "greedy" as possible so we satify the most amount of dependencies possible
var ctors = this.GetTypeConstructors(type);
foreach (var ctor in ctors)
{
if (this.CanConstruct(ctor, parameters, options))
return ctor;
}
return null;
}
private IEnumerable<ConstructorInfo> GetTypeConstructors(Type type)
{
return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count());
}
private object ConstructType(Type requestedType, Type implementationType, ResolveOptions options)
{
return ConstructType(requestedType, implementationType, null, NamedParameterOverloads.Default, options);
}
private object ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, ResolveOptions options)
{
return ConstructType(requestedType, implementationType, constructor, NamedParameterOverloads.Default, options);
}
private object ConstructType(Type requestedType, Type implementationType, NamedParameterOverloads parameters, ResolveOptions options)
{
return ConstructType(requestedType, implementationType, null, parameters, options);
}
private object ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options)
{
var typeToConstruct = implementationType;
if (implementationType.IsGenericTypeDefinition())
{
if (requestedType == null || !requestedType.IsGenericType() || !requestedType.GetGenericArguments().Any())
throw new TinyIoCResolutionException(typeToConstruct);
typeToConstruct = typeToConstruct.MakeGenericType(requestedType.GetGenericArguments());
}
if (constructor == null)
{
// Try and get the best constructor that we can construct
// if we can't construct any then get the constructor
// with the least number of parameters so we can throw a meaningful
// resolve exception
constructor = GetBestConstructor(typeToConstruct, parameters, options) ?? GetTypeConstructors(typeToConstruct).LastOrDefault();
}
if (constructor == null)
throw new TinyIoCResolutionException(typeToConstruct);
var ctorParams = constructor.GetParameters();
object[] args = new object[ctorParams.Count()];
for (int parameterIndex = 0; parameterIndex < ctorParams.Count(); parameterIndex++)
{
var currentParam = ctorParams[parameterIndex];
try
{
args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ?
parameters[currentParam.Name] :
ResolveInternal(
new TypeRegistration(currentParam.ParameterType),
NamedParameterOverloads.Default,
options);
}
catch (TinyIoCResolutionException ex)
{
// If a constructor parameter can't be resolved
// it will throw, so wrap it and throw that this can't
// be resolved.
throw new TinyIoCResolutionException(typeToConstruct, ex);
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(typeToConstruct, ex);
}
}
try
{
#if COMPILED_EXPRESSIONS
var constructionDelegate = CreateObjectConstructionDelegateWithCache(constructor);
return constructionDelegate.Invoke(args);
#else
return constructor.Invoke(args);
#endif
}
catch (Exception ex)
{
throw new TinyIoCResolutionException(typeToConstruct, ex);
}
}
#if COMPILED_EXPRESSIONS
private static ObjectConstructor CreateObjectConstructionDelegateWithCache(ConstructorInfo constructor)
{
ObjectConstructor objectConstructor;
if (_ObjectConstructorCache.TryGetValue(constructor, out objectConstructor))
return objectConstructor;
// We could lock the cache here, but there's no real side
// effect to two threads creating the same ObjectConstructor
// at the same time, compared to the cost of a lock for
// every creation.
var constructorParams = constructor.GetParameters();
var lambdaParams = Expression.Parameter(typeof(object[]), "parameters");
var newParams = new Expression[constructorParams.Length];
for (int i = 0; i < constructorParams.Length; i++)
{
var paramsParameter = Expression.ArrayIndex(lambdaParams, Expression.Constant(i));
newParams[i] = Expression.Convert(paramsParameter, constructorParams[i].ParameterType);
}
var newExpression = Expression.New(constructor, newParams);
var constructionLambda = Expression.Lambda(typeof(ObjectConstructor), newExpression, lambdaParams);
objectConstructor = (ObjectConstructor)constructionLambda.Compile();
_ObjectConstructorCache[constructor] = objectConstructor;
return objectConstructor;
}
#endif
private void BuildUpInternal(object input, ResolveOptions resolveOptions)
{
var properties = from property in input.GetType().GetProperties()
where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType()
select property;
foreach (var property in properties)
{
if (property.GetValue(input, null) == null)
{
try
{
property.SetValue(input, ResolveInternal(new TypeRegistration(property.PropertyType), NamedParameterOverloads.Default, resolveOptions), null);
}
catch (TinyIoCResolutionException)
{
// Catch any resolution errors and ignore them
}
}
}
}
private IEnumerable<TypeRegistration> GetParentRegistrationsForType(Type resolveType)
{
if (_Parent == null)
return new TypeRegistration[] { };
var registrations = _Parent._RegisteredTypes.Keys.Where(tr => tr.Type == resolveType);
return registrations.Concat(_Parent.GetParentRegistrationsForType(resolveType));
}
private IEnumerable<object> ResolveAllInternal(Type resolveType, bool includeUnnamed)
{
var registrations = _RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(GetParentRegistrationsForType(resolveType));
if (!includeUnnamed)
registrations = registrations.Where(tr => tr.Name != string.Empty);
return registrations.Select(registration => this.ResolveInternal(registration, NamedParameterOverloads.Default, ResolveOptions.Default));
}
private static bool IsValidAssignment(Type registerType, Type registerImplementation)
{
if (!registerType.IsGenericTypeDefinition())
{
if (!registerType.IsAssignableFrom(registerImplementation))
return false;
}
else
{
if (registerType.IsInterface())
{
if(!registerImplementation.GetInterfaces().Any(t => t.Name == registerType.Name))
return false;
}
else if (registerType.IsAbstract() && registerImplementation.BaseType() != registerType)
{
return false;
}
}
return true;
}
#endregion
#region IDisposable Members
bool disposed = false;
public void Dispose()
{
if (!disposed)
{
disposed = true;
_RegisteredTypes.Dispose();
GC.SuppressFinalize(this);
}
}
#endregion
}
}
// reverse shim for WinRT SR changes...
namespace System.Reflection
{
public static class ReverseTypeExtender
{
public static bool IsClass(this Type type)
{
return type.IsClass;
}
public static bool IsAbstract(this Type type)
{
return type.IsAbstract;
}
public static bool IsInterface(this Type type)
{
return type.IsInterface;
}
public static bool IsPrimitive(this Type type)
{
return type.IsPrimitive;
}
public static bool IsValueType(this Type type)
{
return type.IsValueType;
}
public static bool IsGenericType(this Type type)
{
return type.IsGenericType;
}
public static bool IsGenericParameter(this Type type)
{
return type.IsGenericParameter;
}
public static bool IsGenericTypeDefinition(this Type type)
{
return type.IsGenericTypeDefinition;
}
public static Type BaseType(this Type type)
{
return type.BaseType;
}
public static Assembly Assembly(this Type type)
{
return type.Assembly;
}
}
} |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// 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.
namespace SafetySharp.Runtime
{
using System;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using Analysis;
using CompilerServices;
using ISSE.SafetyChecking.ExecutableModel;
using ISSE.SafetyChecking.Formula;
using ISSE.SafetyChecking.Modeling;
using ISSE.SafetyChecking.Utilities;
using Modeling;
using Serialization;
using Utilities;
/// <summary>
/// Represents a runtime model that can be used for model checking or simulation.
/// </summary>
public sealed unsafe class SafetySharpRuntimeModel : ExecutableModel<SafetySharpRuntimeModel>
{
/// <summary>
/// The objects referenced by the model that participate in state serialization.
/// </summary>
private readonly ObjectTable _serializedObjects;
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="serializedData">The serialized data describing the model.</param>
/// <param name="stateHeaderBytes">
/// The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
/// </param>
internal SafetySharpRuntimeModel(SerializedRuntimeModel serializedData, int stateHeaderBytes = 0) : base(stateHeaderBytes)
{
Requires.That(serializedData.Model != null, "Expected a valid model instance.");
var buffer = serializedData.Buffer;
var rootComponents = serializedData.Model.Roots;
var objectTable = serializedData.ObjectTable;
var formulas = serializedData.Formulas;
Requires.NotNull(buffer, nameof(buffer));
Requires.NotNull(rootComponents, nameof(rootComponents));
Requires.NotNull(objectTable, nameof(objectTable));
Requires.NotNull(formulas, nameof(formulas));
Requires.That(stateHeaderBytes % 4 == 0, nameof(stateHeaderBytes), "Expected a multiple of 4.");
Model = serializedData.Model;
SerializedModel = buffer;
RootComponents = rootComponents.Cast<Component>().ToArray();
ExecutableStateFormulas = objectTable.OfType<ExecutableStateFormula>().ToArray();
Formulas = formulas;
StateConstraints = Model.Components.Cast<Component>().SelectMany(component => component.StateConstraints).ToArray();
// Create a local object table just for the objects referenced by the model; only these objects
// have to be serialized and deserialized. The local object table does not contain, for instance,
// the closure types of the state formulas.
Faults = objectTable.OfType<Fault>().Where(fault => fault.IsUsed).ToArray();
_serializedObjects = new ObjectTable(Model.ReferencedObjects);
Objects = objectTable;
StateVectorLayout = SerializationRegistry.Default.GetStateVectorLayout(Model, _serializedObjects, SerializationMode.Optimized);
UpdateFaultSets();
_deserialize = StateVectorLayout.CreateDeserializer(_serializedObjects);
_serialize = StateVectorLayout.CreateSerializer(_serializedObjects);
_restrictRanges = StateVectorLayout.CreateRangeRestrictor(_serializedObjects);
PortBinding.BindAll(objectTable);
InitializeConstructionState();
CheckConsistencyAfterInitialization();
}
/// <summary>
/// Gets a copy of the original model the runtime model was generated from.
/// </summary>
internal ModelBase Model { get; }
/// <summary>
/// Gets all of the objects referenced by the model, including those that do not take part in state serialization.
/// </summary>
internal ObjectTable Objects { get; }
/// <summary>
/// Gets the model's <see cref="StateVectorLayout" />.
/// </summary>
internal StateVectorLayout StateVectorLayout { get; }
/// <summary>
/// Gets the size of the state vector in bytes. The size is always a multiple of 4.
/// </summary>
public override int StateVectorSize => StateVectorLayout.SizeInBytes + StateHeaderBytes;
/// <summary>
/// Gets the root components of the model.
/// </summary>
public Component[] RootComponents { get; }
/// <summary>
/// Gets the state formulas of the model.
/// </summary>
internal ExecutableStateFormula[] ExecutableStateFormulas { get; }
/// <summary>
/// Gets the state formulas of the model.
/// </summary>
public override AtomarPropositionFormula[] AtomarPropositionFormulas => ExecutableStateFormulas;
/// <summary>
/// Computes an initial state of the model.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void ExecuteInitialStep()
{
foreach (var obj in _serializedObjects.OfType<IInitializable>())
{
try
{
obj.Initialize();
}
catch (Exception e)
{
throw new ModelException(e);
}
}
_restrictRanges();
}
/// <summary>
/// Updates the state of the model by executing a single step.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void ExecuteStep()
{
foreach (var component in RootComponents)
{
try
{
component.Update();
}
catch (Exception e)
{
throw new ModelException(e);
}
}
_restrictRanges();
}
/// <summary>
/// Disposes the object, releasing all managed and unmanaged resources.
/// </summary>
/// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param>
protected override void OnDisposing(bool disposing)
{
if (disposing)
Objects.OfType<IDisposable>().SafeDisposeAll();
}
/// <summary>
/// Creates a <see cref="SafetySharpRuntimeModel" /> instance from the <paramref name="model" /> and the <paramref name="formulas" />.
/// </summary>
/// <param name="model">The model the runtime model should be created for.</param>
/// <param name="formulas">The formulas the model should be able to check.</param>
internal static SafetySharpRuntimeModel Create(ModelBase model, params Formula[] formulas)
{
Requires.NotNull(model, nameof(model));
Requires.NotNull(formulas, nameof(formulas));
var creator = CreateExecutedModelCreator(model, formulas);
return creator.Create(0);
}
public override void SetChoiceResolver(ChoiceResolver choiceResolver)
{
foreach (var choice in Objects.OfType<Choice>())
choice.Resolver = choiceResolver;
}
public override CounterExampleSerialization<SafetySharpRuntimeModel> CounterExampleSerialization { get; } = new SafetySharpCounterExampleSerialization();
public static CoupledExecutableModelCreator<SafetySharpRuntimeModel> CreateExecutedModelCreator(ModelBase model, params Formula[] formulasToCheckInBaseModel)
{
Requires.NotNull(model, nameof(model));
Requires.NotNull(formulasToCheckInBaseModel, nameof(formulasToCheckInBaseModel));
Func<int,SafetySharpRuntimeModel> creatorFunc;
// serializer.Serialize has potentially a side effect: Model binding. The model gets bound when it isn't
// bound already. The lock ensures that this binding is only made by one thread because model.EnsureIsBound
// is not reentrant.
lock (model)
{
var serializer = new RuntimeModelSerializer();
model.EnsureIsBound(); // Bind the model explicitly. Otherwise serialize.Serializer makes it implicitly.
serializer.Serialize(model, formulasToCheckInBaseModel);
creatorFunc = serializer.Load;
}
var faults = model.Faults;
return new CoupledExecutableModelCreator<SafetySharpRuntimeModel>(creatorFunc, model, formulasToCheckInBaseModel, faults);
}
public static ExecutableModelCreator<SafetySharpRuntimeModel> CreateExecutedModelFromFormulasCreator(ModelBase model)
{
Requires.NotNull(model, nameof(model));
Func<Formula[],CoupledExecutableModelCreator <SafetySharpRuntimeModel>> creator = formulasToCheckInBaseModel =>
{
Requires.NotNull(formulasToCheckInBaseModel, nameof(formulasToCheckInBaseModel));
return CreateExecutedModelCreator(model, formulasToCheckInBaseModel);
};
return new ExecutableModelCreator<SafetySharpRuntimeModel>(creator, model);
}
public override Expression CreateExecutableExpressionFromAtomarPropositionFormula(AtomarPropositionFormula formula)
{
var executableStateFormula = formula as ExecutableStateFormula;
if (executableStateFormula!=null)
{
return Expression.Invoke(Expression.Constant(executableStateFormula.Expression));
}
throw new InvalidOperationException("AtomarPropositionFormula cannot be evaluated. Use ExecutableStateFormula instead.");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Drawing2D;
namespace Scheduler
{
public class Scheduler<T, K> : IRuntimeScheduler, IScheduler<K> where T:ScheduleTask, new()
{
internal class _Resource : IResource
{
public string Name
{
get;
set;
}
public int Count
{
get;
set;
}
public System.Drawing.Color Color
{
get;
set;
}
}
public void Register(string name, int count, int color)
{
_Resource r = new _Resource();
r.Name = name;
r.Count = count;
r.Color = Color.FromArgb(color);
this.Register(r);
}
protected List<ScheduleResource> _resources = new List<ScheduleResource>();
protected LinkedList<T> _tasks = new LinkedList<T>();
Nullable<DateTime> executeStart = null;
public int Current
{
get
{
if (!executeStart.HasValue)
return 0;
else
return (int)new TimeSpan(DateTime.Now.Ticks - executeStart.Value.Ticks).TotalSeconds;
}
}
public double CurrentExecuteTime
{
get
{
if (executeStart == null)
return 0;
else
return new TimeSpan(DateTime.Now.Ticks - executeStart.Value.Ticks).TotalSeconds;
}
}
public Nullable<DateTime> ExecuteStartTime
{
get { return executeStart; }
}
public void Register(IResource res)
{
if (res is ScheduleResource)
_resources.Add(res as ScheduleResource);
else
_resources.Add(new ScheduleResource(res));
}
public IRuntimeResource GetResource(string name)
{
for (int i = 0; i < _resources.Count; i++)
if (name.Equals(_resources[i].Name))
return _resources[i].RuntimeResource;
return null;
}
public int TaskCount
{
get { return _tasks.Count; }
}
public IRuntimeTask GetTask(int id)
{
LinkedListNode<T> t = _tasks.First;
while (t != null)
{
if (t.Value.ID == id)
return t.Value.RuntimeTask;
t = t.Next;
}
return null;
}
public IRuntimeResource[] Resources
{
get
{
IRuntimeResource[] res = new IRuntimeResource[_resources.Count];
for (int i = 0; i < _resources.Count; i++)
res[i] = _resources[i].RuntimeResource;
return res;
}
}
public IRuntimeTask[] Tasks
{
get
{
IRuntimeTask[] t = new IRuntimeTask[_tasks.Count];
int i = 0;
LinkedListNode<T> node = _tasks.First;
while (node != null)
{
t[i] = node.Value.RuntimeTask;
node = node.Next;
i++;
}
return t;
}
}
public virtual int Activate(K task)
{
return Activate(task, null);
}
private int ActivateImpl(T t, K task, Dictionary<int, TaskRelation> relations)
{
if (relations != null)
{
foreach (int key in relations.Keys)
{
t.Relations[key] = relations[key];
}
}
return ActivateImpl(t, task);
}
private int ActivateImpl(T t, K task)
{
if (_tasks.Contains(t))
return -1;
if (IsRunning)
{
List<ScheduleTask> TasksAfter = new List<ScheduleTask>();
foreach (int id in t.Relations.Keys)
{
TaskRelation tr = t.Relations[id];
if (tr == TaskRelation.BeforeRunEnd || tr == TaskRelation.BeforeRunStart)
{
IRuntimeTask it = GetTask(id);
if (it == null)
throw new Exception("subsequential task can not be found");
Status s = GetTask(id).Status;
if (s != Status.NotScheduled && s != Status.Scheduled && s != Status.Unscheduled && s != Status.NotSchedulable)
throw new Exception("subsequential task is running, processed");
}
}
}
LinkedListNode<T> node = null;
if (_tasks.Count == 0)
node = _tasks.AddFirst(t);
else
node = _tasks.AddLast(t);
t.ID = _tasks.Count;
t.Status = Status.NotScheduled;
t.Scheduler = this;
t.SetTask(task);
if (IsRunning)
{
Schedule();
}
return _tasks.Count;
}
public virtual int Activate(K task, Dictionary<int, TaskRelation> relations)
{
T t = new T();
if (relations != null)
{
foreach (int key in relations.Keys)
{
t.Relations[key] = relations[key];
}
}
return ActivateImpl(t, task);
}
public bool IsRunning
{
get
{
return executeStart != null && _runThread != null && _runThread.IsAlive;
}
}
Thread _runThread;
public void Run()
{
if (_runThread != null && _runThread.IsAlive)
return;
if(!executeStart.HasValue)
executeStart = DateTime.Now;
_runThread = new Thread(new ThreadStart(CheckThread));
_runThread.Start();
}
bool CheckTaskStartPoint(ScheduleTask t)
{
ScheduleActivity ac = t.Activities[0];
bool canStart = true;
foreach (LinkedListNode<UnitReservation> ur in ac.UnitReservations)
{
if (ur.Previous != null &&
(ur.Previous.Value.Activity.Status != Status.Cancelled && ur.Previous.Value.Activity.Status != Status.Processed && ur.Previous.Value.Activity.WaitingForCompleted!=true))
canStart = false;
}
foreach (ScheduleTask pt in t.TasksRunAfterEnd)
{
if (pt.Status != Status.Processed && pt.Status != Status.Cancelled)
canStart = false;
}
foreach (ScheduleTask pt in t.TasksRunAfterStart)
{
if (pt.Status == Status.Scheduled)
canStart = false;
}
if (CurrentExecuteTime < t.Activities[0].PlannedStart)
{
canStart = false;
}
return canStart;
}
void RunTask(object t)
{
(t as ScheduleTask).Execute(this);
}
void CheckThread()
{
while (true)
{
LinkedListNode<T> node = _tasks.First;
bool allFinished = true;
while (node != null)
{
if (node.Value.Status != Status.Processed && node.Value.Status != Status.Cancelled)
allFinished = false;
if (node.Value.Status == Status.Scheduled && CheckTaskStartPoint(node.Value))
{
node.Value.ActivityCompleted += new SchedulerEventHandler<ActivityEventArg>(OnActivityCompleted);
node.Value.ActivityStarted += new SchedulerEventHandler<ActivityEventArg>(OnActivityStarted);
node.Value.ActivityCancelled += new SchedulerEventHandler<ActivityEventArg>(OnActivityCancelled);
//node.Value.Execute(this);
Thread t = new Thread(new ParameterizedThreadStart(RunTask));
node.Value.Status = Status.Running;
t.Start(node.Value);
}
node = node.Next;
}
if (allFinished)
{
FireStateChanged();
return;
}
lock (this)
{
CheckRunState();
}
FireStateChanged();
Thread.Sleep(600);
}
}
void CheckMoveLeftOnActivityComplete(ScheduleActivity completedActivity, int completedActivityOffset)
{
LinkedListNode<T> node = _tasks.First;
int offset = completedActivityOffset;
int minNextTaskStartTime = int.MaxValue;
while (node != null)
{
if (node.Value.Status == Status.Running)
{
ScheduleActivity curAct = node.Value.CurrentRunningActivity;
if (curAct != null)
{
if (curAct.Status == Status.Running &&
curAct.WaitingForCompleted == true)
{
//int o = curAct.PlannedDuration - Current + curAct.PlannedStart;
//if (o < offset)
// offset = o;
offset = -1;
}
else if (curAct.Status == Status.Running)
{
int o = curAct.PlannedDuration - curAct.Duration;
if (o < offset)
offset = o;
}
else if (curAct.Equals(completedActivity))
{
}
else
{
offset = -1;
}
}
else
{
offset = -1;
//offsetRight = -1;
}
}
else if (node.Value.Status == Status.Scheduled)
{
int st = node.Value.PlannedStart;
if (st < minNextTaskStartTime)
minNextTaskStartTime = st;
}
node = node.Next;
}
if (offset != -1 && minNextTaskStartTime!=-1)
{
minNextTaskStartTime = minNextTaskStartTime - Current;
if (minNextTaskStartTime < offset)
offset = minNextTaskStartTime;
}
if (offset > 1)
{
node = _tasks.First;
while (node != null)
{
if (node.Value.Status != Status.Processed && node.Value.Status!=Status.Cancelled && node.Value.Status!=Status.Unscheduled
&& node.Value.Status!=Status.NotSchedulable)
{
ScheduleTask t = node.Value;
for (int i = 0; i < t.Activities.Length; i++)
{
ScheduleActivity ac = t.Activities[i];
if (ac.Status == Status.Running)
{
ac.PlannedDuration -= offset;
}
else if (ac.Status != Status.Processed && ac.Status!=Status.Cancelled)
{
ac.PlannedStart -= offset;
}
else if (ac.Status == Status.Processed)
{
}
}
}
node = node.Next;
}
CheckConflict("check left move afte task completed");
}
}
void CheckRunState()
{
//check run state
LinkedListNode<T> node = _tasks.First;
int offset = int.MaxValue;
int offsetRight = -1;
int minNextTaskStartTime = int.MaxValue;
ScheduleActivity moveAct = null;
while (node != null)
{
if (node.Value.Status == Status.Running && node.Value.Activities[0].Status!=Status.Scheduled)
{
ScheduleActivity curAct = node.Value.CurrentRunningActivity;
if (curAct != null)
{
if (curAct.Status == Status.Running &&
curAct.WaitingForCompleted == true)
{
int o1 = curAct.PlannedDuration - Current + curAct.PlannedStart;
if (o1 < offset)
offset = o1;
//offset = -1;
//int o = Current - curAct.PlannedStart - curAct.PlannedDuration;
//if (o > offsetRight)
{
//offsetRight = o;
//moveAct = curAct;
}
}
else if (curAct.Status == Status.Running)
{
//problem here
int o = curAct.PlannedDuration - curAct.Duration-(Current-curAct.PlannedStart);
if (o < offset)
offset = o;
o = Current - curAct.PlannedStart - curAct.PlannedDuration;
if (o > offsetRight)
{
offsetRight = o;
moveAct = curAct;
}
}
else// if (node.Value.CurrentRunningActivity.Status == Status.Processed)
{
offset = -1;
}
}
else
{
offset = -1;
//offsetRight = -1;
}
}
else if (node.Value.Status == Status.Scheduled || (node.Value.Status==Status.Running && node.Value.Activities[0].Status==Status.Scheduled))
{
int st = node.Value.PlannedStart;
if (st < minNextTaskStartTime)
minNextTaskStartTime = st;
int ostart = Current - node.Value.PlannedStart;
if (ostart > offsetRight)
{
offsetRight = ostart;
moveAct = node.Value.Activities[0];
}
}
node = node.Next;
}
if (offset != int.MaxValue)
{
minNextTaskStartTime = minNextTaskStartTime - Current;
if (minNextTaskStartTime < offset)
offset = minNextTaskStartTime;
}
if (offset > 2 && offset != int.MaxValue)
{
node = _tasks.First;
while (node != null)
{
if (node.Value.Status != Status.Processed && node.Value.Status!=Status.Cancelled
&& node.Value.Status!=Status.NotScheduled && node.Value.Status!=Status.NotSchedulable)
{
ScheduleTask t = node.Value;
for (int i = 0; i < t.Activities.Length; i++)
{
ScheduleActivity ac = t.Activities[i];
if (ac.Status == Status.Running)
{
ac.PlannedDuration -= offset;
}
else if (ac.Status != Status.Processed && ac.Status!=Status.Cancelled)
{
ac.PlannedStart -= offset;
}
else if (ac.Status == Status.Processed)
{
}
}
}
node = node.Next;
}
CheckConflict("ChckRunState move left");
//FireStateChanged();
}
else if (offsetRight >= 2)
{
MoveActivityRight(moveAct, offsetRight);
CheckConflict("ChckRunState move left");
//FireStateChanged();
}
}
void OnActivityCancelled(object sender, ActivityEventArg eventArgs)
{
ScheduleActivity act = eventArgs.Activity;
if (act == null)
return;
lock (this)
{
Console.WriteLine("task {0} - {1} activity {2} is cancelled", act.Task.ID, act.Task.Name, act.Name);
ScheduleActivity next=act;
while (next.Next != null)
next = next.Next;
int offset = next.PlannedDuration - Current + next.PlannedStart;
int planStart = act.PlannedStart;
if (act.Previous != null)
{
act.PlannedStart = act.Previous.PlannedDuration + act.Previous.PlannedStart;
}
act.PlannedDuration = Current - act.PlannedStart;
act.Status = Status.Cancelled;
act.Task.Status = Status.Cancelled;
this.Lock();
try
{
next = act.Next;
while (next != null)
{
foreach (string res in next.Resources.Keys)
{
foreach (ScheduleResource r in _resources)
{
if (res.Equals(r.Name))
{
r.RemoveReservationForActivity(next);
break;
}
}
}
next.Reservations.Clear();
next.UnitReservations.Clear();
next.Status = Status.Cancelled;
next.PlannedStart = next.Previous.PlannedDuration + next.Previous.PlannedStart;
next = next.Next;
}
if (offset > 0)
{
//移动activity左移
CheckMoveLeftOnActivityComplete(act, offset);
CheckConflict("Check move left cancelled");
}
FireScheduleStarted();
foreach (ScheduleTask t in _tasks)
{
if (t.Status == Status.Scheduled)
UnSchedule(t);
}
SchedulerImpl();
FireScheduleCompleted();
}
catch (Exception ex)
{
}
finally
{
this.Unlock();
}
FireStateChanged();
}
}
protected void OnActivityStarted(object sender, ActivityEventArg eventArgs)
{
lock (this)
{
ScheduleActivity act = eventArgs.Activity;
Console.WriteLine("task {0} - {1} activity {2} is started", act.Task.ID, act.Task.Name, act.Name);
int planStart = act.PlannedStart;
if (act.Previous != null)
act.PlannedStart = act.Previous.PlannedDuration + act.Previous.PlannedStart;
else
act.PlannedStart = Current;
if(act.Next!=null)
act.PlannedDuration += planStart - act.PlannedStart;
FireStateChanged();
}
}
protected void OnActivityCompleted(object sender, ActivityEventArg eventArgs)
{
lock (this)
{
ScheduleActivity act = eventArgs.Activity;
Console.WriteLine("task {0} - {1} activity {2} is completed", act.Task.ID, act.Task.Name, act.Name);
int offset = act.PlannedDuration - Current + act.PlannedStart;
act.PlannedDuration = Current - act.PlannedStart;
if (offset > 0)
{
//移动activity左移
CheckMoveLeftOnActivityComplete(act, offset);
CheckConflict("after task completed " + act.Task.ID);
if (act.Next != null && act.Next.PlannedStart != act.PlannedDuration + act.PlannedStart)
{
act.Next.PlannedDuration = act.Next.PlannedDuration + (act.Next.PlannedStart - (act.PlannedDuration + act.PlannedStart));
act.Next.PlannedStart = act.PlannedDuration + act.PlannedStart;
}
}
FireStateChanged();
}
}
Dictionary<string, ScheduleResource> _name2res = new Dictionary<string, ScheduleResource>();
Dictionary<int, ScheduleTask> _id2task = new Dictionary<int, ScheduleTask>();
ScheduleTask lastScheduledTask = null;
void UnSchedule(ScheduleTask t)
{
if (t.Status == Status.NotSchedulable || t.Status == Status.NotScheduled || t.Status==Status.Unscheduled)
return;
if (t.Status != Status.Scheduled)
{
throw new Exception("can not unschedule task " + t.ID + ", because it is running, processed");
}
//unschedule the task must be runned before it
LinkedListNode<T> node = _tasks.First;
while (node != null)
{
bool AfterT = false;
foreach (ScheduleTask task in node.Value.TasksRunAfterEnd)
{
if(task.Equals(t))
AfterT=true;
}
foreach (ScheduleTask task in node.Value.TasksRunAfterStart)
{
if (task.Equals(t))
AfterT = true;
}
if (AfterT)
UnSchedule(node.Value);
node = node.Next;
}
//unschedule
for (int i = 0; i < t.Activities.Length; i++)
{
Dictionary<ScheduleResource, bool> res = new Dictionary<ScheduleResource, bool>();
ScheduleActivity act = t.Activities[i];
foreach (LinkedListNode<UnitReservation> ur in act.UnitReservations)
{
res[ur.Value.Resource] = true;
}
foreach (ScheduleResource r in res.Keys)
r.RemoveReservationForActivity(act);
act.Reservations.Clear();
act.UnitReservations.Clear();
act.PlannedDuration = -1;
act.PlannedStart = -1;
act.Status = Status.Unscheduled;
}
t.Status = Status.Unscheduled;
//Console.WriteLine("task " + t.ID + " is unschedule");
FireStateChanged();
}
//stretch or move activity forward, if ok, return null, else return which activity should be move forward
private ScheduleActivity ScheduleBackward(ScheduleActivity ac, int endTime)
{
bool canSchedule = true;
int maxDuration = 0;
int ostart=ac.PlannedStart;
if (ac.Resources.Count > 0)
{
int checkstart=Math.Max(ac.PlannedStart,(int)( endTime - ac.Duration*(1-SchedulerSetting.Instance.DefaultDecreaseRate)));
for (int start = checkstart ; start >= ostart; start--)
{
ac.PlannedStart = start;
ac.PlannedDuration = endTime - start;
if (ac.MaxPlannedDuration >= ac.Duration && ac.PlannedDuration > ac.MaxPlannedDuration)
break;
else if (ac.MaxPlannedDuration < ac.Duration && ac.PlannedDuration > ac.Duration * SchedulerSetting.Instance.MaxPlantimeEnlarge)
break;
foreach (string key in ac.Resources.Keys)
{
ScheduleResource trc = _name2res[key];
int count = ac.Resources[key];
int[] units = null;
if ((units = trc.CheckReservation(ac, ac.PlannedStart, ac.PlannedDuration, count)) != null)
{
if (ac.PlannedDuration> maxDuration)
maxDuration = ac.PlannedDuration;
}
else
{
canSchedule = false;
}
if (!canSchedule)
break;
}
if (!canSchedule)
break;
}
}
else
{
if(ac.MaxPlannedDuration>ac.Duration)
maxDuration = Math.Min(ac.MaxPlannedDuration, endTime - ac.PlannedStart);
else
maxDuration=Math.Min(endTime-ac.PlannedStart,(int)(ac.Duration*SchedulerSetting.Instance.MaxPlantimeEnlarge));
}
if (canSchedule)
{
if (ac.Previous == null && maxDuration > ac.Duration)
maxDuration = ac.Duration;
ac.PlannedDuration = maxDuration;
ac.PlannedStart = endTime - maxDuration;
Console.WriteLine("!Make backward reservation for task {3} activity {0} start={1} duration={2} and endtime={4}",
ac.Name, ac.PlannedStart, ac.PlannedDuration, ac.Task.ID, endTime);
if (ac.Previous != null && ac.Previous.PlannedStart + ac.Previous.PlannedDuration != ac.PlannedStart)
{
return ScheduleBackward(ac.Previous, ac.PlannedStart);
}
return null;
}
return ac;
}
private bool ScheduleForeward(ScheduleActivity ac, int startTime)
{
ac.PlannedStart = startTime;
ac.PlannedDuration = ac.Duration;
int minPlannedDuration = int.MaxValue;
int maxNextFreeTime = 0;
bool canSchedule = true;
if (ac.Resources.Count > 0)
{
foreach (string key in ac.Resources.Keys)
{
ScheduleResource trc = _name2res[key];
int count = ac.Resources[key];
int nextFreeTimeOffset = -1;
int[] units = null;
int planedDuration = 0;
//增加下一个可用位置的记忆
if ((units = trc.CheckReservationForward(ac, ac.PlannedStart, ac.PlannedDuration, count, out planedDuration, out nextFreeTimeOffset)) != null)
{
if (planedDuration < minPlannedDuration)
minPlannedDuration = planedDuration;
if (nextFreeTimeOffset > maxNextFreeTime)
maxNextFreeTime = nextFreeTimeOffset;
}
else
{
if (nextFreeTimeOffset > maxNextFreeTime)
maxNextFreeTime = nextFreeTimeOffset;
canSchedule = false;
}
}
}
else
{
minPlannedDuration = ac.Duration;
maxNextFreeTime = ac.PlannedStart + 1;
}
if (canSchedule)
{
//make reservation
ac.PlannedDuration = minPlannedDuration;
ac.NextAvailableTime = startTime + maxNextFreeTime;
Console.WriteLine("Make forward reservation for task {3} activity {0} start={1} duration={2}", ac.Name, ac.PlannedStart, ac.PlannedDuration,ac.Task.ID);
if (ac.Next != null)
return ScheduleForeward(ac.Next, ac.PlannedStart + ac.PlannedDuration);
else
return true;
}
else
{
bool forward = true;
ScheduleActivity mact = null;
if (ac.Previous != null)
forward = ((mact=ScheduleBackward(ac.Previous, ac.PlannedStart + maxNextFreeTime))==null);
if (forward)
{
return ScheduleForeward(ac, startTime + maxNextFreeTime);
}
else
{
return ScheduleForeward(
mact,
Math.Max(mact.NextAvailableTime, (mact.PlannedStart + 1)));
}
}
}
private void DoSchedule(ScheduleTask t, int level = 0)
{
if (level >= _tasks.Count)
throw new Exception("can not schedule the task due to task relations");
if (t.Status != Status.NotScheduled && t.Status != Status.Unscheduled)
{
return;
}
int startTime = Current;
//unschedule the task must be runned before it
{
LinkedListNode<T> node = _tasks.First;
while (node != null)
{
bool AfterT = false;
foreach (ScheduleTask task in node.Value.TasksRunAfterEnd)
{
if (task.Equals(t))
AfterT = true;
}
foreach (ScheduleTask task in node.Value.TasksRunAfterStart)
{
if (task.Equals(t))
AfterT = true;
}
if (AfterT)
{
UnSchedule(node.Value);
}
node = node.Next;
}
}
//end of unschedule
if (t.TasksRunAfterEnd.Count > 0 || t.TasksRunAfterStart.Count > 0)
{
foreach (ScheduleTask task in t.TasksRunAfterStart)
{
level++;
if (task.Status == Status.NotScheduled)
{
DoSchedule(task, level);
}
startTime = Math.Max(startTime, task.PlannedStart);
}
foreach (ScheduleTask task in t.TasksRunAfterEnd)
{
level++;
if (task.Status == Status.NotScheduled)
{
DoSchedule(task, level);
}
startTime = Math.Max(startTime, task.PlannedStart + task.PlannedDuration);
}
}
if (ScheduleForeward(t.Activities[0], startTime))
{
for (int j = 0; j < t.Activities.Length; j++)
{
ScheduleActivity ac = t.Activities[j];
foreach (string key in ac.Resources.Keys)
{
ScheduleResource trc = _name2res[key];
int count = t.Activities[j].Resources[key];
ac.Reservations[key] = trc.Reserve(ac, ac.PlannedStart, ac.PlannedDuration, count);
if (ac.Reservations[key] == null)
{
throw new Exception("unexpected scheduler error");
}
}
ac.Status = Status.Scheduled;
}
t.Status = Status.Scheduled;
}
else
{
throw new Exception("unexpected scheduler error");
}
if (t.Status != Status.Scheduled)
{
t.Status = Status.NotSchedulable;
}
}
public void Schedule()
{
FireScheduleStarted();
lock(this){
this.Lock();
SchedulerImpl();
this.Unlock();
}
FireScheduleCompleted();
FireStateChanged();
}
protected void SchedulerImpl()
{
_name2res.Clear();
_id2task.Clear();
foreach (ScheduleResource t in _resources)
{
_name2res[t.Name] = t;
}
LinkedListNode<T> node = _tasks.First;
while (node != null)
{
//if (node.Value.Status == Status.NotScheduled)
_id2task[node.Value.ID] = node.Value;
node = node.Next;
}
foreach (ScheduleTask t in _tasks)
{
if (t.Status == Status.NotScheduled || t.Status == Status.Unscheduled)
{
Boolean canSchedule = true;
if (t.Activities == null || t.Activities.Length == 0)
canSchedule = false;
else
foreach (ScheduleActivity act in t.Activities)
{
foreach (string res in act.Resources.Keys)
{
if (!_name2res.ContainsKey(res))
{
canSchedule = false;
}
else if (_name2res[res].AvailableCount < act.Resources[res])
canSchedule = false;
}
}
if (!canSchedule)
t.Status = Status.NotSchedulable;
}
}
node = _tasks.First;
while (node != null)
{
foreach (int key in node.Value.Relations.Keys)
{
TaskRelation rel = node.Value.Relations[key];
ScheduleTask t = _id2task[key];
if (rel == TaskRelation.AfterTaskStart)
{
if (!node.Value.TasksRunAfterStart.Contains(t))
{
node.Value.TasksRunAfterStart.Add(t);
}
}
if (rel == TaskRelation.AfterTaskEnd)
{
if (!node.Value.TasksRunAfterEnd.Contains(t))
{
node.Value.TasksRunAfterEnd.Add(t);
}
}
if (rel == TaskRelation.BeforeRunStart)
{
if (!t.TasksRunAfterStart.Contains(node.Value))
{
t.TasksRunAfterStart.Add(node.Value);
}
}
if (rel == TaskRelation.BeforeRunEnd)
{
if (!t.TasksRunAfterEnd.Contains(node.Value))
{
t.TasksRunAfterEnd.Add(node.Value);
}
}
}
node = node.Next;
}
int count = 1;
while (count > 0)
{
count = 0;
node = _tasks.First;
while (node != null)
{
//Console.WriteLine("task {0} status is {1} and {2} activies", node.Value.ID, node.Value.Status, node.Value.Activities.Length);
if ((node.Value.Status == Status.NotScheduled || node.Value.Status == Status.Unscheduled)
&& node.Value.Status != Status.NotSchedulable
)// && !_scheduledTasks.ContainsKey(node.Value.ID))
{
count++;
DoSchedule(node.Value);
}
node = node.Next;
}
}
}
public bool CheckActivityStart(ScheduleActivity next)
{
lock (this)
{
bool canRunNext = true;
if (next != null && next.UnitReservations.Count > 0)
{
for (int j = 0; j < next.UnitReservations.Count; j++)
{
//TODO互锁问题需要解决
LinkedListNode<UnitReservation> nur = next.UnitReservations[j].Previous;
if (nur != null)// && !currentUnit.ContainsKey(nur))
{
ScheduleActivity pRAct = nur.Value.Activity;
if (nur.Value.Activity.Status != Status.Processed && nur.Value.Activity.Status != Status.Cancelled && pRAct.WaitingForCompleted != true)
{
canRunNext = false;
}
}
}
}
return canRunNext;
}
}
//event
Boolean isScheduling=false;
public bool Scheduling { get { return isScheduling; } }
public event EventHandler<SchedulerStateChangeEventArg> StateChanged;
public event EventHandler<SchedulerStateChangeEventArg> TaskScheduleStarted;
public event EventHandler<SchedulerStateChangeEventArg> TaskScheduleCompleted;
void FireScheduleStarted()
{
isScheduling = true;
if (TaskScheduleStarted != null)
TaskScheduleStarted(this, new SchedulerStateChangeEventArg());
}
void FireScheduleCompleted()
{
isScheduling = false;
if (TaskScheduleCompleted != null)
TaskScheduleCompleted(this, new SchedulerStateChangeEventArg());
}
void FireStateChanged()
{
if (StateChanged != null)
{
StateChanged(this, new SchedulerStateChangeEventArg());
}
}
void MoveActivityLeft(ScheduleActivity act, int offset)
{
ScheduleActivity a = act.Next;
int offset2 = int.MaxValue;
foreach (LinkedListNode<UnitReservation> ur in a.UnitReservations)
{
if (ur.Previous != null)
{
int d = ur.Value.Activity.PlannedStart - (ur.Previous.Value.Activity.PlannedStart + ur.Previous.Value.Activity.PlannedDuration);
if (d < offset2)
offset2 = d;
}
}
if (offset < offset2)
offset2 = offset;
if (offset2 <= 0)
return;
a.PlannedStart -= offset2;
if (a.Next != null)
MoveActivityLeft(a.Next, offset2);
foreach (LinkedListNode<UnitReservation> ur in a.UnitReservations)
{
if (ur.Next != null)
MoveActivityLeft(ur.Next.Value.Activity, offset2);
}
}
void MoveAllActivityleft(int offset)
{
LinkedListNode<T> node = _tasks.First;
while (node != null)
{
ScheduleTask t = node.Value;
if (t.Status != Status.Processed && t.Status != Status.Cancelled)
{
for (int i = 0; i < t.Activities.Length; i++)
{
ScheduleActivity ac = t.Activities[i];
if (ac.Status == Status.Running)
{
ac.PlannedDuration -= offset;
}
else if (ac.Status != Status.Processed)
{
ac.PlannedStart -= offset;
}
}
}
node = node.Next;
}
}
//>>>>>>>>>>>
void DoMovePreActivity(ScheduleActivity act)
{
ScheduleActivity pre = act.Previous;
while (pre != null)
{
if (pre.Status == Status.Processed )
return;
ScheduleActivity next = pre.Next;
int gap = next.PlannedStart - pre.PlannedStart - pre.PlannedDuration;
if (gap <= 0)
{
return;
}
bool canMove = true;
foreach (LinkedListNode<UnitReservation> ur in pre.UnitReservations)
{
if (ur.Next != null && ur.Next.Value.PlannedStart - ur.Value.PlannedStart - ur.Value.PlannedDuration < gap)
{
canMove = false;
}
}
if (pre.Status == Status.Running)
{
pre.PlannedDuration += gap;
return;
}
if (canMove || next.Equals(act))
{
pre.PlannedStart += gap;
}
else
{
bool canStretch = true;
foreach (LinkedListNode<UnitReservation> ur in pre.Next.UnitReservations)
{
if (ur.Previous != null && ur.Value.PlannedStart - ur.Previous.Value.PlannedStart - ur.Previous.Value.PlannedDuration < gap)
canStretch = false;
}
if (canStretch)
{
next.PlannedStart -= gap;
next.PlannedDuration += gap;
}
}
pre = pre.Previous;
}
}
void DoMoveActibityRight(ScheduleActivity act, int offset, int level = 0)
{
int start = act.PlannedStart;
int duration = act.PlannedDuration;
level += 1;
//处理后边的activity
if (act.Status != Status.Scheduled && act.Status != Status.Running)
return;
if (act.Next != null)
{
ScheduleActivity s = act.Next;
if (s != null)
{
//nextActs[s] = true;
int offset2 = s.PlannedStart - start - duration;
int offset3 = s.PlannedDuration - s.Duration;
if (offset3>0 && offset3>=offset)
{
s.PlannedStart += offset;
s.PlannedDuration -= offset;
}
else if (offset3 > 0 && offset3<offset)
{
s.PlannedStart += offset3;
s.PlannedDuration -= offset3;
DoMoveActibityRight(s, offset - offset3, level);
}
else if (offset3<=0 && offset2 < offset && offset-offset2>0)
{
DoMoveActibityRight(s, offset - offset2, level);
}
}
}
if (act.UnitReservations != null)
{
for (int i = 0; i < act.UnitReservations.Count; i++)
{
//Dictionary<ScheduleActivity, bool> nextActs = new Dictionary<ScheduleActivity, bool>();
if (act.UnitReservations[i].Next != null)
{
ScheduleActivity s = act.UnitReservations[i].Next.Value.Activity;
//if (nextActs.ContainsKey(s))
if (s != null)
{
//nextActs[s] = true;
int offset2 = s.PlannedStart - start - duration;
int offset3 = s.PlannedDuration - s.Duration;
if (offset3 > 0 && offset3 >= offset)
{
s.PlannedStart += offset;
s.PlannedDuration -= offset;
}
else if (offset3 > 0 && offset3 < offset)
{
s.PlannedStart += offset3;
s.PlannedDuration -= offset3;
DoMoveActibityRight(s, offset - offset3, level);
}
else if (offset3 <= 0 && offset2 < offset && offset - offset2 > 0)
{
DoMoveActibityRight(s, offset - offset2, level);
}
}
}
}
}
if (act.Index == act.Task.ActivityCount - 1)
{
LinkedListNode<T> node = _tasks.First;
while (node != null)
{
if (node.Value.TasksRunAfterEnd.Contains(act.Task))
{
ScheduleActivity s = node.Value.Activities[0];
if (s != null)
{
//nextActs[s] = true;
int offset2 = s.PlannedStart - start - duration;
if (offset2 < offset)
{
DoMoveActibityRight(s, offset - offset2, level);
}
}
}
node = node.Next;
}
}
if (level != 1)
{
act.PlannedStart += offset;
//DoMovePreActivity(act);
}
else
{
if (act.Status == Status.Scheduled)
{
act.PlannedStart += offset;
}
else
{
act.PlannedDuration += offset;
}
}
}
void MoveActivityRight(ScheduleActivity act, int offset)
{
DoMoveActibityRight(act, offset);
int count = 0;
while ((count = DoMoveGap()) > 0)
{
}
DoMoveGapLeft();
}
void DoMoveGapLeft()
{
//前移有空隙的Activity
LinkedListNode<T> node = _tasks.First;
while (node != null)
{
ScheduleTask t = node.Value;
if (!(t.Status == Status.Scheduled || t.Status == Status.Running))
{
node = node.Next;
continue;
}
for (int i = t.Activities.Length - 1; i >=1 ; i--)
{
ScheduleActivity aNext = t.Activities[i];
if (aNext.Status == Status.Processed || aNext.Status==Status.Cancelled || aNext.Status == Status.Running)
{
break;
}
int distance = aNext.PlannedStart - aNext.Previous.PlannedStart - aNext.Previous.PlannedDuration;
if (distance <= 0)
continue;
//前边activity向左延伸
bool canStretch = true;
foreach (LinkedListNode<UnitReservation> ur in aNext.UnitReservations)
{
if (ur.Previous != null)
{
int d = ur.Value.PlannedStart - ur.Previous.Value.PlannedStart - ur.Previous.Value.PlannedDuration;
if (d < distance)
canStretch = false;
}
}
if (canStretch)
{
aNext.PlannedStart -= distance;
aNext.PlannedDuration += distance;
}
else
{
MoveActivityRight(aNext.Previous, distance);
}
}
node = node.Next;
}
}
int DoMoveGap()
{
//前移有空隙的Activity
LinkedListNode<T> node = _tasks.Last;
int movedCount = 0;
while (node != null)
{
ScheduleTask t = node.Value;
if (!(t.Status == Status.Scheduled || t.Status == Status.Running))
{
node = node.Previous;
continue;
}
for (int i = t.Activities.Length - 2; i >= 0; i--)
{
ScheduleActivity a = t.Activities[i];
ScheduleActivity aNext = t.Activities[i + 1];
bool canMove = true;
if (a.Status == Status.Processed || a.Status==Status.Cancelled)
{
break;
}
int distance = aNext.PlannedStart - a.PlannedStart - a.PlannedDuration;
if (distance <= 0)
continue;
foreach (LinkedListNode<UnitReservation> ur in a.UnitReservations)
{
if (ur.Next != null)
{
int d = ur.Next.Value.PlannedStart - ur.Value.PlannedDuration - ur.Value.PlannedStart;
if (d < distance)
distance = d;
}
}
if (distance <= 0)
continue;
if (a.Status == Status.Running)
{
a.PlannedDuration += distance;
movedCount++;
}
else if (canMove)
{
a.PlannedStart += distance;
movedCount++;
}
}
node = node.Previous;
}
return movedCount;
}
bool CheckConflict(string desc)
{
return false;
bool ok = true;
foreach (ScheduleResource res in _resources)
{
for (int i = 0; i < res.Count; i++)
{
UnitReservations ur = res.GetReservationsForUnit(i);
LinkedListNode<UnitReservation> node = ur.First;
while (node != null)
{
if (node.Next != null)
{
if(ScheduleResource.IsIntersct2(node.Value.PlannedStart, node.Value.PlannedDuration+node.Value.PlannedStart,
node.Next.Value.PlannedStart, node.Next.Value.PlannedStart+node.Next.Value.PlannedDuration)){
ScheduleActivity a = node.Value.Activity;
ScheduleActivity aNext = node.Next.Value.Activity;
MessageBox.Show(string.Format("activity {0}/{1} {4}-{5} and {2}/{3} {6}-{7} conflict",
a.Name, a.Task.ID, aNext.Name, aNext.Task.ID, a.PlannedStart, a.PlannedDuration,
aNext.PlannedStart, aNext.PlannedDuration),desc);
ok = false;
}
}
node = node.Next;
}
}
}
return !ok;
}
public void Lock()
{
Monitor.Enter(_tasks);
}
public void Unlock()
{
Monitor.Exit(_tasks);
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RenderingExtensions.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides extension methods for <see cref="IRenderContext" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Provides extension methods for <see cref="IRenderContext" />.
/// </summary>
public static class RenderingExtensions
{
/* Length constants used to draw triangles and stars
___
/\ |
/ \ |
/ \ | M2
/ \ |
/ \ |
/ + \ ---
/ \ |
/ \ | M1
/________________\ _|_
|--------|-------|
1 1
|
\ | / ---
\ | / | M3
\ | / |
---------+-------- ---
/ | \ | M3
/ | \ |
/ | \ ---
|
|-----|-----|
M3 M3
*/
/// <summary>
/// The vertical distance to the bottom points of the triangles.
/// </summary>
private static readonly double M1 = Math.Tan(Math.PI / 6);
/// <summary>
/// The vertical distance to the top points of the triangles .
/// </summary>
private static readonly double M2 = Math.Sqrt(1 + (M1 * M1));
/// <summary>
/// The horizontal/vertical distance to the end points of the stars.
/// </summary>
private static readonly double M3 = Math.Tan(Math.PI / 4);
/// <summary>
/// Draws a clipped polyline through the specified points.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="points">The points.</param>
/// <param name="minDistSquared">The minimum line segment length (squared).</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="strokeThickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array (in device independent units, 1/96 inch).</param>
/// <param name="lineJoin">The line join.</param>
/// <param name="aliased">Set to <c>true</c> to draw as an aliased line.</param>
/// <param name="outputBuffer">The output buffer.</param>
/// <param name="pointsRendered">The points rendered callback.</param>
public static void DrawClippedLine(
this IRenderContext rc,
OxyRect clippingRectangle,
IList<ScreenPoint> points,
double minDistSquared,
OxyColor stroke,
double strokeThickness,
double[] dashArray,
OxyPenLineJoin lineJoin,
bool aliased,
List<ScreenPoint> outputBuffer = null,
Action<IList<ScreenPoint>> pointsRendered = null)
{
var n = points.Count;
if (n == 0)
{
return;
}
if (outputBuffer != null)
{
outputBuffer.Clear();
}
else
{
outputBuffer = new List<ScreenPoint>(n);
}
// draws the points in the output buffer and calls the callback (if specified)
Action drawLine = () =>
{
EnsureNonEmptyLineIsVisible(outputBuffer);
rc.DrawLine(outputBuffer, stroke, strokeThickness, dashArray, lineJoin, aliased);
// Execute the 'callback'
if (pointsRendered != null)
{
pointsRendered(outputBuffer);
}
};
var clipping = new CohenSutherlandClipping(clippingRectangle);
if (n == 1 && clipping.IsInside(points[0]))
{
outputBuffer.Add(points[0]);
}
int lastPointIndex = 0;
for (int i = 1; i < n; i++)
{
// Calculate the clipped version of previous and this point.
var sc0 = points[i - 1];
var sc1 = points[i];
bool isInside = clipping.ClipLine(ref sc0, ref sc1);
if (!isInside)
{
// the line segment is outside the clipping rectangle
// keep the previous coordinate for minimum distance comparison
continue;
}
// length calculation (inlined for performance)
var dx = sc1.X - points[lastPointIndex].X;
var dy = sc1.Y - points[lastPointIndex].Y;
if ((dx * dx) + (dy * dy) > minDistSquared || outputBuffer.Count == 0 || i == n - 1)
{
// point comparison inlined for performance
// ReSharper disable CompareOfFloatsByEqualityOperator
if (sc0.X != points[lastPointIndex].X || sc0.Y != points[lastPointIndex].Y || outputBuffer.Count == 0)
// ReSharper restore disable CompareOfFloatsByEqualityOperator
{
outputBuffer.Add(new ScreenPoint(sc0.X, sc0.Y));
}
outputBuffer.Add(new ScreenPoint(sc1.X, sc1.Y));
lastPointIndex = i;
}
if (clipping.IsInside(points[i]) || outputBuffer.Count == 0)
{
continue;
}
// we are leaving the clipping region - render the line
drawLine();
outputBuffer.Clear();
}
if (outputBuffer.Count > 0)
{
drawLine();
}
}
/// <summary>
/// Draws the clipped line segments.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke.</param>
/// <param name="strokeThickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array (in device independent units, 1/96 inch).</param>
/// <param name="lineJoin">The line join.</param>
/// <param name="aliased">Set to <c>true</c> to draw as an aliased line.</param>
public static void DrawClippedLineSegments(
this IRenderContext rc,
OxyRect clippingRectangle,
IList<ScreenPoint> points,
OxyColor stroke,
double strokeThickness,
double[] dashArray,
OxyPenLineJoin lineJoin,
bool aliased)
{
if (rc.SetClip(clippingRectangle))
{
rc.DrawLineSegments(points, stroke, strokeThickness, dashArray, lineJoin, aliased);
rc.ResetClip();
return;
}
var clipping = new CohenSutherlandClipping(clippingRectangle);
var clippedPoints = new List<ScreenPoint>(points.Count);
for (int i = 0; i + 1 < points.Count; i += 2)
{
var s0 = points[i];
var s1 = points[i + 1];
if (clipping.ClipLine(ref s0, ref s1))
{
clippedPoints.Add(s0);
clippedPoints.Add(s1);
}
}
rc.DrawLineSegments(clippedPoints, stroke, strokeThickness, dashArray, lineJoin, aliased);
}
/// <summary>
/// Draws the specified image.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="image">The image.</param>
/// <param name="x">The destination X position.</param>
/// <param name="y">The destination Y position.</param>
/// <param name="w">The width.</param>
/// <param name="h">The height.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolate">Interpolate the image if set to <c>true</c>.</param>
public static void DrawImage(
this IRenderContext rc,
OxyImage image,
double x,
double y,
double w,
double h,
double opacity,
bool interpolate)
{
rc.DrawImage(image, 0, 0, image.Width, image.Height, x, y, w, h, opacity, interpolate);
}
/// <summary>
/// Draws the clipped image.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="source">The source.</param>
/// <param name="x">The destination X position.</param>
/// <param name="y">The destination Y position.</param>
/// <param name="w">The width.</param>
/// <param name="h">The height.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolate">interpolate if set to <c>true</c>.</param>
public static void DrawClippedImage(
this IRenderContext rc,
OxyRect clippingRectangle,
OxyImage source,
double x,
double y,
double w,
double h,
double opacity,
bool interpolate)
{
if (x > clippingRectangle.Right || x + w < clippingRectangle.Left || y > clippingRectangle.Bottom || y + h < clippingRectangle.Top)
{
return;
}
if (rc.SetClip(clippingRectangle))
{
// The render context supports clipping, then we can draw the whole image
rc.DrawImage(source, x, y, w, h, opacity, interpolate);
rc.ResetClip();
return;
}
// Fint the positions of the clipping rectangle normalized to image coordinates (0,1)
var i0 = (clippingRectangle.Left - x) / w;
var i1 = (clippingRectangle.Right - x) / w;
var j0 = (clippingRectangle.Top - y) / h;
var j1 = (clippingRectangle.Bottom - y) / h;
// Find the origin of the clipped source rectangle
var srcx = i0 < 0 ? 0u : i0 * source.Width;
var srcy = j0 < 0 ? 0u : j0 * source.Height;
srcx = (int)Math.Ceiling(srcx);
srcy = (int)Math.Ceiling(srcy);
// Find the size of the clipped source rectangle
var srcw = i1 > 1 ? source.Width - srcx : (i1 * source.Width) - srcx;
var srch = j1 > 1 ? source.Height - srcy : (j1 * source.Height) - srcy;
srcw = (int)srcw;
srch = (int)srch;
if ((int)srcw <= 0 || (int)srch <= 0)
{
return;
}
// The clipped destination rectangle
var destx = i0 < 0 ? x : x + (srcx / source.Width * w);
var desty = j0 < 0 ? y : y + (srcy / source.Height * h);
var destw = w * srcw / source.Width;
var desth = h * srch / source.Height;
rc.DrawImage(source, srcx, srcy, srcw, srch, destx, desty, destw, desth, opacity, interpolate);
}
/// <summary>
/// Draws the polygon within the specified clipping rectangle.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="points">The points.</param>
/// <param name="minDistSquared">The squared minimum distance between points.</param>
/// <param name="fill">The fill.</param>
/// <param name="stroke">The stroke.</param>
/// <param name="strokeThickness">The stroke thickness.</param>
/// <param name="lineStyle">The line style.</param>
/// <param name="lineJoin">The line join.</param>
/// <param name="aliased">The aliased.</param>
public static void DrawClippedPolygon(
this IRenderContext rc,
OxyRect clippingRectangle,
IList<ScreenPoint> points,
double minDistSquared,
OxyColor fill,
OxyColor stroke,
double strokeThickness = 1.0,
LineStyle lineStyle = LineStyle.Solid,
OxyPenLineJoin lineJoin = OxyPenLineJoin.Miter,
bool aliased = false)
{
// TODO: minDistSquared should be implemented or removed
if (rc.SetClip(clippingRectangle))
{
rc.DrawPolygon(points, fill, stroke, strokeThickness, lineStyle.GetDashArray(), lineJoin, aliased);
rc.ResetClip();
return;
}
var clippedPoints = SutherlandHodgmanClipping.ClipPolygon(clippingRectangle, points);
rc.DrawPolygon(clippedPoints, fill, stroke, strokeThickness, lineStyle.GetDashArray(), lineJoin, aliased);
}
/// <summary>
/// Draws the clipped rectangle.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="rect">The rectangle to draw.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public static void DrawClippedRectangle(
this IRenderContext rc,
OxyRect clippingRectangle,
OxyRect rect,
OxyColor fill,
OxyColor stroke,
double thickness)
{
if (rc.SetClip(clippingRectangle))
{
rc.DrawRectangle(rect, fill, stroke, thickness);
rc.ResetClip();
return;
}
var clippedRect = ClipRect(rect, clippingRectangle);
if (clippedRect == null)
{
return;
}
rc.DrawRectangle(clippedRect.Value, fill, stroke, thickness);
}
/// <summary>
/// Draws the clipped rectangle as a polygon.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="rect">The rectangle to draw.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public static void DrawClippedRectangleAsPolygon(
this IRenderContext rc,
OxyRect clippingRectangle,
OxyRect rect,
OxyColor fill,
OxyColor stroke,
double thickness)
{
if (rc.SetClip(clippingRectangle))
{
rc.DrawRectangleAsPolygon(rect, fill, stroke, thickness);
rc.ResetClip();
return;
}
var clippedRect = ClipRect(rect, clippingRectangle);
if (clippedRect == null)
{
return;
}
rc.DrawRectangleAsPolygon(clippedRect.Value, fill, stroke, thickness);
}
/// <summary>
/// Draws a clipped ellipse.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="n">The number of points around the ellipse.</param>
public static void DrawClippedEllipse(
this IRenderContext rc,
OxyRect clippingRectangle,
OxyRect rect,
OxyColor fill,
OxyColor stroke,
double thickness,
int n = 100)
{
if (rc.SetClip(clippingRectangle))
{
rc.DrawEllipse(rect, fill, stroke, thickness);
rc.ResetClip();
return;
}
var points = new ScreenPoint[n];
double cx = (rect.Left + rect.Right) / 2;
double cy = (rect.Top + rect.Bottom) / 2;
double rx = (rect.Right - rect.Left) / 2;
double ry = (rect.Bottom - rect.Top) / 2;
for (int i = 0; i < n; i++)
{
double a = Math.PI * 2 * i / (n - 1);
points[i] = new ScreenPoint(cx + (rx * Math.Cos(a)), cy + (ry * Math.Sin(a)));
}
rc.DrawClippedPolygon(clippingRectangle, points, 4, fill, stroke, thickness);
}
/// <summary>
/// Draws the clipped text.
/// </summary>
/// <param name="rc">The rendering context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="p">The position.</param>
/// <param name="text">The text.</param>
/// <param name="fill">The fill color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="rotate">The rotation angle.</param>
/// <param name="horizontalAlignment">The horizontal align.</param>
/// <param name="verticalAlignment">The vertical align.</param>
/// <param name="maxSize">Size of the max.</param>
public static void DrawClippedText(
this IRenderContext rc,
OxyRect clippingRectangle,
ScreenPoint p,
string text,
OxyColor fill,
string fontFamily = null,
double fontSize = 10,
double fontWeight = 500,
double rotate = 0,
HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment verticalAlignment = VerticalAlignment.Top,
OxySize? maxSize = null)
{
if (rc.SetClip(clippingRectangle))
{
rc.DrawText(p, text, fill, fontFamily, fontSize, fontWeight, rotate, horizontalAlignment, verticalAlignment, maxSize);
rc.ResetClip();
return;
}
// fall back simply check position
if (clippingRectangle.Contains(p.X, p.Y))
{
rc.DrawText(p, text, fill, fontFamily, fontSize, fontWeight, rotate, horizontalAlignment, verticalAlignment, maxSize);
}
}
/// <summary>
/// Draws clipped math text.
/// </summary>
/// <param name="rc">The rendering context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="p">The position.</param>
/// <param name="text">The text.</param>
/// <param name="fill">The fill color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="rotate">The rotation angle.</param>
/// <param name="horizontalAlignment">The horizontal align.</param>
/// <param name="verticalAlignment">The vertical align.</param>
/// <param name="maxSize">Size of the max.</param>
public static void DrawClippedMathText(
this IRenderContext rc,
OxyRect clippingRectangle,
ScreenPoint p,
string text,
OxyColor fill,
string fontFamily = null,
double fontSize = 10,
double fontWeight = 500,
double rotate = 0,
HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment verticalAlignment = VerticalAlignment.Top,
OxySize? maxSize = null)
{
if (rc.SetClip(clippingRectangle))
{
rc.DrawMathText(p, text, fill, fontFamily, fontSize, fontWeight, rotate, horizontalAlignment, verticalAlignment, maxSize);
rc.ResetClip();
return;
}
// fall back simply check position
if (clippingRectangle.Contains(p.X, p.Y))
{
rc.DrawMathText(p, text, fill, fontFamily, fontSize, fontWeight, rotate, horizontalAlignment, verticalAlignment, maxSize);
}
}
/// <summary>
/// Draws multi-line text at the specified point.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="point">The point.</param>
/// <param name="text">The text.</param>
/// <param name="color">The text color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">The font size.</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="dy">The line spacing.</param>
public static void DrawMultilineText(this IRenderContext rc, ScreenPoint point, string text, OxyColor color, string fontFamily = null, double fontSize = 10, double fontWeight = FontWeights.Normal, double dy = 12)
{
var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++)
{
rc.DrawText(
new ScreenPoint(point.X, point.Y + (i * dy)),
lines[i],
color,
fontWeight: fontWeight,
fontSize: fontSize);
}
}
/// <summary>
/// Draws a line specified by coordinates.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="x0">The x0.</param>
/// <param name="y0">The y0.</param>
/// <param name="x1">The x1.</param>
/// <param name="y1">The y1.</param>
/// <param name="pen">The pen.</param>
/// <param name="aliased">Aliased line if set to <c>true</c>.</param>
public static void DrawLine(
this IRenderContext rc, double x0, double y0, double x1, double y1, OxyPen pen, bool aliased = true)
{
if (pen == null)
{
return;
}
rc.DrawLine(
new[] { new ScreenPoint(x0, y0), new ScreenPoint(x1, y1) },
pen.Color,
pen.Thickness,
pen.ActualDashArray,
pen.LineJoin,
aliased);
}
/// <summary>
/// Draws the line segments.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="points">The points.</param>
/// <param name="pen">The pen.</param>
/// <param name="aliased">if set to <c>true</c> [aliased].</param>
public static void DrawLineSegments(
this IRenderContext rc, IList<ScreenPoint> points, OxyPen pen, bool aliased = true)
{
if (pen == null)
{
return;
}
rc.DrawLineSegments(points, pen.Color, pen.Thickness, pen.ActualDashArray, pen.LineJoin, aliased);
}
/// <summary>
/// Renders the marker.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="p">The center point of the marker.</param>
/// <param name="type">The marker type.</param>
/// <param name="outline">The outline.</param>
/// <param name="size">The size of the marker.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="strokeThickness">The stroke thickness.</param>
public static void DrawMarker(
this IRenderContext rc,
OxyRect clippingRectangle,
ScreenPoint p,
MarkerType type,
IList<ScreenPoint> outline,
double size,
OxyColor fill,
OxyColor stroke,
double strokeThickness)
{
rc.DrawMarkers(clippingRectangle, new[] { p }, type, outline, new[] { size }, fill, stroke, strokeThickness);
}
/// <summary>
/// Draws a list of markers.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="markerPoints">The marker points.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="markerType">Type of the marker.</param>
/// <param name="markerOutline">The marker outline.</param>
/// <param name="markerSize">Size of the marker.</param>
/// <param name="markerFill">The marker fill.</param>
/// <param name="markerStroke">The marker stroke.</param>
/// <param name="markerStrokeThickness">The marker stroke thickness.</param>
/// <param name="resolution">The resolution.</param>
/// <param name="binOffset">The bin Offset.</param>
public static void DrawMarkers(
this IRenderContext rc,
IList<ScreenPoint> markerPoints,
OxyRect clippingRectangle,
MarkerType markerType,
IList<ScreenPoint> markerOutline,
double markerSize,
OxyColor markerFill,
OxyColor markerStroke,
double markerStrokeThickness,
int resolution = 0,
ScreenPoint binOffset = new ScreenPoint())
{
DrawMarkers(
rc,
clippingRectangle,
markerPoints,
markerType,
markerOutline,
new[] { markerSize },
markerFill,
markerStroke,
markerStrokeThickness,
resolution,
binOffset);
}
/// <summary>
/// Draws a list of markers.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <param name="markerPoints">The marker points.</param>
/// <param name="markerType">Type of the marker.</param>
/// <param name="markerOutline">The marker outline.</param>
/// <param name="markerSize">Size of the markers.</param>
/// <param name="markerFill">The marker fill.</param>
/// <param name="markerStroke">The marker stroke.</param>
/// <param name="markerStrokeThickness">The marker stroke thickness.</param>
/// <param name="resolution">The resolution.</param>
/// <param name="binOffset">The bin Offset.</param>
public static void DrawMarkers(
this IRenderContext rc,
OxyRect clippingRectangle,
IList<ScreenPoint> markerPoints,
MarkerType markerType,
IList<ScreenPoint> markerOutline,
IList<double> markerSize,
OxyColor markerFill,
OxyColor markerStroke,
double markerStrokeThickness,
int resolution = 0,
ScreenPoint binOffset = new ScreenPoint())
{
if (markerType == MarkerType.None)
{
return;
}
int n = markerPoints.Count;
var ellipses = new List<OxyRect>(n);
var rects = new List<OxyRect>(n);
var polygons = new List<IList<ScreenPoint>>(n);
var lines = new List<ScreenPoint>(n);
var hashset = new Dictionary<uint, bool>();
int i = 0;
double minx = clippingRectangle.Left;
double maxx = clippingRectangle.Right;
double miny = clippingRectangle.Top;
double maxy = clippingRectangle.Bottom;
foreach (var p in markerPoints)
{
if (resolution > 1)
{
var x = (int)((p.X - binOffset.X) / resolution);
var y = (int)((p.Y - binOffset.Y) / resolution);
uint hash = (uint)(x << 16) + (uint)y;
if (hashset.ContainsKey(hash))
{
i++;
continue;
}
hashset.Add(hash, true);
}
bool outside = p.x < minx || p.x > maxx || p.y < miny || p.y > maxy;
if (!outside)
{
int j = i < markerSize.Count ? i : 0;
AddMarkerGeometry(p, markerType, markerOutline, markerSize[j], ellipses, rects, polygons, lines);
}
i++;
}
if (ellipses.Count > 0)
{
rc.DrawEllipses(ellipses, markerFill, markerStroke, markerStrokeThickness);
}
if (rects.Count > 0)
{
rc.DrawRectangles(rects, markerFill, markerStroke, markerStrokeThickness);
}
if (polygons.Count > 0)
{
rc.DrawPolygons(polygons, markerFill, markerStroke, markerStrokeThickness);
}
if (lines.Count > 0)
{
rc.DrawLineSegments(lines, markerStroke, markerStrokeThickness);
}
}
/// <summary>
/// Draws the rectangle as an aliased polygon.
/// (makes sure pixel alignment is the same as for lines)
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill.</param>
/// <param name="stroke">The stroke.</param>
/// <param name="thickness">The thickness.</param>
public static void DrawRectangleAsPolygon(this IRenderContext rc, OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
var sp0 = new ScreenPoint(rect.Left, rect.Top);
var sp1 = new ScreenPoint(rect.Right, rect.Top);
var sp2 = new ScreenPoint(rect.Right, rect.Bottom);
var sp3 = new ScreenPoint(rect.Left, rect.Bottom);
rc.DrawPolygon(new[] { sp0, sp1, sp2, sp3 }, fill, stroke, thickness, null, OxyPenLineJoin.Miter, true);
}
/// <summary>
/// Draws a circle at the specified position.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="x">The center x-coordinate.</param>
/// <param name="y">The center y-coordinate.</param>
/// <param name="r">The radius.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
public static void DrawCircle(this IRenderContext rc, double x, double y, double r, OxyColor fill, OxyColor stroke, double thickness = 1)
{
rc.DrawEllipse(new OxyRect(x - r, y - r, r * 2, r * 2), fill, stroke, thickness);
}
/// <summary>
/// Draws a circle at the specified position.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="center">The center.</param>
/// <param name="r">The radius.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
public static void DrawCircle(this IRenderContext rc, ScreenPoint center, double r, OxyColor fill, OxyColor stroke, double thickness = 1)
{
DrawCircle(rc, center.X, center.Y, r, fill, stroke, thickness);
}
/// <summary>
/// Fills a circle at the specified position.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="center">The center.</param>
/// <param name="r">The radius.</param>
/// <param name="fill">The fill color.</param>
public static void FillCircle(this IRenderContext rc, ScreenPoint center, double r, OxyColor fill)
{
DrawCircle(rc, center.X, center.Y, r, fill, OxyColors.Undefined, 0d);
}
/// <summary>
/// Fills a rectangle at the specified position.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="rectangle">The rectangle.</param>
/// <param name="fill">The fill color.</param>
public static void FillRectangle(this IRenderContext rc, OxyRect rectangle, OxyColor fill)
{
rc.DrawRectangle(rectangle, fill, OxyColors.Undefined, 0d);
}
/// <summary>
/// Draws the rectangle as an aliased polygon.
/// (makes sure pixel alignment is the same as for lines)
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill.</param>
/// <param name="stroke">The stroke.</param>
/// <param name="thickness">The thickness.</param>
public static void DrawRectangleAsPolygon(this IRenderContext rc, OxyRect rect, OxyColor fill, OxyColor stroke, OxyThickness thickness)
{
if (thickness.Left.Equals(thickness.Right) && thickness.Left.Equals(thickness.Top) && thickness.Left.Equals(thickness.Bottom))
{
DrawRectangleAsPolygon(rc, rect, fill, stroke, thickness.Left);
return;
}
var sp0 = new ScreenPoint(rect.Left, rect.Top);
var sp1 = new ScreenPoint(rect.Right, rect.Top);
var sp2 = new ScreenPoint(rect.Right, rect.Bottom);
var sp3 = new ScreenPoint(rect.Left, rect.Bottom);
rc.DrawPolygon(new[] { sp0, sp1, sp2, sp3 }, fill, OxyColors.Undefined, 0, null, OxyPenLineJoin.Miter, true);
rc.DrawLine(new[] { sp0, sp1 }, stroke, thickness.Top, null, OxyPenLineJoin.Miter, true);
rc.DrawLine(new[] { sp1, sp2 }, stroke, thickness.Right, null, OxyPenLineJoin.Miter, true);
rc.DrawLine(new[] { sp2, sp3 }, stroke, thickness.Bottom, null, OxyPenLineJoin.Miter, true);
rc.DrawLine(new[] { sp3, sp0 }, stroke, thickness.Left, null, OxyPenLineJoin.Miter, true);
}
/// <summary>
/// Adds a marker geometry.
/// </summary>
/// <param name="p">The position of the marker.</param>
/// <param name="type">The type.</param>
/// <param name="outline">The outline.</param>
/// <param name="size">The size.</param>
/// <param name="ellipses">The ellipse collection.</param>
/// <param name="rects">The rectangle collection.</param>
/// <param name="polygons">The polygon collection.</param>
/// <param name="lines">The line collection.</param>
private static void AddMarkerGeometry(
ScreenPoint p,
MarkerType type,
IEnumerable<ScreenPoint> outline,
double size,
IList<OxyRect> ellipses,
IList<OxyRect> rects,
IList<IList<ScreenPoint>> polygons,
IList<ScreenPoint> lines)
{
if (type == MarkerType.Custom)
{
if (outline == null)
{
throw new ArgumentNullException("outline", "The outline should be set when MarkerType is 'Custom'.");
}
var poly = outline.Select(o => new ScreenPoint(p.X + (o.x * size), p.Y + (o.y * size))).ToList();
polygons.Add(poly);
return;
}
switch (type)
{
case MarkerType.Circle:
{
ellipses.Add(new OxyRect(p.x - size, p.y - size, size * 2, size * 2));
break;
}
case MarkerType.Square:
{
rects.Add(new OxyRect(p.x - size, p.y - size, size * 2, size * 2));
break;
}
case MarkerType.Diamond:
{
polygons.Add(
new[]
{
new ScreenPoint(p.x, p.y - (M2 * size)), new ScreenPoint(p.x + (M2 * size), p.y),
new ScreenPoint(p.x, p.y + (M2 * size)), new ScreenPoint(p.x - (M2 * size), p.y)
});
break;
}
case MarkerType.Triangle:
{
polygons.Add(
new[]
{
new ScreenPoint(p.x - size, p.y + (M1 * size)),
new ScreenPoint(p.x + size, p.y + (M1 * size)), new ScreenPoint(p.x, p.y - (M2 * size))
});
break;
}
case MarkerType.Plus:
case MarkerType.Star:
{
lines.Add(new ScreenPoint(p.x - size, p.y));
lines.Add(new ScreenPoint(p.x + size, p.y));
lines.Add(new ScreenPoint(p.x, p.y - size));
lines.Add(new ScreenPoint(p.x, p.y + size));
break;
}
}
switch (type)
{
case MarkerType.Cross:
case MarkerType.Star:
{
lines.Add(new ScreenPoint(p.x - (size * M3), p.y - (size * M3)));
lines.Add(new ScreenPoint(p.x + (size * M3), p.y + (size * M3)));
lines.Add(new ScreenPoint(p.x - (size * M3), p.y + (size * M3)));
lines.Add(new ScreenPoint(p.x + (size * M3), p.y - (size * M3)));
break;
}
}
}
/// <summary>
/// Calculates the clipped version of a rectangle.
/// </summary>
/// <param name="rect">The rectangle to clip.</param>
/// <param name="clippingRectangle">The clipping rectangle.</param>
/// <returns>The clipped rectangle, or <c>null</c> if the rectangle is outside the clipping area.</returns>
private static OxyRect? ClipRect(OxyRect rect, OxyRect clippingRectangle)
{
if (rect.Right < clippingRectangle.Left)
{
return null;
}
if (rect.Left > clippingRectangle.Right)
{
return null;
}
if (rect.Top > clippingRectangle.Bottom)
{
return null;
}
if (rect.Bottom < clippingRectangle.Top)
{
return null;
}
if (rect.Right > clippingRectangle.Right)
{
rect.Right = clippingRectangle.Right;
}
if (rect.Left < clippingRectangle.Left)
{
rect.Width = rect.Right - clippingRectangle.Left;
rect.Left = clippingRectangle.Left;
}
if (rect.Top < clippingRectangle.Top)
{
rect.Height = rect.Bottom - clippingRectangle.Top;
rect.Top = clippingRectangle.Top;
}
if (rect.Bottom > clippingRectangle.Bottom)
{
rect.Bottom = clippingRectangle.Bottom;
}
if (rect.Width <= 0 || rect.Height <= 0)
{
return null;
}
return rect;
}
/// <summary>
/// Makes sure that a non empty line is visible.
/// </summary>
/// <param name="pts">The points (screen coordinates).</param>
/// <remarks>If the line contains one point, another point is added.
/// If the line contains two points at the same position, the points are moved 2 pixels apart.</remarks>
private static void EnsureNonEmptyLineIsVisible(IList<ScreenPoint> pts)
{
// Check if the line contains two points and they are at the same point
if (pts.Count == 2)
{
if (pts[0].DistanceTo(pts[1]) < 1)
{
// Modify to a small horizontal line to make sure it is being rendered
pts[1] = new ScreenPoint(pts[0].X + 1, pts[0].Y);
pts[0] = new ScreenPoint(pts[0].X - 1, pts[0].Y);
}
}
// Check if the line contains a single point
if (pts.Count == 1)
{
// Add a second point to make sure the line is being rendered as a small dot
pts.Add(new ScreenPoint(pts[0].X + 1, pts[0].Y));
pts[0] = new ScreenPoint(pts[0].X - 1, pts[0].Y);
}
}
}
} |
using com.microsoft.dx.officewopi.Models;
using com.microsoft.dx.officewopi.Models.Wopi;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Runtime.Caching;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;
namespace com.microsoft.dx.officewopi.Utils
{
public static class WopiUtil
{
//WOPI protocol constants
public const string WOPI_BASE_PATH = @"/wopi/";
public const string WOPI_CHILDREN_PATH = @"/children";
public const string WOPI_CONTENTS_PATH = @"/contents";
public const string WOPI_FILES_PATH = @"files/";
public const string WOPI_FOLDERS_PATH = @"folders/";
/// <summary>
/// Populates a list of files with action details from WOPI discovery
/// </summary>
public async static Task PopulateActions(this IEnumerable<DetailedFileModel> files)
{
if (files.Count() > 0)
{
foreach (var file in files)
{
await file.PopulateActions();
}
}
}
/// <summary>
/// Populates a file with action details from WOPI discovery based on the file extension
/// </summary>
public async static Task PopulateActions(this DetailedFileModel file)
{
// Get the discovery informations
var actions = await GetDiscoveryInfo();
var fileExt = file.BaseFileName.Substring(file.BaseFileName.LastIndexOf('.') + 1).ToLower();
file.Actions = actions.Where(i => i.ext == fileExt).OrderBy(i => i.isDefault).ToList();
}
/// <summary>
/// Gets the discovery information from WOPI discovery and caches it appropriately
/// </summary>
public async static Task<List<WopiAction>> GetDiscoveryInfo()
{
List<WopiAction> actions = new List<WopiAction>();
// Determine if the discovery data is cached
MemoryCache memoryCache = MemoryCache.Default;
if (memoryCache.Contains("DiscoData"))
actions = (List<WopiAction>)memoryCache["DiscoData"];
else
{
// Data isn't cached, so we will use the Wopi Discovery endpoint to get the data
HttpClient client = new HttpClient();
using (HttpResponseMessage response = await client.GetAsync(ConfigurationManager.AppSettings["WopiDiscovery"]))
{
if (response.IsSuccessStatusCode)
{
// Read the xml string from the response
string xmlString = await response.Content.ReadAsStringAsync();
// Parse the xml string into Xml
var discoXml = XDocument.Parse(xmlString);
// Convert the discovery xml into list of WopiApp
var xapps = discoXml.Descendants("app");
foreach (var xapp in xapps)
{
// Parse the actions for the app
var xactions = xapp.Descendants("action");
foreach (var xaction in xactions)
{
actions.Add(new WopiAction()
{
app = xapp.Attribute("name").Value,
favIconUrl = xapp.Attribute("favIconUrl").Value,
checkLicense = Convert.ToBoolean(xapp.Attribute("checkLicense").Value),
name = xaction.Attribute("name").Value,
ext = (xaction.Attribute("ext") != null) ? xaction.Attribute("ext").Value : String.Empty,
progid = (xaction.Attribute("progid") != null) ? xaction.Attribute("progid").Value : String.Empty,
isDefault = (xaction.Attribute("default") != null) ? true : false,
urlsrc = xaction.Attribute("urlsrc").Value,
requires = (xaction.Attribute("requires") != null) ? xaction.Attribute("requires").Value : String.Empty
});
}
// Cache the discovey data for an hour
memoryCache.Add("DiscoData", actions, DateTimeOffset.Now.AddHours(1));
}
}
}
}
return actions;
}
/// <summary>
/// Forms the correct action url for the file and host
/// </summary>
public static string GetActionUrl(WopiAction action, FileModel file, string authority)
{
// Initialize the urlsrc
var urlsrc = action.urlsrc;
// Look through the action placeholders
var phCnt = 0;
foreach (var p in WopiUrlPlaceholders.Placeholders)
{
if (urlsrc.Contains(p))
{
// Replace the placeholder value accordingly
var ph = WopiUrlPlaceholders.GetPlaceholderValue(p);
if (!String.IsNullOrEmpty(ph))
{
urlsrc = urlsrc.Replace(p, ph + "&");
phCnt++;
}
else
urlsrc = urlsrc.Replace(p, ph);
}
}
// Add the WOPISrc to the end of the request
urlsrc += ((phCnt > 0) ? "" : "?") + String.Format("WOPISrc=https://{0}/wopi/files/{1}", authority, file.id.ToString());
return urlsrc;
}
/// <summary>
/// Validates the WOPI Proof on an incoming WOPI request
/// </summary>
public async static Task<bool> ValidateWopiProof(HttpContext context)
{
// Make sure the request has the correct headers
if (context.Request.Headers[WopiRequestHeaders.PROOF] == null ||
context.Request.Headers[WopiRequestHeaders.TIME_STAMP] == null)
return false;
// Set the requested proof values
var requestProof = context.Request.Headers[WopiRequestHeaders.PROOF];
var requestProofOld = String.Empty;
if (context.Request.Headers[WopiRequestHeaders.PROOF_OLD] != null)
requestProofOld = context.Request.Headers[WopiRequestHeaders.PROOF_OLD];
// Get the WOPI proof info from discovery
var discoProof = await getWopiProof(context);
// Encode the values into bytes
var accessTokenBytes = Encoding.UTF8.GetBytes(context.Request.QueryString["access_token"]);
var hostUrl = context.Request.Url.OriginalString.Replace(":44300", "").Replace(":443", "");
var hostUrlBytes = Encoding.UTF8.GetBytes(hostUrl.ToUpperInvariant());
var timeStampBytes = BitConverter.GetBytes(Convert.ToInt64(context.Request.Headers[WopiRequestHeaders.TIME_STAMP])).Reverse().ToArray();
// Build expected proof
List<byte> expected = new List<byte>(
4 + accessTokenBytes.Length +
4 + hostUrlBytes.Length +
4 + timeStampBytes.Length);
// Add the values to the expected variable
expected.AddRange(BitConverter.GetBytes(accessTokenBytes.Length).Reverse().ToArray());
expected.AddRange(accessTokenBytes);
expected.AddRange(BitConverter.GetBytes(hostUrlBytes.Length).Reverse().ToArray());
expected.AddRange(hostUrlBytes);
expected.AddRange(BitConverter.GetBytes(timeStampBytes.Length).Reverse().ToArray());
expected.AddRange(timeStampBytes);
byte[] expectedBytes = expected.ToArray();
return (verifyProof(expectedBytes, requestProof, discoProof.value) ||
verifyProof(expectedBytes, requestProof, discoProof.oldvalue) ||
verifyProof(expectedBytes, requestProofOld, discoProof.value));
}
/// <summary>
/// Verifies the proof against a specified key
/// </summary>
private static bool verifyProof(byte[] expectedProof, string proofFromRequest, string proofFromDiscovery)
{
using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider())
{
try
{
rsaProvider.ImportCspBlob(Convert.FromBase64String(proofFromDiscovery));
return rsaProvider.VerifyData(expectedProof, "SHA256", Convert.FromBase64String(proofFromRequest));
}
catch (FormatException)
{
return false;
}
catch (CryptographicException)
{
return false;
}
}
}
/// <summary>
/// Gets the WOPI proof details from the WOPI discovery endpoint and caches it appropriately
/// </summary>
internal async static Task<WopiProof> getWopiProof(HttpContext context)
{
WopiProof wopiProof = null;
// Check cache for this data
MemoryCache memoryCache = MemoryCache.Default;
if (memoryCache.Contains("WopiProof"))
wopiProof = (WopiProof)memoryCache["WopiProof"];
else
{
HttpClient client = new HttpClient();
using (HttpResponseMessage response = await client.GetAsync(ConfigurationManager.AppSettings["WopiDiscovery"]))
{
if (response.IsSuccessStatusCode)
{
// Read the xml string from the response
string xmlString = await response.Content.ReadAsStringAsync();
// Parse the xml string into Xml
var discoXml = XDocument.Parse(xmlString);
// Convert the discovery xml into list of WopiApp
var proof = discoXml.Descendants("proof-key").FirstOrDefault();
wopiProof = new WopiProof()
{
value = proof.Attribute("value").Value,
modulus = proof.Attribute("modulus").Value,
exponent = proof.Attribute("exponent").Value,
oldvalue = proof.Attribute("oldvalue").Value,
oldmodulus = proof.Attribute("oldmodulus").Value,
oldexponent = proof.Attribute("oldexponent").Value
};
// Add to cache for 20min
memoryCache.Add("WopiProof", wopiProof, DateTimeOffset.Now.AddMinutes(20));
}
}
}
return wopiProof;
}
}
/// <summary>
/// Contains valid WOPI response headers
/// </summary>
public class WopiResponseHeaders
{
//WOPI Header Consts
public const string HOST_ENDPOINT = "X-WOPI-HostEndpoint";
public const string INVALID_FILE_NAME_ERROR = "X-WOPI-InvalidFileNameError";
public const string LOCK = "X-WOPI-Lock";
public const string LOCK_FAILURE_REASON = "X-WOPI-LockFailureReason";
public const string LOCKED_BY_OTHER_INTERFACE = "X-WOPI-LockedByOtherInterface";
public const string MACHINE_NAME = "X-WOPI-MachineName";
public const string PREF_TRACE = "X-WOPI-PerfTrace";
public const string SERVER_ERROR = "X-WOPI-ServerError";
public const string SERVER_VERSION = "X-WOPI-ServerVersion";
public const string VALID_RELATIVE_TARGET = "X-WOPI-ValidRelativeTarget";
}
/// <summary>
/// Contains valid WOPI request headers
/// </summary>
public class WopiRequestHeaders
{
//WOPI Header Consts
public const string APP_ENDPOINT = "X-WOPI-AppEndpoint";
public const string CLIENT_VERSION = "X-WOPI-ClientVersion";
public const string CORRELATION_ID = "X-WOPI-CorrelationId";
public const string LOCK = "X-WOPI-Lock";
public const string MACHINE_NAME = "X-WOPI-MachineName";
public const string MAX_EXPECTED_SIZE = "X-WOPI-MaxExpectedSize";
public const string OLD_LOCK = "X-WOPI-OldLock";
public const string OVERRIDE = "X-WOPI-Override";
public const string OVERWRITE_RELATIVE_TARGET = "X-WOPI-OverwriteRelativeTarget";
public const string PREF_TRACE_REQUESTED = "X-WOPI-PerfTraceRequested";
public const string PROOF = "X-WOPI-Proof";
public const string PROOF_OLD = "X-WOPI-ProofOld";
public const string RELATIVE_TARGET = "X-WOPI-RelativeTarget";
public const string REQUESTED_NAME = "X-WOPI-RequestedName";
public const string SESSION_CONTEXT = "X-WOPI-SessionContext";
public const string SIZE = "X-WOPI-Size";
public const string SUGGESTED_TARGET = "X-WOPI-SuggestedTarget";
public const string TIME_STAMP = "X-WOPI-TimeStamp";
}
/// <summary>
/// Contains all valid URL placeholders for different WOPI actions
/// </summary>
public class WopiUrlPlaceholders
{
public static List<string> Placeholders = new List<string>() { BUSINESS_USER,
DC_LLCC, DISABLE_ASYNC, DISABLE_CHAT, DISABLE_BROADCAST,
EMBDDED, FULLSCREEN, PERFSTATS, RECORDING, THEME_ID, UI_LLCC, VALIDATOR_TEST_CATEGORY
};
public const string BUSINESS_USER = "<IsLicensedUser=BUSINESS_USER&>";
public const string DC_LLCC = "<rs=DC_LLCC&>";
public const string DISABLE_ASYNC = "<na=DISABLE_ASYNC&>";
public const string DISABLE_CHAT = "<dchat=DISABLE_CHAT&>";
public const string DISABLE_BROADCAST = "<vp=DISABLE_BROADCAST&>";
public const string EMBDDED = "<e=EMBEDDED&>";
public const string FULLSCREEN = "<fs=FULLSCREEN&>";
public const string PERFSTATS = "<showpagestats=PERFSTATS&>";
public const string RECORDING = "<rec=RECORDING&>";
public const string THEME_ID = "<thm=THEME_ID&>";
public const string UI_LLCC = "<ui=UI_LLCC&>";
public const string VALIDATOR_TEST_CATEGORY = "<testcategory=VALIDATOR_TEST_CATEGORY>";
/// <summary>
/// Sets a specific WOPI URL placeholder with the correct value
/// Most of these are hard-coded in this WOPI implementation
/// </summary>
public static string GetPlaceholderValue(string placeholder)
{
var ph = placeholder.Substring(1, placeholder.IndexOf("="));
string result = "";
switch (placeholder)
{
case BUSINESS_USER:
result = ph + "1";
break;
case DC_LLCC:
case UI_LLCC:
result = ph + "1033";
break;
case DISABLE_ASYNC:
case DISABLE_BROADCAST:
case EMBDDED:
case FULLSCREEN:
case RECORDING:
case THEME_ID:
// These are all broadcast related actions
result = ph + "true";
break;
case DISABLE_CHAT:
result = ph + "false";
break;
case PERFSTATS:
result = ""; // No documentation
break;
case VALIDATOR_TEST_CATEGORY:
result = ph + "OfficeOnline"; //This value can be set to All, OfficeOnline or OfficeNativeClient to activate tests specific to Office Online and Office for iOS. If omitted, the default value is All.
break;
default:
result = "";
break;
}
return result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.