context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* nwitsml Copyright 2010 Setiri LLC Derived from the jwitsml project, Copyright 2010 Statoil ASA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace witsmllib.v131 { /** * Version specific implementation of the WitsmlRig type. * * @author <a href="mailto:info@nwitsml.org">NWitsml</a> */ using System; using witsmllib.util; using System.Xml.Linq; sealed class WitsmlRig : witsmllib.WitsmlRig { /** * Create a new WITSML rig instance. * * @param server Server this instance lives within. Non-null. * @param parent Parent of instance. May be null. * @param parentId ID of parent instance. May be null. */ private WitsmlRig(WitsmlServer server, String id, String name, WitsmlObject parent, String parentId) :base(server, id, name, parent, parentId) {} /** * Factory method for this type. * * @param server Server the new instance lives within. Non-null. * @param parent Parent instance. Always null on this level. * @param element XML element to create instance from. Non-null. * @return New WITSML rig instance. Never null. */ static WitsmlObject newInstance(WitsmlServer server, WitsmlObject parent, XElement element) { //Debug.Assert(element != null : "element cannot be null"; String id = element.Attribute("uid").Value; String parentId = element.Attribute("uidWellbore").Value; String name = element.Element(element.Name.Namespace + "name").Value.Trim(); //, element.getNamespace()); WitsmlRig rig = new WitsmlRig(server, id, name, parent, parentId); rig.update(element); return rig; } /** * Return complete XML query for this type. * * @param id ID of instance to get. May be empty to indicate all. * Non-null. * @param parentId Parent IDs. Closest first. May be empty if instances * are accessed from the root. Non-null. * @return XML query. Never null. */ static String getQuery(String id, params String[] parentId) { //Debug.Assert(id != null : "id cannot be null"; //Debug.Assert(parentId != null : "parentId cannot be null"; String uidWellbore = parentId.Length > 0 ? parentId[0] : ""; String uidWell = parentId.Length > 1 ? parentId[1] : ""; String query = "<rigs xmlns=\"" + WitsmlVersion.VERSION_1_3_1.getNamespace() + "\">" + " <rig uidWell =\"" + uidWell + "\"" + " uidWellbore =\"" + uidWellbore + "\"" + " uid = \"" + id + "\">" + " <name/>" + " <owner/>" + " <typeRig/>" + " <manufacturer/>" + " <yearEntService/>" + " <classRig/>" + " <approvals/>" + " <registration/>" + " <telNumber/>" + " <faxNumber/>" + " <emailAddress/>" + " <nameContact/>" + " <ratingDrillDepth uom=\"" + WitsmlServer.distUom+"\"/>" + " <isOffshore/>" + " <dtmRefToDtmPerm uom=\"" + WitsmlServer.distUom+"\"/>" + " <airGap uom=\"" + WitsmlServer.distUom+"\"/>" + " <dtmReference/>" + " <dTimStartOp/>" + " <dTimEndOp/>" + " <bop>" + " </bop>" + " <pits>" + " <indexPit/>" + " <dTimInstall/>" + " <dTimRemove/>" + " <capMx uom=\"" + WitsmlServer.volUom+"\"/>" + " <owner/>" + " <type/>" + " <isActive/>" + " </pits>" + " <pumps>" + " <indexPump/>" + " <manufacturer/>" + " <model/>" + " <dTimInstall/>" + " <dTimRemove/>" + " <owner/>" + " <typePump/>" + " <numCyl/>" + " <odRod uom=\"" + WitsmlServer.distUom+"\"/>" + " <idLiner uom=\"" + WitsmlServer.distUom+"\"/>" + " <pumpAction/>" + " <eff/>" + " <lenStroke uom=\"" + WitsmlServer.distUom+"\"/>" + " <presMx/>" + " <powHydMx/>" + " <spmMx/>" + " <displacement uom=\"" + WitsmlServer.volUom+"\"/>" + " <presDamp/>" + " <volDamp uom=\"" + WitsmlServer.volUom+"\"/>" + " <powMechMx/>" + " </pumps>" + " <shakers>" + // TODO " </shakers>" + " <centrifuge>" + // TODO " </centrifuge>" + " <hydroclone>" + // TODO " </hydroclone>" + " <degasser>" + // TODO " </degasser>" + " <surfaceEquipment>" + // TODO " </surfaceEquipment>" + " <numDerricks/>" + " <typeDerrick/>" + " <ratingDerrick/>" + " <htDerrick uom=\"" + WitsmlServer.distUom+"\"/>" + " <ratingHkld/>" + " <capWindDerrick/>" + " <wtBlock/>" + " <ratingBlock/>" + " <numBlockLines/>" + " <typeHook/>" + " <ratingHook/>" + " <sizeDrillLine uom=\"" + WitsmlServer.distUom+"\"/>" + " <typeDrawWorks/>" + " <powerDrawWorks/>" + " <ratingDrawWorks/>" + " <motorDrawWorks/>" + " <descBrake/>" + " <typeSwivel/>" + " <ratingSwivel/>" + " <rotSystem/>" + " <descRotSystem/>" + " <ratingTqRotSys/>" + " <rotSizeOpening uom=\"" + WitsmlServer.distUom+"\"/>" + " <ratingRotSystem/>" + " <scrSystem/>" + " <pipeHandlingSystem/>" + " <capBulkMud uom=\"" + WitsmlServer.volUom+"\"/>" + " <capLiquidMud uom=\"" + WitsmlServer.volUom+"\"/>" + " <capDrillWater uom=\"" + WitsmlServer.volUom+"\"/>" + " <capPotableWater uom=\"" + WitsmlServer.volUom+"\"/>" + " <capFuel uom=\"" + WitsmlServer.volUom+"\"/>" + " <capBulkCement uom=\"" + WitsmlServer.volUom+"\"/>" + " <mainEngine/>" + " <generator/>" + " <cementUnit/>" + " <numBunks/>" + " <bunksPerRoom/>" + " <numCranes/>" + " <numAnch/>" + " <moorType/>" + " <numGuideTens/>" + " <numRiserTens/>" + " <varDeckLdMx uom=\"" + WitsmlServer.forceUom+"\"/>" + " <vdlStorm uom=\"" + WitsmlServer.forceUom+"\"/>" + " <numThrusters/>" + " <azimuthing/>" + " <motionCompensationMn uom=\"" + WitsmlServer.forceUom+"\"/>" + " <motionCompensationMx uom=\"" + WitsmlServer.forceUom+"\"/>" + " <strokeMotionCompensation uom=\"" + WitsmlServer.distUom+"\"/>" + " <riserAngleLimit uom=\"rad\"/>" + " <heaveMx uom=\"" + WitsmlServer.distUom+"\"/>" + " <gantry/>" + " <flares/>" + " </rig>" + "</rigs>"; return query; } /** * Parse the specified DOM element and instantiate the properties * of this instance. * * @param element XML element to parse. Non-null. */ void update(XElement element) { //Debug.Assert(element != null : "element cannot be null"; owner = XmlUtil.update(element, "owner", owner); rigType = XmlUtil.update(element, "typeRig", rigType); manufacturer = XmlUtil.update(element, "manufacturer", manufacturer); startYear = XmlUtil.update(element, "yearEntService", startYear); rigClass = XmlUtil.update(element, "classRig", rigClass); approvals = XmlUtil.update(element, "approvals", approvals); registrationLocation = XmlUtil.update(element, "registration", registrationLocation); phoneNumber = XmlUtil.update(element, "telNumber", phoneNumber); faxNumber = XmlUtil.update(element, "faxNumber", faxNumber); emailAddress = XmlUtil.update(element, "emailAddress", emailAddress); contactName = XmlUtil.update(element, "nameContact", contactName); drillDepthRating = XmlUtil.update(element, "ratingDrillDepth", drillDepthRating); waterDepthRating = XmlUtil.update(element, "ratingWaterDepth", waterDepthRating); _isOffshore = XmlUtil.update(element, "isOffshore", _isOffshore); drillingDatumToPermanentDatumDistance = XmlUtil.update(element, "dtmRefToDtmPerm", drillingDatumToPermanentDatumDistance); airGap = XmlUtil.update(element, "airGap", airGap); datum = XmlUtil.update(element, "dtmReference", datum); operationStartTime = XmlUtil.update(element, "dTimStartOp", operationStartTime); operationEndTime = XmlUtil.update(element, "dTimEndOp", operationEndTime); XElement commonDataElement = element.Element(element.Name.Namespace + "commonData");//, element.getNamespace()); if (commonDataElement != null) commonData = new WitsmlCommonData(commonDataElement); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using PulseWaveAnalyzer.model; namespace PulseWaveAnalyzer { public partial class frmLibrary : Form { private Medicine memM; private Prescript memP; private Bitmap bmpPicpVal; private double getMedicineMild() { if (rbNone.Checked) return 0.0; if (rbWarm.Checked) return 0.5; if (rbHot.Checked) return 1.0; if (rbCool.Checked) return -0.5; return -1.0; } private void setMedicineMild(double val) { if (val == 0.0) rbNone.Checked = true; else if (val == 0.5) rbWarm.Checked = true; else if (val == 1.0) rbHot.Checked = true; else if (val == -0.5) rbCool.Checked = true; else rbCold.Checked = true; } private void drawPrescriptValue() { double[] e = memP.prescriptE(); int bw = picpVal.Width / e.Length; Graphics g = Graphics.FromImage(bmpPicpVal); Brush b; g.Clear(Color.White); for (int i = 0; i < e.Length; i++) { if (e[i] == 0.0) b = Brushes.White; else if (e[i] > 0.0) b = Brushes.Red; else b = Brushes.Blue; g.FillRectangle(b, i * bw, 0, bw, (int)(Math.Abs(e[i]) * picpVal.Height)); } picpVal.Image = bmpPicpVal; } public frmLibrary() { InitializeComponent(); memM = new Medicine(); memP = new Prescript(); mlist.Items.Clear(); plist.Items.Clear(); pmlist.Items.Clear(); pplist.Items.Clear(); bmpPicpVal = new Bitmap(picpVal.Width, picpVal.Height); drawPrescriptValue(); foreach (Medicine x in Database.medicineDB) { mlist.Items.Add(x.name); pmlist.Items.Add(x.name); } foreach (Prescript x in Database.prescriptDB) { plist.Items.Add(x.name); } } private void btnmNew_Click(object sender, EventArgs e) { mlist.ClearSelected(); txtmName.Text = ""; rbNone.Checked = true; //rbCold.Checked = false; //rbWarm.Checked = false; cbBL.Checked = false; cbGB.Checked = false; cbHT.Checked = false; cbKI.Checked = false; cbLI.Checked = false; cbLR.Checked = false; cbLU.Checked = false; cbPC.Checked = false; cbSI.Checked = false; cbSP.Checked = false; cbST.Checked = false; cbTB.Checked = false; } private void btnpNew_Click(object sender, EventArgs e) { plist.ClearSelected(); txtpName.Text = ""; pplist.Items.Clear(); memP.clear(); Graphics.FromImage(bmpPicpVal).Clear(Color.White); picpVal.Image = bmpPicpVal; } private void mlist_SelectedIndexChanged(object sender, EventArgs e) { if (mlist.SelectedIndex < 0) return; Medicine m = Database.medicineDB[mlist.SelectedIndex]; txtmName.Text = m.name; setMedicineMild(m.mild); if (m.merdian[0] != 0.0) cbHT.Checked = true; else cbHT.Checked = false; if (m.merdian[1] != 0.0) cbLR.Checked = true; else cbLR.Checked = false; if (m.merdian[2] != 0.0) cbKI.Checked = true; else cbKI.Checked = false; if (m.merdian[3] != 0.0) cbSP.Checked = true; else cbSP.Checked = false; if (m.merdian[4] != 0.0) cbLU.Checked = true; else cbLU.Checked = false; if (m.merdian[5] != 0.0) cbST.Checked = true; else cbST.Checked = false; if (m.merdian[6] != 0.0) cbGB.Checked = true; else cbGB.Checked = false; if (m.merdian[7] != 0.0) cbBL.Checked = true; else cbBL.Checked = false; if (m.merdian[8] != 0.0) cbLI.Checked = true; else cbLI.Checked = false; if (m.merdian[9] != 0.0) cbTB.Checked = true; else cbTB.Checked = false; if (m.merdian[10] != 0.0) cbSI.Checked = true; else cbSI.Checked = false; if (m.merdian[11] != 0.0) cbPC.Checked = true; else cbPC.Checked = false; } private void plist_SelectedIndexChanged(object sender, EventArgs e) { if (plist.SelectedIndex < 0) return; Prescript p = Database.prescriptDB[plist.SelectedIndex]; txtpName.Text = p.name; pplist.Items.Clear(); memP.clear(); foreach (PrescriptNode pn in p.getPrescriptMedicines()) { pplist.Items.Add(string.Format("{0:F}g\t", pn.weight) + pn.med.name); memP.add(pn.med, pn.weight, pn.state); } drawPrescriptValue(); } private void btnCancel_Click(object sender, EventArgs e) { if (mlist.SelectedIndex < 0) { btnmNew_Click(sender, e); } else { mlist_SelectedIndexChanged(sender, e); } } private void btnpCancel_Click(object sender, EventArgs e) { if (mlist.SelectedIndex < 0) { btnpNew_Click(sender, e); } else { plist_SelectedIndexChanged(sender, e); } } private void setMedicine(Medicine m) { if (m == null) return; m.name = txtmName.Text; m.mild = getMedicineMild(); if (cbHT.Checked) m.merdian[0] = 1.0; else m.merdian[0] = 0.0; if (cbLR.Checked) m.merdian[1] = 1.0; else m.merdian[1] = 0.0; if (cbKI.Checked) m.merdian[2] = 1.0; else m.merdian[2] = 0.0; if (cbSP.Checked) m.merdian[3] = 1.0; else m.merdian[3] = 0.0; if (cbLU.Checked) m.merdian[4] = 1.0; else m.merdian[4] = 0.0; if (cbST.Checked) m.merdian[5] = 1.0; else m.merdian[5] = 0.0; if (cbGB.Checked) m.merdian[6] = 1.0; else m.merdian[6] = 0.0; if (cbBL.Checked) m.merdian[7] = 1.0; else m.merdian[7] = 0.0; if (cbLI.Checked) m.merdian[8] = 1.0; else m.merdian[8] = 0.0; if (cbTB.Checked) m.merdian[9] = 1.0; else m.merdian[9] = 0.0; if (cbSI.Checked) m.merdian[10] = 1.0; else m.merdian[10] = 0.0; if (cbPC.Checked) m.merdian[11] = 1.0; else m.merdian[11] = 0.0; } private void btnmOK_Click(object sender, EventArgs e) { Medicine m; if (mlist.SelectedIndex < 0) { m = new Medicine(); m.id = -1; setMedicine(m); DBParser.addMedicine(Database.medicineDB, m); if (m.id > 0) Database.medicineDB.Add(m); mlist.Items.Add(m.name); //mlist.SelectedIndex = mlist.Items.Count - 1; pmlist.Items.Add(m.name); btnmNew_Click(sender, e); } else { m = Database.medicineDB[mlist.SelectedIndex]; setMedicine(m); DBParser.updateMedicine(m); mlist.Items[mlist.SelectedIndex] = m.name; pmlist.Items[mlist.SelectedIndex] = m.name; mlist_SelectedIndexChanged(sender, e); } txtmName.Focus(); } private void setPrescript(Prescript p) { if (p == null) return; p.name = txtpName.Text; p.clear(); foreach (PrescriptNode x in memP.getPrescriptMedicines()) { p.add(x.med, x.weight, x.state); } } private void btnpOK_Click(object sender, EventArgs e) { Prescript p; if (plist.SelectedIndex < 0) { p = new Prescript(); p.id = -1; setPrescript(p); DBParser.addPrescript(Database.prescriptDB, p); if (p.id > 0) Database.prescriptDB.Add(p); plist.Items.Add(p.name); //plist.SelectedIndex = plist.Items.Count - 1; btnpNew_Click(sender, e); } else { p = Database.prescriptDB[plist.SelectedIndex]; setPrescript(p); DBParser.updatePrescript(p); plist.Items[plist.SelectedIndex] = p.name; plist_SelectedIndexChanged(sender, e); } txtpName.Focus(); } private void btnDel_Click(object sender, EventArgs e) { if (pplist.SelectedIndex < 0) return; memP.del(memP.getPrescriptMedicines()[pplist.SelectedIndex].med); pplist.Items.RemoveAt(pplist.SelectedIndex); drawPrescriptValue(); } private void btnAdd_Click(object sender, EventArgs e) { if (pmlist.SelectedIndex < 0) return; if (memP.indexOf(Database.medicineDB[pmlist.SelectedIndex]) < 0) { pplist.Items.Add(string.Format("{0:F}g\t", numpmWeight.Value) + pmlist.Items[pmlist.SelectedIndex]); } memP.add(Database.medicineDB[pmlist.SelectedIndex], decimal.ToDouble(numpmWeight.Value), 0.0); memP.sort(); updatePplist(); drawPrescriptValue(); } private void updatePplist() { pplist.Items.Clear(); foreach (PrescriptNode x in memP.getPrescriptMedicines()) { pplist.Items.Add(string.Format("{0:F}g\t", x.weight) + x.med.name); } } private void txtpmSearch_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { int i = 0; foreach (object x in pmlist.Items) { if (txtpmSearch.Text.Equals(x)) break; i++; } if (i < pmlist.Items.Count) { txtpmSearch.Text = ""; pmlist.SelectedIndex = i; } else { txtpmSearch.SelectionStart = 0; txtpmSearch.SelectionLength = txtpmSearch.Text.Length; } } } private void txtpSearch_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { int i = 0; foreach (object x in plist.Items) { if (txtpSearch.Text.Equals(x)) break; i++; } if (i < plist.Items.Count) { txtpSearch.Text = ""; plist.SelectedIndex = i; } else { txtpSearch.SelectionStart = 0; txtpSearch.SelectionLength = txtpSearch.Text.Length; } } } private void txtmSearch_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { int i = 0; foreach (object x in mlist.Items) { if (txtmSearch.Text.Equals(x)) break; i++; } if (i < mlist.Items.Count) { txtmSearch.Text = ""; mlist.SelectedIndex = i; } else { txtmSearch.SelectionStart = 0; txtmSearch.SelectionLength = txtmSearch.Text.Length; } } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Fungus { public class TextTagParser { public enum TokenType { Invalid, Words, // A string of words BoldStart, // b BoldEnd, // /b ItalicStart, // i ItalicEnd, // /i ColorStart, // color=red ColorEnd, // /color Wait, // w, w=0.5 WaitForInputNoClear, // wi WaitForInputAndClear, // wc WaitOnPunctuationStart, // wp, wp=0.5 WaitOnPunctuationEnd, // /wp Clear, // c SpeedStart, // s, s=60 SpeedEnd, // /s Exit, // x Message, // m=MessageName VerticalPunch, // {vpunch=0.5} HorizontalPunch, // {hpunch=0.5} Punch, // {shake=0.5} Flash, // {flash=0.5} Audio, // {audio=Sound} AudioLoop, // {audioloop=Sound} AudioPause, // {audiopause=Sound} AudioStop // {audiostop=Sound} } public class Token { public TokenType type = TokenType.Invalid; public string param = ""; } public static string GetTagHelp() { return "" + "\t{b} Bold Text {/b}\n" + "\t{i} Italic Text {/i}\n" + "\t{color=red} Color Text (color){/color}\n" + "\n" + "\t{s}, {s=60} Writing speed (chars per sec){/s}\n" + "\t{w}, {w=0.5} Wait (seconds)\n" + "\t{wi} Wait for input\n" + "\t{wc} Wait for input and clear\n" + "\t{wp}, {wp=0.5} Wait on punctuation (seconds){/wp}\n" + "\t{c} Clear\n" + "\t{x} Exit, advance to the next command without waiting for input\n" + "\n" + "\t{vpunch=0.5} Vertically punch screen (intensity)\n" + "\t{hpunch=0.5} Horizontally punch screen (intensity)\n" + "\t{shake=1} Shake screen (intensity)\n" + "\t{shiver=1} Shiver screen (intensity)\n" + "\t{flash=0.5} Flash screen (duration)\n" + "\n" + "\t{audio=AudioObjectName} Play Audio Once\n" + "\t{audioloop=AudioObjectName} Play Audio Loop\n" + "\t{audiopause=AudioObjectName} Pause Audio\n" + "\t{audiostop=AudioObjectName} Stop Audio\n" + "\n" + "\t{m=MessageName} Broadcast message\n" + "\t{$VarName} Substitute variable"; } public virtual List<Token> Tokenize(string storyText) { List<Token> tokens = new List<Token>(); string pattern = @"\{.*?\}"; Regex myRegex = new Regex(pattern); Match m = myRegex.Match(storyText); // m is the first match int position = 0; while (m.Success) { // Get bit leading up to tag string preText = storyText.Substring(position, m.Index - position); string tagText = m.Value; if (preText != "") { AddWordsToken(tokens, preText); } AddTagToken(tokens, tagText); position = m.Index + tagText.Length; m = m.NextMatch(); } if (position < storyText.Length) { string postText = storyText.Substring(position, storyText.Length - position); if (postText.Length > 0) { AddWordsToken(tokens, postText); } } // Remove all leading whitespace & newlines after a {c} or {wc} tag // These characters are usually added for legibility when editing, but are not // desireable when viewing the text in game. bool trimLeading = false; foreach (Token token in tokens) { if (trimLeading && token.type == TokenType.Words) { token.param = token.param.TrimStart(' ', '\t', '\r', '\n'); } if (token.type == TokenType.Clear || token.type == TokenType.WaitForInputAndClear) { trimLeading = true; } else { trimLeading = false; } } return tokens; } protected virtual void AddWordsToken(List<Token> tokenList, string words) { Token token = new Token(); token.type = TokenType.Words; token.param = words; tokenList.Add(token); } protected virtual void AddTagToken(List<Token> tokenList, string tagText) { if (tagText.Length < 3 || tagText.Substring(0,1) != "{" || tagText.Substring(tagText.Length - 1,1) != "}") { return; } string tag = tagText.Substring(1, tagText.Length - 2); TokenType type = TokenType.Invalid; string paramText = ExtractParameter(tag); if (tag == "b") { type = TokenType.BoldStart; } else if (tag == "/b") { type = TokenType.BoldEnd; } else if (tag == "i") { type = TokenType.ItalicStart; } else if (tag == "/i") { type = TokenType.ItalicEnd; } else if (tag.StartsWith("color=")) { type = TokenType.ColorStart; } else if (tag == "/color") { type = TokenType.ColorEnd; } else if (tag == "wi") { type = TokenType.WaitForInputNoClear; } if (tag == "wc") { type = TokenType.WaitForInputAndClear; } else if (tag.StartsWith("wp=")) { type = TokenType.WaitOnPunctuationStart; } else if (tag == "wp") { type = TokenType.WaitOnPunctuationStart; } else if (tag == "/wp") { type = TokenType.WaitOnPunctuationEnd; } else if (tag.StartsWith("w=")) { type = TokenType.Wait; } else if (tag == "w") { type = TokenType.Wait; } else if (tag == "c") { type = TokenType.Clear; } else if (tag.StartsWith("s=")) { type = TokenType.SpeedStart; } else if (tag == "s") { type = TokenType.SpeedStart; } else if (tag == "/s") { type = TokenType.SpeedEnd; } else if (tag == "x") { type = TokenType.Exit; } else if (tag.StartsWith("m=")) { type = TokenType.Message; } else if (tag.StartsWith("vpunch") || tag.StartsWith("vpunch=")) { type = TokenType.VerticalPunch; } else if (tag.StartsWith("hpunch") || tag.StartsWith("hpunch=")) { type = TokenType.HorizontalPunch; } else if (tag.StartsWith("punch") || tag.StartsWith("punch=")) { type = TokenType.Punch; } else if (tag.StartsWith("flash") || tag.StartsWith("flash=")) { type = TokenType.Flash; } else if (tag.StartsWith("audio=")) { type = TokenType.Audio; } else if (tag.StartsWith("audioloop=")) { type = TokenType.AudioLoop; } else if (tag.StartsWith("audiopause=")) { type = TokenType.AudioPause; } else if (tag.StartsWith("audiostop=")) { type = TokenType.AudioStop; } if (type != TokenType.Invalid) { Token token = new Token(); token.type = type; token.param = paramText.Trim(); tokenList.Add(token); } else { Debug.LogWarning("Invalid text tag " + tag); } } protected virtual string ExtractParameter(string input) { int index = input.IndexOf('='); if (index == -1) { return ""; } return input.Substring(index +1); } } }
using System; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Versioning; using System.Text.RegularExpressions; using System.Threading; using IntegrationTests; using Npgsql; using static System.Globalization.CultureInfo; using static Bullseye.Targets; using static SimpleExec.Command; namespace build { internal class Build { private const string BUILD_VERSION = "5.0.0"; private const string GITHUB_REPO = "https://github.com/jasperfx/lamar.git"; private const string Forwards = @" getting_started documentation/ documentation/ioc/ documentation/ioc/concepts/ documentation/ioc/bootstrapping/ documentation/ioc/aspnetcore/ documentation/ioc/blazor/ documentation/ioc/registration/ documentation/ioc/registration/registry-dsl/ documentation/ioc/registration/inline-dependencies/ documentation/ioc/registration/auto-registration-and-conventions/ documentation/ioc/registration/configured-instance/ documentation/ioc/registration/policies/ documentation/ioc/registration/policies/ documentation/ioc/registration/changing-configuration-at-runtime/ documentation/ioc/registration/constructor-selection/ documentation/ioc/registration/existing-objects/ documentation/ioc/registration/attributes/ documentation/ioc/lifetime/ documentation/ioc/resolving/ documentation/ioc/resolving/get-a-service-by-plugintype/ documentation/ioc/resolving/get-a-service-by-plugin-type-and-name/ documentation/ioc/resolving/get-all-services-by-plugin-type/ documentation/ioc/resolving/try-getting-an-optional-service-by-plugin-type/ documentation/ioc/resolving/try-geting-an-optional-service-by-plugin-type-and-name/ documentation/ioc/resolving/requesting-a-concrete-type/ documentation/ioc/generics/ documentation/ioc/decorators/ documentation/ioc/diagnostics/ documentation/ioc/diagnostics/whatdoihave/ documentation/ioc/diagnostics/validating-container-configuration/ documentation/ioc/diagnostics/environment-tests/ documentation/ioc/diagnostics/build-plans/ documentation/ioc/diagnostics/using-the-container-model/ documentation/ioc/diagnostics/type-scanning/ documentation/ioc/auto-wiring/ documentation/ioc/lambdas/ documentation/ioc/injecting-at-runtime/ documentation/ioc/disposing/ documentation/ioc/lazy-resolution/ documentation/ioc/nested-containers/ documentation/ioc/setter-injection/ documentation/ioc/working-with-enumerable-types/ documentation/compilation/ documentation/compilation/assemblygenerator/ documentation/compilation/sourcewriter/ documentation/compilation/frames/ documentation/compilation/frames/variables/ documentation/compilation/frames/frame/ documentation/compilation/frames/extension-methods/ documentation/compilation/frames/injected-fields/ "; private static void Main(string[] args) { Target("default", DependsOn("test", "commands")); Target("restore", () => { Run("dotnet", "restore Jasper.sln"); }); Target("compile", DependsOn("restore"),() => { Run("dotnet", $"build Jasper.sln --no-restore"); }); Target("test", DependsOn("compile"),() => { RunTests("Jasper.Testing"); //RunTests("Jasper.Http.Testing"); }); Target("full", DependsOn("test", "test-persistence", "storyteller", "test-tcp", "test-rabbitmq", "test-pulsar")); Target("test-persistence", DependsOn("docker-up", "compile"), () => { RunTests("Jasper.Persistence.Testing"); }); Target("test-rabbitmq", DependsOn("docker-up", "compile"), () => { RunTests("Jasper.RabbitMQ.Tests"); }); Target("test-pulsar", DependsOn("docker-up", "compile"), () => { RunTests("Jasper.Pulsar.Tests"); }); Target("test-tcp", DependsOn("compile"), () => { RunTests("Jasper.Tcp.Tests"); }); Target("commands", DependsOn("compile"),() => { var original = Directory.GetCurrentDirectory(); /* Dir.chdir("src/Subscriber") do sh "dotnet run -- ?" sh "dotnet run -- export-json-schema obj/schema" end */ Directory.SetCurrentDirectory(Path.Combine(original, "src", "ConsoleApp")); RunCurrentProject("?"); RunCurrentProject("export-json-schema obj/schema"); RunCurrentProject("describe"); Directory.SetCurrentDirectory(original); }); Target("ci", DependsOn("default")); Target("install", () => RunNpm("install")); Target("benchmark", () => { Run("dotnet", "run -c Release", workingDirectory:"src/Benchmarks"); }); Target("install-mdsnippets", IgnoreIfFailed(() => Run("dotnet", $"tool install -g MarkdownSnippets.Tool") )); Target("docs", DependsOn("install", "install-mdsnippets"), () => { // Run docs site RunNpm("run docs"); }); Target("docs-build", DependsOn("install", "install-mdsnippets"), () => { // Run docs site RunNpm("run docs-build"); }); Target("clear-inline-samples", () => { var files = Directory.GetFiles("./docs", "*.md", SearchOption.AllDirectories); var pattern = @"<!-- snippet:(.+)-->[\s\S]*?<!-- endSnippet -->"; var replacePattern = $"<!-- snippet:$1-->{Environment.NewLine}<!-- endSnippet -->"; foreach (var file in files) { // Console.WriteLine(file); var content = File.ReadAllText(file); if (!content.Contains("<!-- snippet:")) { continue; } var updatedContent = Regex.Replace(content, pattern, replacePattern); File.WriteAllText(file, updatedContent); } }); Target("publish-docs", DependsOn("docs-build"), () => { var docTargetDir = "doc-target"; var branchName = "gh-pages"; Run("git", $"clone -b {branchName} {GITHUB_REPO} {InitializeDirectory(docTargetDir)}"); // if you are not using git --global config, un-comment the block below, update and use it // Run("git", "config user.email user_email", docTargetDir); // Run("git", "config user.name user_name", docTargetDir); // Clean off all the files in the doc-target directory foreach (var file in Directory.EnumerateFiles(docTargetDir)) { if (Path.GetFileName(file) == ".nojekyll") continue; File.Delete(file); } var buildDir = Path.Combine(Environment.CurrentDirectory, "docs", ".vitepress", "dist"); CopyFilesRecursively(buildDir, docTargetDir); WriteForwards(); Run("git", "add --all", docTargetDir); Run("git", $"commit -a -m \"Documentation Update for {BUILD_VERSION}\" --allow-empty", docTargetDir); Run("git", $"push origin {branchName}", docTargetDir); }); Target("storyteller", DependsOn("compile"), () => Run("dotnet", $"run --culture en-US", "src/StorytellerSpecs")); Target("open_st", DependsOn("compile"), () => Run("dotnet", $"storyteller open --culture en-US", "src/StorytellerSpecs")); Target("docker-up", () => { Run("docker", "compose up -d"); WaitForDatabaseToBeReady(); }); RunTargetsAndExit(args); } private static void WaitForDatabaseToBeReady() { var attempt = 0; while (attempt < 10) try { using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select 1"; cmd.ExecuteReader(); Console.WriteLine("Postgresql is up and ready!"); break; } catch (Exception) { Thread.Sleep(250); attempt++; } } private static void WriteForwards() { var reader = new StringReader(Forwards); var url = reader.ReadLine(); while (url != null) { if (!string.IsNullOrEmpty(url)) { WriteForwardingHtml(url, "lamar/guide"); } url = reader.ReadLine(); } } private static void WriteForwardingHtml(string from, string to) { var parts = from.TrimEnd('/').Split('/'); var directory = "doc-target"; for (var i = 0; i < parts.Length - 1; i++) { directory = Path.Combine(directory, parts[i]); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } var html = $@"<head> <meta http-equiv='refresh' content='5; URL=https://jasperfx.github.io/lamar/guide/' /> </head> <body> <p>If you are not redirected in five seconds, <a href='https://jasperfx.github.io/lamar/guide/'>click here</a>.</p> </body> ".Replace("'", "\""); var destination = Path.Combine(directory, parts.Last() + ".html"); File.WriteAllText(destination, html); } private static void RunCurrentProject(string args) { Run("dotnet", $"run --framework net5.0 --no-build --no-restore -- {args}"); } private static void CopyFilesRecursively(string sourcePath, string targetPath) { //Now Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); } //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } } private static string InitializeDirectory(string path) { EnsureDirectoriesDeleted(path); Directory.CreateDirectory(path); return path; } private static void EnsureDirectoriesDeleted(params string[] paths) { foreach (var path in paths) { if (Directory.Exists(path)) { var dir = new DirectoryInfo(path); DeleteDirectory(dir); } } } private static void DeleteDirectory(DirectoryInfo baseDir) { baseDir.Attributes = FileAttributes.Normal; foreach (var childDir in baseDir.GetDirectories()) DeleteDirectory(childDir); foreach (var file in baseDir.GetFiles()) file.IsReadOnly = false; baseDir.Delete(true); } private static void RunNpm(string args) => Run("npm", args, windowsName: "cmd.exe", windowsArgs: $"/c npm {args}"); private static void RunTests(string projectName, string directoryName = "src") { Run("dotnet", $"test -f net5.0 --no-build --no-restore {directoryName}/{projectName}/{projectName}.csproj"); } private static string GetEnvironmentVariable(string variableName) { var val = Environment.GetEnvironmentVariable(variableName); // Azure devops converts environment variable to upper case and dot to underscore // https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch // Attempt to fetch variable by updating it if (string.IsNullOrEmpty(val)) { val = Environment.GetEnvironmentVariable(variableName.ToUpper().Replace(".", "_")); } Console.WriteLine(val); return val; } private static string GetFramework() { var frameworkName = Assembly.GetEntryAssembly().GetCustomAttribute<TargetFrameworkAttribute>().FrameworkName; var version = float.Parse(frameworkName.Split('=')[1].Replace("v",""), InvariantCulture.NumberFormat); return version < 5.0 ? $"netcoreapp{version.ToString("N1", InvariantCulture.NumberFormat)}" : $"net{version.ToString("N1", InvariantCulture.NumberFormat)}"; } private static Action IgnoreIfFailed(Action action) { return () => { try { action(); } catch (Exception exception) { Console.WriteLine(exception.Message); } }; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools; namespace Microsoft.PythonTools.Repl { [Export(typeof(IInteractiveEvaluatorProvider))] sealed class PythonReplEvaluatorProvider : IInteractiveEvaluatorProvider, IDisposable { private readonly IInterpreterRegistryService _interpreterService; private readonly IPythonWorkspaceContextProvider _workspaceContextProvider; private readonly IServiceProvider _serviceProvider; private readonly IVsSolution _solution; private readonly SolutionEventsListener _solutionEvents; private const string _prefix = "E915ECDA-2F45-4398-9E07-15A877137F44"; [ImportingConstructor] public PythonReplEvaluatorProvider( [Import] IInterpreterRegistryService interpreterService, [Import] IPythonWorkspaceContextProvider workspaceContextProvider, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider ) { Debug.Assert(interpreterService != null); _interpreterService = interpreterService; _workspaceContextProvider = workspaceContextProvider; _serviceProvider = serviceProvider; _solution = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution)); _solutionEvents = new SolutionEventsListener(_solution); _solutionEvents.ProjectLoaded += ProjectChanged; _solutionEvents.ProjectClosing += ProjectChanged; _solutionEvents.ProjectRenamed += ProjectChanged; _solutionEvents.SolutionOpened += SolutionChanged; _solutionEvents.SolutionClosed += SolutionChanged; _solutionEvents.StartListeningForChanges(); _workspaceContextProvider.WorkspaceClosed += OnWorkspaceChanged; _workspaceContextProvider.WorkspaceInitialized += OnWorkspaceChanged; } private void OnWorkspaceChanged(object sender, PythonWorkspaceContextEventArgs e) { EvaluatorsChanged?.Invoke(this, EventArgs.Empty); } private void SolutionChanged(object sender, EventArgs e) { EvaluatorsChanged?.Invoke(this, EventArgs.Empty); } private void ProjectChanged(object sender, ProjectEventArgs e) { EvaluatorsChanged?.Invoke(this, EventArgs.Empty); } public void Dispose() { _solutionEvents.Dispose(); _workspaceContextProvider.WorkspaceClosed -= OnWorkspaceChanged; _workspaceContextProvider.WorkspaceInitialized -= OnWorkspaceChanged; } public event EventHandler EvaluatorsChanged; public IEnumerable<KeyValuePair<string, string>> GetEvaluators() { _serviceProvider.MustBeCalledFromUIThread(); foreach (var interpreter in _interpreterService.Configurations.Where(PythonInterpreterFactoryExtensions.IsRunnable)) { yield return new KeyValuePair<string, string>( interpreter.Description, GetEvaluatorId(interpreter) ); } var solution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution; if (solution != null) { foreach (var project in solution.EnumerateLoadedPythonProjects()) { if (project.IsClosed || project.IsClosing) { continue; } yield return new KeyValuePair<string, string>( Strings.ReplProjectProjectCaption.FormatUI(project.Caption), GetEvaluatorId(project) ); } } var workspace = _workspaceContextProvider.Workspace; if (workspace != null) { yield return new KeyValuePair<string, string>( Strings.ReplWorkspaceCaption.FormatUI(workspace.WorkspaceName), GetEvaluatorId(workspace) ); } } internal static string GetEvaluatorId(InterpreterConfiguration config) { return "{0};env;{1};{2}".FormatInvariant( _prefix, config.Description, config.Id ); } internal static string GetEvaluatorId(PythonProjectNode project) { return "{0};project;{1};{2}".FormatInvariant( _prefix, project.Caption, project.GetMkDocument() ); } internal static string GetEvaluatorId(IPythonWorkspaceContext workspace) { return "{0};workspace;{1};{2}".FormatInvariant( _prefix, workspace.WorkspaceName, workspace.Location ); } internal static string GetTemporaryId(string key, InterpreterConfiguration config) { return GetEvaluatorId(config) + ";" + key; } public IInteractiveEvaluator GetEvaluator(string evaluatorId) { if (string.IsNullOrEmpty(evaluatorId)) { return null; } // Max out at 10 splits to protect against malicious IDs var bits = evaluatorId.Split(new[] { ';' }, 10); if (bits.Length < 2 || !bits[0].Equals(_prefix, StringComparison.OrdinalIgnoreCase)) { return null; } if (bits[1].Equals("env", StringComparison.OrdinalIgnoreCase)) { return GetEnvironmentEvaluator(bits.Skip(2).ToArray()); } if (bits[1].Equals("project", StringComparison.OrdinalIgnoreCase)) { return GetProjectEvaluator(bits.Skip(2).ToArray()); } if (bits[1].Equals("workspace", StringComparison.OrdinalIgnoreCase)) { return GetWorkspaceEvaluator(bits.Skip(2).ToArray()); } return null; } private IInteractiveEvaluator GetEnvironmentEvaluator(IReadOnlyList<string> args) { _serviceProvider.MustBeCalledFromUIThread(); var config = _interpreterService.FindConfiguration(args.ElementAtOrDefault(1)); var eval = new PythonInteractiveEvaluator(_serviceProvider) { DisplayName = args.ElementAtOrDefault(0), Configuration = new LaunchConfiguration(config) }; eval.Configuration.SearchPaths = _serviceProvider.GetPythonToolsService().GetGlobalPythonSearchPaths(config).ToList(); return eval; } private IInteractiveEvaluator GetProjectEvaluator(IReadOnlyList<string> args) { _serviceProvider.MustBeCalledFromUIThread(); var project = args.ElementAtOrDefault(1); var eval = new PythonInteractiveEvaluator(_serviceProvider) { DisplayName = args.ElementAtOrDefault(0), ProjectMoniker = project }; eval.UpdatePropertiesFromProjectMoniker(); return eval; } private IInteractiveEvaluator GetWorkspaceEvaluator(IReadOnlyList<string> args) { _serviceProvider.MustBeCalledFromUIThread(); var workspace = args.ElementAtOrDefault(1); var eval = new PythonInteractiveEvaluator(_serviceProvider) { DisplayName = args.ElementAtOrDefault(0), WorkspaceMoniker = workspace }; eval.UpdatePropertiesFromWorkspaceMoniker(); return eval; } } }
// // 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. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Threading; using NUnit.Framework; #if !NUNIT using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif using NLog.Common; using NLog.Internal; using NLog.Targets; [TestFixture] public class TargetTests : NLogTestBase { [Test] public void InitializeTest() { var target = new MyTarget(); target.Initialize(null); // initialize was called once Assert.AreEqual(1, target.InitializeCount); Assert.AreEqual(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Test] public void InitializeFailedTest() { var target = new MyTarget(); target.ThrowOnInitialize = true; try { target.Initialize(null); Assert.Fail("Expected exception."); } catch (InvalidOperationException) { } // after exception in Initialize(), the target becomes non-functional and all Write() operations var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.AreEqual(0, target.WriteCount); Assert.AreEqual(1, exceptions.Count); Assert.IsNotNull(exceptions[0]); Assert.AreEqual("Target " + target + " failed to initialize.", exceptions[0].Message); Assert.AreEqual("Init error.", exceptions[0].InnerException.Message); } [Test] public void DoubleInitializeTest() { var target = new MyTarget(); target.Initialize(null); target.Initialize(null); // initialize was called once Assert.AreEqual(1, target.InitializeCount); Assert.AreEqual(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Test] public void DoubleCloseTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); target.Close(); // initialize and close were called once each Assert.AreEqual(1, target.InitializeCount); Assert.AreEqual(1, target.CloseCount); Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Test] public void CloseWithoutInitializeTest() { var target = new MyTarget(); target.Close(); // nothing was called Assert.AreEqual(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Test] public void WriteWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); // write was not called Assert.AreEqual(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.AreEqual(4, exceptions.Count); exceptions.ForEach(Assert.IsNull); } [Test] public void WriteOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.AreEqual(1, target.InitializeCount); Assert.AreEqual(1, target.CloseCount); // write was not called Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); // but all callbacks were invoked with null values Assert.AreEqual(4, exceptions.Count); exceptions.ForEach(Assert.IsNull); } [Test] public void FlushTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Initialize(null); target.Flush(exceptions.Add); // flush was called Assert.AreEqual(1, target.FlushCount); Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.AreEqual(1, exceptions.Count); exceptions.ForEach(Assert.IsNull); } [Test] public void FlushWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.AreEqual(1, exceptions.Count); exceptions.ForEach(Assert.IsNull); // flush was not called Assert.AreEqual(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Test] public void FlushOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); Assert.AreEqual(1, target.InitializeCount); Assert.AreEqual(1, target.CloseCount); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.AreEqual(1, exceptions.Count); exceptions.ForEach(Assert.IsNull); // flush was not called Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Test] public void LockingTest() { var target = new MyTarget(); target.Initialize(null); var mre = new ManualResetEvent(false); Exception backgroundThreadException = null; Thread t = new Thread(() => { try { target.BlockingOperation(1000); } catch (Exception ex) { backgroundThreadException = ex; } finally { mre.Set(); } }); target.Initialize(null); t.Start(); Thread.Sleep(50); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); target.Flush(exceptions.Add); target.Close(); exceptions.ForEach(Assert.IsNull); mre.WaitOne(); if (backgroundThreadException != null) { Assert.Fail(backgroundThreadException.ToString()); } } [Test] public void GivenNullEvents_WhenWriteAsyncLogEvents_ThenNoExceptionAreThrown() { var target = new MyTarget(); try { target.WriteAsyncLogEvents(null); } catch (Exception e) { Assert.Fail("Exeption thrown: " + e); } } public class MyTarget : Target { private int inBlockingOperation; public int InitializeCount { get; set; } public int CloseCount { get; set; } public int FlushCount { get; set; } public int WriteCount { get; set; } public int WriteCount2 { get; set; } public bool ThrowOnInitialize { get; set; } public int WriteCount3 { get; set; } protected override void InitializeTarget() { if (this.ThrowOnInitialize) { throw new InvalidOperationException("Init error."); } Assert.AreEqual(0, this.inBlockingOperation); this.InitializeCount++; base.InitializeTarget(); } protected override void CloseTarget() { Assert.AreEqual(0, this.inBlockingOperation); this.CloseCount++; base.CloseTarget(); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Assert.AreEqual(0, this.inBlockingOperation); this.FlushCount++; base.FlushAsync(asyncContinuation); } protected override void Write(LogEventInfo logEvent) { Assert.AreEqual(0, this.inBlockingOperation); this.WriteCount++; } protected override void Write(AsyncLogEventInfo logEvent) { Assert.AreEqual(0, this.inBlockingOperation); this.WriteCount2++; base.Write(logEvent); } protected override void Write(AsyncLogEventInfo[] logEvents) { Assert.AreEqual(0, this.inBlockingOperation); this.WriteCount3++; base.Write(logEvents); } public void BlockingOperation(int millisecondsTimeout) { lock (this.SyncRoot) { this.inBlockingOperation++; Thread.Sleep(millisecondsTimeout); this.inBlockingOperation--; } } } } }
// <copyright file="ObservableMasterSlaveCollection{T}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Threading; using IX.Observable.Adapters; using IX.Observable.DebugAide; using IX.Observable.StateChanges; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Threading; using JetBrains.Annotations; namespace IX.Observable; /// <summary> /// An observable collection created from a master collection (to which updates go) and many slave, read-only /// collections. /// </summary> /// <typeparam name="T">The type of the item.</typeparam> /// <seealso cref="IX.Observable.ObservableListBase{T}" /> /// <seealso cref="IList{T}" /> /// <seealso cref="IReadOnlyCollection{T}" /> /// <seealso cref="ICollection{T}" /> /// <seealso cref="ICollection" /> /// <seealso cref="IList" /> /// <seealso cref="Observable.ObservableCollectionBase{TItem}" /> [DebuggerDisplay("ObservableMasterSlaveCollection, Count = {" + nameof(Count) + "}")] [DebuggerTypeProxy(typeof(CollectionDebugView<>))] [PublicAPI] public class ObservableMasterSlaveCollection<T> : ObservableListBase<T> { #region Constructors and destructors /// <summary> /// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class. /// </summary> public ObservableMasterSlaveCollection() : base(new MultiListMasterSlaveListAdapter<T>()) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class. /// </summary> /// <param name="context">The synchronization context to use, if any.</param> public ObservableMasterSlaveCollection(SynchronizationContext context) : base( new MultiListMasterSlaveListAdapter<T>(), context) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class. /// </summary> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableMasterSlaveCollection(bool suppressUndoable) : base( new MultiListMasterSlaveListAdapter<T>(), suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class. /// </summary> /// <param name="context">The synchronization context to use, if any.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableMasterSlaveCollection( SynchronizationContext context, bool suppressUndoable) : base( new MultiListMasterSlaveListAdapter<T>(), context, suppressUndoable) { } #endregion #region Properties and indexers /// <summary> /// Gets the count after an add operation. Used internally. /// </summary> /// <value> /// The count after add. /// </value> protected override int CountAfterAdd => ((MultiListMasterSlaveListAdapter<T>)this.InternalListContainer).MasterCount; #endregion #region Methods /// <summary> /// Sets the master list. /// </summary> /// <typeparam name="TList">The type of the list.</typeparam> /// <param name="list">The list.</param> public void SetMasterList<TList>(TList list) where TList : class, IList<T>, INotifyCollectionChanged { this.RequiresNotDisposed(); using (this.WriteLock()) { ((MultiListMasterSlaveListAdapter<T>)this.InternalListContainer).SetMaster(list); } this.RaiseCollectionReset(); this.RaisePropertyChanged(nameof(this.Count)); this.RaisePropertyChanged(Constants.ItemsName); } /// <summary> /// Sets a slave list. /// </summary> /// <typeparam name="TList">The type of the list.</typeparam> /// <param name="list">The list.</param> public void SetSlaveList<TList>(TList list) where TList : class, IEnumerable<T>, INotifyCollectionChanged { this.RequiresNotDisposed(); using (this.WriteLock()) { ((MultiListMasterSlaveListAdapter<T>)this.InternalListContainer).SetSlave(list); } this.RaiseCollectionReset(); this.RaisePropertyChanged(nameof(this.Count)); this.RaisePropertyChanged(Constants.ItemsName); } /// <summary> /// Removes a slave list. /// </summary> /// <typeparam name="TList">The type of the list.</typeparam> /// <param name="list">The list.</param> public void RemoveSlaveList<TList>(TList list) where TList : class, IEnumerable<T>, INotifyCollectionChanged { this.RequiresNotDisposed(); using (this.WriteLock()) { ((MultiListMasterSlaveListAdapter<T>)this.InternalListContainer).RemoveSlave(list); } this.RaiseCollectionReset(); this.RaisePropertyChanged(nameof(this.Count)); this.RaisePropertyChanged(Constants.ItemsName); } /// <summary> /// Adds an item to the <see cref="T:IX.Observable.ObservableCollectionBase`1" />. /// </summary> /// <param name="item">The object to add to the <see cref="T:IX.Observable.ObservableCollectionBase`1" />.</param> /// <remarks>On concurrent collections, this method is write-synchronized.</remarks> public override void Add(T item) { this.IncreaseIgnoreMustResetCounter(); base.Add(item); } /// <summary> /// Inserts an item at the specified index. /// </summary> /// <param name="index">The index at which to insert.</param> /// <param name="item">The item.</param> public override void Insert( int index, T item) { this.IncreaseIgnoreMustResetCounter(); base.Insert( index, item); } /// <summary> /// Removes the first occurrence of a specific object from the /// <see cref="T:IX.Observable.ObservableCollectionBase`1" />. /// </summary> /// <param name="item">The object to remove from the <see cref="T:IX.Observable.ObservableCollectionBase`1" />.</param> /// <returns> /// <see langword="true" /> if <paramref name="item" /> was successfully removed from the /// <see cref="T:IX.Observable.ObservableCollectionBase`1" />; otherwise, <see langword="false" />. /// This method also returns false if <paramref name="item" /> is not found in the original /// <see cref="T:IX.Observable.ObservableCollectionBase`1" />. /// </returns> /// <remarks>On concurrent collections, this method is write-synchronized.</remarks> public override bool Remove(T item) { this.IncreaseIgnoreMustResetCounter(); if (base.Remove(item)) { return true; } this.IncreaseIgnoreMustResetCounter(-1); return false; } /// <summary> /// Removes an item at the specified index. /// </summary> /// <param name="index">The index at which to remove an item from.</param> public override void RemoveAt(int index) { this.RequiresNotDisposed(); T item; using (ReadWriteSynchronizationLocker lockContext = this.ReadWriteLock()) { if (index >= this.InternalListContainer.Count) { return; } lockContext.Upgrade(); item = this.InternalListContainer[index]; this.IncreaseIgnoreMustResetCounter(); this.InternalListContainer.RemoveAt(index); this.PushUndoLevel( new RemoveStateChange<T>( index, item)); } this.RaiseCollectionChangedRemove( item, index); this.RaisePropertyChanged(nameof(this.Count)); this.ContentsMayHaveChanged(); } /// <summary> /// Removes all items from the <see cref="ObservableMasterSlaveCollection{T}" />. /// </summary> /// <returns>An array containing the original collection items.</returns> /// <remarks>On concurrent collections, this method is write-synchronized.</remarks> protected override T[] ClearInternal() { this.RequiresNotDisposed(); T[] originalArray; using (this.WriteLock()) { var container = (MultiListMasterSlaveListAdapter<T>)this.InternalListContainer; this.IncreaseIgnoreMustResetCounter(container.SlavesCount + 1); originalArray = new T[container.MasterCount]; container.MasterCopyTo( originalArray, 0); this.InternalListContainer.Clear(); this.PushUndoLevel(new ClearStateChange<T>(originalArray)); } this.RaiseCollectionReset(); this.RaisePropertyChanged(nameof(this.Count)); this.ContentsMayHaveChanged(); return originalArray; } /// <summary> /// Called when the contents may have changed so that proper notifications can happen. /// </summary> protected override void ContentsMayHaveChanged() => this.RaisePropertyChanged(Constants.ItemsName); #endregion }
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Web; using System.Web.Caching; using System.Xml; using System.Configuration; using System.Collections.Generic; using Umbraco.Core.Logging; using Umbraco.Core.CodeAnnotations; namespace Umbraco.Core.Configuration { //NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc... // we have this two tasks logged: // http://issues.umbraco.org/issue/U4-58 // http://issues.umbraco.org/issue/U4-115 //TODO: Re-enable logging !!!! //TODO: We need to convert this to a real section, it's currently using HttpRuntime.Cache to detect cahnges, this is real poor, especially in a console app /// <summary> /// The UmbracoSettings Class contains general settings information for the entire Umbraco instance based on information from the /config/umbracoSettings.config file /// </summary> internal class UmbracoSettings { private static bool GetKeyValue(string key, bool defaultValue) { bool value; string stringValue = GetKey(key); if (string.IsNullOrWhiteSpace(stringValue)) return defaultValue; if (bool.TryParse(stringValue, out value)) return value; return defaultValue; } private static int GetKeyValue(string key, int defaultValue) { int value; string stringValue = GetKey(key); if (string.IsNullOrWhiteSpace(stringValue)) return defaultValue; if (int.TryParse(stringValue, out value)) return value; return defaultValue; } /// <summary> /// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config) /// </summary> private static void ResetInternal() { _addTrailingSlash = null; _forceSafeAliases = null; _useLegacySchema = null; _useDomainPrefixes = null; _umbracoLibraryCacheDuration = null; SettingsFilePath = null; } internal const string TempFriendlyXmlChildContainerNodename = ""; // "children"; /// <summary> /// Gets the umbraco settings document. /// </summary> /// <value>The _umbraco settings.</value> internal static XmlDocument UmbracoSettingsXmlDoc { get { var us = (XmlDocument)HttpRuntime.Cache["umbracoSettingsFile"] ?? EnsureSettingsDocument(); return us; } } private static string _path; /// <summary> /// Gets/sets the settings file path, the setter can be used in unit tests /// </summary> internal static string SettingsFilePath { get { return _path ?? (_path = GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar); } set { _path = value; } } internal const string Filename = "umbracoSettings.config"; internal static XmlDocument EnsureSettingsDocument() { var settingsFile = HttpRuntime.Cache["umbracoSettingsFile"]; // Check for language file in cache if (settingsFile == null) { var temp = new XmlDocument(); var settingsReader = new XmlTextReader(SettingsFilePath + Filename); try { temp.Load(settingsReader); HttpRuntime.Cache.Insert("umbracoSettingsFile", temp, new CacheDependency(SettingsFilePath + Filename)); } catch (XmlException e) { throw new XmlException("Your umbracoSettings.config file fails to pass as valid XML. Refer to the InnerException for more information", e); } catch (Exception e) { LogHelper.Error<UmbracoSettings>("Error reading umbracoSettings file: " + e.ToString(), e); } settingsReader.Close(); return temp; } else return (XmlDocument)settingsFile; } internal static void Save() { UmbracoSettingsXmlDoc.Save(SettingsFilePath + Filename); } /// <summary> /// Selects a xml node in the umbraco settings config file. /// </summary> /// <param name="key">The xpath query to the specific node.</param> /// <returns>If found, it returns the specific configuration xml node.</returns> internal static XmlNode GetKeyAsNode(string key) { if (key == null) throw new ArgumentException("Key cannot be null"); EnsureSettingsDocument(); if (UmbracoSettingsXmlDoc == null || UmbracoSettingsXmlDoc.DocumentElement == null) return null; return UmbracoSettingsXmlDoc.DocumentElement.SelectSingleNode(key); } /// <summary> /// Gets the value of configuration xml node with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> internal static string GetKey(string key) { EnsureSettingsDocument(); string attrName = null; var pos = key.IndexOf('@'); if (pos > 0) { attrName = key.Substring(pos + 1); key = key.Substring(0, pos - 1); } var node = UmbracoSettingsXmlDoc.DocumentElement.SelectSingleNode(key); if (node == null) return string.Empty; if (pos < 0) { if (node.FirstChild == null || node.FirstChild.Value == null) return string.Empty; return node.FirstChild.Value; } else { var attr = node.Attributes[attrName]; if (attr == null) return string.Empty; return attr.Value; } } /// <summary> /// Gets a value indicating whether the media library will create new directories in the /media directory. /// </summary> /// <value> /// <c>true</c> if new directories are allowed otherwise, <c>false</c>. /// </value> internal static bool UploadAllowDirectories { get { return bool.Parse(GetKey("/settings/content/UploadAllowDirectories")); } } /// <summary> /// THIS IS TEMPORARY until we fix up settings all together, this setting is actually not 'settable' but is /// here for future purposes since we check for thsi settings in the module. /// </summary> internal static bool EnableBaseRestHandler { get { return true; } } /// <summary> /// THIS IS TEMPORARY until we fix up settings all together, this setting is actually not 'settable' but is /// here for future purposes since we check for thsi settings in the module. /// </summary> internal static string BootSplashPage { get { return "~/config/splashes/booting.aspx"; } } /// <summary> /// Gets a value indicating whether logging is enabled in umbracoSettings.config (/settings/logging/enableLogging). /// </summary> /// <value><c>true</c> if logging is enabled; otherwise, <c>false</c>.</value> internal static bool EnableLogging { get { // We return true if no enable logging element is present in // umbracoSettings (to enable default behaviour when upgrading) var enableLogging = GetKey("/settings/logging/enableLogging"); return String.IsNullOrEmpty(enableLogging) || bool.Parse(enableLogging); } } /// <summary> /// Gets a value indicating whether logging happens async. /// </summary> /// <value><c>true</c> if async logging is enabled; otherwise, <c>false</c>.</value> internal static bool EnableAsyncLogging { get { string value = GetKey("/settings/logging/enableAsyncLogging"); bool result; if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) return result; return false; } } /// <summary> /// Gets the assembly of an external logger that can be used to store log items in 3rd party systems /// </summary> internal static string ExternalLoggerAssembly { get { var value = GetKeyAsNode("/settings/logging/externalLogger"); return value != null ? value.Attributes["assembly"].Value : ""; } } /// <summary> /// Gets the type of an external logger that can be used to store log items in 3rd party systems /// </summary> internal static string ExternalLoggerType { get { var value = GetKeyAsNode("/settings/logging/externalLogger"); return value != null ? value.Attributes["type"].Value : ""; } } /// <summary> /// Long Audit Trail to external log too /// </summary> internal static bool ExternalLoggerLogAuditTrail { get { var value = GetKeyAsNode("/settings/logging/externalLogger"); if (value != null) { var logAuditTrail = value.Attributes["logAuditTrail"].Value; bool result; if (!string.IsNullOrEmpty(logAuditTrail) && bool.TryParse(logAuditTrail, out result)) return result; } return false; } } /// <summary> /// Keep user alive as long as they have their browser open? Default is true /// </summary> internal static bool KeepUserLoggedIn { get { var value = GetKey("/settings/security/keepUserLoggedIn"); bool result; if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) return result; return true; } } /// <summary> /// Enables the experimental canvas (live) editing on the frontend of the website /// </summary> internal static bool EnableCanvasEditing { get { var value = GetKey("/settings/content/EnableCanvasEditing"); bool result; if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) return result; return true; } } /// <summary> /// Show disabled users in the tree in the Users section in the backoffice /// </summary> internal static bool HideDisabledUsersInBackoffice { get { string value = GetKey("/settings/security/hideDisabledUsersInBackoffice"); bool result; if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) return result; return false; } } /// <summary> /// Gets a value indicating whether the logs will be auto cleaned /// </summary> /// <value><c>true</c> if logs are to be automatically cleaned; otherwise, <c>false</c></value> internal static bool AutoCleanLogs { get { string value = GetKey("/settings/logging/autoCleanLogs"); bool result; if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) return result; return false; } } /// <summary> /// Gets the value indicating the log cleaning frequency (in miliseconds) /// </summary> internal static int CleaningMiliseconds { get { string value = GetKey("/settings/logging/cleaningMiliseconds"); int result; if (!string.IsNullOrEmpty(value) && int.TryParse(value, out result)) return result; return -1; } } internal static int MaxLogAge { get { string value = GetKey("/settings/logging/maxLogAge"); int result; if (!string.IsNullOrEmpty(value) && int.TryParse(value, out result)) return result; return -1; } } /// <summary> /// Gets the disabled log types. /// </summary> /// <value>The disabled log types.</value> internal static XmlNode DisabledLogTypes { get { return GetKeyAsNode("/settings/logging/disabledLogTypes"); } } /// <summary> /// Gets the package server url. /// </summary> /// <value>The package server url.</value> internal static string PackageServer { get { return "packages.umbraco.org"; } } static bool? _useDomainPrefixes = null; /// <summary> /// Gets a value indicating whether umbraco will use domain prefixes. /// </summary> /// <value><c>true</c> if umbraco will use domain prefixes; otherwise, <c>false</c>.</value> internal static bool UseDomainPrefixes { get { // default: false return _useDomainPrefixes ?? GetKeyValue("/settings/requestHandler/useDomainPrefixes", false); } /*internal*/ set { // for unit tests only _useDomainPrefixes = value; } } static bool? _addTrailingSlash = null; /// <summary> /// This will add a trailing slash (/) to urls when in directory url mode /// NOTICE: This will always return false if Directory Urls in not active /// </summary> internal static bool AddTrailingSlash { get { // default: false return GlobalSettings.UseDirectoryUrls && (_addTrailingSlash ?? GetKeyValue("/settings/requestHandler/addTrailingSlash", false)); } /*internal*/ set { // for unit tests only _addTrailingSlash = value; } } /// <summary> /// Gets a value indicating whether umbraco will use ASP.NET MasterPages for rendering instead of its propriatary templating system. /// </summary> /// <value><c>true</c> if umbraco will use ASP.NET MasterPages; otherwise, <c>false</c>.</value> internal static bool UseAspNetMasterPages { get { try { bool result; if (bool.TryParse(GetKey("/settings/templates/useAspNetMasterPages"), out result)) return result; return false; } catch { return false; } } } /// <summary> /// Gets a value indicating whether umbraco will attempt to load any skins to override default template files /// </summary> /// <value><c>true</c> if umbraco will override templates with skins if present and configured <c>false</c>.</value> internal static bool EnableTemplateFolders { get { try { bool result; if (bool.TryParse(GetKey("/settings/templates/enableTemplateFolders"), out result)) return result; return false; } catch { return false; } } } //TODO: I"m not sure why we need this, need to ask Gareth what the deal is, pretty sure we can remove it or change it, seems like // massive overkill. /// <summary> /// razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml /// </summary> internal static IEnumerable<string> NotDynamicXmlDocumentElements { get { try { List<string> items = new List<string>(); XmlNode root = GetKeyAsNode("/settings/scripting/razor/notDynamicXmlDocumentElements"); foreach (XmlNode element in root.SelectNodes(".//element")) { items.Add(element.InnerText); } return items; } catch { return new List<string>() { "p", "div" }; } } } private static IEnumerable<RazorDataTypeModelStaticMappingItem> _razorDataTypeModelStaticMapping; private static readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim(); internal static IEnumerable<RazorDataTypeModelStaticMappingItem> RazorDataTypeModelStaticMapping { get { /* <dataTypeModelStaticMappings> <mapping dataTypeGuid="ef94c406-9e83-4058-a780-0375624ba7ca">DigibizAdvancedMediaPicker.RazorModel.ModelBinder</mapping> <mapping documentTypeAlias="RoomPage" nodeTypeAlias="teaser">DigibizAdvancedMediaPicker.RazorModel.ModelBinder</mapping> </dataTypeModelStaticMappings> */ using (var l = new UpgradeableReadLock(Lock)) { if (_razorDataTypeModelStaticMapping == null) { l.UpgradeToWriteLock(); List<RazorDataTypeModelStaticMappingItem> items = new List<RazorDataTypeModelStaticMappingItem>(); XmlNode root = GetKeyAsNode("/settings/scripting/razor/dataTypeModelStaticMappings"); if (root != null) { foreach (XmlNode element in root.SelectNodes(".//mapping")) { string propertyTypeAlias = null, nodeTypeAlias = null; Guid? dataTypeGuid = null; if (!string.IsNullOrEmpty(element.InnerText)) { if (element.Attributes["dataTypeGuid"] != null) { dataTypeGuid = (Guid?)new Guid(element.Attributes["dataTypeGuid"].Value); } if (element.Attributes["propertyTypeAlias"] != null && !string.IsNullOrEmpty(element.Attributes["propertyTypeAlias"].Value)) { propertyTypeAlias = element.Attributes["propertyTypeAlias"].Value; } if (element.Attributes["nodeTypeAlias"] != null && !string.IsNullOrEmpty(element.Attributes["nodeTypeAlias"].Value)) { nodeTypeAlias = element.Attributes["nodeTypeAlias"].Value; } items.Add(new RazorDataTypeModelStaticMappingItem() { DataTypeGuid = dataTypeGuid, PropertyTypeAlias = propertyTypeAlias, NodeTypeAlias = nodeTypeAlias, TypeName = element.InnerText, Raw = element.OuterXml }); } } } _razorDataTypeModelStaticMapping = items; } return _razorDataTypeModelStaticMapping; } } } /// <summary> /// Gets a value indicating whether umbraco will clone XML cache on publish. /// </summary> /// <value> /// <c>true</c> if umbraco will clone XML cache on publish; otherwise, <c>false</c>. /// </value> internal static bool CloneXmlCacheOnPublish { get { try { bool result; if (bool.TryParse(GetKey("/settings/content/cloneXmlContent"), out result)) return result; return false; } catch { return false; } } } /// <summary> /// Gets a value indicating whether rich text editor content should be parsed by tidy. /// </summary> /// <value><c>true</c> if content is parsed; otherwise, <c>false</c>.</value> internal static bool TidyEditorContent { get { return bool.Parse(GetKey("/settings/content/TidyEditorContent")); } } /// <summary> /// Gets the encoding type for the tidyied content. /// </summary> /// <value>The encoding type as string.</value> internal static string TidyCharEncoding { get { string encoding = GetKey("/settings/content/TidyCharEncoding"); if (String.IsNullOrEmpty(encoding)) { encoding = "UTF8"; } return encoding; } } /// <summary> /// Gets the property context help option, this can either be 'text', 'icon' or 'none' /// </summary> /// <value>The property context help option.</value> internal static string PropertyContextHelpOption { get { return GetKey("/settings/content/PropertyContextHelpOption").ToLower(); } } internal static string DefaultBackofficeProvider { get { string defaultProvider = GetKey("/settings/providers/users/DefaultBackofficeProvider"); if (String.IsNullOrEmpty(defaultProvider)) defaultProvider = "UsersMembershipProvider"; return defaultProvider; } } private static bool? _forceSafeAliases; /// <summary> /// Whether to force safe aliases (no spaces, no special characters) at businesslogic level on contenttypes and propertytypes /// </summary> internal static bool ForceSafeAliases { get { // default: true return _forceSafeAliases ?? GetKeyValue("/settings/content/ForceSafeAliases", true); } /*internal*/ set { // used for unit testing _forceSafeAliases = value; } } /// <summary> /// Gets a value indicating whether to try to skip IIS custom errors. /// </summary> [UmbracoWillObsolete("Use UmbracoSettings.For<WebRouting>.TrySkipIisCustomErrors instead.")] internal static bool TrySkipIisCustomErrors { get { return GetKeyValue("/settings/web.routing/@trySkipIisCustomErrors", false); } } /// <summary> /// Gets a value indicating whether internal redirect preserves the template. /// </summary> [UmbracoWillObsolete("Use UmbracoSettings.For<WebRouting>.InternalRedirectPerservesTemplate instead.")] internal static bool InternalRedirectPreservesTemplate { get { return GetKeyValue("/settings/web.routing/@internalRedirectPreservesTemplate", false); } } /// <summary> /// File types that will not be allowed to be uploaded via the content/media upload control /// </summary> public static IEnumerable<string> DisallowedUploadFiles { get { var val = GetKey("/settings/content/disallowedUploadFiles"); return val.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); } } /// <summary> /// Gets the allowed image file types. /// </summary> /// <value>The allowed image file types.</value> internal static string ImageFileTypes { get { return GetKey("/settings/content/imaging/imageFileTypes").ToLowerInvariant(); } } /// <summary> /// Gets the allowed script file types. /// </summary> /// <value>The allowed script file types.</value> internal static string ScriptFileTypes { get { return GetKey("/settings/content/scripteditor/scriptFileTypes"); } } private static int? _umbracoLibraryCacheDuration; /// <summary> /// Gets the duration in seconds to cache queries to umbraco library member and media methods /// Default is 1800 seconds (30 minutes) /// </summary> internal static int UmbracoLibraryCacheDuration { get { // default: 1800 return _umbracoLibraryCacheDuration ?? GetKeyValue("/settings/content/UmbracoLibraryCacheDuration", 1800); } /*internal*/ set { // for unit tests only _umbracoLibraryCacheDuration = value; } } /// <summary> /// Gets the path to the scripts folder used by the script editor. /// </summary> /// <value>The script folder path.</value> internal static string ScriptFolderPath { get { return GetKey("/settings/content/scripteditor/scriptFolderPath"); } } /// <summary> /// Enabled or disable the script/code editor /// </summary> internal static bool ScriptDisableEditor { get { string _tempValue = GetKey("/settings/content/scripteditor/scriptDisableEditor"); if (_tempValue != String.Empty) return bool.Parse(_tempValue); else return false; } } /// <summary> /// Gets a value indicating whether umbraco will ensure unique node naming. /// This will ensure that nodes cannot have the same url, but will add extra characters to a url. /// ex: existingnodename.aspx would become existingnodename(1).aspx if a node with the same name is found /// </summary> /// <value><c>true</c> if umbraco ensures unique node naming; otherwise, <c>false</c>.</value> internal static bool EnsureUniqueNaming { get { try { return bool.Parse(GetKey("/settings/content/ensureUniqueNaming")); } catch { return false; } } } /// <summary> /// Gets the notification email sender. /// </summary> /// <value>The notification email sender.</value> internal static string NotificationEmailSender { get { return GetKey("/settings/content/notifications/email"); } } /// <summary> /// Gets a value indicating whether notification-emails are HTML. /// </summary> /// <value> /// <c>true</c> if html notification-emails are disabled; otherwise, <c>false</c>. /// </value> internal static bool NotificationDisableHtmlEmail { get { var tempValue = GetKey("/settings/content/notifications/disableHtmlEmail"); return tempValue != String.Empty && bool.Parse(tempValue); } } /// <summary> /// Gets the allowed attributes on images. /// </summary> /// <value>The allowed attributes on images.</value> internal static string ImageAllowedAttributes { get { return GetKey("/settings/content/imaging/allowedAttributes"); } } internal static XmlNode ImageAutoFillImageProperties { get { return GetKeyAsNode("/settings/content/imaging/autoFillImageProperties"); } } /// <summary> /// Gets the scheduled tasks as XML /// </summary> /// <value>The scheduled tasks.</value> internal static XmlNode ScheduledTasks { get { return GetKeyAsNode("/settings/scheduledTasks"); } } /// <summary> /// Gets a list of characters that will be replaced when generating urls /// </summary> /// <value>The URL replacement characters.</value> internal static XmlNode UrlReplaceCharacters { get { return GetKeyAsNode("/settings/requestHandler/urlReplacing"); } } /// <summary> /// Whether to replace double dashes from url (ie my--story----from--dash.aspx caused by multiple url replacement chars /// </summary> internal static bool RemoveDoubleDashesFromUrlReplacing { get { try { return bool.Parse(UrlReplaceCharacters.Attributes.GetNamedItem("removeDoubleDashes").Value); } catch { return false; } } } /// <summary> /// Gets a value indicating whether umbraco will use distributed calls. /// This enables umbraco to share cache and content across multiple servers. /// Used for load-balancing high-traffic sites. /// </summary> /// <value><c>true</c> if umbraco uses distributed calls; otherwise, <c>false</c>.</value> internal static bool UseDistributedCalls { get { try { return bool.Parse(GetKeyAsNode("/settings/distributedCall").Attributes.GetNamedItem("enable").Value); } catch { return false; } } } /// <summary> /// Gets the ID of the user with access rights to perform the distributed calls. /// </summary> /// <value>The distributed call user.</value> internal static int DistributedCallUser { get { try { return int.Parse(GetKey("/settings/distributedCall/user")); } catch { return -1; } } } /// <summary> /// Gets the html injected into a (x)html page if Umbraco is running in preview mode /// </summary> internal static string PreviewBadge { get { try { return GetKey("/settings/content/PreviewBadge"); } catch { return "<a id=\"umbracoPreviewBadge\" style=\"position: absolute; top: 0; right: 0; border: 0; width: 149px; height: 149px; background: url('{1}/preview/previewModeBadge.png') no-repeat;\" href=\"{0}/endPreview.aspx?redir={2}\"><span style=\"display:none;\">In Preview Mode - click to end</span></a>"; } } } /// <summary> /// Gets IP or hostnames of the distribution servers. /// These servers will receive a call everytime content is created/deleted/removed /// and update their content cache accordingly, ensuring a consistent cache on all servers /// </summary> /// <value>The distribution servers.</value> internal static XmlNode DistributionServers { get { try { return GetKeyAsNode("/settings/distributedCall/servers"); } catch { return null; } } } /// <summary> /// Gets HelpPage configurations. /// A help page configuration specify language, user type, application, application url and /// the target help page url. /// </summary> internal static XmlNode HelpPages { get { try { return GetKeyAsNode("/settings/help"); } catch { return null; } } } /// <summary> /// Gets all repositories registered, and returns them as XmlNodes, containing name, alias and webservice url. /// These repositories are used by the build-in package installer and uninstaller to install new packages and check for updates. /// All repositories should have a unique alias. /// All packages installed from a repository gets the repository alias included in the install information /// </summary> /// <value>The repository servers.</value> internal static XmlNode Repositories { get { try { return GetKeyAsNode("/settings/repositories"); } catch { return null; } } } /// <summary> /// Gets a value indicating whether umbraco will use the viewstate mover module. /// The viewstate mover will move all asp.net viewstate information to the bottom of the aspx page /// to ensure that search engines will index text instead of javascript viewstate information. /// </summary> /// <value> /// <c>true</c> if umbraco will use the viewstate mover module; otherwise, <c>false</c>. /// </value> internal static bool UseViewstateMoverModule { get { try { return bool.Parse( GetKeyAsNode("/settings/viewstateMoverModule").Attributes.GetNamedItem("enable").Value); } catch { return false; } } } /// <summary> /// Tells us whether the Xml Content cache is disabled or not /// Default is enabled /// </summary> internal static bool IsXmlContentCacheDisabled { get { try { bool xmlCacheEnabled; string value = GetKey("/settings/content/XmlCacheEnabled"); if (bool.TryParse(value, out xmlCacheEnabled)) return !xmlCacheEnabled; // Return default return false; } catch { return false; } } } /// <summary> /// Check if there's changes to the umbraco.config xml file cache on disk on each request /// Makes it possible to updates environments by syncing the umbraco.config file across instances /// Relates to http://umbraco.codeplex.com/workitem/30722 /// </summary> internal static bool XmlContentCheckForDiskChanges { get { try { bool checkForDiskChanges; string value = GetKey("/settings/content/XmlContentCheckForDiskChanges"); if (bool.TryParse(value, out checkForDiskChanges)) return checkForDiskChanges; // Return default return false; } catch { return false; } } } /// <summary> /// If this is enabled, all Umbraco objects will generate data in the preview table (cmsPreviewXml). /// If disabled, only documents will generate data. /// This feature is useful if anyone would like to see how data looked at a given time /// </summary> internal static bool EnableGlobalPreviewStorage { get { try { bool globalPreviewEnabled = false; string value = GetKey("/settings/content/GlobalPreviewStorageEnabled"); if (bool.TryParse(value, out globalPreviewEnabled)) return !globalPreviewEnabled; // Return default return false; } catch { return false; } } } private static bool? _useLegacySchema; /// <summary> /// Whether to use the new 4.1 schema or the old legacy schema /// </summary> /// <value> /// <c>true</c> if yes, use the old node/data model; otherwise, <c>false</c>. /// </value> internal static bool UseLegacyXmlSchema { get { // default: true return _useLegacySchema ?? GetKeyValue("/settings/content/UseLegacyXmlSchema", false); } /*internal*/ set { // used for unit testing _useLegacySchema = value; } } [Obsolete("This setting is not used anymore, the only file extensions that are supported are .cs and .vb files")] internal static IEnumerable<string> AppCodeFileExtensionsList { get { return (from XmlNode x in AppCodeFileExtensions where !String.IsNullOrEmpty(x.InnerText) select x.InnerText).ToList(); } } [Obsolete("This setting is not used anymore, the only file extensions that are supported are .cs and .vb files")] internal static XmlNode AppCodeFileExtensions { get { XmlNode value = GetKeyAsNode("/settings/developer/appCodeFileExtensions"); if (value != null) { return value; } // default is .cs and .vb value = UmbracoSettingsXmlDoc.CreateElement("appCodeFileExtensions"); value.AppendChild(XmlHelper.AddTextNode(UmbracoSettingsXmlDoc, "ext", "cs")); value.AppendChild(XmlHelper.AddTextNode(UmbracoSettingsXmlDoc, "ext", "vb")); return value; } } /// <summary> /// Tells us whether the Xml to always update disk cache, when changes are made to content /// Default is enabled /// </summary> internal static bool ContinouslyUpdateXmlDiskCache { get { try { bool updateDiskCache; string value = GetKey("/settings/content/ContinouslyUpdateXmlDiskCache"); if (bool.TryParse(value, out updateDiskCache)) return updateDiskCache; // Return default return false; } catch { return true; } } } /// <summary> /// Tells us whether to use a splash page while umbraco is initializing content. /// If not, requests are queued while umbraco loads content. For very large sites (+10k nodes) it might be usefull to /// have a splash page /// Default is disabled /// </summary> internal static bool EnableSplashWhileLoading { get { try { bool updateDiskCache; string value = GetKey("/settings/content/EnableSplashWhileLoading"); if (bool.TryParse(value, out updateDiskCache)) return updateDiskCache; // Return default return false; } catch { return false; } } } private static bool? _resolveUrlsFromTextString; internal static bool ResolveUrlsFromTextString { get { if (_resolveUrlsFromTextString == null) { try { bool enableDictionaryFallBack; var value = GetKey("/settings/content/ResolveUrlsFromTextString"); if (value != null) if (bool.TryParse(value, out enableDictionaryFallBack)) _resolveUrlsFromTextString = enableDictionaryFallBack; } catch (Exception ex) { Trace.WriteLine("Could not load /settings/content/ResolveUrlsFromTextString from umbracosettings.config:\r\n {0}", ex.Message); // set url resolving to true (default (legacy) behavior) to ensure we don't keep writing to trace _resolveUrlsFromTextString = true; } } return _resolveUrlsFromTextString == true; } } private static RenderingEngine? _defaultRenderingEngine; /// <summary> /// Enables MVC, and at the same time disable webform masterpage templates. /// This ensure views are automaticly created instead of masterpages. /// Views are display in the tree instead of masterpages and a MVC template editor /// is used instead of the masterpages editor /// </summary> /// <value><c>true</c> if umbraco defaults to using MVC views for templating, otherwise <c>false</c>.</value> internal static RenderingEngine DefaultRenderingEngine { get { if (_defaultRenderingEngine == null) { try { var engine = RenderingEngine.WebForms; var value = GetKey("/settings/templates/defaultRenderingEngine"); if (value != null) { Enum<RenderingEngine>.TryParse(value, true, out engine); } _defaultRenderingEngine = engine; } catch (Exception ex) { LogHelper.Error<UmbracoSettings>("Could not load /settings/templates/defaultRenderingEngine from umbracosettings.config", ex); _defaultRenderingEngine = RenderingEngine.WebForms; } } return _defaultRenderingEngine.Value; } //internal set //{ // _defaultRenderingEngine = value; // var node = UmbracoSettingsXmlDoc.DocumentElement.SelectSingleNode("/settings/templates/defaultRenderingEngine"); // node.InnerText = value.ToString(); //} } private static MacroErrorBehaviour? _macroErrorBehaviour; /// <summary> /// This configuration setting defines how to handle macro errors: /// - Inline - Show error within macro as text (default and current Umbraco 'normal' behavior) /// - Silent - Suppress error and hide macro /// - Throw - Throw an exception and invoke the global error handler (if one is defined, if not you'll get a YSOD) /// </summary> /// <value>MacroErrorBehaviour enum defining how to handle macro errors.</value> internal static MacroErrorBehaviour MacroErrorBehaviour { get { if (_macroErrorBehaviour == null) { try { var behaviour = MacroErrorBehaviour.Inline; var value = GetKey("/settings/content/MacroErrors"); if (value != null) { Enum<MacroErrorBehaviour>.TryParse(value, true, out behaviour); } _macroErrorBehaviour = behaviour; } catch (Exception ex) { LogHelper.Error<UmbracoSettings>("Could not load /settings/content/MacroErrors from umbracosettings.config", ex); _macroErrorBehaviour = MacroErrorBehaviour.Inline; } } return _macroErrorBehaviour.Value; } } private static IconPickerBehaviour? _iconPickerBehaviour; /// <summary> /// This configuration setting defines how to show icons in the document type editor. /// - ShowDuplicates - Show duplicates in files and sprites. (default and current Umbraco 'normal' behaviour) /// - HideSpriteDuplicates - Show files on disk and hide duplicates from the sprite /// - HideFileDuplicates - Show files in the sprite and hide duplicates on disk /// </summary> /// <value>MacroErrorBehaviour enum defining how to show icons in the document type editor.</value> internal static IconPickerBehaviour IconPickerBehaviour { get { if (_iconPickerBehaviour == null) { try { var behaviour = IconPickerBehaviour.ShowDuplicates; var value = GetKey("/settings/content/DocumentTypeIconList"); if (value != null) { Enum<IconPickerBehaviour>.TryParse(value, true, out behaviour); } _iconPickerBehaviour = behaviour; } catch (Exception ex) { LogHelper.Error<UmbracoSettings>("Could not load /settings/content/DocumentTypeIconList from umbracosettings.config", ex); _iconPickerBehaviour = IconPickerBehaviour.ShowDuplicates; } } return _iconPickerBehaviour.Value; } } /// <summary> /// Configuration regarding webservices /// </summary> /// <remarks>Put in seperate class for more logik/seperation</remarks> internal class WebServices { /// <summary> /// Gets a value indicating whether this <see cref="WebServices"/> is enabled. /// </summary> /// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value> public static bool Enabled { get { try { return bool.Parse(GetKeyAsNode("/settings/webservices").Attributes.GetNamedItem("enabled").Value); } catch { return false; } } } #region "Webservice configuration" /// <summary> /// Gets the document service users who have access to use the document web service /// </summary> /// <value>The document service users.</value> public static string[] DocumentServiceUsers { get { try { return GetKey("/settings/webservices/documentServiceUsers").Split(','); } catch { return new string[0]; } } } /// <summary> /// Gets the file service users who have access to use the file web service /// </summary> /// <value>The file service users.</value> public static string[] FileServiceUsers { get { try { return GetKey("/settings/webservices/fileServiceUsers").Split(','); } catch { return new string[0]; } } } /// <summary> /// Gets the folders used by the file web service /// </summary> /// <value>The file service folders.</value> public static string[] FileServiceFolders { get { try { return GetKey("/settings/webservices/fileServiceFolders").Split(','); } catch { return new string[0]; } } } /// <summary> /// Gets the member service users who have access to use the member web service /// </summary> /// <value>The member service users.</value> public static string[] MemberServiceUsers { get { try { return GetKey("/settings/webservices/memberServiceUsers").Split(','); } catch { return new string[0]; } } } /// <summary> /// Gets the stylesheet service users who have access to use the stylesheet web service /// </summary> /// <value>The stylesheet service users.</value> public static string[] StylesheetServiceUsers { get { try { return GetKey("/settings/webservices/stylesheetServiceUsers").Split(','); } catch { return new string[0]; } } } /// <summary> /// Gets the template service users who have access to use the template web service /// </summary> /// <value>The template service users.</value> public static string[] TemplateServiceUsers { get { try { return GetKey("/settings/webservices/templateServiceUsers").Split(','); } catch { return new string[0]; } } } /// <summary> /// Gets the media service users who have access to use the media web service /// </summary> /// <value>The media service users.</value> public static string[] MediaServiceUsers { get { try { return GetKey("/settings/webservices/mediaServiceUsers").Split(','); } catch { return new string[0]; } } } /// <summary> /// Gets the maintenance service users who have access to use the maintance web service /// </summary> /// <value>The maintenance service users.</value> public static string[] MaintenanceServiceUsers { get { try { return GetKey("/settings/webservices/maintenanceServiceUsers").Split(','); } catch { return new string[0]; } } } #endregion } #region Extensible settings /// <summary> /// Resets settings that were set programmatically, to their initial values. /// </summary> /// <remarks>To be used in unit tests.</remarks> internal static void Reset() { ResetInternal(); using (new WriteLock(SectionsLock)) { foreach (var section in Sections.Values) section.ResetSection(); } } private static readonly ReaderWriterLockSlim SectionsLock = new ReaderWriterLockSlim(); private static readonly Dictionary<Type, UmbracoConfigurationSection> Sections = new Dictionary<Type, UmbracoConfigurationSection>(); /// <summary> /// Gets the specified UmbracoConfigurationSection. /// </summary> /// <typeparam name="T">The type of the UmbracoConfigurationSectiont.</typeparam> /// <returns>The UmbracoConfigurationSection of the specified type.</returns> public static T For<T>() where T : UmbracoConfigurationSection, new() { var sectionType = typeof (T); using (new WriteLock(SectionsLock)) { if (Sections.ContainsKey(sectionType)) return Sections[sectionType] as T; var attr = sectionType.GetCustomAttribute<ConfigurationKeyAttribute>(false); if (attr == null) throw new InvalidOperationException(string.Format("Type \"{0}\" is missing attribute ConfigurationKeyAttribute.", sectionType.FullName)); var sectionKey = attr.ConfigurationKey; if (string.IsNullOrWhiteSpace(sectionKey)) throw new InvalidOperationException(string.Format("Type \"{0}\" ConfigurationKeyAttribute value is null or empty.", sectionType.FullName)); var section = GetSection(sectionType, sectionKey); Sections[sectionType] = section; return section as T; } } private static UmbracoConfigurationSection GetSection(Type sectionType, string key) { if (!sectionType.Inherits<UmbracoConfigurationSection>()) throw new ArgumentException(string.Format( "Type \"{0}\" does not inherit from UmbracoConfigurationSection.", sectionType.FullName), "sectionType"); var section = ConfigurationManager.GetSection(key); if (section != null && section.GetType() != sectionType) throw new InvalidCastException(string.Format("Section at key \"{0}\" is of type \"{1}\" and not \"{2}\".", key, section.GetType().FullName, sectionType.FullName)); if (section != null) return section as UmbracoConfigurationSection; section = Activator.CreateInstance(sectionType) as UmbracoConfigurationSection; if (section == null) throw new NullReferenceException(string.Format( "Activator failed to create an instance of type \"{0}\" for key\"{1}\" and returned null.", sectionType.FullName, key)); return section as UmbracoConfigurationSection; } #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. // // This is where we group together all the internal calls. // using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Internal.Runtime; namespace System.Runtime { internal enum DispatchCellType { InterfaceAndSlot = 0x0, MetadataToken = 0x1, VTableOffset = 0x2, } internal struct DispatchCellInfo { public DispatchCellType CellType; public EETypePtr InterfaceType; public ushort InterfaceSlot; public byte HasCache; public uint MetadataToken; public uint VTableOffset; } internal static class InternalCalls { // // internalcalls for System.GC. // // Force a garbage collection. [RuntimeExport("RhCollect")] internal static void RhCollect(int generation, InternalGCCollectionMode mode) { RhpCollect(generation, mode); } [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] private static extern void RhpCollect(int generation, InternalGCCollectionMode mode); [RuntimeExport("RhGetGcTotalMemory")] internal static long RhGetGcTotalMemory() { return RhpGetGcTotalMemory(); } [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] private static extern long RhpGetGcTotalMemory(); [RuntimeExport("RhStartNoGCRegion")] internal static Int32 RhStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC) { return RhpStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC); } [RuntimeExport("RhEndNoGCRegion")] internal static Int32 RhEndNoGCRegion() { return RhpEndNoGCRegion(); } // // internalcalls for System.Runtime.__Finalizer. // // Fetch next object which needs finalization or return null if we've reached the end of the list. [RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizableObject")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern Object RhpGetNextFinalizableObject(); // // internalcalls for System.Runtime.InteropServices.GCHandle. // // Allocate handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAlloc")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type); // Allocate dependent handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocDependent")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary); // Allocate variable handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocVariable")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern IntPtr RhpHandleAllocVariable(Object value, uint type); [RuntimeImport(Redhawk.BaseName, "RhHandleGet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern Object RhHandleGet(IntPtr handle); [RuntimeImport(Redhawk.BaseName, "RhHandleSet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern IntPtr RhHandleSet(IntPtr handle, Object value); // // internal calls for allocation // [RuntimeImport(Redhawk.BaseName, "RhpNewFast")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe object RhpNewFast(EEType* pEEType); // BEWARE: not for finalizable objects! [RuntimeImport(Redhawk.BaseName, "RhpNewFinalizable")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe object RhpNewFinalizable(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpNewArray")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe object RhpNewArray(EEType* pEEType, int length); #if FEATURE_64BIT_ALIGNMENT [RuntimeImport(Redhawk.BaseName, "RhpNewFastAlign8")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe object RhpNewFastAlign8(EEType * pEEType); // BEWARE: not for finalizable objects! [RuntimeImport(Redhawk.BaseName, "RhpNewFinalizableAlign8")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe object RhpNewFinalizableAlign8(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpNewArrayAlign8")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe object RhpNewArrayAlign8(EEType* pEEType, int length); [RuntimeImport(Redhawk.BaseName, "RhpNewFastMisalign")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe object RhpNewFastMisalign(EEType * pEEType); #endif // FEATURE_64BIT_ALIGNMENT [RuntimeImport(Redhawk.BaseName, "RhpBox")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe void RhpBox(object obj, ref byte data); [RuntimeImport(Redhawk.BaseName, "RhUnbox")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal extern static unsafe void RhUnbox(object obj, ref byte data, EEType* pUnboxToEEType); [RuntimeImport(Redhawk.BaseName, "RhpCopyObjectContents")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpCopyObjectContents(object objDest, object objSrc); [RuntimeImport(Redhawk.BaseName, "RhpAssignRef")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpAssignRef(ref Object address, object obj); #if FEATURE_GC_STRESS // // internal calls for GC stress // [RuntimeImport(Redhawk.BaseName, "RhpInitializeGcStress")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpInitializeGcStress(); #endif // FEATURE_GC_STRESS [RuntimeImport(Redhawk.BaseName, "RhpEHEnumInitFromStackFrameIterator")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe bool RhpEHEnumInitFromStackFrameIterator(ref StackFrameIterator pFrameIter, byte** pMethodStartAddress, void* pEHEnum); [RuntimeImport(Redhawk.BaseName, "RhpEHEnumNext")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe bool RhpEHEnumNext(void* pEHEnum, void* pEHClause); [RuntimeImport(Redhawk.BaseName, "RhpGetArrayBaseType")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe EEType* RhpGetArrayBaseType(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpHasDispatchMap")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe bool RhpHasDispatchMap(EEType* pEETypen); [RuntimeImport(Redhawk.BaseName, "RhpGetDispatchMap")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe DispatchResolve.DispatchMap* RhpGetDispatchMap(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpGetSealedVirtualSlot")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpGetSealedVirtualSlot(EEType* pEEType, ushort slot); [RuntimeImport(Redhawk.BaseName, "RhpGetDispatchCellInfo")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpGetDispatchCellInfo(IntPtr pCell, out DispatchCellInfo newCellInfo); [RuntimeImport(Redhawk.BaseName, "RhpSearchDispatchCellCache")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpSearchDispatchCellCache(IntPtr pCell, EEType* pInstanceType); [RuntimeImport(Redhawk.BaseName, "RhpUpdateDispatchCellCache")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpUpdateDispatchCellCache(IntPtr pCell, IntPtr pTargetCode, EEType* pInstanceType, ref DispatchCellInfo newCellInfo); [RuntimeImport(Redhawk.BaseName, "RhpGetClasslibFunction")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void* RhpGetClasslibFunction(IntPtr address, EH.ClassLibFunctionId id); // // StackFrameIterator // [RuntimeImport(Redhawk.BaseName, "RhpSfiInit")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern unsafe bool RhpSfiInit(ref StackFrameIterator pThis, void* pStackwalkCtx, bool instructionFault); [RuntimeImport(Redhawk.BaseName, "RhpSfiNext")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern bool RhpSfiNext(ref StackFrameIterator pThis, out uint uExCollideClauseIdx, out bool fUnwoundReversePInvoke); // // DebugEventSource // [RuntimeImport(Redhawk.BaseName, "RhpGetRequestedExceptionEvents")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern ExceptionEventKind RhpGetRequestedExceptionEvents(); [DllImport(Redhawk.BaseName)] internal static extern unsafe void RhpSendExceptionEventToDebugger(ExceptionEventKind eventKind, byte* ip, UIntPtr sp); // // Miscellaneous helpers. // // Get the rarely used (optional) flags of an EEType. If they're not present 0 will be returned. [RuntimeImport(Redhawk.BaseName, "RhpGetEETypeRareFlags")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe UInt32 RhpGetEETypeRareFlags(EEType* pEEType); // Retrieve the offset of the value embedded in a Nullable<T>. [RuntimeImport(Redhawk.BaseName, "RhpGetNullableEETypeValueOffset")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe byte RhpGetNullableEETypeValueOffset(EEType* pEEType); // Retrieve the target type T in a Nullable<T>. [RuntimeImport(Redhawk.BaseName, "RhpGetNullableEEType")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe EEType* RhpGetNullableEEType(EEType* pEEType); // For an ICastable type return a pointer to code that implements ICastable.IsInstanceOfInterface. [RuntimeImport(Redhawk.BaseName, "RhpGetICastableIsInstanceOfInterfaceMethod")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpGetICastableIsInstanceOfInterfaceMethod(EEType* pEEType); // For an ICastable type return a pointer to code that implements ICastable.GetImplType. [RuntimeImport(Redhawk.BaseName, "RhpGetICastableGetImplTypeMethod")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpGetICastableGetImplTypeMethod(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizerInitCallback")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpGetNextFinalizerInitCallback(); [RuntimeImport(Redhawk.BaseName, "RhpCallCatchFunclet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpCallCatchFunclet( object exceptionObj, byte* pHandlerIP, void* pvRegDisplay, ref EH.ExInfo exInfo); [RuntimeImport(Redhawk.BaseName, "RhpCallFinallyFunclet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpCallFinallyFunclet(byte* pHandlerIP, void* pvRegDisplay); [RuntimeImport(Redhawk.BaseName, "RhpCallFilterFunclet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe bool RhpCallFilterFunclet( object exceptionObj, byte* pFilterIP, void* pvRegDisplay); [RuntimeImport(Redhawk.BaseName, "RhpFallbackFailFast")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpFallbackFailFast(); [RuntimeImport(Redhawk.BaseName, "RhpSetThreadDoNotTriggerGC")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static void RhpSetThreadDoNotTriggerGC(); [System.Diagnostics.Conditional("DEBUG")] [RuntimeImport(Redhawk.BaseName, "RhpValidateExInfoStack")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static void RhpValidateExInfoStack(); [RuntimeImport(Redhawk.BaseName, "RhpCopyContextFromExInfo")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpCopyContextFromExInfo(void* pOSContext, int cbOSContext, EH.PAL_LIMITED_CONTEXT* pPalContext); [RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatchHelper")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static IntPtr RhpGetCastableObjectDispatchHelper(); [RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatchHelper_TailCalled")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static IntPtr RhpGetCastableObjectDispatchHelper_TailCalled(); [RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatch_CommonStub")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static IntPtr RhpGetCastableObjectDispatch_CommonStub(); [RuntimeImport(Redhawk.BaseName, "RhpGetTailCallTLSDispatchCell")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static IntPtr RhpGetTailCallTLSDispatchCell(); [RuntimeImport(Redhawk.BaseName, "RhpSetTLSDispatchCell")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpSetTLSDispatchCell(IntPtr pCell); [RuntimeImport(Redhawk.BaseName, "RhpGetNumThunkBlocksPerMapping")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static int RhpGetNumThunkBlocksPerMapping(); [RuntimeImport(Redhawk.BaseName, "RhpGetNumThunksPerBlock")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static int RhpGetNumThunksPerBlock(); [RuntimeImport(Redhawk.BaseName, "RhpGetThunkSize")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static int RhpGetThunkSize(); [RuntimeImport(Redhawk.BaseName, "RhpGetThunkDataBlockAddress")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static IntPtr RhpGetThunkDataBlockAddress(IntPtr thunkStubAddress); [RuntimeImport(Redhawk.BaseName, "RhpGetThunkStubsBlockAddress")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static IntPtr RhpGetThunkStubsBlockAddress(IntPtr thunkDataAddress); [RuntimeImport(Redhawk.BaseName, "RhpGetNextThunkStubsBlockAddress")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static IntPtr RhpGetNextThunkStubsBlockAddress(IntPtr currentThunkStubsBlockAddress); //------------------------------------------------------------------------------------------------------------ // PInvoke-based internal calls // // These either do not need to be called in cooperative mode or, in some cases, MUST be called in preemptive // mode. Note that they must use the Cdecl calling convention due to a limitation in our .obj file linking // support. //------------------------------------------------------------------------------------------------------------ // Block the current thread until at least one object needs to be finalized (returns true) or // memory is low (returns false and the finalizer thread should initiate a garbage collection). [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern UInt32 RhpWaitForFinalizerRequest(); // Indicate that the current round of finalizations is complete. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern void RhpSignalFinalizationComplete(); [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern void RhpAcquireCastCacheLock(); [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern void RhpReleaseCastCacheLock(); [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal extern static long PalGetTickCount64(); [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern void RhpAcquireThunkPoolLock(); [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern void RhpReleaseThunkPoolLock(); [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr RhAllocateThunksMapping(); // Enters a no GC region, possibly doing a blocking GC if there is not enough // memory available to satisfy the caller's request. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern Int32 RhpStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC); // Exits a no GC region, possibly doing a GC to clean up the garbage that // the caller allocated. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern Int32 RhpEndNoGCRegion(); } }
// <copyright file="UserLUTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using MathNet.Numerics.LinearAlgebra; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// LU factorization tests for a user matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class UserLUTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorLU = matrixI.LU(); // Check lower triangular part. var matrixL = factorLU.L; Assert.AreEqual(matrixI.RowCount, matrixL.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount); for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < matrixL.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixL[i, j]); } } // Check upper triangular part. var matrixU = factorLU.U; Assert.AreEqual(matrixI.RowCount, matrixU.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount); for (var i = 0; i < matrixU.RowCount; i++) { for (var j = 0; j < matrixU.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixU[i, j]); } } } /// <summary> /// LU factorization fails with a non-square matrix. /// </summary> [Test] public void LUFailsWithNonSquareMatrix() { var matrix = new UserDefinedMatrix(3, 2); Assert.That(() => matrix.LU(), Throws.ArgumentException); } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = UserDefinedMatrix.Identity(order); var lu = matrixI.LU(); Assert.AreEqual(Complex.One, lu.Determinant); } /// <summary> /// Can factorize a random square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanFactorizeRandomMatrix(int order) { var matrixX = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var factorLU = matrixX.LU(); var matrixL = factorLU.L; var matrixU = factorLU.U; // Make sure the factors have the right dimensions. Assert.AreEqual(order, matrixL.RowCount); Assert.AreEqual(order, matrixL.ColumnCount); Assert.AreEqual(order, matrixU.RowCount); Assert.AreEqual(order, matrixU.ColumnCount); // Make sure the L factor is lower triangular. for (var i = 0; i < matrixL.RowCount; i++) { Assert.AreEqual(Complex.One, matrixL[i, i]); for (var j = i + 1; j < matrixL.ColumnCount; j++) { Assert.AreEqual(Complex.Zero, matrixL[i, j]); } } // Make sure the U factor is upper triangular. for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < i; j++) { Assert.AreEqual(Complex.Zero, matrixU[i, j]); } } // Make sure the LU factor times it's transpose is the original matrix. var matrixXfromLU = matrixL * matrixU; var permutationInverse = factorLU.P.Inverse(); matrixXfromLU.PermuteRows(permutationInverse); for (var i = 0; i < matrixXfromLU.RowCount; i++) { for (var j = 0; j < matrixXfromLU.ColumnCount; j++) { AssertHelpers.AlmostEqualRelative(matrixX[i, j], matrixXfromLU[i, j], 9); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray()); var resultx = factorLU.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrix(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixX = factorLU.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray()); var vectorbCopy = vectorb.Clone(); var resultx = new UserDefinedVector(order); factorLU.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix row number.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixBCopy = matrixB.Clone(); var matrixX = new UserDefinedMatrix(order, order); factorLU.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } /// <summary> /// Can inverse a matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanInverse(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixAInverse = factorLU.Inverse(); // The inverse dimension is equal A Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount); Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount); var matrixIdentity = matrixA * matrixAInverse; // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Check if multiplication of A and AI produced identity matrix. for (var i = 0; i < matrixIdentity.RowCount; i++) { AssertHelpers.AlmostEqualRelative(matrixIdentity[i, i], Complex.One, 9); } } } }
// // ImageHandler.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using Xwt.Backends; using System.Drawing; using System.Collections.Generic; using System.Runtime.InteropServices; using Xwt.Drawing; using System.IO; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using MonoMac.CoreGraphics; #else using Foundation; using AppKit; using CoreGraphics; using ObjCRuntime; #endif namespace Xwt.Mac { public class ImageHandler: ImageBackendHandler { static readonly IntPtr sel_alloc = new Selector ("alloc").Handle; static readonly IntPtr sel_release = new Selector ("release").Handle; static readonly IntPtr sel_initWithIconRef = new Selector ("initWithIconRef:").Handle; static readonly IntPtr cls_NSImage = new Class (typeof (NSImage)).Handle; static Dictionary<string, NSImage> stockIcons = new Dictionary<string, NSImage> (); public override object LoadFromStream (Stream stream) { using (NSData data = NSData.FromStream (stream)) { return new NSImage (data); } } public override object LoadFromFile (string file) { return new NSImage (file); } public override object CreateMultiResolutionImage (IEnumerable<object> images) { NSImage res = new NSImage (); foreach (NSImage img in images) res.AddRepresentations (img.Representations ()); return res; } public override object CreateMultiSizeIcon (IEnumerable<object> images) { if (images.Count () == 1) return images.First (); NSImage res = new NSImage (); foreach (NSImage img in images) res.AddRepresentations (img.Representations ()); return res; } public override object CreateCustomDrawn (ImageDrawCallback drawCallback) { return new CustomImage (ApplicationContext, drawCallback); } public override Xwt.Drawing.Image GetStockIcon (string id) { NSImage img; if (!stockIcons.TryGetValue (id, out img)) { img = LoadStockIcon (id); stockIcons [id] = img; } return ApplicationContext.Toolkit.WrapImage (img); } public override void SaveToStream (object backend, System.IO.Stream stream, ImageFileType fileType) { NSImage img = backend as NSImage; if (img == null) throw new NotSupportedException (); var imageData = img.AsTiff (); var imageRep = (NSBitmapImageRep) NSBitmapImageRep.ImageRepFromData (imageData); var props = new NSDictionary (); imageData = imageRep.RepresentationUsingTypeProperties (fileType.ToMacFileType (), props); using (var s = imageData.AsStream ()) { s.CopyTo (stream); } } public override bool IsBitmap (object handle) { NSImage img = handle as NSImage; return img != null && img.Representations ().OfType<NSBitmapImageRep> ().Any (); } public override object ConvertToBitmap (object handle, double width, double height, double scaleFactor, ImageFormat format) { int pixelWidth = (int)(width * scaleFactor); int pixelHeight = (int)(height * scaleFactor); if (handle is CustomImage) { var flags = CGBitmapFlags.ByteOrderDefault; int bytesPerRow; switch (format) { case ImageFormat.ARGB32: bytesPerRow = pixelWidth * 4; flags |= CGBitmapFlags.PremultipliedFirst; break; case ImageFormat.RGB24: bytesPerRow = pixelWidth * 3; flags |= CGBitmapFlags.None; break; default: throw new NotImplementedException ("ImageFormat: " + format.ToString ()); } var bmp = new CGBitmapContext (IntPtr.Zero, pixelWidth, pixelHeight, 8, bytesPerRow, Util.DeviceRGBColorSpace, flags); bmp.TranslateCTM (0, pixelHeight); bmp.ScaleCTM ((float)scaleFactor, (float)-scaleFactor); var ctx = new CGContextBackend { Context = bmp, Size = new SizeF ((float)width, (float)height), InverseViewTransform = bmp.GetCTM ().Invert (), ScaleFactor = scaleFactor }; var ci = (CustomImage)handle; ci.DrawInContext (ctx); var img = new NSImage (((CGBitmapContext)bmp).ToImage (), new SizeF (pixelWidth, pixelHeight)); var imageData = img.AsTiff (); var imageRep = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData (imageData); var im = new NSImage (); im.AddRepresentation (imageRep); im.Size = new SizeF ((float)width, (float)height); bmp.Dispose (); return im; } else { NSImage img = (NSImage)handle; NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault (); if (bitmap == null) { var imageData = img.AsTiff (); var imageRep = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData (imageData); var im = new NSImage (); im.AddRepresentation (imageRep); im.Size = new SizeF ((float)width, (float)height); return im; } return handle; } } public override Xwt.Drawing.Color GetBitmapPixel (object handle, int x, int y) { NSImage img = (NSImage)handle; NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault (); if (bitmap != null) return bitmap.ColorAt (x, y).ToXwtColor (); else throw new InvalidOperationException ("Not a bitmnap image"); } public override void SetBitmapPixel (object handle, int x, int y, Xwt.Drawing.Color color) { NSImage img = (NSImage)handle; NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault (); if (bitmap != null) bitmap.SetColorAt (color.ToNSColor (), x, y); else throw new InvalidOperationException ("Not a bitmnap image"); } public override bool HasMultipleSizes (object handle) { NSImage img = (NSImage)handle; return img.Size.Width == 0 && img.Size.Height == 0; } public override Size GetSize (object handle) { NSImage img = (NSImage)handle; NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault (); if (bitmap != null) return new Size (bitmap.PixelsWide, bitmap.PixelsHigh); else return new Size ((int)img.Size.Width, (int)img.Size.Height); } public override object CopyBitmap (object handle) { return ((NSImage)handle).Copy (); } public override void CopyBitmapArea (object backend, int srcX, int srcY, int width, int height, object dest, int destX, int destY) { throw new NotImplementedException (); } public override object CropBitmap (object backend, int srcX, int srcY, int width, int height) { NSImage img = (NSImage)backend; NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault (); if (bitmap != null) { var empty = CGRect.Empty; var cgi = bitmap.AsCGImage (ref empty, null, null).WithImageInRect (new CGRect (srcX, srcY, width, height)); NSImage res = new NSImage (cgi, new CGSize (width, height)); cgi.Dispose (); return res; } else throw new InvalidOperationException ("Not a bitmap image"); } static NSImage FromResource (string res) { var stream = typeof(ImageHandler).Assembly.GetManifestResourceStream (res); using (stream) using (NSData data = NSData.FromStream (stream)) { return new NSImage (data); } } static NSImage NSImageFromResource (string id) { return (NSImage) Toolkit.GetBackend (Xwt.Drawing.Image.FromResource (typeof(ImageHandler), id)); } static NSImage LoadStockIcon (string id) { switch (id) { case StockIconId.ZoomIn: return NSImageFromResource ("zoom-in.png"); case StockIconId.ZoomOut: return NSImageFromResource ("zoom-out.png"); } NSImage image = null; IntPtr iconRef; var type = Util.ToIconType (id); if (type != 0 && GetIconRef (-32768/*kOnSystemDisk*/, 1835098995/*kSystemIconsCreator*/, type, out iconRef) == 0) { try { var alloced = Messaging.IntPtr_objc_msgSend (cls_NSImage, sel_alloc); image = (NSImage) Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr (alloced, sel_initWithIconRef, iconRef)); // NSImage (IntPtr) ctor retains, but since it is the sole owner, we don't want that Messaging.void_objc_msgSend (image.Handle, sel_release); } finally { ReleaseIconRef (iconRef); } } return image; } [DllImport ("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/LaunchServices")] static extern int GetIconRef (short vRefNum, int creator, int iconType, out IntPtr iconRef); [DllImport ("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/LaunchServices")] static extern int ReleaseIconRef (IntPtr iconRef); } public class CustomImage: NSImage { ImageDrawCallback drawCallback; ApplicationContext actx; NSCustomImageRep imgRep; public CustomImage (ApplicationContext actx, ImageDrawCallback drawCallback) { this.actx = actx; this.drawCallback = drawCallback; imgRep = new NSCustomImageRep (new Selector ("drawIt:"), this); AddRepresentation (imgRep); } [Export ("drawIt:")] public void DrawIt (NSObject ob) { CGContext ctx = NSGraphicsContext.CurrentContext.GraphicsPort; if (!NSGraphicsContext.CurrentContext.IsFlipped) { // Custom drawing is done using flipped order, so if the target surface is not flipped, we need to flip it ctx.TranslateCTM (0, Size.Height); ctx.ScaleCTM (1, -1); } DrawInContext (ctx); } internal void DrawInContext (CGContext ctx) { var backend = new CGContextBackend { Context = ctx, InverseViewTransform = ctx.GetCTM ().Invert () }; DrawInContext (backend); } internal void DrawInContext (CGContextBackend ctx) { var s = ctx.Size != SizeF.Empty ? ctx.Size : Size; actx.InvokeUserCode (delegate { drawCallback (ctx, new Rectangle (0, 0, s.Width, s.Height)); }); } public CustomImage Clone () { return new CustomImage (actx, drawCallback); } } }
using System.Diagnostics; using System.IO; using System.IO.Compression; using ArrayUtil = Lucene.Net.Util.ArrayUtil; using BytesRef = Lucene.Net.Util.BytesRef; namespace Lucene.Net.Codecs.Compressing { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using DataInput = Lucene.Net.Store.DataInput; using DataOutput = Lucene.Net.Store.DataOutput; /// <summary> /// A compression mode. Tells how much effort should be spent on compression and /// decompression of stored fields. /// <para/> /// @lucene.experimental /// </summary> public abstract class CompressionMode { /// <summary> /// A compression mode that trades compression ratio for speed. Although the /// compression ratio might remain high, compression and decompression are /// very fast. Use this mode with indices that have a high update rate but /// should be able to load documents from disk quickly. /// </summary> public static readonly CompressionMode FAST = new CompressionModeAnonymousInnerClassHelper(); private class CompressionModeAnonymousInnerClassHelper : CompressionMode { public CompressionModeAnonymousInnerClassHelper() { } public override Compressor NewCompressor() { return new LZ4FastCompressor(); } public override Decompressor NewDecompressor() { return LZ4_DECOMPRESSOR; } public override string ToString() { return "FAST"; } } /// <summary> /// A compression mode that trades speed for compression ratio. Although /// compression and decompression might be slow, this compression mode should /// provide a good compression ratio. this mode might be interesting if/when /// your index size is much bigger than your OS cache. /// </summary> public static readonly CompressionMode HIGH_COMPRESSION = new CompressionModeAnonymousInnerClassHelper2(); private class CompressionModeAnonymousInnerClassHelper2 : CompressionMode { public CompressionModeAnonymousInnerClassHelper2() { } public override Compressor NewCompressor() { return new DeflateCompressor(CompressionLevel.Optimal); } public override Decompressor NewDecompressor() { return new DeflateDecompressor(); } public override string ToString() { return "HIGH_COMPRESSION"; } } /// <summary> /// This compression mode is similar to <see cref="FAST"/> but it spends more time /// compressing in order to improve the compression ratio. This compression /// mode is best used with indices that have a low update rate but should be /// able to load documents from disk quickly. /// </summary> public static readonly CompressionMode FAST_DECOMPRESSION = new CompressionModeAnonymousInnerClassHelper3(); private class CompressionModeAnonymousInnerClassHelper3 : CompressionMode { public CompressionModeAnonymousInnerClassHelper3() { } public override Compressor NewCompressor() { return new LZ4HighCompressor(); } public override Decompressor NewDecompressor() { return LZ4_DECOMPRESSOR; } public override string ToString() { return "FAST_DECOMPRESSION"; } } /// <summary> /// Sole constructor. </summary> protected internal CompressionMode() { } /// <summary> /// Create a new <see cref="Compressor"/> instance. /// </summary> public abstract Compressor NewCompressor(); /// <summary> /// Create a new <see cref="Decompressor"/> instance. /// </summary> public abstract Decompressor NewDecompressor(); private static readonly Decompressor LZ4_DECOMPRESSOR = new DecompressorAnonymousInnerClassHelper(); private class DecompressorAnonymousInnerClassHelper : Decompressor { public DecompressorAnonymousInnerClassHelper() { } public override void Decompress(DataInput @in, int originalLength, int offset, int length, BytesRef bytes) { Debug.Assert(offset + length <= originalLength); // add 7 padding bytes, this is not necessary but can help decompression run faster if (bytes.Bytes.Length < originalLength + 7) { bytes.Bytes = new byte[ArrayUtil.Oversize(originalLength + 7, 1)]; } int decompressedLength = LZ4.Decompress(@in, offset + length, bytes.Bytes, 0); if (decompressedLength > originalLength) { throw new CorruptIndexException("Corrupted: lengths mismatch: " + decompressedLength + " > " + originalLength + " (resource=" + @in + ")"); } bytes.Offset = offset; bytes.Length = length; } public override object Clone() { return this; } } private sealed class LZ4FastCompressor : Compressor { private readonly LZ4.HashTable ht; internal LZ4FastCompressor() { ht = new LZ4.HashTable(); } public override void Compress(byte[] bytes, int off, int len, DataOutput @out) { LZ4.Compress(bytes, off, len, @out, ht); } } private sealed class LZ4HighCompressor : Compressor { internal readonly LZ4.HCHashTable ht; internal LZ4HighCompressor() { ht = new LZ4.HCHashTable(); } public override void Compress(byte[] bytes, int off, int len, DataOutput @out) { LZ4.CompressHC(bytes, off, len, @out, ht); } } private sealed class DeflateDecompressor : Decompressor { internal DeflateDecompressor() { } public override void Decompress(DataInput input, int originalLength, int offset, int length, BytesRef bytes) { Debug.Assert(offset + length <= originalLength); if (length == 0) { bytes.Length = 0; return; } byte[] compressedBytes = new byte[input.ReadVInt32()]; input.ReadBytes(compressedBytes, 0, compressedBytes.Length); byte[] decompressedBytes = null; using (MemoryStream decompressedStream = new MemoryStream()) { using (MemoryStream compressedStream = new MemoryStream(compressedBytes)) { using (DeflateStream dStream = new DeflateStream(compressedStream, System.IO.Compression.CompressionMode.Decompress)) { dStream.CopyTo(decompressedStream); } } decompressedBytes = decompressedStream.ToArray(); } if (decompressedBytes.Length != originalLength) { throw new CorruptIndexException("Length mismatch: " + decompressedBytes.Length + " != " + originalLength + " (resource=" + input + ")"); } bytes.Bytes = decompressedBytes; bytes.Offset = offset; bytes.Length = length; } public override object Clone() { return new DeflateDecompressor(); } } private class DeflateCompressor : Compressor { private CompressionLevel compressionLevel; internal DeflateCompressor(CompressionLevel level) { compressionLevel = level; } public override void Compress(byte[] bytes, int off, int len, DataOutput output) { byte[] resultArray = null; using (MemoryStream compressionMemoryStream = new MemoryStream()) { using (DeflateStream deflateStream = new DeflateStream(compressionMemoryStream, compressionLevel)) { deflateStream.Write(bytes, off, len); } resultArray = compressionMemoryStream.ToArray(); } if (resultArray.Length == 0) { Debug.Assert(len == 0, len.ToString()); output.WriteVInt32(0); return; } else { output.WriteVInt32(resultArray.Length); output.WriteBytes(resultArray, resultArray.Length); } } } } }
// Copyright (c) 2013-2016 Jae-jun Kang // See the file LICENSE for details. using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace x2 { /// <summary> /// Abstract base class for TCP/IP server links. /// </summary> public abstract class AbstractTcpServer : ServerLink { protected Socket socket; private volatile bool incomingKeepaliveEnabled; private volatile bool outgoingKeepaliveEnabled; /// <summary> /// Gets whether this link is currently listening or not. /// </summary> public bool Listening { get { return (socket != null && socket.IsBound); } } // Socket option properties /// <summary> /// Gets or sets a boolean value indicating whether the client sockets /// are not to use the Nagle algorithm. /// </summary> public bool NoDelay { get; set; } // Keepalive properties /// <summary> /// Gets or sets a boolean value indicating whether this link checks /// for incomming keepalive events /// </summary> public bool IncomingKeepaliveEnabled { get { return incomingKeepaliveEnabled; } set { incomingKeepaliveEnabled = value; } } /// <summary> /// Gets or sets a boolean value indicating whether this link emits /// outgoing keepalive events. /// </summary> public bool OutgoingKeepaliveEnabled { get { return outgoingKeepaliveEnabled; } set { outgoingKeepaliveEnabled = value; } } /// <summary> /// Gets or sets the maximum number of successive keepalive failures /// allowed before the link closes the session. /// </summary> public int MaxKeepaliveFailureCount { get; set; } /// <summary> /// Gets or sets a boolean value indicating whether this link ignores /// keepalive failures. /// </summary> public bool IgnoreKeepaliveFailure { get; set; } static AbstractTcpServer() { EventFactory.Register(HeartbeatEvent.TypeId, HeartbeatEvent.New); } /// <summary> /// Initializes a new instance of the AbstractTcpServer class. /// </summary> protected AbstractTcpServer(string name) : base(name) { // Default socket options NoDelay = true; } public void Listen(int port) { Listen(IPAddress.Any, port); } public void Listen(string ip, int port) { Listen(IPAddress.Parse(ip), port); } public void Listen(IPAddress ip, int port) { if (socket != null) { throw new InvalidOperationException(); } EndPoint endpoint = new IPEndPoint(ip, port); try { socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Bind(endpoint); socket.Listen(Int32.MaxValue); AcceptInternal(); Log.Info("{0} listening on {1}", Name, endpoint); } catch (Exception e) { Log.Error("{0} error listening on {1} : {2}", Name, endpoint, e.Message); throw; } } /// <summary> /// Provides an actual implementation of Accept. /// </summary> protected abstract void AcceptInternal(); protected override void Dispose(bool disposing) { if (disposed) { return; } if (socket != null) { socket.Close(); } base.Dispose(disposing); } /// <summary> /// <see cref="ServerLink.OnAcceptInternal"/> /// </summary> protected override bool OnAcceptInternal(LinkSession session) { var tcpSession = (AbstractTcpSession)session; var clientSocket = tcpSession.Socket; try { // Adjust client socket options. clientSocket.NoDelay = NoDelay; tcpSession.BeginReceive(true); Log.Info("{0} {1} accepted from {2}", Name, tcpSession.InternalHandle, clientSocket.RemoteEndPoint); return base.OnAcceptInternal(session); } catch (ObjectDisposedException ode) { Log.Warn("{0} {1} accept error: {2}", Name, tcpSession.InternalHandle, ode); return false; } } protected override void Setup() { Bind(Hub.HeartbeatEvent, OnHeartbeatEvent); } private void OnHeartbeatEvent(HeartbeatEvent e) { if (!IncomingKeepaliveEnabled && !OutgoingKeepaliveEnabled) { return; } List<LinkSession> snapshot; using (new ReadLock(rwlock)) { snapshot = new List<LinkSession>(sessions.Count); var list = sessions.Values; for (int i = 0, count = list.Count; i < count; ++i) { snapshot.Add(list[i]); } } for (int i = 0, count = snapshot.Count; i < count; ++i) { var tcpSession = (AbstractTcpSession)snapshot[i]; if (tcpSession.SocketConnected) { int failureCount = tcpSession.Keepalive( incomingKeepaliveEnabled, outgoingKeepaliveEnabled); if (MaxKeepaliveFailureCount > 0 && failureCount > MaxKeepaliveFailureCount) { Log.Warn("{0} {1} closed due to the keepalive failure", Name, tcpSession.Handle); tcpSession.OnDisconnect(); } } } } } }
/* This is free software distributed under the terms of the MIT license, reproduced below. It may be used for any purpose, including commercial purposes, at absolutely no cost. No paperwork, no royalties, no GNU-like "copyleft" restrictions. Just download and enjoy. Copyright (c) 2014 Chimera Software, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using UnityEngine; using System.Xml; using System.Collections; using TMPro; using System.Collections.Generic; using System; using UnityEngine.EventSystems; using UnityEngine.UI; public class DetectTextClickTMPro : MonoBehaviour, IPointerClickHandler, IPointerUpHandler, IPointerDownHandler, ICanvasRaycastFilter { public PUTMPro entity; private void IsCloserToPoint(Vector3 mousePoint, Vector3 testPoint, TMP_LinkInfo testLink, ref float minDistance, ref TMP_LinkInfo minLinkInfo) { float testDistance = Vector3.SqrMagnitude (mousePoint - testPoint); if (testDistance < minDistance) { minDistance = testDistance; minLinkInfo = testLink; } } public bool TestForHit(Vector2 screenPoint, Camera eventCamera, Action<string, int> block) { TMP_TextInfo textInfo = null; TMP_Text text = null; float fontSize = 0; if (entity.text != null) { text = entity.text; textInfo = entity.text.textInfo; fontSize = entity.text.fontSize; } if (entity.textGUI != null) { text = entity.textGUI; textInfo = entity.textGUI.textInfo; fontSize = entity.textGUI.fontSize; } if (textInfo != null) { // find the closest link to our touch point float minDistance = 999999; TMP_LinkInfo minLinkInfo = new TMP_LinkInfo (); Transform rectTransform = text.transform; Vector3 position = screenPoint; // Convert position into Worldspace coordinates TMP_TextUtilities.ScreenPointToWorldPointInRectangle (rectTransform, position, eventCamera, out position); // Find the distance by font size after its transformed Vector3 minFontDistance = rectTransform.TransformPoint(Vector3.zero) - rectTransform.TransformPoint(new Vector3(fontSize * 2.0f, 0.0f, 0.0f)); minDistance = minFontDistance.sqrMagnitude; for (int i = 0; i < text.textInfo.linkCount; i++) { TMP_LinkInfo linkInfo = text.textInfo.linkInfo [i]; bool isBeginRegion = false; Vector3 bl = Vector3.zero; Vector3 tl = Vector3.zero; Vector3 br = Vector3.zero; Vector3 tr = Vector3.zero; // center of every character in every word for (int j = 0; j < linkInfo.linkTextLength; j++) { int characterIndex = linkInfo.linkTextfirstCharacterIndex + j; TMP_CharacterInfo currentCharInfo = text.textInfo.characterInfo[characterIndex]; Vector3 cp = (currentCharInfo.topRight + currentCharInfo.bottomLeft) * 0.5f; cp = rectTransform.TransformPoint (cp); IsCloserToPoint (position, cp, linkInfo, ref minDistance, ref minLinkInfo); } /* // Iterate through each character of the word for (int j = 0; j < linkInfo.linkTextLength; j++) { int characterIndex = linkInfo.linkTextfirstCharacterIndex + j; TMP_CharacterInfo currentCharInfo = text.textInfo.characterInfo [characterIndex]; int currentLine = currentCharInfo.lineNumber; // Check if Link characters are on the current page if (text.overflowMode == TextOverflowModes.Page && currentCharInfo.pageNumber + 1 != text.pageToDisplay) continue; if (isBeginRegion == false) { isBeginRegion = true; bl = rectTransform.TransformPoint (new Vector3 (currentCharInfo.bottomLeft.x, currentCharInfo.descender, 0)); tl = rectTransform.TransformPoint (new Vector3 (currentCharInfo.bottomLeft.x, currentCharInfo.ascender, 0)); // If Word is one character if (linkInfo.linkTextLength == 1) { isBeginRegion = false; br = rectTransform.TransformPoint (new Vector3 (currentCharInfo.topRight.x, currentCharInfo.descender, 0)); tr = rectTransform.TransformPoint (new Vector3 (currentCharInfo.topRight.x, currentCharInfo.ascender, 0)); // Check for Intersection IsCloserToPoint (position, bl, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, tl, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, tr, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, br, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, (bl + br + tl + tr) * 0.25f, linkInfo, ref minDistance, ref minLinkInfo); } } // Last Character of Word if (isBeginRegion && j == linkInfo.linkTextLength - 1) { isBeginRegion = false; br = rectTransform.TransformPoint (new Vector3 (currentCharInfo.topRight.x, currentCharInfo.descender, 0)); tr = rectTransform.TransformPoint (new Vector3 (currentCharInfo.topRight.x, currentCharInfo.ascender, 0)); IsCloserToPoint (position, bl, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, tl, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, tr, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, br, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, (bl + br + tl + tr) * 0.25f, linkInfo, ref minDistance, ref minLinkInfo); } // If Word is split on more than one line. else if (isBeginRegion && currentLine != text.textInfo.characterInfo [characterIndex + 1].lineNumber) { isBeginRegion = false; br = rectTransform.TransformPoint (new Vector3 (currentCharInfo.topRight.x, currentCharInfo.descender, 0)); tr = rectTransform.TransformPoint (new Vector3 (currentCharInfo.topRight.x, currentCharInfo.ascender, 0)); IsCloserToPoint (position, bl, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, tl, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, tr, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, br, linkInfo, ref minDistance, ref minLinkInfo); IsCloserToPoint (position, (bl + br + tl + tr) * 0.25f, linkInfo, ref minDistance, ref minLinkInfo); } } */ } if (minLinkInfo.GetLinkText() != null) { int linkIdx = Array.IndexOf(text.textInfo.linkInfo, minLinkInfo); if (linkIdx >= 0) { if (block != null) { block(minLinkInfo.GetLinkText(), linkIdx); } return true; } } } return false; } public bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera) { if (gameObject.activeSelf == false) return false; return TestForHit(screenPoint, eventCamera, null); } public void OnPointerClick(PointerEventData eventData) { if (gameObject.activeSelf == false) return; TestForHit (Input.mousePosition, eventData.pressEventCamera, (linkText, clickedLinkID) => { if(entity != null){ entity.LinkClicked (linkText, clickedLinkID); } }); } public void OnPointerDown(PointerEventData data) { } public void OnPointerUp(PointerEventData data) { } } public class PUTMPro : PUGameObject { static Dictionary<string,TMP_FontAsset> fontAssets = new Dictionary<string, TMP_FontAsset>(); public static string DefaultFont = "Fonts/ArialRegular"; public TextMeshProUGUI textGUI; public TextMeshPro text; public string onLinkClick; public Action<string, int> OnLinkClickAction; public Func<string, int, string> TranslateLinkAction; public string value = null; public bool sizeToFit = false; public bool enableWordWrapping = true; public int maxVisibleLines = 0; public int maxSize = 200; public int minSize = 0; public string font; public string fontStyle; public int fontSize = 32; public int lineSpacing = 0; public Color fontColor = Color.white; public TextAlignmentOptions alignment = TextAlignmentOptions.TopLeft; public TextOverflowModes overflowMode = TextOverflowModes.Truncate; public PUTMPro() { } public void LinkClicked(string linkText, int linkID) { if (TranslateLinkAction != null) { linkText = TranslateLinkAction (linkText, linkID); } if (OnLinkClickAction != null) { OnLinkClickAction (linkText, linkID); } if (OnLinkClickAction == null && PUText.GlobalOnLinkClickAction != null) { PUText.GlobalOnLinkClickAction (linkText, linkID, this); } if (onLinkClick != null) { NotificationCenter.postNotification (Scope (), onLinkClick, NotificationCenter.Args ("link", linkText, "linkID", linkID)); } } static public TMP_FontAsset GetFont(string path) { if (fontAssets.ContainsKey (path)) { return fontAssets [path]; } TMP_FontAsset font = PlanetUnityOverride.LoadResource(typeof(TMP_FontAsset), path) as TMP_FontAsset; if (font != null) { fontAssets [path] = font; } return font; } public override void gaxb_final(TB.TBXMLElement element, object _parent, Hashtable args) { string attrib; if (font == null) { font = DefaultFont; } if(element != null){ attrib = element.GetAttribute ("font"); if (attrib != null) { font = attrib; } attrib = element.GetAttribute ("onLinkClick"); if (attrib != null) { onLinkClick = PlanetUnityOverride.processString (_parent, attrib); } attrib = element.GetAttribute ("fontSize"); if (attrib != null) { fontSize = (int)(float.Parse (PlanetUnityOverride.processString (_parent, attrib))); } attrib = element.GetAttribute ("fontStyle"); if (attrib != null) { fontStyle = attrib; } attrib = element.GetAttribute ("sizeToFit"); if (attrib != null) { sizeToFit = bool.Parse (PlanetUnityOverride.processString(_parent, attrib)); } attrib = element.GetAttribute ("maxSize"); if (attrib != null) { maxSize = (int)(float.Parse (PlanetUnityOverride.processString(_parent, attrib))); } attrib = element.GetAttribute ("enableWordWrapping"); if (attrib != null) { enableWordWrapping = bool.Parse (attrib); } attrib = element.GetAttribute ("maxVisibleLines"); if (attrib != null) { maxVisibleLines = int.Parse (attrib); } attrib = element.GetAttribute ("minSize"); if (attrib != null) { minSize = (int)(float.Parse (PlanetUnityOverride.processString(_parent, attrib))); } attrib = element.GetAttribute ("alignment"); if (attrib != null) { alignment = (TextAlignmentOptions)Enum.Parse (typeof(TextAlignmentOptions), attrib); } attrib = element.GetAttribute ("fontColor"); if (attrib != null) { fontColor = fontColor.PUParse (attrib); } attrib = element.GetAttribute ("overflowMode"); if (attrib != null) { overflowMode = (TextOverflowModes)Enum.Parse(typeof(TextOverflowModes), attrib); } attrib = element.GetAttribute ("lineSpacing"); if (attrib != null) { lineSpacing = (int)(float.Parse (PlanetUnityOverride.processString(_parent, attrib))); } value = element.GetAttribute ("value"); value = PlanetUnityOverride.processString (_parent, value); } base.gaxb_final(element, _parent, args); } public override void gaxb_complete() { base.gaxb_complete (); ScheduleForOnEnable (); GenerateTextComponent (); if ((onLinkClick != null || OnLinkClickAction != null || PUText.GlobalOnLinkClickAction != null)) { gameObject.AddComponent<DetectTextClickTMPro> (); DetectTextClickTMPro script = gameObject.GetComponent<DetectTextClickTMPro> (); script.entity = this; if (gameObject.GetComponent<Graphic> () == null) { gameObject.AddComponent<InvisibleHitGraphic> (); } // TODO: This hack was necessary for getting clicking to work on TMPro... LeanTween.delayedCall (0, () => { if(textGUI != null){ //textGUI.RegisterGraphicForCanvas(); } }); } } // This is required for application-level subclasses public override void gaxb_init () { base.gaxb_init (); gaxb_addToParent(); } public override void OnEnable () { FixErrorWithAttributes (); } public override void OnDisable () { FixErrorWithAttributes (); } private void FixErrorWithAttributes() { // Note: Some attributes do not seem to work properly if the text view is immediately disabled. // For those attributes, we reset them on enable to ensure they are updated properly PlanetUnityGameObject.ScheduleTask (() => { textGUI.alignment = alignment; }); } public virtual void GenerateTextComponent() { textGUI = gameObject.GetComponent<TextMeshProUGUI> (); if (textGUI == null) { textGUI = gameObject.AddComponent<TextMeshProUGUI> (); } textGUI.font = GetFont(font); textGUI.enableWordWrapping = enableWordWrapping; textGUI.richText = true; if(fontStyle != null){ textGUI.fontStyle = (FontStyles)Enum.Parse (typeof(FontStyles), fontStyle); } textGUI.fontSize = fontSize; textGUI.overflowMode = overflowMode; if (maxVisibleLines > 0) { textGUI.maxVisibleLines = maxVisibleLines; } textGUI.enableAutoSizing = sizeToFit; textGUI.lineSpacing = lineSpacing; textGUI.fontSizeMin = minSize; textGUI.fontSizeMax = maxSize; //public enum TextAlignmentOptions { TopLeft = 0, Top = 1, TopRight = 2, TopJustified = 3, Left = 4, Center = 5, Right = 6, Justified = 7, BottomLeft = 8, Bottom = 9, BottomRight = 10, BottomJustified = 11, BaselineLeft = 12, Baseline = 13, BaselineRight = 14, BaselineJustified = 15 }; textGUI.alignment = alignment; textGUI.color = fontColor; textGUI.text = PlanetUnityStyle.ReplaceStyleTags(value); UpdateRectTransform (); } public void SetSizeToFit(float idealNumberfLines) { textGUI.enableAutoSizing = true; textGUI.fontSizeMax = (rectTransform.rect.height / idealNumberfLines) * 0.75f; } public Vector2 CalculateTextSize (string text, float maxWidth) { bool savedAutoSizing = textGUI.enableAutoSizing; textGUI.enableAutoSizing = false; Vector2 prefSize = textGUI.GetPreferredValues(text, maxWidth, Mathf.Infinity); if (prefSize.x > maxWidth) { prefSize.x = maxWidth; } textGUI.enableAutoSizing = savedAutoSizing; return prefSize; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Text; internal partial class Interop { internal partial class WinHttp { [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, int flags); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpCloseHandle( IntPtr handle); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, [In] StringBuilder headers, uint headersLength, uint modifiers); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, [In] StringBuilder headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReceiveResponse( SafeWinHttpHandle requestHandle, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, IntPtr buffer, ref uint bufferLength, ref uint index); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref uint buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpGetIEProxyConfigForCurrentUser( out WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out WINHTTP_PROXY_INFO proxyInfo); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using MongoDB.Driver; using MongoMembership.Utils; namespace MongoMembership.Mongo { internal class MongoGateway : IMongoGateway { private readonly IMongoCollection<User> usersCollection; private readonly IMongoCollection<Role> rolesCollection; public MongoGateway(string mongoConnectionString) { var mongoUrl = new MongoUrl(mongoConnectionString); var dataBase = new MongoClient(mongoUrl).GetDatabase(mongoUrl.DatabaseName); usersCollection = dataBase.GetCollection<User>(nameof(User)); rolesCollection = dataBase.GetCollection<Role>(nameof(Role)); CreateIndex(); } public void DropUsers() { usersCollection.DeleteMany(u => true); } public void DropRoles() { rolesCollection.DeleteMany(r => true); } #region User public void CreateUser(User user) { user.UsernameLowercase = user.Username?.ToLowerInvariant(); user.EmailLowercase = user.Email?.ToLowerInvariant(); usersCollection.InsertOne(user); } public void UpdateUser(User user) { usersCollection.FindOneAndReplace(f => f.Id == user.Id, user); } public void RemoveUser(User user) { user.IsDeleted = true; UpdateUser(user); } public User GetById(string id) { return usersCollection.FindSync(f => f.Id == id).SingleOrDefault(); } public User GetByUserName(string applicationName, string username) { username = username?.ToLowerInvariant(); return usersCollection .FindSync(UserFilter(applicationName, u => u.UsernameLowercase == username)) .SingleOrDefault(); } public User GetByEmail(string applicationName, string email) { email = email?.ToLowerInvariant(); return usersCollection .FindSync(UserFilter(applicationName, u => u.EmailLowercase == email)) .SingleOrDefault(); } public IEnumerable<User> GetAllByEmail(string applicationName, string email, int pageIndex, int pageSize, out int totalRecords) { email = email?.ToLowerInvariant(); var filter = UserFilter(applicationName, u => u.UsernameLowercase.Contains(email)); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetAllByUserName(string applicationName, string username, int pageIndex, int pageSize, out int totalRecords) { username = username?.ToLowerInvariant(); var filter = UserFilter(applicationName, u => u.UsernameLowercase.Contains(username)); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetAllAnonymByUserName(string applicationName, string username, int pageIndex, int pageSize, out int totalRecords) { username = username?.ToLowerInvariant(); var filter = UserFilter(applicationName, u => u.IsAnonymous && u.UsernameLowercase.Contains(username)); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetAll(string applicationName, int pageIndex, int pageSize, out int totalRecords) { var filter = UserFilter(applicationName, _ => true); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetAllAnonym(string applicationName, int pageIndex, int pageSize, out int totalRecords) { var filter = UserFilter(applicationName, u => u.IsAnonymous); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetAllInactiveSince(string applicationName, DateTime inactiveDate, int pageIndex, int pageSize, out int totalRecords) { var filter = UserFilter(applicationName, u => u.LastActivityDate <= inactiveDate); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetAllInactiveAnonymSince(string applicationName, DateTime inactiveDate, int pageIndex, int pageSize, out int totalRecords) { var filter = UserFilter(applicationName, u => u.IsAnonymous && u.LastActivityDate <= inactiveDate); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetInactiveSinceByUserName(string applicationName, string username, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { username = username?.ToLowerInvariant(); var filter = UserFilter(applicationName, u => u.UsernameLowercase.Contains(username) && u.LastActivityDate <= userInactiveSinceDate); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public IEnumerable<User> GetInactiveAnonymSinceByUserName(string applicationName, string username, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { username = username?.ToLowerInvariant(); var filter = UserFilter(applicationName, u => u.IsAnonymous && u.UsernameLowercase.Contains(username) && u.LastActivityDate <= userInactiveSinceDate); var result = GetAll(filter, pageIndex, pageSize); totalRecords = result.Item2; return result.Item1; } public int GetUserForPeriodOfTime(string applicationName, TimeSpan timeSpan) { var timeInPast = DateTime.UtcNow.Subtract(timeSpan); return (int)usersCollection.Count(u => u.ApplicationName == applicationName && u.LastActivityDate > timeInPast); } #endregion #region Role public void CreateRole(Role role) { role.RoleNameLowercased = role.RoleName?.ToLowerInvariant(); rolesCollection.InsertOne(role); } public void RemoveRole(string applicationName, string roleName) { roleName = roleName?.ToLowerInvariant(); rolesCollection.DeleteMany(r => r.ApplicationName == applicationName && r.RoleNameLowercased == roleName); } public string[] GetAllRoles(string applicationName) { return rolesCollection .FindSync(role => role.ApplicationName == applicationName) .ToList() .Select(role => role.RoleName) .ToArray(); } public string[] GetRolesForUser(string applicationName, string username) { if (username.IsNullOrWhiteSpace()) return null; var user = GetByUserName(applicationName, username); return user?.Roles?.ToArray(); } public string[] GetUsersInRole(string applicationName, string roleName) { if (roleName.IsNullOrWhiteSpace()) return null; return usersCollection .FindSync(user => user.ApplicationName == applicationName && (user.Roles.Contains(roleName.ToLowerInvariant()) || user.Roles.Contains(roleName))) .ToList() .Select(user => user.Username) .ToArray(); } public bool IsUserInRole(string applicationName, string username, string roleName) { var user = GetByUserName(applicationName, username); if (user == null) return false; return user.Roles.Any(r => string.Equals(r, roleName, StringComparison.InvariantCultureIgnoreCase)); } public bool IsRoleExists(string applicationName, string roleName) { roleName = roleName?.ToLowerInvariant(); return rolesCollection.FindSync(RoleFilter(applicationName, r => r.RoleNameLowercased == roleName)).Any(); } #endregion private static FilterDefinition<User> UserFilter(string applicationName, Expression<Func<User, bool>> extraFilter) { return Builders<User>.Filter.And( Builders<User>.Filter.Eq(u => u.IsDeleted, false), Builders<User>.Filter.Eq(u => u.ApplicationName, applicationName), Builders<User>.Filter.Where(extraFilter) ); } private static FilterDefinition<Role> RoleFilter(string applicationName, Expression<Func<Role, bool>> extraFilter) { return Builders<Role>.Filter.And( Builders<Role>.Filter.Eq(u => u.ApplicationName, applicationName), Builders<Role>.Filter.Where(extraFilter) ); } private Tuple<ICollection<User>, int> GetAll(FilterDefinition<User> filter, int pageIndex, int pageSize) { var options = new FindOptions<User> { Skip = pageIndex * pageSize, Limit = pageSize, }; var users = usersCollection.FindSync(filter, options).ToList(); var total = (int)usersCollection.Count(filter); return new Tuple<ICollection<User>, int>(users, total); } private void CreateIndex() { var combinedUserIndex = usersCollection.Indexes.CreateOne( Builders<User>.IndexKeys.Combine( Builders<User>.IndexKeys.Text(_ => _.ApplicationName), Builders<User>.IndexKeys.Text(_ => _.EmailLowercase), Builders<User>.IndexKeys.Text(_ => _.UsernameLowercase), Builders<User>.IndexKeys.Text(_ => _.Roles), Builders<User>.IndexKeys.Ascending(_ => _.IsAnonymous), Builders<User>.IndexKeys.Ascending(_ => _.LastActivityDate) ), new CreateIndexOptions() { Name = "UserCollectionIndex", Background = true }); var combinedRoleCollectionKey = rolesCollection.Indexes.CreateOne( Builders<Role>.IndexKeys.Combine( Builders<Role>.IndexKeys.Text(_ => _.ApplicationName), Builders<Role>.IndexKeys.Text(_ => _.RoleNameLowercased) ), new CreateIndexOptions() { Name = "RoleCollectionIndex", Background = true }); } } }
//------------------------------------------------------------------------------ // <copyright file="XmlWriterSettings.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Security.Permissions; using System.Runtime.Versioning; #if !SILVERLIGHT #if !HIDE_XSL using System.Xml.Xsl.Runtime; #endif #endif namespace System.Xml { #if !SILVERLIGHT public enum XmlOutputMethod { Xml = 0, // Use Xml 1.0 rules to serialize Html = 1, // Use Html rules specified by Xslt specification to serialize Text = 2, // Only serialize text blocks AutoDetect = 3, // Choose between Xml and Html output methods at runtime (using Xslt rules to do so) } #endif /// <summary> /// Three-state logic enumeration. /// </summary> internal enum TriState { Unknown = -1, False = 0, True = 1, }; internal enum XmlStandalone { // Do not change the constants - XmlBinaryWriter depends in it Omit = 0, Yes = 1, No = 2, } // XmlWriterSettings class specifies basic features of an XmlWriter. #if !SILVERLIGHT [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #endif public sealed class XmlWriterSettings { // // Fields // #if ASYNC || FEATURE_NETCORE bool useAsync; #endif // Text settings Encoding encoding; #if FEATURE_LEGACYNETCF private bool dontWriteEncodingTag; #endif bool omitXmlDecl; NewLineHandling newLineHandling; string newLineChars; TriState indent; string indentChars; bool newLineOnAttributes; bool closeOutput; NamespaceHandling namespaceHandling; // Conformance settings ConformanceLevel conformanceLevel; bool checkCharacters; bool writeEndDocumentOnClose; #if !SILVERLIGHT // Xslt settings XmlOutputMethod outputMethod; List<XmlQualifiedName> cdataSections = new List<XmlQualifiedName>(); bool doNotEscapeUriAttributes; bool mergeCDataSections; string mediaType; string docTypeSystem; string docTypePublic; XmlStandalone standalone; bool autoXmlDecl; #endif // read-only flag bool isReadOnly; // // Constructor // public XmlWriterSettings() { Initialize(); } // // Properties // #if ASYNC || FEATURE_NETCORE public bool Async { get { return useAsync; } set { CheckReadOnly("Async"); useAsync = value; } } #endif // Text public Encoding Encoding { get { return encoding; } set { CheckReadOnly("Encoding"); encoding = value; } } #if FEATURE_LEGACYNETCF internal bool DontWriteEncodingTag { get { return dontWriteEncodingTag; } set { CheckReadOnly("DontWriteEncodingTag"); dontWriteEncodingTag = value; } } #endif // True if an xml declaration should *not* be written. public bool OmitXmlDeclaration { get { return omitXmlDecl; } set { CheckReadOnly("OmitXmlDeclaration"); omitXmlDecl = value; } } // See NewLineHandling enum for details. public NewLineHandling NewLineHandling { get { return newLineHandling; } set { CheckReadOnly("NewLineHandling"); if ((uint)value > (uint)NewLineHandling.None) { throw new ArgumentOutOfRangeException("value"); } newLineHandling = value; } } // Line terminator string. By default, this is a carriage return followed by a line feed ("\r\n"). public string NewLineChars { get { return newLineChars; } set { CheckReadOnly("NewLineChars"); if (value == null) { throw new ArgumentNullException("value"); } newLineChars = value; } } // True if output should be indented using rules that are appropriate to the output rules (i.e. Xml, Html, etc). public bool Indent { get { return indent == TriState.True; } set { CheckReadOnly("Indent"); indent = value ? TriState.True : TriState.False; } } // Characters to use when indenting. This is usually tab or some spaces, but can be anything. public string IndentChars { get { return indentChars; } set { CheckReadOnly("IndentChars"); if (value == null) { throw new ArgumentNullException("value"); } indentChars = value; } } // Whether or not indent attributes on new lines. public bool NewLineOnAttributes { get { return newLineOnAttributes; } set { CheckReadOnly("NewLineOnAttributes"); newLineOnAttributes = value; } } // Whether or not the XmlWriter should close the underlying stream or TextWriter when Close is called on the XmlWriter. public bool CloseOutput { get { return closeOutput; } set { CheckReadOnly("CloseOutput"); closeOutput = value; } } // Conformance // See ConformanceLevel enum for details. public ConformanceLevel ConformanceLevel { get { return conformanceLevel; } set { CheckReadOnly("ConformanceLevel"); if ((uint)value > (uint)ConformanceLevel.Document) { throw new ArgumentOutOfRangeException("value"); } conformanceLevel = value; } } // Whether or not to check content characters that they are valid XML characters. public bool CheckCharacters { get { return checkCharacters; } set { CheckReadOnly("CheckCharacters"); checkCharacters = value; } } // Whether or not to remove duplicate namespace declarations public NamespaceHandling NamespaceHandling { get { return namespaceHandling; } set { CheckReadOnly("NamespaceHandling"); if ((uint)value > (uint)(NamespaceHandling.OmitDuplicates)) { throw new ArgumentOutOfRangeException("value"); } namespaceHandling = value; } } //Whether or not to auto complete end-element when close/dispose public bool WriteEndDocumentOnClose { get { return writeEndDocumentOnClose; } set { CheckReadOnly("WriteEndDocumentOnClose"); writeEndDocumentOnClose = value; } } #if !SILVERLIGHT // Specifies the method (Html, Xml, etc.) that will be used to serialize the result tree. public XmlOutputMethod OutputMethod { get { return outputMethod; } internal set { outputMethod = value; } } #endif // // Public methods // public void Reset() { CheckReadOnly("Reset"); Initialize(); } // Deep clone all settings (except read-only, which is always set to false). The original and new objects // can now be set independently of each other. public XmlWriterSettings Clone() { XmlWriterSettings clonedSettings = MemberwiseClone() as XmlWriterSettings; #if !SILVERLIGHT // Deep clone shared settings that are not immutable clonedSettings.cdataSections = new List<XmlQualifiedName>(cdataSections); #endif clonedSettings.isReadOnly = false; return clonedSettings; } // // Internal properties // #if !SILVERLIGHT // Set of XmlQualifiedNames that identify any elements that need to have text children wrapped in CData sections. internal List<XmlQualifiedName> CDataSectionElements { get { Debug.Assert(cdataSections != null); return cdataSections; } } // Used in Html writer to disable encoding of uri attributes public bool DoNotEscapeUriAttributes { get { return doNotEscapeUriAttributes; } set { CheckReadOnly("DoNotEscapeUriAttributes"); doNotEscapeUriAttributes = value; } } internal bool MergeCDataSections { get { return mergeCDataSections; } set { CheckReadOnly("MergeCDataSections"); mergeCDataSections = value; } } // Used in Html writer when writing Meta element. Null denotes the default media type. internal string MediaType { get { return mediaType; } set { CheckReadOnly("MediaType"); mediaType = value; } } // System Id in doc-type declaration. Null denotes the absence of the system Id. internal string DocTypeSystem { get { return docTypeSystem; } set { CheckReadOnly("DocTypeSystem"); docTypeSystem = value; } } // Public Id in doc-type declaration. Null denotes the absence of the public Id. internal string DocTypePublic { get { return docTypePublic; } set { CheckReadOnly("DocTypePublic"); docTypePublic = value; } } // Yes for standalone="yes", No for standalone="no", and Omit for no standalone. internal XmlStandalone Standalone { get { return standalone; } set { CheckReadOnly("Standalone"); standalone = value; } } // True if an xml declaration should automatically be output (no need to call WriteStartDocument) internal bool AutoXmlDeclaration { get { return autoXmlDecl; } set { CheckReadOnly("AutoXmlDeclaration"); autoXmlDecl = value; } } // If TriState.Unknown, then Indent property was not explicitly set. In this case, the AutoDetect output // method will default to Indent=true for Html and Indent=false for Xml. internal TriState IndentInternal { get { return indent; } set { indent = value; } } internal bool IsQuerySpecific { get { return cdataSections.Count != 0 || docTypePublic != null || docTypeSystem != null || standalone == XmlStandalone.Yes; } } #endif #if !SILVERLIGHT [ResourceConsumption(ResourceScope.Machine)] [ResourceExposure(ResourceScope.Machine)] internal XmlWriter CreateWriter(string outputFileName) { if (outputFileName == null) { throw new ArgumentNullException("outputFileName"); } // need to clone the settigns so that we can set CloseOutput to true to make sure the stream gets closed in the end XmlWriterSettings newSettings = this; if (!newSettings.CloseOutput) { newSettings = newSettings.Clone(); newSettings.CloseOutput = true; } FileStream fs = null; try { // open file stream #if !ASYNC fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read); #else fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000, useAsync); #endif // create writer return newSettings.CreateWriter(fs); } catch { if (fs != null) { fs.Close(); } throw; } } #endif internal XmlWriter CreateWriter(Stream output) { if (output == null) { throw new ArgumentNullException("output"); } XmlWriter writer; // create raw writer #if SILVERLIGHT Debug.Assert(Encoding.UTF8.WebName == "utf-8"); if (this.Encoding.WebName == "utf-8") { // Encoding.CodePage is not supported in Silverlight // create raw UTF-8 writer if (this.Indent) { writer = new XmlUtf8RawTextWriterIndent(output, this); } else { writer = new XmlUtf8RawTextWriter(output, this); } } else { // create raw writer for other encodings if (this.Indent) { writer = new XmlEncodedRawTextWriterIndent(output, this); } else { writer = new XmlEncodedRawTextWriter(output, this); } } #else Debug.Assert(Encoding.UTF8.WebName == "utf-8"); if (this.Encoding.WebName == "utf-8") { // Encoding.CodePage is not supported in Silverlight // create raw UTF-8 writer switch (this.OutputMethod) { case XmlOutputMethod.Xml: if (this.Indent) { writer = new XmlUtf8RawTextWriterIndent(output, this); } else { writer = new XmlUtf8RawTextWriter(output, this); } break; case XmlOutputMethod.Html: if (this.Indent) { writer = new HtmlUtf8RawTextWriterIndent(output, this); } else { writer = new HtmlUtf8RawTextWriter(output, this); } break; case XmlOutputMethod.Text: writer = new TextUtf8RawTextWriter(output, this); break; case XmlOutputMethod.AutoDetect: writer = new XmlAutoDetectWriter(output, this); break; default: Debug.Assert(false, "Invalid XmlOutputMethod setting."); return null; } } else { // Otherwise, create a general-purpose writer than can do any encoding switch (this.OutputMethod) { case XmlOutputMethod.Xml: if (this.Indent) { writer = new XmlEncodedRawTextWriterIndent(output, this); } else { writer = new XmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Html: if (this.Indent) { writer = new HtmlEncodedRawTextWriterIndent(output, this); } else { writer = new HtmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Text: writer = new TextEncodedRawTextWriter(output, this); break; case XmlOutputMethod.AutoDetect: writer = new XmlAutoDetectWriter(output, this); break; default: Debug.Assert(false, "Invalid XmlOutputMethod setting."); return null; } } // Wrap with Xslt/XQuery specific writer if needed; // XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer. if (this.OutputMethod != XmlOutputMethod.AutoDetect) { if (this.IsQuerySpecific) { // Create QueryOutputWriter if CData sections or DocType need to be tracked writer = new QueryOutputWriter((XmlRawWriter)writer, this); } } #endif // !SILVERLIGHT // wrap with well-formed writer writer = new XmlWellFormedWriter(writer, this); #if ASYNC if (useAsync) { writer = new XmlAsyncCheckWriter(writer); } #endif return writer; } internal XmlWriter CreateWriter(TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } XmlWriter writer; // create raw writer #if SILVERLIGHT if (this.Indent) { writer = new XmlEncodedRawTextWriterIndent(output, this); } else { writer = new XmlEncodedRawTextWriter(output, this); } #else switch (this.OutputMethod) { case XmlOutputMethod.Xml: if (this.Indent) { writer = new XmlEncodedRawTextWriterIndent(output, this); } else { writer = new XmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Html: if (this.Indent) { writer = new HtmlEncodedRawTextWriterIndent(output, this); } else { writer = new HtmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Text: writer = new TextEncodedRawTextWriter(output, this); break; case XmlOutputMethod.AutoDetect: writer = new XmlAutoDetectWriter(output, this); break; default: Debug.Assert(false, "Invalid XmlOutputMethod setting."); return null; } // XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer. if (this.OutputMethod != XmlOutputMethod.AutoDetect) { if (this.IsQuerySpecific) { // Create QueryOutputWriter if CData sections or DocType need to be tracked writer = new QueryOutputWriter((XmlRawWriter)writer, this); } } #endif //SILVERLIGHT // wrap with well-formed writer writer = new XmlWellFormedWriter(writer, this); #if ASYNC if (useAsync) { writer = new XmlAsyncCheckWriter(writer); } #endif return writer; } internal XmlWriter CreateWriter(XmlWriter output) { if (output == null) { throw new ArgumentNullException("output"); } return AddConformanceWrapper(output); } internal bool ReadOnly { get { return isReadOnly; } set { isReadOnly = value; } } void CheckReadOnly(string propertyName) { if (isReadOnly) { throw new XmlException(Res.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName); } } // // Private methods // void Initialize() { encoding = Encoding.UTF8; omitXmlDecl = false; newLineHandling = NewLineHandling.Replace; newLineChars = Environment.NewLine; // "\r\n" on Windows, "\n" on Unix indent = TriState.Unknown; indentChars = " "; newLineOnAttributes = false; closeOutput = false; namespaceHandling = NamespaceHandling.Default; conformanceLevel = ConformanceLevel.Document; checkCharacters = true; writeEndDocumentOnClose = true; #if !SILVERLIGHT outputMethod = XmlOutputMethod.Xml; cdataSections.Clear(); mergeCDataSections = false; mediaType = null; docTypeSystem = null; docTypePublic = null; standalone = XmlStandalone.Omit; doNotEscapeUriAttributes = false; #endif #if ASYNC || FEATURE_NETCORE useAsync = false; #endif isReadOnly = false; } private XmlWriter AddConformanceWrapper(XmlWriter baseWriter) { ConformanceLevel confLevel = ConformanceLevel.Auto; XmlWriterSettings baseWriterSettings = baseWriter.Settings; bool checkValues = false; bool checkNames = false; bool replaceNewLines = false; bool needWrap = false; if (baseWriterSettings == null) { // assume the V1 writer already do all conformance checking; // wrap only if NewLineHandling == Replace or CheckCharacters is true if (this.newLineHandling == NewLineHandling.Replace) { replaceNewLines = true; needWrap = true; } if (this.checkCharacters) { checkValues = true; needWrap = true; } } else { if (this.conformanceLevel != baseWriterSettings.ConformanceLevel) { confLevel = this.ConformanceLevel; needWrap = true; } if (this.checkCharacters && !baseWriterSettings.CheckCharacters) { checkValues = true; checkNames = confLevel == ConformanceLevel.Auto; needWrap = true; } if (this.newLineHandling == NewLineHandling.Replace && baseWriterSettings.NewLineHandling == NewLineHandling.None) { replaceNewLines = true; needWrap = true; } } XmlWriter writer = baseWriter; if (needWrap) { if (confLevel != ConformanceLevel.Auto) { writer = new XmlWellFormedWriter(writer, this); } if (checkValues || replaceNewLines) { writer = new XmlCharCheckingWriter(writer, checkValues, checkNames, replaceNewLines, this.NewLineChars); } } #if !SILVERLIGHT if (this.IsQuerySpecific && (baseWriterSettings == null || !baseWriterSettings.IsQuerySpecific)) { // Create QueryOutputWriterV1 if CData sections or DocType need to be tracked writer = new QueryOutputWriterV1(writer, this); } #endif return writer; } // // Internal methods // #if !SILVERLIGHT #if !HIDE_XSL #if !DISABLE_XSLT_COMPILER /// <summary> /// Serialize the object to BinaryWriter. /// </summary> internal void GetObjectData(XmlQueryDataWriter writer) { // Encoding encoding; // NOTE: For Encoding we serialize only CodePage, and ignore EncoderFallback/DecoderFallback. // It suffices for XSLT purposes, but not in the general case. Debug.Assert(Encoding.Equals(Encoding.GetEncoding(Encoding.CodePage)), "Cannot serialize encoding correctly"); writer.Write(Encoding.CodePage); // bool omitXmlDecl; writer.Write(OmitXmlDeclaration); // NewLineHandling newLineHandling; writer.Write((sbyte)NewLineHandling); // string newLineChars; writer.WriteStringQ(NewLineChars); // TriState indent; writer.Write((sbyte)IndentInternal); // string indentChars; writer.WriteStringQ(IndentChars); // bool newLineOnAttributes; writer.Write(NewLineOnAttributes); // bool closeOutput; writer.Write(CloseOutput); // ConformanceLevel conformanceLevel; writer.Write((sbyte)ConformanceLevel); // bool checkCharacters; writer.Write(CheckCharacters); // XmlOutputMethod outputMethod; writer.Write((sbyte)outputMethod); // List<XmlQualifiedName> cdataSections; writer.Write(cdataSections.Count); foreach (XmlQualifiedName qname in cdataSections) { writer.Write(qname.Name); writer.Write(qname.Namespace); } // bool mergeCDataSections; writer.Write(mergeCDataSections); // string mediaType; writer.WriteStringQ(mediaType); // string docTypeSystem; writer.WriteStringQ(docTypeSystem); // string docTypePublic; writer.WriteStringQ(docTypePublic); // XmlStandalone standalone; writer.Write((sbyte)standalone); // bool autoXmlDecl; writer.Write(autoXmlDecl); // bool isReadOnly; writer.Write(ReadOnly); } /// <summary> /// Deserialize the object from BinaryReader. /// </summary> internal XmlWriterSettings(XmlQueryDataReader reader) { // Encoding encoding; Encoding = Encoding.GetEncoding(reader.ReadInt32()); // bool omitXmlDecl; OmitXmlDeclaration = reader.ReadBoolean(); // NewLineHandling newLineHandling; NewLineHandling = (NewLineHandling)reader.ReadSByte(0, (sbyte)NewLineHandling.None); // string newLineChars; NewLineChars = reader.ReadStringQ(); // TriState indent; IndentInternal = (TriState)reader.ReadSByte((sbyte)TriState.Unknown, (sbyte)TriState.True); // string indentChars; IndentChars = reader.ReadStringQ(); // bool newLineOnAttributes; NewLineOnAttributes = reader.ReadBoolean(); // bool closeOutput; CloseOutput = reader.ReadBoolean(); // ConformanceLevel conformanceLevel; ConformanceLevel = (ConformanceLevel)reader.ReadSByte(0, (sbyte)ConformanceLevel.Document); // bool checkCharacters; CheckCharacters = reader.ReadBoolean(); // XmlOutputMethod outputMethod; outputMethod = (XmlOutputMethod)reader.ReadSByte(0, (sbyte)XmlOutputMethod.AutoDetect); // List<XmlQualifiedName> cdataSections; int length = reader.ReadInt32(); cdataSections = new List<XmlQualifiedName>(length); for (int idx = 0; idx < length; idx++) { cdataSections.Add(new XmlQualifiedName(reader.ReadString(), reader.ReadString())); } // bool mergeCDataSections; mergeCDataSections = reader.ReadBoolean(); // string mediaType; mediaType = reader.ReadStringQ(); // string docTypeSystem; docTypeSystem = reader.ReadStringQ(); // string docTypePublic; docTypePublic = reader.ReadStringQ(); // XmlStandalone standalone; Standalone = (XmlStandalone)reader.ReadSByte(0, (sbyte)XmlStandalone.No); // bool autoXmlDecl; autoXmlDecl = reader.ReadBoolean(); // bool isReadOnly; ReadOnly = reader.ReadBoolean(); } #endif #else internal void GetObjectData(object writer) { } internal XmlWriterSettings(object reader) { } #endif #endif } }
#region File Description //----------------------------------------------------------------------------- // ProceduralPrimitive.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace SoccerPitch { public abstract class ProceduralPrimitive<T> : IDisposable where T : struct { #region fields // Once all the geometry has been specified, the InitializePrimitive // method copies the vertex and index data into these buffers, which // store it on the GPU ready for efficient rendering. protected VertexDeclaration vertexDeclaration; protected VertexBuffer vertexBuffer; protected IndexBuffer indexBuffer; protected List<ushort> indices = new List<ushort>(); protected List<T> vertices = new List<T>(); #endregion #region Initialization /// <summary> /// Adds a new index to the primitive model. This should only be called /// during the initialization process, before InitializePrimitive. /// </summary> protected void AddIndex(int index) { if (index > ushort.MaxValue) throw new ArgumentOutOfRangeException("index"); indices.Add((ushort)index); } /// <summary> /// Adds a new vertex to the primitive model. This should only be called /// during the initialization process, before InitializePrimitive. /// </summary> protected void AddVertex(T vertex) { vertices.Add(vertex); } /// <summary> /// Once all the geometry has been specified by calling AddVertex and AddIndex, /// this method copies the vertex and index data into GPU format buffers, ready /// for efficient rendering. protected void InitializePrimitive(GraphicsDevice graphicsDevice, VertexDeclaration vertexDeclaration) { // Create a vertex buffer, and copy our vertex data into it. vertexBuffer = new VertexBuffer(graphicsDevice, vertexDeclaration, vertices.Count, BufferUsage.None); vertexBuffer.SetData(vertices.ToArray()); // Create an index buffer, and copy our index data into it. indexBuffer = new IndexBuffer(graphicsDevice, typeof(ushort), indices.Count, BufferUsage.None); indexBuffer.SetData(indices.ToArray()); } #endregion #region Destruction /// <summary> /// Frees resources used by this object. /// </summary> public void Dispose() { if (vertexDeclaration != null) vertexDeclaration.Dispose(); if (vertexBuffer != null) vertexBuffer.Dispose(); if (indexBuffer != null) indexBuffer.Dispose(); } #endregion /// <summary> /// Queries the index of the current vertex. This starts at /// zero, and increments every time AddVertex is called. /// </summary> protected int CurrentVertex { get { return vertices.Count; } } #region Draw /// <summary> /// Draws the primitive model, using the specified effect. Unlike the other /// Draw overload where you just specify the world/view/projection matrices /// and color, this method does not set any renderstates, so you must make /// sure all states are set to sensible values before you call it. /// </summary> public void Draw(Effect effect) { GraphicsDevice graphicsDevice = effect.GraphicsDevice; // Set vertex buffer, and index buffer. graphicsDevice.SetVertexBuffer(vertexBuffer); graphicsDevice.Indices = indexBuffer; // Draw the model, using the specified effect. foreach (EffectPass effectPass in effect.CurrentTechnique.Passes) { effectPass.Apply(); int primitiveCount = indices.Count / 3; graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Count, 0, primitiveCount); } } /// <summary> /// Draws the primitive model, using a BasicEffect shader with default /// lighting. Unlike the other Draw overload where you specify a custom /// effect, this method sets important renderstates to sensible values /// for 3D model rendering, so you do not need to set these states before /// you call it. /// </summary> public void Draw(BasicEffect basicEffect, Matrix world, Matrix view, Matrix projection, Color color) { // Set BasicEffect parameters. basicEffect.World = world; basicEffect.View = view; basicEffect.Projection = projection; basicEffect.DiffuseColor = color.ToVector3(); basicEffect.Alpha = color.A / 255.0f; if (color.A < 255) { basicEffect.GraphicsDevice.DepthStencilState = DepthStencilState.None; basicEffect.GraphicsDevice.BlendState = BlendState.Additive; } else { basicEffect.GraphicsDevice.DepthStencilState = DepthStencilState.Default; basicEffect.GraphicsDevice.BlendState = BlendState.Opaque; } // Draw the model, using BasicEffect. Draw(basicEffect); } /// <summary> /// Draws the primitive model, using an AlphaTestEffect shader. /// </summary> public void DrawAlphaTest(AlphaTestEffect atEffect, Matrix world, Matrix view, Matrix projection, Color color) { // Set AlphaTest effect parameters. atEffect.World = world; atEffect.View = view; atEffect.Projection = projection; atEffect.DiffuseColor = color.ToVector3(); atEffect.Alpha = color.A / 255.0f; if (color.A < 255) { atEffect.GraphicsDevice.DepthStencilState = DepthStencilState.None; atEffect.GraphicsDevice.BlendState = BlendState.Additive; } else { atEffect.GraphicsDevice.DepthStencilState = DepthStencilState.Default; atEffect.GraphicsDevice.BlendState = BlendState.Opaque; } // Draw the model, using the AlphaTestEffect. Draw(atEffect); } /// <summary> /// Draws the primitive model, using a DualTextureEffect shader. /// </summary> public void DrawDualTextured(DualTextureEffect dtEffect, Matrix world, Matrix view, Matrix projection, Color color) { // Set DrawDualTextured effect parameters. dtEffect.World = world; dtEffect.View = view; dtEffect.Projection = projection; dtEffect.DiffuseColor = color.ToVector3(); dtEffect.Alpha = color.A / 255.0f; if (color.A < 255) { dtEffect.GraphicsDevice.DepthStencilState = DepthStencilState.None; dtEffect.GraphicsDevice.BlendState = BlendState.Additive; } else { dtEffect.GraphicsDevice.DepthStencilState = DepthStencilState.Default; dtEffect.GraphicsDevice.BlendState = BlendState.Opaque; } // Draw the model, using DualTextureEffect. Draw(dtEffect); } #endregion } } // end Namespace
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk) // // This file is part of SharpMap. // SharpMap is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // SharpMap is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License // along with SharpMap; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Collections.Generic; using NetTopologySuite.Geometries; namespace SharpMap.Utilities { /// <summary> /// Calculates Affine and Helmert transformation using Least-Squares Regression of input and output points /// </summary> public class LeastSquaresTransform { private readonly List<Coordinate> inputs; private readonly List<Coordinate> outputs; /// <summary> /// Initialize Least Squares transformations /// </summary> public LeastSquaresTransform() { inputs = new List<Coordinate>(); outputs = new List<Coordinate>(); } /// <summary> /// Adds an input and output value pair to the collection /// </summary> /// <param name="input"></param> /// <param name="output"></param> public void AddInputOutputPoint(Coordinate input, Coordinate output) { inputs.Add(input); outputs.Add(output); } /// <summary> /// Removes input and output value pair at the specified index /// </summary> /// <param name="i"></param> public void RemoveInputOutputPointAt(int i) { inputs.RemoveAt(i); outputs.RemoveAt(i); } /// <summary> /// Gets the input point value at the specified index /// </summary> /// <param name="i">index</param> /// <returns>Input point value a index 'i'</returns> public Coordinate GetInputPoint(int i) { return inputs[i]; } /// <summary> /// Sets the input point value at the specified index /// </summary> /// <param name="p">Point value</param> /// <param name="i">index</param> public void SetInputPointAt(Coordinate p, int i) { inputs[i] = p; } /// <summary> /// Gets the output point value at the specified index /// </summary> /// <param name="i">index</param> /// <returns>Output point value a index 'i'</returns> public Coordinate GetOutputPoint(int i) { return outputs[i]; } /// <summary> /// Sets the output point value at the specified index /// </summary> /// <param name="p">Point value</param> /// <param name="i">index</param> public void SetOutputPointAt(Coordinate p, int i) { outputs[i] = p; } /// <summary> /// Return an array with the six affine transformation parameters {a,b,c,d,e,f} and the sum of the squares of the residuals (s0) /// </summary> /// <remarks> /// a,b defines scale vector 1 of coordinate system, d,e scale vector 2. c,f defines offset. /// <para> /// Converting from input (X,Y) to output coordinate system (X',Y') is done by: /// X' = a*X + b*Y + c, Y' = d*X + e*Y + f /// </para> /// <para> /// Transformation based on Mikhail "Introduction to Modern Photogrammetry" p. 399-300. /// Extended to arbitrary number of measurements by M. Nielsen /// </para> /// </remarks> /// <returns>Array with the six transformation parameters and sum of squared residuals: a,b,c,d,e,f,s0</returns> public double[] GetAffineTransformation() { if (inputs.Count < 3) throw (new Exception("At least 3 measurements required to calculate affine transformation")); //double precision isn't always enough when transforming large numbers. //Lets subtract some mean values and add them later again: //Find approximate center values: Coordinate meanInput = new Coordinate(0, 0); Coordinate meanOutput = new Coordinate(0, 0); for (int i = 0; i < inputs.Count; i++) { meanInput.X += inputs[i].X; meanInput.Y += inputs[i].Y; meanOutput.X += outputs[i].X; meanOutput.Y += outputs[i].Y; } meanInput.X = Math.Round(meanInput.X/inputs.Count); meanInput.Y = Math.Round(meanInput.Y/inputs.Count); meanOutput.X = Math.Round(meanOutput.X/inputs.Count); meanOutput.Y = Math.Round(meanOutput.Y/inputs.Count); double[][] N = CreateMatrix(3, 3); //Create normal equation: transpose(B)*B //B: matrix of calibrated values. Example of row in B: [x , y , -1] for (int i = 0; i < inputs.Count; i++) { //Subtract mean values inputs[i].X -= meanInput.X; inputs[i].Y -= meanInput.Y; outputs[i].X -= meanOutput.X; outputs[i].Y -= meanOutput.Y; //Calculate summed values N[0][0] += Math.Pow(inputs[i].X, 2); N[0][1] += inputs[i].X*inputs[i].Y; N[0][2] += -inputs[i].X; N[1][1] += Math.Pow(inputs[i].Y, 2); N[1][2] += -inputs[i].Y; } N[2][2] = inputs.Count; double[] t1 = new double[3]; double[] t2 = new double[3]; for (int i = 0; i < inputs.Count; i++) { t1[0] += inputs[i].X*outputs[i].X; t1[1] += inputs[i].Y*outputs[i].X; t1[2] += -outputs[i].X; t2[0] += inputs[i].X*outputs[i].Y; t2[1] += inputs[i].Y*outputs[i].Y; t2[2] += -outputs[i].Y; } double[] trans = new double[7]; // Solve equation N = transpose(B)*t1 double frac = 1/ (-N[0][0]*N[1][1]*N[2][2] + N[0][0]*Math.Pow(N[1][2], 2) + Math.Pow(N[0][1], 2)*N[2][2] - 2*N[1][2]*N[0][1]*N[0][2] + N[1][1]*Math.Pow(N[0][2], 2)); trans[0] = (-N[0][1]*N[1][2]*t1[2] + N[0][1]*t1[1]*N[2][2] - N[0][2]*N[1][2]*t1[1] + N[0][2]*N[1][1]*t1[2] - t1[0]*N[1][1]*N[2][2] + t1[0]*Math.Pow(N[1][2], 2))*frac; trans[1] = (-N[0][1]*N[0][2]*t1[2] + N[0][1]*t1[0]*N[2][2] + N[0][0]*N[1][2]*t1[2] - N[0][0]*t1[1]*N[2][2] - N[0][2]*N[1][2]*t1[0] + Math.Pow(N[0][2], 2)*t1[1])*frac; trans[2] = -(-N[1][2]*N[0][1]*t1[0] + Math.Pow(N[0][1], 2)*t1[2] + N[0][0]*N[1][2]*t1[1] - N[0][0]*N[1][1]*t1[2] - N[0][2]*N[0][1]*t1[1] + N[1][1]*N[0][2]*t1[0])*frac; trans[2] += - meanOutput.X + meanInput.X; // Solve equation N = transpose(B)*t2 trans[3] = (-N[0][1]*N[1][2]*t2[2] + N[0][1]*t2[1]*N[2][2] - N[0][2]*N[1][2]*t2[1] + N[0][2]*N[1][1]*t2[2] - t2[0]*N[1][1]*N[2][2] + t2[0]*Math.Pow(N[1][2], 2))*frac; trans[4] = (-N[0][1]*N[0][2]*t2[2] + N[0][1]*t2[0]*N[2][2] + N[0][0]*N[1][2]*t2[2] - N[0][0]*t2[1]*N[2][2] - N[0][2]*N[1][2]*t2[0] + Math.Pow(N[0][2], 2)*t2[1])*frac; trans[5] = -(-N[1][2]*N[0][1]*t2[0] + Math.Pow(N[0][1], 2)*t2[2] + N[0][0]*N[1][2]*t2[1] - N[0][0]*N[1][1]*t2[2] - N[0][2]*N[0][1]*t2[1] + N[1][1]*N[0][2]*t2[0])*frac; trans[5] += - meanOutput.Y + meanInput.Y; //Restore values for (int i = 0; i < inputs.Count; i++) { inputs[i].X += meanInput.X; inputs[i].Y += meanInput.Y; outputs[i].X += meanOutput.X; outputs[i].Y += meanOutput.Y; } //Calculate s0 double s0 = 0; for (int i = 0; i < inputs.Count; i++) { double x = inputs[i].X*trans[0] + inputs[i].Y*trans[1] + trans[2]; double y = inputs[i].X*trans[3] + inputs[i].Y*trans[4] + trans[5]; s0 += Math.Pow(x - outputs[i].X, 2) + Math.Pow(y - outputs[i].Y, 2); } trans[6] = Math.Sqrt(s0)/(inputs.Count); return trans; } /// <summary> /// Calculates the four helmert transformation parameters {a,b,c,d} and the sum of the squares of the residuals (s0) /// </summary> /// <remarks> /// <para> /// a,b defines scale vector 1 of coordinate system, d,e scale vector 2. /// c,f defines offset. /// </para> /// <para> /// Converting from input (X,Y) to output coordinate system (X',Y') is done by: /// X' = a*X + b*Y + c, Y' = -b*X + a*Y + d /// </para> /// <para>This is a transformation initially based on the affine transformation but slightly simpler.</para> /// </remarks> /// <returns>Array with the four transformation parameters, and sum of squared residuals: a,b,c,d,s0</returns> public double[] GetHelmertTransformation() { if (inputs.Count < 2) throw (new Exception("At least 2 measurements required to calculate helmert transformation")); //double precision isn't always enough. Lets subtract some mean values and add them later again: //Find approximate center values: Coordinate meanInput = new Coordinate(0, 0); Coordinate meanOutput = new Coordinate(0, 0); for (int i = 0; i < inputs.Count; i++) { meanInput.X += inputs[i].X; meanInput.Y += inputs[i].Y; meanOutput.X += outputs[i].X; meanOutput.Y += outputs[i].Y; } meanInput.X = Math.Round(meanInput.X/inputs.Count); meanInput.Y = Math.Round(meanInput.Y/inputs.Count); meanOutput.X = Math.Round(meanOutput.X/inputs.Count); meanOutput.Y = Math.Round(meanOutput.Y/inputs.Count); double b00 = 0; double b02 = 0; double b03 = 0; double[] t = new double[4]; for (int i = 0; i < inputs.Count; i++) { //Subtract mean values inputs[i].X -= meanInput.X; inputs[i].Y -= meanInput.Y; outputs[i].X -= meanOutput.X; outputs[i].Y -= meanOutput.Y; //Calculate summed values b00 += Math.Pow(inputs[i].X, 2) + Math.Pow(inputs[i].Y, 2); b02 -= inputs[i].X; b03 -= inputs[i].Y; t[0] += -(inputs[i].X*outputs[i].X) - (inputs[i].Y*outputs[i].Y); t[1] += -(inputs[i].Y*outputs[i].X) + (inputs[i].X*outputs[i].Y); t[2] += outputs[i].X; t[3] += outputs[i].Y; } double frac = 1/(-inputs.Count*b00 + Math.Pow(b02, 2) + Math.Pow(b03, 2)); double[] result = new double[5]; result[0] = (-inputs.Count*t[0] + b02*t[2] + b03*t[3])*frac; result[1] = (-inputs.Count*t[1] + b03*t[2] - b02*t[3])*frac; result[2] = (b02*t[0] + b03*t[1] - t[2]*b00)*frac + meanOutput.X; result[3] = (b03*t[0] - b02*t[1] - t[3]*b00)*frac + meanOutput.Y; //Restore values for (int i = 0; i < inputs.Count; i++) { inputs[i].X += meanInput.X; inputs[i].Y += meanInput.Y; outputs[i].X += meanOutput.X; outputs[i].Y += meanOutput.Y; } //Calculate s0 double s0 = 0; for (int i = 0; i < inputs.Count; i++) { double x = inputs[i].X*result[0] + inputs[i].Y*result[1] + result[2]; double y = -inputs[i].X*result[1] + inputs[i].Y*result[0] + result[3]; s0 += Math.Pow(x - outputs[i].X, 2) + Math.Pow(y - outputs[i].Y, 2); } result[4] = Math.Sqrt(s0)/(inputs.Count); return result; } /// <summary> /// Creates an n x m matrix of doubles /// </summary> /// <param name="n">width of matrix</param> /// <param name="m">height of matrix</param> /// <returns>n*m matrix</returns> private double[][] CreateMatrix(int n, int m) { double[][] N = new double[n][]; for (int i = 0; i < n; i++) { N[i] = new double[m]; } return N; } } }
using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Model; #region License // // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Collections.Generic; namespace FluentMigrator.Builders { /// <summary> /// This class provides a common location for logic pertaining to setting and maintaining /// expressions for expression builders which manipulate the the ColumnDefinition. /// </summary> /// <remarks> /// This is a support class for the migrator framework and is not intended for external use. /// TODO: make this internal, and the change assembly info so InternalsVisibleTo is set for the test assemblies. /// </remarks> public class ColumnExpressionBuilderHelper { private readonly Dictionary<ColumnDefinition, ExistingRowsData> _existingRowsDataByColumn; private readonly IColumnExpressionBuilder _builder; private readonly IMigrationContext _context; /// <summary> /// Initializes a new instance of the <see cref="ColumnExpressionBuilderHelper"/> class. /// </summary> /// <remarks> /// This constructor exists only to ease creating mock objects. /// </remarks> protected ColumnExpressionBuilderHelper() { } /// <summary> /// Initializes a new instance of the <see cref="ColumnExpressionBuilderHelper"/> class. /// </summary> /// <param name="builder">The expression builder</param> /// <param name="context">The migration context</param> public ColumnExpressionBuilderHelper(IColumnExpressionBuilder builder, IMigrationContext context) { _builder = builder; _context = context; _existingRowsDataByColumn = new Dictionary<ColumnDefinition, ExistingRowsData>(); } /// <summary> /// Either updates the IsNullable flag on the column, or creates/removes the SetNotNull expression, depending /// on whether the column has a 'Set existing rows' expression. /// </summary> public virtual void SetNullable(bool isNullable) { var column = _builder.Column; ExistingRowsData exRowExpr; if (_existingRowsDataByColumn.TryGetValue(column, out exRowExpr)) { if (exRowExpr.SetExistingRowsExpression != null) { if (isNullable) { //Remove additional expression to set column to not null. _context.Expressions.Remove(exRowExpr.SetColumnNotNullableExpression); exRowExpr.SetColumnNotNullableExpression = null; } else { //Add expression to set column to not null. //If it already exists, just leave it. if (exRowExpr.SetColumnNotNullableExpression == null) { //stuff that matters shouldn't change at this point, so we're free to make a //copy of the col def. //TODO: make a SetColumnNotNullExpression, which just takes the bare minimum, rather //than modifying column with all parameters. ColumnDefinition notNullColDef = (ColumnDefinition)column.Clone(); notNullColDef.ModificationType = ColumnModificationType.Alter; notNullColDef.IsNullable = false; exRowExpr.SetColumnNotNullableExpression = new AlterColumnExpression { Column = notNullColDef, TableName = _builder.TableName, SchemaName = _builder.SchemaName }; _context.Expressions.Add(exRowExpr.SetColumnNotNullableExpression); } } //Setting column explicitly to nullable, as the actual nullable value //will be set by the SetColumnNotNullableExpression after the column is created and populated. column.IsNullable = true; return; } } //At this point, we know there's no existing row expression, so just pass it onto the //underlying column. column.IsNullable = isNullable; } /// <summary> /// Adds the existing row default value. If the column has a value for IsNullable, this will also /// call SetNullable to create the expression, and will then set the column IsNullable to false. /// </summary> public virtual void SetExistingRowsTo(object existingRowValue) { //TODO: validate that 'value' isn't set to null for non nullable columns. If set to //null, maybe just remove the expressions?.. not sure of best way to handle this. var column = _builder.Column; if (column.ModificationType == ColumnModificationType.Create) { //ensure an UpdateDataExpression is created and cached for this column ExistingRowsData exRowExpr; if (!_existingRowsDataByColumn.TryGetValue(column, out exRowExpr)) { exRowExpr = new ExistingRowsData(); _existingRowsDataByColumn.Add(column, exRowExpr); } if (exRowExpr.SetExistingRowsExpression == null) { exRowExpr.SetExistingRowsExpression = new UpdateDataExpression { TableName = _builder.TableName, SchemaName = _builder.SchemaName, IsAllRows = true, }; _context.Expressions.Add(exRowExpr.SetExistingRowsExpression); //Call SetNullable, to ensure that not-null columns are correctly set to //not null after existing rows have data populated. SetNullable(column.IsNullable ?? true); } exRowExpr.SetExistingRowsExpression.Set = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>(column.Name, existingRowValue) }; } } /// <summary> /// Creates a new CREATE INDEX expression to create a new unique index /// </summary> /// <param name="indexName">The new name of the index</param> public virtual void Unique(string indexName) { var column = _builder.Column; column.IsUnique = true; var index = new CreateIndexExpression { Index = new IndexDefinition { Name = indexName, SchemaName = _builder.SchemaName, TableName = _builder.TableName, IsUnique = true } }; index.Index.Columns.Add(new IndexColumnDefinition { Name = _builder.Column.Name }); _context.Expressions.Add(index); } /// <summary> /// Creates a new CREATE INDEX expression /// </summary> /// <param name="indexName">The index name</param> public virtual void Indexed(string indexName) { _builder.Column.IsIndexed = true; var index = new CreateIndexExpression { Index = new IndexDefinition { Name = indexName, SchemaName = _builder.SchemaName, TableName = _builder.TableName } }; index.Index.Columns.Add(new IndexColumnDefinition { Name = _builder.Column.Name }); _context.Expressions.Add(index); } /// <summary> /// For each distinct column which has an existing row default, an instance of this /// will be stored in the _expressionsByColumn. /// </summary> private class ExistingRowsData { public UpdateDataExpression SetExistingRowsExpression; public AlterColumnExpression SetColumnNotNullableExpression; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal sealed class StringFunctions : ValueQuery { private Function.FunctionType _funcType; private IList<Query> _argList; public StringFunctions(Function.FunctionType funcType, IList<Query> argList) { Debug.Assert(argList != null, "Use 'new Query[]{}' instead."); _funcType = funcType; _argList = argList; } private StringFunctions(StringFunctions other) : base(other) { _funcType = other._funcType; Query[] tmp = new Query[other._argList.Count]; { for (int i = 0; i < tmp.Length; i++) { tmp[i] = Clone(other._argList[i]); } } _argList = tmp; } public override void SetXsltContext(XsltContext context) { for (int i = 0; i < _argList.Count; i++) { _argList[i].SetXsltContext(context); } } public override object Evaluate(XPathNodeIterator nodeIterator) { switch (_funcType) { case Function.FunctionType.FuncString: return toString(nodeIterator); case Function.FunctionType.FuncConcat: return Concat(nodeIterator); case Function.FunctionType.FuncStartsWith: return StartsWith(nodeIterator); case Function.FunctionType.FuncContains: return Contains(nodeIterator); case Function.FunctionType.FuncSubstringBefore: return SubstringBefore(nodeIterator); case Function.FunctionType.FuncSubstringAfter: return SubstringAfter(nodeIterator); case Function.FunctionType.FuncSubstring: return Substring(nodeIterator); case Function.FunctionType.FuncStringLength: return StringLength(nodeIterator); case Function.FunctionType.FuncNormalize: return Normalize(nodeIterator); case Function.FunctionType.FuncTranslate: return Translate(nodeIterator); } return string.Empty; } internal static string toString(double num) { return num.ToString("R", NumberFormatInfo.InvariantInfo); } internal static string toString(bool b) { return b ? "true" : "false"; } private string toString(XPathNodeIterator nodeIterator) { if (_argList.Count > 0) { object argVal = _argList[0].Evaluate(nodeIterator); switch (GetXPathType(argVal)) { case XPathResultType.NodeSet: XPathNavigator value = _argList[0].Advance(); return value != null ? value.Value : string.Empty; case XPathResultType.String: return (string)argVal; case XPathResultType.Boolean: return ((bool)argVal) ? "true" : "false"; case XPathResultType_Navigator: return ((XPathNavigator)argVal).Value; default: Debug.Assert(GetXPathType(argVal) == XPathResultType.Number); return toString((double)argVal); } } return nodeIterator.Current.Value; } public override XPathResultType StaticType { get { if (_funcType == Function.FunctionType.FuncStringLength) { return XPathResultType.Number; } if ( _funcType == Function.FunctionType.FuncStartsWith || _funcType == Function.FunctionType.FuncContains ) { return XPathResultType.Boolean; } return XPathResultType.String; } } private string Concat(XPathNodeIterator nodeIterator) { int count = 0; StringBuilder s = new StringBuilder(); while (count < _argList.Count) { s.Append(_argList[count++].Evaluate(nodeIterator).ToString()); } return s.ToString(); } private bool StartsWith(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0; } private static readonly CompareInfo s_compareInfo = CultureInfo.InvariantCulture.CompareInfo; private bool Contains(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); return s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0; } private string SubstringBefore(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); if (s2.Length == 0) { return s2; } int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal); return (idx < 1) ? string.Empty : s1.Substring(0, idx); } private string SubstringAfter(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); if (s2.Length == 0) { return s1; } int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal); return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length); } private string Substring(XPathNodeIterator nodeIterator) { string str1 = _argList[0].Evaluate(nodeIterator).ToString(); double num = XmlConvert.XPathRound(XmlConvert.ToXPathDouble(_argList[1].Evaluate(nodeIterator))) - 1; if (Double.IsNaN(num) || str1.Length <= num) { return string.Empty; } if (_argList.Count == 3) { double num1 = XmlConvert.XPathRound(XmlConvert.ToXPathDouble(_argList[2].Evaluate(nodeIterator))); if (Double.IsNaN(num1)) { return string.Empty; } if (num < 0 || num1 < 0) { num1 = num + num1; // NOTE: condition is true for NaN if (!(num1 > 0)) { return string.Empty; } num = 0; } double maxlength = str1.Length - num; if (num1 > maxlength) { num1 = maxlength; } return str1.Substring((int)num, (int)num1); } if (num < 0) { num = 0; } return str1.Substring((int)num); } private Double StringLength(XPathNodeIterator nodeIterator) { if (_argList.Count > 0) { return _argList[0].Evaluate(nodeIterator).ToString().Length; } return nodeIterator.Current.Value.Length; } private string Normalize(XPathNodeIterator nodeIterator) { string value; if (_argList.Count > 0) { value = _argList[0].Evaluate(nodeIterator).ToString(); } else { value = nodeIterator.Current.Value; } int modifyPos = -1; char[] chars = value.ToCharArray(); bool firstSpace = false; // Start false to trim the beginning XmlCharType xmlCharType = XmlCharType.Instance; for (int comparePos = 0; comparePos < chars.Length; comparePos++) { if (!xmlCharType.IsWhiteSpace(chars[comparePos])) { firstSpace = true; modifyPos++; chars[modifyPos] = chars[comparePos]; } else if (firstSpace) { firstSpace = false; modifyPos++; chars[modifyPos] = ' '; } } // Trim end if (modifyPos > -1 && chars[modifyPos] == ' ') modifyPos--; return new string(chars, 0, modifyPos + 1); } private string Translate(XPathNodeIterator nodeIterator) { string value = _argList[0].Evaluate(nodeIterator).ToString(); string mapFrom = _argList[1].Evaluate(nodeIterator).ToString(); string mapTo = _argList[2].Evaluate(nodeIterator).ToString(); int modifyPos = -1; char[] chars = value.ToCharArray(); for (int comparePos = 0; comparePos < chars.Length; comparePos++) { int index = mapFrom.IndexOf(chars[comparePos]); if (index != -1) { if (index < mapTo.Length) { modifyPos++; chars[modifyPos] = mapTo[index]; } } else { modifyPos++; chars[modifyPos] = chars[comparePos]; } } return new string(chars, 0, modifyPos + 1); } public override XPathNodeIterator Clone() { return new StringFunctions(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Text; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Intermediate; using Xunit; namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X { public class InjectDirectiveTest { [Fact] public void InjectDirectivePass_Execute_DefinesProperty() { // Arrange var codeDocument = CreateDocument(@" @inject PropertyType PropertyName "); var engine = CreateEngine(); var pass = new InjectDirective.Pass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var @class = FindClassNode(irDocument); Assert.NotNull(@class); Assert.Equal(2, @class.Children.Count); var node = Assert.IsType<InjectIntermediateNode>(@class.Children[1]); Assert.Equal("PropertyType", node.TypeName); Assert.Equal("PropertyName", node.MemberName); } [Fact] public void InjectDirectivePass_Execute_DedupesPropertiesByName() { // Arrange var codeDocument = CreateDocument(@" @inject PropertyType PropertyName @inject PropertyType2 PropertyName "); var engine = CreateEngine(); var pass = new InjectDirective.Pass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var @class = FindClassNode(irDocument); Assert.NotNull(@class); Assert.Equal(2, @class.Children.Count); var node = Assert.IsType<InjectIntermediateNode>(@class.Children[1]); Assert.Equal("PropertyType2", node.TypeName); Assert.Equal("PropertyName", node.MemberName); } [Fact] public void InjectDirectivePass_Execute_ExpandsTModel_WithDynamic() { // Arrange var codeDocument = CreateDocument(@" @inject PropertyType<TModel> PropertyName "); var engine = CreateEngine(); var pass = new InjectDirective.Pass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var @class = FindClassNode(irDocument); Assert.NotNull(@class); Assert.Equal(2, @class.Children.Count); var node = Assert.IsType<InjectIntermediateNode>(@class.Children[1]); Assert.Equal("PropertyType<dynamic>", node.TypeName); Assert.Equal("PropertyName", node.MemberName); } [Fact] public void InjectDirectivePass_Execute_ExpandsTModel_WithModelTypeFirst() { // Arrange var codeDocument = CreateDocument(@" @model ModelType @inject PropertyType<TModel> PropertyName "); var engine = CreateEngine(); var pass = new InjectDirective.Pass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var @class = FindClassNode(irDocument); Assert.NotNull(@class); Assert.Equal(2, @class.Children.Count); var node = Assert.IsType<InjectIntermediateNode>(@class.Children[1]); Assert.Equal("PropertyType<ModelType>", node.TypeName); Assert.Equal("PropertyName", node.MemberName); } [Fact] public void InjectDirectivePass_Execute_ExpandsTModel_WithModelType() { // Arrange var codeDocument = CreateDocument(@" @inject PropertyType<TModel> PropertyName @model ModelType "); var engine = CreateEngine(); var pass = new InjectDirective.Pass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var @class = FindClassNode(irDocument); Assert.NotNull(@class); Assert.Equal(2, @class.Children.Count); var node = Assert.IsType<InjectIntermediateNode>(@class.Children[1]); Assert.Equal("PropertyType<ModelType>", node.TypeName); Assert.Equal("PropertyName", node.MemberName); } private RazorCodeDocument CreateDocument(string content) { var source = RazorSourceDocument.Create(content, "test.cshtml"); return RazorCodeDocument.Create(source); } private ClassDeclarationIntermediateNode FindClassNode(IntermediateNode node) { var visitor = new ClassNodeVisitor(); visitor.Visit(node); return visitor.Node; } private RazorEngine CreateEngine() { var configuration = RazorConfiguration.Create(RazorLanguageVersion.Version_1_1, "test", Array.Empty<RazorExtension>()); return RazorProjectEngine.Create(configuration, RazorProjectFileSystem.Empty, b => { // Notice we're not registering the InjectDirective.Pass here so we can run it on demand. b.AddDirective(InjectDirective.Directive); b.AddDirective(ModelDirective.Directive); }).Engine; } private DocumentIntermediateNode CreateIRDocument(RazorEngine engine, RazorCodeDocument codeDocument) { for (var i = 0; i < engine.Phases.Count; i++) { var phase = engine.Phases[i]; phase.Execute(codeDocument); if (phase is IRazorDocumentClassifierPhase) { break; } } return codeDocument.GetDocumentIntermediateNode(); } private string GetCSharpContent(IntermediateNode node) { var builder = new StringBuilder(); for (var i = 0; i < node.Children.Count; i++) { var child = node.Children[i] as IntermediateToken; if (child.Kind == TokenKind.CSharp) { builder.Append(child.Content); } } return builder.ToString(); } private class ClassNodeVisitor : IntermediateNodeWalker { public ClassDeclarationIntermediateNode Node { get; set; } public override void VisitClassDeclaration(ClassDeclarationIntermediateNode node) { Node = node; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace System.Numerics { /// <summary> /// A structure encapsulating three single precision floating point values and provides hardware accelerated methods. /// </summary> public partial struct Vector3 : IEquatable<Vector3>, IFormattable { #region Public Static Properties /// <summary> /// Returns the vector (0,0,0). /// </summary> public static Vector3 Zero { get { return new Vector3(); } } /// <summary> /// Returns the vector (1,1,1). /// </summary> public static Vector3 One { get { return new Vector3(1.0f, 1.0f, 1.0f); } } /// <summary> /// Returns the vector (1,0,0). /// </summary> public static Vector3 UnitX { get { return new Vector3(1.0f, 0.0f, 0.0f); } } /// <summary> /// Returns the vector (0,1,0). /// </summary> public static Vector3 UnitY { get { return new Vector3(0.0f, 1.0f, 0.0f); } } /// <summary> /// Returns the vector (0,0,1). /// </summary> public static Vector3 UnitZ { get { return new Vector3(0.0f, 0.0f, 1.0f); } } #endregion Public Static Properties #region Public Instance Methods /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int hash = this.X.GetHashCode(); hash = HashCodeHelper.CombineHashCodes(hash, this.Y.GetHashCode()); hash = HashCodeHelper.CombineHashCodes(hash, this.Z.GetHashCode()); return hash; } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Vector3 instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Vector3; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (obj == null || !(obj is Vector3)) return false; return Equals((Vector3)obj); } /// <summary> /// Returns a String representing this Vector3 instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector3 instance, using the specified format to format individual elements. /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector3 instance, using the specified format to format individual elements /// and the given IFormatProvider. /// </summary> /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public string ToString(string format, IFormatProvider formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator + " "; sb.Append("<"); sb.Append(((IFormattable)this.X).ToString(format, formatProvider)); sb.Append(separator); sb.Append(((IFormattable)this.Y).ToString(format, formatProvider)); sb.Append(separator); sb.Append(((IFormattable)this.Z).ToString(format, formatProvider)); sb.Append(">"); return sb.ToString(); } /// <summary> /// Returns the length of the vector. /// </summary> /// <returns>The vector's length.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { if (Vector.IsHardwareAccelerated) { float ls = Vector3.Dot(this, this); return (float)System.Math.Sqrt(ls); } else { float ls = X * X + Y * Y + Z * Z; return (float)System.Math.Sqrt(ls); } } /// <summary> /// Returns the length of the vector squared. This operation is cheaper than Length(). /// </summary> /// <returns>The vector's length squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(this, this); } else { return X * X + Y * Y + Z * Z; } } #endregion Public Instance Methods #region Public Static Methods /// <summary> /// Returns the Euclidean distance between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 difference = value1 - value2; float ls = Vector3.Dot(difference, difference); return (float)System.Math.Sqrt(ls); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float dz = value1.Z - value2.Z; float ls = dx * dx + dy * dy + dz * dz; return (float)System.Math.Sqrt((double)ls); } } /// <summary> /// Returns the Euclidean distance squared between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 difference = value1 - value2; return Vector3.Dot(difference, difference); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float dz = value1.Z - value2.Z; return dx * dx + dy * dy + dz * dz; } } /// <summary> /// Returns a vector with the same direction as the given vector, but with a length of 1. /// </summary> /// <param name="value">The vector to normalize.</param> /// <returns>The normalized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Normalize(Vector3 value) { if (Vector.IsHardwareAccelerated) { float length = value.Length(); return value / length; } else { float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z; float length = (float)System.Math.Sqrt(ls); return new Vector3(value.X / length, value.Y / length, value.Z / length); } } /// <summary> /// Computes the cross product of two vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The cross product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Cross(Vector3 vector1, Vector3 vector2) { return new Vector3( vector1.Y * vector2.Z - vector1.Z * vector2.Y, vector1.Z * vector2.X - vector1.X * vector2.Z, vector1.X * vector2.Y - vector1.Y * vector2.X); } /// <summary> /// Returns the reflection of a vector off a suface that has the specified normal. /// </summary> /// <param name="vector">The source vector.</param> /// <param name="normal">The normal of the surface being reflected off.</param> /// <returns>The reflected vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Reflect(Vector3 vector, Vector3 normal) { if (Vector.IsHardwareAccelerated) { float dot = Vector3.Dot(vector, normal); Vector3 temp = normal * dot * 2f; return vector - temp; } else { float dot = vector.X * normal.X + vector.Y * normal.Y + vector.Z * normal.Z; float tempX = normal.X * dot * 2f; float tempY = normal.Y * dot * 2f; float tempZ = normal.Z * dot * 2f; return new Vector3(vector.X - tempX, vector.Y - tempY, vector.Z - tempZ); } } /// <summary> /// Restricts a vector between a min and max value. /// </summary> /// <param name="value1">The source vector.</param> /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> /// <returns>The restricted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { // This compare order is very important!!! // We must follow HLSL behavior in the case user specfied min value is bigger than max value. float x = value1.X; x = (x > max.X) ? max.X : x; x = (x < min.X) ? min.X : x; float y = value1.Y; y = (y > max.Y) ? max.Y : y; y = (y < min.Y) ? min.Y : y; float z = value1.Z; z = (z > max.Z) ? max.Z : z; z = (z < min.Z) ? min.Z : z; return new Vector3(x, y, z); } /// <summary> /// Linearly interpolates between two vectors based on the given weighting. /// </summary> /// <param name="value1">The first source vector.</param> /// <param name="value2">The second source vector.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param> /// <returns>The interpolated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { if (Vector.IsHardwareAccelerated) { Vector3 firstInfluence = value1 * (1f - amount); Vector3 secondInfluence = value2 * amount; return firstInfluence + secondInfluence; } else { return new Vector3( value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount, value1.Z + (value2.Z - value1.Z) * amount); } } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector3( position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix) { return new Vector3( normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31, normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32, normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33); } /// <summary> /// Transforms a vector by the given Quaternion rotation value. /// </summary> /// <param name="value">The source vector to be rotated.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 value, Quaternion rotation) { float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wx2 = rotation.W * x2; float wy2 = rotation.W * y2; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float yz2 = rotation.Y * z2; float zz2 = rotation.Z * z2; return new Vector3( value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2), value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2), value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2)); } #endregion Public Static Methods #region Public operator methods // All these methods should be inlined as they are implemented // over JIT intrinsics /// <summary> /// Adds two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Add(Vector3 left, Vector3 right) { return left + right; } /// <summary> /// Subtracts the second vector from the first. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Subtract(Vector3 left, Vector3 right) { return left - right; } /// <summary> /// Multiplies two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The product vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Vector3 right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Single right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The scalar value.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Single left, Vector3 right) { return left * right; } /// <summary> /// Divides the first vector by the second. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The vector resulting from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Vector3 right) { return left / right; } /// <summary> /// Divides the vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="divisor">The scalar value.</param> /// <returns>The result of the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Single divisor) { return left / divisor; } /// <summary> /// Negates a given vector. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Negate(Vector3 value) { return -value; } #endregion Public operator methods } }
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System; using System.Collections.Generic; using Gvr.Internal; /// The GvrViewer object communicates with the head-mounted display. /// Is is repsonsible for: /// - Querying the device for viewing parameters /// - Retrieving the latest head tracking data /// - Providing the rendered scene to the device for distortion correction (optional) /// /// There should only be one of these in a scene. An instance will be generated automatically /// by this script at runtime, or you can add one via the Editor if you wish to customize /// its starting properties. [AddComponentMenu("GoogleVR/GvrViewer")] public class GvrViewer : MonoBehaviour { /// The singleton instance of the GvrViewer class. public static GvrViewer Instance { get { #if UNITY_EDITOR if (instance == null && !Application.isPlaying) { instance = UnityEngine.Object.FindObjectOfType<GvrViewer>(); } #endif if (instance == null) { Debug.LogError("No GvrViewer instance found. Ensure one exists in the scene, or call " + "GvrViewer.Create() at startup to generate one.\n" + "If one does exist but hasn't called Awake() yet, " + "then this error is due to order-of-initialization.\n" + "In that case, consider moving " + "your first reference to GvrViewer.Instance to a later point in time.\n" + "If exiting the scene, this indicates that the GvrViewer object has already " + "been destroyed."); } return instance; } } private static GvrViewer instance = null; /// Generate a GvrViewer instance. Takes no action if one already exists. public static void Create() { if (instance == null && UnityEngine.Object.FindObjectOfType<GvrViewer>() == null) { Debug.Log("Creating GvrViewer object"); var go = new GameObject("GvrViewer", typeof(GvrViewer)); go.transform.localPosition = Vector3.zero; // sdk will be set by Awake(). } } /// The StereoController instance attached to the main camera, or null if there is none. /// @note Cached for performance. public static StereoController Controller { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR Camera camera = Camera.main; // Cache for performance, if possible. if (camera != currentMainCamera || currentController == null) { currentMainCamera = camera; currentController = camera.GetComponent<StereoController>(); } return currentController; #else return null; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } private static StereoController currentController; private static Camera currentMainCamera; /// Determine whether the scene renders in stereo or mono. /// Supported only for versions of Unity *without* the GVR integration. /// VRModeEnabled will be a no-op for versions of Unity with the GVR integration. /// _True_ means to render in stereo, and _false_ means to render in mono. public bool VRModeEnabled { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR return vrModeEnabled; #else return UnityEngine.VR.VRSettings.enabled; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } set { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR if (value != vrModeEnabled && device != null) { device.SetVRModeEnabled(value); } vrModeEnabled = value; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } // Ignore private field is assigned but its value is never used compile warning. #pragma warning disable 414 [SerializeField] private bool vrModeEnabled = true; #pragma warning restore 414 /// Methods for performing lens distortion correction. public enum DistortionCorrectionMethod { None, ///< No distortion correction Native, ///< Use the native C++ plugin Unity, ///< Perform distortion correction in Unity (recommended) } /// Determines the distortion correction method used by the SDK to render the /// #StereoScreen texture on the phone. If _Native_ is selected but not supported /// by the device, the _Unity_ method will be used instead. public DistortionCorrectionMethod DistortionCorrection { get { return distortionCorrection; } set { if (device != null && device.RequiresNativeDistortionCorrection()) { value = DistortionCorrectionMethod.Native; } if (value != distortionCorrection && device != null) { device.SetDistortionCorrectionEnabled(value == DistortionCorrectionMethod.Native && NativeDistortionCorrectionSupported); device.UpdateScreenData(); } distortionCorrection = value; } } [SerializeField] #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR private DistortionCorrectionMethod distortionCorrection = DistortionCorrectionMethod.Native; #else private DistortionCorrectionMethod distortionCorrection = DistortionCorrectionMethod.Unity; #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR /// The native SDK will apply a neck offset to the head tracking, resulting in /// a more realistic model of a person's head position. This control determines /// the scale factor of the offset. To turn off the neck model, set it to 0, and /// to turn it all on, set to 1. Intermediate values can be used to animate from /// on to off or vice versa. public float NeckModelScale { get { return neckModelScale; } set { value = Mathf.Clamp01(value); if (!Mathf.Approximately(value, neckModelScale) && device != null) { device.SetNeckModelScale(value); } neckModelScale = value; } } [SerializeField] private float neckModelScale = 0.0f; #if UNITY_EDITOR /// Restores level head tilt in when playing in the Unity Editor after you /// release the Ctrl key. public bool autoUntiltHead = true; /// @cond /// Use unity remote as the input source. public bool UseUnityRemoteInput = false; /// @endcond /// The screen size to emulate when testing in the Unity Editor. public GvrProfile.ScreenSizes ScreenSize { get { return screenSize; } set { if (value != screenSize) { screenSize = value; if (device != null) { device.UpdateScreenData(); } } } } [SerializeField] private GvrProfile.ScreenSizes screenSize = GvrProfile.ScreenSizes.Nexus5; /// The viewer type to emulate when testing in the Unity Editor. public GvrProfile.ViewerTypes ViewerType { get { return viewerType; } set { if (value != viewerType) { viewerType = value; if (device != null) { device.UpdateScreenData(); } } } } [SerializeField] private GvrProfile.ViewerTypes viewerType = GvrProfile.ViewerTypes.CardboardMay2015; #endif // The VR device that will be providing input data. private static BaseVRDevice device; /// Whether native distortion correction functionality is supported by the VR device. public bool NativeDistortionCorrectionSupported { get; private set; } /// Whether the VR device supports showing a native UI layer, for example for settings. public bool NativeUILayerSupported { get; private set; } /// Scales the resolution of the #StereoScreen. Set to less than 1.0 to increase /// rendering speed while decreasing sharpness, or greater than 1.0 to do the /// opposite. public float StereoScreenScale { get { return stereoScreenScale; } set { value = Mathf.Clamp(value, 0.1f, 10.0f); // Sanity. if (stereoScreenScale != value) { stereoScreenScale = value; StereoScreen = null; } } } [SerializeField] private float stereoScreenScale = 1; /// The texture that Unity renders the scene to. After the frame has been rendered, /// this texture is drawn to the screen with a lens distortion correction effect. /// The texture size is based on the size of the screen, the lens distortion /// parameters, and the #StereoScreenScale factor. public RenderTexture StereoScreen { get { // Don't need it except for distortion correction. if (distortionCorrection == DistortionCorrectionMethod.None || !VRModeEnabled) { return null; } if (stereoScreen == null) { // Create on demand. StereoScreen = device.CreateStereoScreen(); // Note: uses set{} } return stereoScreen; } set { if (value == stereoScreen) { return; } if (stereoScreen != null) { stereoScreen.Release(); } stereoScreen = value; if (OnStereoScreenChanged != null) { OnStereoScreenChanged(stereoScreen); } } } private static RenderTexture stereoScreen = null; /// A callback for notifications that the StereoScreen property has changed. public delegate void StereoScreenChangeDelegate(RenderTexture newStereoScreen); /// Emitted when the StereoScreen property has changed. public event StereoScreenChangeDelegate OnStereoScreenChanged; /// Describes the current device, including phone screen. public GvrProfile Profile { get { return device.Profile; } } /// Returns true if GoogleVR is NOT supported natively. /// That is, this version of Unity does not have native integration but supports /// the GVR SDK (5.2, 5.3), or the current VR player is the in-editor emulator. public static bool NoNativeGVRSupport { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR return true; #else return false; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } /// Distinguish the stereo eyes. public enum Eye { Left, ///< The left eye Right, ///< The right eye Center ///< The "center" eye (unused) } /// When retrieving the #Projection and #Viewport properties, specifies /// whether you want the values as seen through the viewer's lenses (`Distorted`) or /// as if no lenses were present (`Undistorted`). public enum Distortion { Distorted, ///< Viewing through the lenses Undistorted ///< No lenses } /// The transformation of head from origin in the tracking system. public Pose3D HeadPose { get { return device.GetHeadPose(); } } /// The transformation from head to eye. public Pose3D EyePose(Eye eye) { return device.GetEyePose(eye); } /// The projection matrix for a given eye. /// This matrix is an off-axis perspective projection with near and far /// clipping planes of 1m and 1000m, respectively. The GvrEye script /// takes care of adjusting the matrix for its particular camera. public Matrix4x4 Projection(Eye eye, Distortion distortion = Distortion.Distorted) { return device.GetProjection(eye, distortion); } /// The screen space viewport that the camera for the specified eye should render into. /// In the _Distorted_ case, this will be either the left or right half of the `StereoScreen` /// render texture. In the _Undistorted_ case, it refers to the actual rectangle on the /// screen that the eye can see. public Rect Viewport(Eye eye, Distortion distortion = Distortion.Distorted) { return device.GetViewport(eye, distortion); } /// The distance range from the viewer in user-space meters where objects may be viewed /// comfortably in stereo. If the center of interest falls outside this range, the stereo /// eye separation should be adjusted to keep the onscreen disparity within the limits set /// by this range. If native integration is not supported, or the current VR player is the /// in-editor emulator, StereoController will handle this if the _checkStereoComfort_ is /// enabled. public Vector2 ComfortableViewingRange { get { return defaultComfortableViewingRange; } } private readonly Vector2 defaultComfortableViewingRange = new Vector2(0.4f, 100000.0f); /// @cond // Optional. Set to a URI obtained from the Google Cardboard profile generator at // https://www.google.com/get/cardboard/viewerprofilegenerator/ // Example: Cardboard I/O 2015 viewer profile //public Uri DefaultDeviceProfile = new Uri("http://google.com/cardboard/cfg?p=CgZHb29nbGUSEkNhcmRib2FyZCBJL08gMjAxNR0J-SA9JQHegj0qEAAAcEIAAHBCAABwQgAAcEJYADUpXA89OghX8as-YrENP1AAYAM"); public Uri DefaultDeviceProfile = null; /// @endcond private void InitDevice() { if (device != null) { device.Destroy(); } device = BaseVRDevice.GetDevice(); device.Init(); List<string> diagnostics = new List<string>(); NativeDistortionCorrectionSupported = device.SupportsNativeDistortionCorrection(diagnostics); if (diagnostics.Count > 0) { Debug.LogWarning("Built-in distortion correction disabled. Causes: [" + String.Join("; ", diagnostics.ToArray()) + "]"); } diagnostics.Clear(); NativeUILayerSupported = device.SupportsNativeUILayer(diagnostics); if (diagnostics.Count > 0) { Debug.LogWarning("Built-in UI layer disabled. Causes: [" + String.Join("; ", diagnostics.ToArray()) + "]"); } if (DefaultDeviceProfile != null) { device.SetDefaultDeviceProfile(DefaultDeviceProfile); } device.SetDistortionCorrectionEnabled(distortionCorrection == DistortionCorrectionMethod.Native && NativeDistortionCorrectionSupported); device.SetNeckModelScale(neckModelScale); #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR device.SetVRModeEnabled(vrModeEnabled); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR device.UpdateScreenData(); } /// @note Each scene load causes an OnDestroy of the current SDK, followed /// by and Awake of a new one. That should not cause the underlying native /// code to hiccup. Exception: developer may call Application.DontDestroyOnLoad /// on the SDK if they want it to survive across scene loads. void Awake() { if (instance == null) { instance = this; } if (instance != this) { Debug.LogError("There must be only one GvrViewer object in a scene."); UnityEngine.Object.DestroyImmediate(this); return; } #if UNITY_IOS Application.targetFrameRate = 60; #endif // Prevent the screen from dimming / sleeping Screen.sleepTimeout = SleepTimeout.NeverSleep; InitDevice(); StereoScreen = null; // Set up stereo pre- and post-render stages only for: // - Unity without the GVR native integration // - In-editor emulator when the current platform is Android or iOS. // Since GVR is the only valid VR SDK on Android or iOS, this prevents it from // interfering with VR SDKs on other platforms. #if !UNITY_HAS_GOOGLEVR || (UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)) AddPrePostRenderStages(); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } void Start() { // Set up stereo controller only for: // - Unity without the GVR native integration // - In-editor emulator when the current platform is Android or iOS. // Since GVR is the only valid VR SDK on Android or iOS, this prevents it from // interfering with VR SDKs on other platforms. #if !UNITY_HAS_GOOGLEVR || (UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)) AddStereoControllerToCameras(); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR void AddPrePostRenderStages() { var preRender = UnityEngine.Object.FindObjectOfType<GvrPreRender>(); if (preRender == null) { var go = new GameObject("PreRender", typeof(GvrPreRender)); go.SendMessage("Reset"); go.transform.parent = transform; } var postRender = UnityEngine.Object.FindObjectOfType<GvrPostRender>(); if (postRender == null) { var go = new GameObject("PostRender", typeof(GvrPostRender)); go.SendMessage("Reset"); go.transform.parent = transform; } } #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR /// Whether the viewer's trigger was pulled. True for exactly one complete frame /// after each pull. public bool Triggered { get; private set; } /// Whether the viewer was tilted on its side. True for exactly one complete frame /// after each tilt. Whether and how to respond to this event is up to the app. public bool Tilted { get; private set; } /// Whether the viewer profile has possibly changed. This is meant to indicate /// that a new QR code has been scanned, although currently it is actually set any time the /// application is unpaused, whether it was due to a profile change or not. True for one /// frame. public bool ProfileChanged { get; private set; } /// Whether the user has pressed the "VR Back Button", which on Android should be treated the /// same as the normal system Back Button, although you can respond to either however you want /// in your app. public bool BackButtonPressed { get; private set; } // Only call device.UpdateState() once per frame. private int updatedToFrame = 0; /// Reads the latest tracking data from the phone. This must be /// called before accessing any of the poses and matrices above. /// /// Multiple invocations per frame are OK: Subsequent calls merely yield the /// cached results of the first call. To minimize latency, it should be first /// called later in the frame (for example, in `LateUpdate`) if possible. public void UpdateState() { if (updatedToFrame != Time.frameCount) { updatedToFrame = Time.frameCount; device.UpdateState(); if (device.profileChanged) { if (distortionCorrection != DistortionCorrectionMethod.Native && device.RequiresNativeDistortionCorrection()) { DistortionCorrection = DistortionCorrectionMethod.Native; } if (stereoScreen != null && device.ShouldRecreateStereoScreen(stereoScreen.width, stereoScreen.height)) { StereoScreen = null; } } DispatchEvents(); } } private void DispatchEvents() { // Update flags first by copying from device and other inputs. Triggered = Input.GetMouseButtonDown(0); #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Triggered |= GvrController.ClickButtonDown; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Tilted = device.tilted; ProfileChanged = device.profileChanged; BackButtonPressed = device.backButtonPressed || Input.GetKeyDown(KeyCode.Escape); // Reset device flags. device.tilted = false; device.profileChanged = false; device.backButtonPressed = false; } /// Presents the #StereoScreen to the device for distortion correction and display. /// @note This function is only used if #DistortionCorrection is set to _Native_, /// and it only has an effect if the device supports it. public void PostRender(RenderTexture stereoScreen) { if (NativeDistortionCorrectionSupported && stereoScreen != null && stereoScreen.IsCreated()) { device.PostRender(stereoScreen); } } /// Resets the tracker so that the user's current direction becomes forward. public void Recenter() { device.Recenter(); } /// Launch the device pairing and setup dialog. public void ShowSettingsDialog() { device.ShowSettingsDialog(); } #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR /// Add a StereoController to any camera that does not have a Render Texture (meaning it is /// rendering to the screen). public static void AddStereoControllerToCameras() { for (int i = 0; i < Camera.allCameras.Length; i++) { Camera camera = Camera.allCameras[i]; if (camera.targetTexture == null && camera.cullingMask != 0 && camera.GetComponent<StereoController>() == null && camera.GetComponent<GvrEye>() == null && camera.GetComponent<GvrPreRender>() == null && camera.GetComponent<GvrPostRender>() == null) { camera.gameObject.AddComponent<StereoController>(); } } } #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR void OnEnable() { #if UNITY_EDITOR // This can happen if you edit code while the editor is in Play mode. if (device == null) { InitDevice(); } #endif device.OnPause(false); } void OnDisable() { device.OnPause(true); } void OnApplicationPause(bool pause) { device.OnPause(pause); } void OnApplicationFocus(bool focus) { device.OnFocus(focus); } void OnApplicationQuit() { device.OnApplicationQuit(); } void OnDestroy() { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR VRModeEnabled = false; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR if (device != null) { device.Destroy(); } if (instance == this) { instance = null; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the GuardiaTipoPractica class. /// </summary> [Serializable] public partial class GuardiaTipoPracticaCollection : ActiveList<GuardiaTipoPractica, GuardiaTipoPracticaCollection> { public GuardiaTipoPracticaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>GuardiaTipoPracticaCollection</returns> public GuardiaTipoPracticaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { GuardiaTipoPractica o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Guardia_TipoPracticas table. /// </summary> [Serializable] public partial class GuardiaTipoPractica : ActiveRecord<GuardiaTipoPractica>, IActiveRecord { #region .ctors and Default Settings public GuardiaTipoPractica() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public GuardiaTipoPractica(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public GuardiaTipoPractica(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public GuardiaTipoPractica(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Guardia_TipoPracticas", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "id"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarIdPadre = new TableSchema.TableColumn(schema); colvarIdPadre.ColumnName = "idPadre"; colvarIdPadre.DataType = DbType.Int32; colvarIdPadre.MaxLength = 0; colvarIdPadre.AutoIncrement = false; colvarIdPadre.IsNullable = true; colvarIdPadre.IsPrimaryKey = false; colvarIdPadre.IsForeignKey = false; colvarIdPadre.IsReadOnly = false; colvarIdPadre.DefaultSetting = @""; colvarIdPadre.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPadre); TableSchema.TableColumn colvarClase = new TableSchema.TableColumn(schema); colvarClase.ColumnName = "clase"; colvarClase.DataType = DbType.Int32; colvarClase.MaxLength = 0; colvarClase.AutoIncrement = false; colvarClase.IsNullable = true; colvarClase.IsPrimaryKey = false; colvarClase.IsForeignKey = false; colvarClase.IsReadOnly = false; colvarClase.DefaultSetting = @""; colvarClase.ForeignKeyTableName = ""; schema.Columns.Add(colvarClase); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 100; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarUrlIcono = new TableSchema.TableColumn(schema); colvarUrlIcono.ColumnName = "urlIcono"; colvarUrlIcono.DataType = DbType.AnsiString; colvarUrlIcono.MaxLength = 200; colvarUrlIcono.AutoIncrement = false; colvarUrlIcono.IsNullable = true; colvarUrlIcono.IsPrimaryKey = false; colvarUrlIcono.IsForeignKey = false; colvarUrlIcono.IsReadOnly = false; colvarUrlIcono.DefaultSetting = @""; colvarUrlIcono.ForeignKeyTableName = ""; schema.Columns.Add(colvarUrlIcono); TableSchema.TableColumn colvarVinculadoPrestaciones = new TableSchema.TableColumn(schema); colvarVinculadoPrestaciones.ColumnName = "vinculadoPrestaciones"; colvarVinculadoPrestaciones.DataType = DbType.Boolean; colvarVinculadoPrestaciones.MaxLength = 0; colvarVinculadoPrestaciones.AutoIncrement = false; colvarVinculadoPrestaciones.IsNullable = true; colvarVinculadoPrestaciones.IsPrimaryKey = false; colvarVinculadoPrestaciones.IsForeignKey = false; colvarVinculadoPrestaciones.IsReadOnly = false; colvarVinculadoPrestaciones.DefaultSetting = @""; colvarVinculadoPrestaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarVinculadoPrestaciones); TableSchema.TableColumn colvarAdvertencia = new TableSchema.TableColumn(schema); colvarAdvertencia.ColumnName = "advertencia"; colvarAdvertencia.DataType = DbType.AnsiString; colvarAdvertencia.MaxLength = -1; colvarAdvertencia.AutoIncrement = false; colvarAdvertencia.IsNullable = true; colvarAdvertencia.IsPrimaryKey = false; colvarAdvertencia.IsForeignKey = false; colvarAdvertencia.IsReadOnly = false; colvarAdvertencia.DefaultSetting = @""; colvarAdvertencia.ForeignKeyTableName = ""; schema.Columns.Add(colvarAdvertencia); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Guardia_TipoPracticas",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("IdPadre")] [Bindable(true)] public int? IdPadre { get { return GetColumnValue<int?>(Columns.IdPadre); } set { SetColumnValue(Columns.IdPadre, value); } } [XmlAttribute("Clase")] [Bindable(true)] public int? Clase { get { return GetColumnValue<int?>(Columns.Clase); } set { SetColumnValue(Columns.Clase, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("UrlIcono")] [Bindable(true)] public string UrlIcono { get { return GetColumnValue<string>(Columns.UrlIcono); } set { SetColumnValue(Columns.UrlIcono, value); } } [XmlAttribute("VinculadoPrestaciones")] [Bindable(true)] public bool? VinculadoPrestaciones { get { return GetColumnValue<bool?>(Columns.VinculadoPrestaciones); } set { SetColumnValue(Columns.VinculadoPrestaciones, value); } } [XmlAttribute("Advertencia")] [Bindable(true)] public string Advertencia { get { return GetColumnValue<string>(Columns.Advertencia); } set { SetColumnValue(Columns.Advertencia, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varId,int? varIdPadre,int? varClase,string varNombre,string varUrlIcono,bool? varVinculadoPrestaciones,string varAdvertencia) { GuardiaTipoPractica item = new GuardiaTipoPractica(); item.Id = varId; item.IdPadre = varIdPadre; item.Clase = varClase; item.Nombre = varNombre; item.UrlIcono = varUrlIcono; item.VinculadoPrestaciones = varVinculadoPrestaciones; item.Advertencia = varAdvertencia; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varId,int? varIdPadre,int? varClase,string varNombre,string varUrlIcono,bool? varVinculadoPrestaciones,string varAdvertencia) { GuardiaTipoPractica item = new GuardiaTipoPractica(); item.Id = varId; item.IdPadre = varIdPadre; item.Clase = varClase; item.Nombre = varNombre; item.UrlIcono = varUrlIcono; item.VinculadoPrestaciones = varVinculadoPrestaciones; item.Advertencia = varAdvertencia; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdPadreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn ClaseColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn UrlIconoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn VinculadoPrestacionesColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn AdvertenciaColumn { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"id"; public static string IdPadre = @"idPadre"; public static string Clase = @"clase"; public static string Nombre = @"nombre"; public static string UrlIcono = @"urlIcono"; public static string VinculadoPrestaciones = @"vinculadoPrestaciones"; public static string Advertencia = @"advertencia"; } #endregion #region Update PK Collections #endregion #region Deep Save #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. #pragma warning disable 0184 using System; using System.Runtime.InteropServices; internal class Program { private static void Eval(int testCase, bool b1, bool b2) { if (b1 != b2) throw new Exception(string.Format("case {0:000} failed: v1 {1} v2 {2}", testCase, b1, b2)); } private static void TestCase0001() { { IntE v = default(IntE); Enum o = v; Eval(0001, o is IntE, true); Eval(0002, o is IntE[], false); Eval(0003, o is IntE?, true); Eval(0004, o is IntE?[], false); Eval(0005, o is ByteE, false); Eval(0006, o is ByteE[], false); Eval(0007, o is ByteE?, false); Eval(0008, o is ByteE?[], false); Eval(0009, o is LongE, false); Eval(0010, o is LongE[], false); Eval(0011, o is LongE?, false); Eval(0012, o is LongE?[], false); Eval(0013, o is object, true); Eval(0014, o is object[], false); Eval(0015, o is string, false); Eval(0016, o is string[], false); Eval(0017, o is ValueType, true); Eval(0018, o is ValueType[], false); Eval(0019, o is Array, false); Eval(0020, o is Array[], false); Eval(0021, o is Enum, true); Eval(0022, o is Enum[], false); Eval(0023, o is Delegate, false); Eval(0024, o is Delegate[], false); Eval(0025, o is MulticastDelegate, false); Eval(0026, o is MulticastDelegate[], false); Eval(0027, o is IEmpty, false); Eval(0028, o is IEmpty[], false); Eval(0029, o is INotEmpty, false); Eval(0030, o is INotEmpty[], false); // Eval(0031, o is IEmptyGen<int>, false); // Eval(0032, o is IEmptyGen<int>[], false); // Eval(0033, o is INotEmptyGen<int>, false); // Eval(0034, o is INotEmptyGen<int>[], false); Eval(0035, o is SimpleDelegate, false); Eval(0036, o is SimpleDelegate[], false); // Eval(0037, o is GenericDelegate<int>, false); // Eval(0038, o is GenericDelegate<int>[], false); Eval(0039, o is EmptyClass, false); Eval(0040, o is EmptyClass[], false); Eval(0041, o is NotEmptyClass, false); Eval(0042, o is NotEmptyClass[], false); // Eval(0043, o is EmptyClassGen<int>, false); // Eval(0044, o is EmptyClassGen<int>[], false); // Eval(0045, o is NotEmptyClassGen<Guid>, false); // Eval(0046, o is NotEmptyClassGen<Guid>[], false); // Eval(0047, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0048, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0049, o is NestedClass, false); Eval(0050, o is NestedClass[], false); // Eval(0051, o is NestedClassGen<Decimal>, false); // Eval(0052, o is NestedClassGen<Decimal>[], false); Eval(0053, o is ImplementOneInterfaceC, false); Eval(0054, o is ImplementOneInterfaceC[], false); Eval(0055, o is ImplementTwoInterfaceC, false); Eval(0056, o is ImplementTwoInterfaceC[], false); // Eval(0057, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0058, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0059, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0060, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0061, o is ImplementAllInterfaceC<int>, false); // Eval(0062, o is ImplementAllInterfaceC<int>[], false); Eval(0063, o is SealedClass, false); Eval(0064, o is SealedClass[], false); } { IntE? v = default(IntE); Enum o = v; Eval(0065, o is IntE, true); Eval(0066, o is IntE[], false); Eval(0067, o is IntE?, true); Eval(0068, o is IntE?[], false); Eval(0069, o is ByteE, false); Eval(0070, o is ByteE[], false); Eval(0071, o is ByteE?, false); Eval(0072, o is ByteE?[], false); Eval(0073, o is LongE, false); Eval(0074, o is LongE[], false); Eval(0075, o is LongE?, false); Eval(0076, o is LongE?[], false); Eval(0077, o is object, true); Eval(0078, o is object[], false); Eval(0079, o is string, false); Eval(0080, o is string[], false); Eval(0081, o is ValueType, true); Eval(0082, o is ValueType[], false); Eval(0083, o is Array, false); Eval(0084, o is Array[], false); Eval(0085, o is Enum, true); Eval(0086, o is Enum[], false); Eval(0087, o is Delegate, false); Eval(0088, o is Delegate[], false); Eval(0089, o is MulticastDelegate, false); Eval(0090, o is MulticastDelegate[], false); Eval(0091, o is IEmpty, false); Eval(0092, o is IEmpty[], false); Eval(0093, o is INotEmpty, false); Eval(0094, o is INotEmpty[], false); // Eval(0095, o is IEmptyGen<int>, false); // Eval(0096, o is IEmptyGen<int>[], false); // Eval(0097, o is INotEmptyGen<int>, false); // Eval(0098, o is INotEmptyGen<int>[], false); Eval(0099, o is SimpleDelegate, false); Eval(0100, o is SimpleDelegate[], false); // Eval(0101, o is GenericDelegate<int>, false); // Eval(0102, o is GenericDelegate<int>[], false); Eval(0103, o is EmptyClass, false); Eval(0104, o is EmptyClass[], false); Eval(0105, o is NotEmptyClass, false); Eval(0106, o is NotEmptyClass[], false); // Eval(0107, o is EmptyClassGen<int>, false); // Eval(0108, o is EmptyClassGen<int>[], false); // Eval(0109, o is NotEmptyClassGen<Guid>, false); // Eval(0110, o is NotEmptyClassGen<Guid>[], false); // Eval(0111, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0112, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0113, o is NestedClass, false); Eval(0114, o is NestedClass[], false); // Eval(0115, o is NestedClassGen<Decimal>, false); // Eval(0116, o is NestedClassGen<Decimal>[], false); Eval(0117, o is ImplementOneInterfaceC, false); Eval(0118, o is ImplementOneInterfaceC[], false); Eval(0119, o is ImplementTwoInterfaceC, false); Eval(0120, o is ImplementTwoInterfaceC[], false); // Eval(0121, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0122, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0123, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0124, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0125, o is ImplementAllInterfaceC<int>, false); // Eval(0126, o is ImplementAllInterfaceC<int>[], false); Eval(0127, o is SealedClass, false); Eval(0128, o is SealedClass[], false); } { IntE? v = default(IntE?); Enum o = v; Eval(0129, o is IntE, false); Eval(0130, o is IntE[], false); Eval(0131, o is IntE?, false); Eval(0132, o is IntE?[], false); Eval(0133, o is ByteE, false); Eval(0134, o is ByteE[], false); Eval(0135, o is ByteE?, false); Eval(0136, o is ByteE?[], false); Eval(0137, o is LongE, false); Eval(0138, o is LongE[], false); Eval(0139, o is LongE?, false); Eval(0140, o is LongE?[], false); Eval(0141, o is object, false); Eval(0142, o is object[], false); Eval(0143, o is string, false); Eval(0144, o is string[], false); Eval(0145, o is ValueType, false); Eval(0146, o is ValueType[], false); Eval(0147, o is Array, false); Eval(0148, o is Array[], false); Eval(0149, o is Enum, false); Eval(0150, o is Enum[], false); Eval(0151, o is Delegate, false); Eval(0152, o is Delegate[], false); Eval(0153, o is MulticastDelegate, false); Eval(0154, o is MulticastDelegate[], false); Eval(0155, o is IEmpty, false); Eval(0156, o is IEmpty[], false); Eval(0157, o is INotEmpty, false); Eval(0158, o is INotEmpty[], false); // Eval(0159, o is IEmptyGen<int>, false); // Eval(0160, o is IEmptyGen<int>[], false); // Eval(0161, o is INotEmptyGen<int>, false); // Eval(0162, o is INotEmptyGen<int>[], false); Eval(0163, o is SimpleDelegate, false); Eval(0164, o is SimpleDelegate[], false); // Eval(0165, o is GenericDelegate<int>, false); // Eval(0166, o is GenericDelegate<int>[], false); Eval(0167, o is EmptyClass, false); Eval(0168, o is EmptyClass[], false); Eval(0169, o is NotEmptyClass, false); Eval(0170, o is NotEmptyClass[], false); // Eval(0171, o is EmptyClassGen<int>, false); // Eval(0172, o is EmptyClassGen<int>[], false); // Eval(0173, o is NotEmptyClassGen<Guid>, false); // Eval(0174, o is NotEmptyClassGen<Guid>[], false); // Eval(0175, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0176, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0177, o is NestedClass, false); Eval(0178, o is NestedClass[], false); // Eval(0179, o is NestedClassGen<Decimal>, false); // Eval(0180, o is NestedClassGen<Decimal>[], false); Eval(0181, o is ImplementOneInterfaceC, false); Eval(0182, o is ImplementOneInterfaceC[], false); Eval(0183, o is ImplementTwoInterfaceC, false); Eval(0184, o is ImplementTwoInterfaceC[], false); // Eval(0185, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0186, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0187, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0188, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0189, o is ImplementAllInterfaceC<int>, false); // Eval(0190, o is ImplementAllInterfaceC<int>[], false); Eval(0191, o is SealedClass, false); Eval(0192, o is SealedClass[], false); } } // end of test case 0001 private static void TestCase0002() { { ByteE v = default(ByteE); Enum o = v; Eval(0193, o is IntE, false); Eval(0194, o is IntE[], false); Eval(0195, o is IntE?, false); Eval(0196, o is IntE?[], false); Eval(0197, o is ByteE, true); Eval(0198, o is ByteE[], false); Eval(0199, o is ByteE?, true); Eval(0200, o is ByteE?[], false); Eval(0201, o is LongE, false); Eval(0202, o is LongE[], false); Eval(0203, o is LongE?, false); Eval(0204, o is LongE?[], false); Eval(0205, o is object, true); Eval(0206, o is object[], false); Eval(0207, o is string, false); Eval(0208, o is string[], false); Eval(0209, o is ValueType, true); Eval(0210, o is ValueType[], false); Eval(0211, o is Array, false); Eval(0212, o is Array[], false); Eval(0213, o is Enum, true); Eval(0214, o is Enum[], false); Eval(0215, o is Delegate, false); Eval(0216, o is Delegate[], false); Eval(0217, o is MulticastDelegate, false); Eval(0218, o is MulticastDelegate[], false); Eval(0219, o is IEmpty, false); Eval(0220, o is IEmpty[], false); Eval(0221, o is INotEmpty, false); Eval(0222, o is INotEmpty[], false); // Eval(0223, o is IEmptyGen<int>, false); // Eval(0224, o is IEmptyGen<int>[], false); // Eval(0225, o is INotEmptyGen<int>, false); // Eval(0226, o is INotEmptyGen<int>[], false); Eval(0227, o is SimpleDelegate, false); Eval(0228, o is SimpleDelegate[], false); // Eval(0229, o is GenericDelegate<int>, false); // Eval(0230, o is GenericDelegate<int>[], false); Eval(0231, o is EmptyClass, false); Eval(0232, o is EmptyClass[], false); Eval(0233, o is NotEmptyClass, false); Eval(0234, o is NotEmptyClass[], false); // Eval(0235, o is EmptyClassGen<int>, false); // Eval(0236, o is EmptyClassGen<int>[], false); // Eval(0237, o is NotEmptyClassGen<Guid>, false); // Eval(0238, o is NotEmptyClassGen<Guid>[], false); // Eval(0239, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0240, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0241, o is NestedClass, false); Eval(0242, o is NestedClass[], false); // Eval(0243, o is NestedClassGen<Decimal>, false); // Eval(0244, o is NestedClassGen<Decimal>[], false); Eval(0245, o is ImplementOneInterfaceC, false); Eval(0246, o is ImplementOneInterfaceC[], false); Eval(0247, o is ImplementTwoInterfaceC, false); Eval(0248, o is ImplementTwoInterfaceC[], false); // Eval(0249, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0250, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0251, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0252, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0253, o is ImplementAllInterfaceC<int>, false); // Eval(0254, o is ImplementAllInterfaceC<int>[], false); Eval(0255, o is SealedClass, false); Eval(0256, o is SealedClass[], false); } { ByteE? v = default(ByteE); Enum o = v; Eval(0257, o is IntE, false); Eval(0258, o is IntE[], false); Eval(0259, o is IntE?, false); Eval(0260, o is IntE?[], false); Eval(0261, o is ByteE, true); Eval(0262, o is ByteE[], false); Eval(0263, o is ByteE?, true); Eval(0264, o is ByteE?[], false); Eval(0265, o is LongE, false); Eval(0266, o is LongE[], false); Eval(0267, o is LongE?, false); Eval(0268, o is LongE?[], false); Eval(0269, o is object, true); Eval(0270, o is object[], false); Eval(0271, o is string, false); Eval(0272, o is string[], false); Eval(0273, o is ValueType, true); Eval(0274, o is ValueType[], false); Eval(0275, o is Array, false); Eval(0276, o is Array[], false); Eval(0277, o is Enum, true); Eval(0278, o is Enum[], false); Eval(0279, o is Delegate, false); Eval(0280, o is Delegate[], false); Eval(0281, o is MulticastDelegate, false); Eval(0282, o is MulticastDelegate[], false); Eval(0283, o is IEmpty, false); Eval(0284, o is IEmpty[], false); Eval(0285, o is INotEmpty, false); Eval(0286, o is INotEmpty[], false); // Eval(0287, o is IEmptyGen<int>, false); // Eval(0288, o is IEmptyGen<int>[], false); // Eval(0289, o is INotEmptyGen<int>, false); // Eval(0290, o is INotEmptyGen<int>[], false); Eval(0291, o is SimpleDelegate, false); Eval(0292, o is SimpleDelegate[], false); // Eval(0293, o is GenericDelegate<int>, false); // Eval(0294, o is GenericDelegate<int>[], false); Eval(0295, o is EmptyClass, false); Eval(0296, o is EmptyClass[], false); Eval(0297, o is NotEmptyClass, false); Eval(0298, o is NotEmptyClass[], false); // Eval(0299, o is EmptyClassGen<int>, false); // Eval(0300, o is EmptyClassGen<int>[], false); // Eval(0301, o is NotEmptyClassGen<Guid>, false); // Eval(0302, o is NotEmptyClassGen<Guid>[], false); // Eval(0303, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0304, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0305, o is NestedClass, false); Eval(0306, o is NestedClass[], false); // Eval(0307, o is NestedClassGen<Decimal>, false); // Eval(0308, o is NestedClassGen<Decimal>[], false); Eval(0309, o is ImplementOneInterfaceC, false); Eval(0310, o is ImplementOneInterfaceC[], false); Eval(0311, o is ImplementTwoInterfaceC, false); Eval(0312, o is ImplementTwoInterfaceC[], false); // Eval(0313, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0314, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0315, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0316, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0317, o is ImplementAllInterfaceC<int>, false); // Eval(0318, o is ImplementAllInterfaceC<int>[], false); Eval(0319, o is SealedClass, false); Eval(0320, o is SealedClass[], false); } { ByteE? v = default(ByteE?); Enum o = v; Eval(0321, o is IntE, false); Eval(0322, o is IntE[], false); Eval(0323, o is IntE?, false); Eval(0324, o is IntE?[], false); Eval(0325, o is ByteE, false); Eval(0326, o is ByteE[], false); Eval(0327, o is ByteE?, false); Eval(0328, o is ByteE?[], false); Eval(0329, o is LongE, false); Eval(0330, o is LongE[], false); Eval(0331, o is LongE?, false); Eval(0332, o is LongE?[], false); Eval(0333, o is object, false); Eval(0334, o is object[], false); Eval(0335, o is string, false); Eval(0336, o is string[], false); Eval(0337, o is ValueType, false); Eval(0338, o is ValueType[], false); Eval(0339, o is Array, false); Eval(0340, o is Array[], false); Eval(0341, o is Enum, false); Eval(0342, o is Enum[], false); Eval(0343, o is Delegate, false); Eval(0344, o is Delegate[], false); Eval(0345, o is MulticastDelegate, false); Eval(0346, o is MulticastDelegate[], false); Eval(0347, o is IEmpty, false); Eval(0348, o is IEmpty[], false); Eval(0349, o is INotEmpty, false); Eval(0350, o is INotEmpty[], false); // Eval(0351, o is IEmptyGen<int>, false); // Eval(0352, o is IEmptyGen<int>[], false); // Eval(0353, o is INotEmptyGen<int>, false); // Eval(0354, o is INotEmptyGen<int>[], false); Eval(0355, o is SimpleDelegate, false); Eval(0356, o is SimpleDelegate[], false); // Eval(0357, o is GenericDelegate<int>, false); // Eval(0358, o is GenericDelegate<int>[], false); Eval(0359, o is EmptyClass, false); Eval(0360, o is EmptyClass[], false); Eval(0361, o is NotEmptyClass, false); Eval(0362, o is NotEmptyClass[], false); // Eval(0363, o is EmptyClassGen<int>, false); // Eval(0364, o is EmptyClassGen<int>[], false); // Eval(0365, o is NotEmptyClassGen<Guid>, false); // Eval(0366, o is NotEmptyClassGen<Guid>[], false); // Eval(0367, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0368, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0369, o is NestedClass, false); Eval(0370, o is NestedClass[], false); // Eval(0371, o is NestedClassGen<Decimal>, false); // Eval(0372, o is NestedClassGen<Decimal>[], false); Eval(0373, o is ImplementOneInterfaceC, false); Eval(0374, o is ImplementOneInterfaceC[], false); Eval(0375, o is ImplementTwoInterfaceC, false); Eval(0376, o is ImplementTwoInterfaceC[], false); // Eval(0377, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0378, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0379, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0380, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0381, o is ImplementAllInterfaceC<int>, false); // Eval(0382, o is ImplementAllInterfaceC<int>[], false); Eval(0383, o is SealedClass, false); Eval(0384, o is SealedClass[], false); } } // end of test case 0002 private static void TestCase0003() { { LongE v = default(LongE); Enum o = v; Eval(0385, o is IntE, false); Eval(0386, o is IntE[], false); Eval(0387, o is IntE?, false); Eval(0388, o is IntE?[], false); Eval(0389, o is ByteE, false); Eval(0390, o is ByteE[], false); Eval(0391, o is ByteE?, false); Eval(0392, o is ByteE?[], false); Eval(0393, o is LongE, true); Eval(0394, o is LongE[], false); Eval(0395, o is LongE?, true); Eval(0396, o is LongE?[], false); Eval(0397, o is object, true); Eval(0398, o is object[], false); Eval(0399, o is string, false); Eval(0400, o is string[], false); Eval(0401, o is ValueType, true); Eval(0402, o is ValueType[], false); Eval(0403, o is Array, false); Eval(0404, o is Array[], false); Eval(0405, o is Enum, true); Eval(0406, o is Enum[], false); Eval(0407, o is Delegate, false); Eval(0408, o is Delegate[], false); Eval(0409, o is MulticastDelegate, false); Eval(0410, o is MulticastDelegate[], false); Eval(0411, o is IEmpty, false); Eval(0412, o is IEmpty[], false); Eval(0413, o is INotEmpty, false); Eval(0414, o is INotEmpty[], false); // Eval(0415, o is IEmptyGen<int>, false); // Eval(0416, o is IEmptyGen<int>[], false); // Eval(0417, o is INotEmptyGen<int>, false); // Eval(0418, o is INotEmptyGen<int>[], false); Eval(0419, o is SimpleDelegate, false); Eval(0420, o is SimpleDelegate[], false); // Eval(0421, o is GenericDelegate<int>, false); // Eval(0422, o is GenericDelegate<int>[], false); Eval(0423, o is EmptyClass, false); Eval(0424, o is EmptyClass[], false); Eval(0425, o is NotEmptyClass, false); Eval(0426, o is NotEmptyClass[], false); // Eval(0427, o is EmptyClassGen<int>, false); // Eval(0428, o is EmptyClassGen<int>[], false); // Eval(0429, o is NotEmptyClassGen<Guid>, false); // Eval(0430, o is NotEmptyClassGen<Guid>[], false); // Eval(0431, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0432, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0433, o is NestedClass, false); Eval(0434, o is NestedClass[], false); // Eval(0435, o is NestedClassGen<Decimal>, false); // Eval(0436, o is NestedClassGen<Decimal>[], false); Eval(0437, o is ImplementOneInterfaceC, false); Eval(0438, o is ImplementOneInterfaceC[], false); Eval(0439, o is ImplementTwoInterfaceC, false); Eval(0440, o is ImplementTwoInterfaceC[], false); // Eval(0441, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0442, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0443, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0444, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0445, o is ImplementAllInterfaceC<int>, false); // Eval(0446, o is ImplementAllInterfaceC<int>[], false); Eval(0447, o is SealedClass, false); Eval(0448, o is SealedClass[], false); } { LongE? v = default(LongE); Enum o = v; Eval(0449, o is IntE, false); Eval(0450, o is IntE[], false); Eval(0451, o is IntE?, false); Eval(0452, o is IntE?[], false); Eval(0453, o is ByteE, false); Eval(0454, o is ByteE[], false); Eval(0455, o is ByteE?, false); Eval(0456, o is ByteE?[], false); Eval(0457, o is LongE, true); Eval(0458, o is LongE[], false); Eval(0459, o is LongE?, true); Eval(0460, o is LongE?[], false); Eval(0461, o is object, true); Eval(0462, o is object[], false); Eval(0463, o is string, false); Eval(0464, o is string[], false); Eval(0465, o is ValueType, true); Eval(0466, o is ValueType[], false); Eval(0467, o is Array, false); Eval(0468, o is Array[], false); Eval(0469, o is Enum, true); Eval(0470, o is Enum[], false); Eval(0471, o is Delegate, false); Eval(0472, o is Delegate[], false); Eval(0473, o is MulticastDelegate, false); Eval(0474, o is MulticastDelegate[], false); Eval(0475, o is IEmpty, false); Eval(0476, o is IEmpty[], false); Eval(0477, o is INotEmpty, false); Eval(0478, o is INotEmpty[], false); // Eval(0479, o is IEmptyGen<int>, false); // Eval(0480, o is IEmptyGen<int>[], false); // Eval(0481, o is INotEmptyGen<int>, false); // Eval(0482, o is INotEmptyGen<int>[], false); Eval(0483, o is SimpleDelegate, false); Eval(0484, o is SimpleDelegate[], false); // Eval(0485, o is GenericDelegate<int>, false); // Eval(0486, o is GenericDelegate<int>[], false); Eval(0487, o is EmptyClass, false); Eval(0488, o is EmptyClass[], false); Eval(0489, o is NotEmptyClass, false); Eval(0490, o is NotEmptyClass[], false); // Eval(0491, o is EmptyClassGen<int>, false); // Eval(0492, o is EmptyClassGen<int>[], false); // Eval(0493, o is NotEmptyClassGen<Guid>, false); // Eval(0494, o is NotEmptyClassGen<Guid>[], false); // Eval(0495, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0496, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0497, o is NestedClass, false); Eval(0498, o is NestedClass[], false); // Eval(0499, o is NestedClassGen<Decimal>, false); // Eval(0500, o is NestedClassGen<Decimal>[], false); Eval(0501, o is ImplementOneInterfaceC, false); Eval(0502, o is ImplementOneInterfaceC[], false); Eval(0503, o is ImplementTwoInterfaceC, false); Eval(0504, o is ImplementTwoInterfaceC[], false); // Eval(0505, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0506, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0507, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0508, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0509, o is ImplementAllInterfaceC<int>, false); // Eval(0510, o is ImplementAllInterfaceC<int>[], false); Eval(0511, o is SealedClass, false); Eval(0512, o is SealedClass[], false); } { LongE? v = default(LongE?); Enum o = v; Eval(0513, o is IntE, false); Eval(0514, o is IntE[], false); Eval(0515, o is IntE?, false); Eval(0516, o is IntE?[], false); Eval(0517, o is ByteE, false); Eval(0518, o is ByteE[], false); Eval(0519, o is ByteE?, false); Eval(0520, o is ByteE?[], false); Eval(0521, o is LongE, false); Eval(0522, o is LongE[], false); Eval(0523, o is LongE?, false); Eval(0524, o is LongE?[], false); Eval(0525, o is object, false); Eval(0526, o is object[], false); Eval(0527, o is string, false); Eval(0528, o is string[], false); Eval(0529, o is ValueType, false); Eval(0530, o is ValueType[], false); Eval(0531, o is Array, false); Eval(0532, o is Array[], false); Eval(0533, o is Enum, false); Eval(0534, o is Enum[], false); Eval(0535, o is Delegate, false); Eval(0536, o is Delegate[], false); Eval(0537, o is MulticastDelegate, false); Eval(0538, o is MulticastDelegate[], false); Eval(0539, o is IEmpty, false); Eval(0540, o is IEmpty[], false); Eval(0541, o is INotEmpty, false); Eval(0542, o is INotEmpty[], false); // Eval(0543, o is IEmptyGen<int>, false); // Eval(0544, o is IEmptyGen<int>[], false); // Eval(0545, o is INotEmptyGen<int>, false); // Eval(0546, o is INotEmptyGen<int>[], false); Eval(0547, o is SimpleDelegate, false); Eval(0548, o is SimpleDelegate[], false); // Eval(0549, o is GenericDelegate<int>, false); // Eval(0550, o is GenericDelegate<int>[], false); Eval(0551, o is EmptyClass, false); Eval(0552, o is EmptyClass[], false); Eval(0553, o is NotEmptyClass, false); Eval(0554, o is NotEmptyClass[], false); // Eval(0555, o is EmptyClassGen<int>, false); // Eval(0556, o is EmptyClassGen<int>[], false); // Eval(0557, o is NotEmptyClassGen<Guid>, false); // Eval(0558, o is NotEmptyClassGen<Guid>[], false); // Eval(0559, o is NotEmptyClassConstrainedGen<object>, false); // Eval(0560, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0561, o is NestedClass, false); Eval(0562, o is NestedClass[], false); // Eval(0563, o is NestedClassGen<Decimal>, false); // Eval(0564, o is NestedClassGen<Decimal>[], false); Eval(0565, o is ImplementOneInterfaceC, false); Eval(0566, o is ImplementOneInterfaceC[], false); Eval(0567, o is ImplementTwoInterfaceC, false); Eval(0568, o is ImplementTwoInterfaceC[], false); // Eval(0569, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); // Eval(0570, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); // Eval(0571, o is ImplementTwoInterfaceGenC<int>, false); // Eval(0572, o is ImplementTwoInterfaceGenC<int>[], false); // Eval(0573, o is ImplementAllInterfaceC<int>, false); // Eval(0574, o is ImplementAllInterfaceC<int>[], false); Eval(0575, o is SealedClass, false); Eval(0576, o is SealedClass[], false); } } // end of test case 0003 private static int Main() { try { TestCase0001(); TestCase0002(); TestCase0003(); } catch (Exception e) { System.Console.WriteLine(e.Message); Console.WriteLine("Test FAILED"); return 666; } Console.WriteLine("Test SUCCESS"); return 100; } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System.ComponentModel; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// Basic Asserts on strings. /// </summary> public class StringAssert { #region Equals and ReferenceEquals /// <summary> /// The Equals method throws an AssertionException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new AssertionException("Assert.Equals should not be used for Assertions"); } /// <summary> /// override the default ReferenceEquals to throw an AssertionException. This /// implementation makes sure there is no mistake in calling this function /// as part of Assert. /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static new void ReferenceEquals(object a, object b) { throw new AssertionException("Assert.ReferenceEquals should not be used for Assertions"); } #endregion #region Contains /// <summary> /// Asserts that a string is found within another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Arguments used in formatting the message</param> static public void Contains( string expected, string actual, string message, params object[] args ) { Assert.That(actual, new SubstringConstraint(expected), message, args); } /// <summary> /// Asserts that a string is found within another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> /// <param name="message">The message to display in case of failure</param> static public void Contains( string expected, string actual, string message ) { Contains( expected, actual, message, null ); } /// <summary> /// Asserts that a string is found within another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> static public void Contains( string expected, string actual ) { Contains( expected, actual, string.Empty, null ); } #endregion #region StartsWith /// <summary> /// Asserts that a string starts with another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Arguments used in formatting the message</param> static public void StartsWith( string expected, string actual, string message, params object[] args ) { Assert.That(actual, new StartsWithConstraint(expected), message, args); } /// <summary> /// Asserts that a string starts with another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> /// <param name="message">The message to display in case of failure</param> static public void StartsWith( string expected, string actual, string message ) { StartsWith( expected, actual, message, null ); } /// <summary> /// Asserts that a string starts with another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> static public void StartsWith( string expected, string actual ) { StartsWith( expected, actual, string.Empty, null ); } #endregion #region EndsWith /// <summary> /// Asserts that a string ends with another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Arguments used in formatting the message</param> static public void EndsWith( string expected, string actual, string message, params object[] args ) { Assert.That(actual, new EndsWithConstraint(expected), message, args); } /// <summary> /// Asserts that a string ends with another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> /// <param name="message">The message to display in case of failure</param> static public void EndsWith( string expected, string actual, string message ) { EndsWith( expected, actual, message, null ); } /// <summary> /// Asserts that a string ends with another string. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The string to be examined</param> static public void EndsWith( string expected, string actual ) { EndsWith( expected, actual, string.Empty, null ); } #endregion #region AreEqualIgnoringCase /// <summary> /// Asserts that two strings are equal, without regard to case. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Arguments used in formatting the message</param> static public void AreEqualIgnoringCase( string expected, string actual, string message, params object[] args ) { Assert.That(actual, new EqualConstraint(expected).IgnoreCase, message, args); } /// <summary> /// Asserts that two strings are equal, without regard to case. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> /// <param name="message">The message to display in case of failure</param> static public void AreEqualIgnoringCase( string expected, string actual, string message ) { AreEqualIgnoringCase( expected, actual, message, null ); } /// <summary> /// Asserts that two strings are equal, without regard to case. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> static public void AreEqualIgnoringCase( string expected, string actual ) { AreEqualIgnoringCase( expected, actual, string.Empty, null ); } #endregion #region IsMatch /// <summary> /// Asserts that a string matches an expected regular expression pattern. /// </summary> /// <param name="expected">The expected expression</param> /// <param name="actual">The actual string</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Arguments used in formatting the message</param> static public void IsMatch( string expected, string actual, string message, params object[] args ) { Assert.That(actual, new RegexConstraint(expected), message, args); } /// <summary> /// Asserts that a string matches an expected regular expression pattern. /// </summary> /// <param name="expected">The expected expression</param> /// <param name="actual">The actual string</param> /// <param name="message">The message to display in case of failure</param> static public void IsMatch( string expected, string actual, string message ) { IsMatch( expected, actual, message, null ); } /// <summary> /// Asserts that a string matches an expected regular expression pattern. /// </summary> /// <param name="expected">The expected expression</param> /// <param name="actual">The actual string</param> static public void IsMatch( string expected, string actual ) { IsMatch( expected, actual, string.Empty, null ); } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Text.RegularExpressions; using com.calitha.goldparser; using Epi.Data; using Epi.Web; namespace Epi.Core.AnalysisInterpreter.Rules { /* <table_exposure> ::= '*' | Identifier <table_outcome> ::= '*' | Identifier <Simple_Tables_Statement>::= TABLE <table_exposure> | TABLE <table_exposure> <FreqOpts> | TABLE <table_exposure> <table_outcome> | TABLE <table_exposure> <table_outcome> <FreqOpts> <FreqOpts> ::= <FreqOpts> <FreqOpt> | <FreqOpt> <FreqOpt> ::= <WeightOpt> | <FreqOptStrata> | <OutTableOpt> | <SetClause> | <FreqOptNoWrap> | <FreqOptColumnSize> | <FreqOptPsuvar> <WeightOpt> ::= WEIGHTVAR '=' Identifier <FreqOptStrata> ::= STRATAVAR '=' <IdentifierList> <FreqOptNoWrap> ::= NOWRAP <FreqOptColumnSize> ::= COLUMNSIZE '=' DecLiteral <FreqOptPsuvar> ::= PSUVAR '=' Identifier */ public class Rule_Tables : AnalysisRule { bool HasRun = false; string[] IdentifierList = null; string[] IdentifierList2 = null; Dictionary<string, string> inputVariableList; string[] Stratvar = null; string Exposure = null; string Outcome = null; string OutTable = null; string WeightVar = null; string PSUVar = null; //bool isExceptionList = false; string[] FrequencyOptions = null; string commandText = string.Empty; public bool tablesShowStatistics = true; string parameter1 = null; string parameter2 = null; string parameter3 = null; string parameter4 = null; //DataTable dt = null; EpiInfo.Plugin.IAnalysisStatistic TablesStatistic; public Rule_Tables(Rule_Context pContext, NonterminalToken pToken) : base(pContext) { //this.isExceptionList = false; commandText = this.ExtractTokens(pToken.Tokens); foreach (Token T in pToken.Tokens) { if (T is NonterminalToken) { NonterminalToken NT = (NonterminalToken)T; switch (NT.Symbol.ToString()) { case"<table_exposure>": this.SetTableExposure(NT); break; case "<table_outcome>": this.SetTableOutcome(NT); break; case "<FreqOpts>": //this.SetFreqOpts(NT); this.SetFreqOpts(NT); break; case "<FreqOpt>": this.SetFreqOpt(NT); break; } } else { TerminalToken TT = (TerminalToken)T; switch (TT.Symbol.ToString()) { case"<table_exposure>": case "<table_outcome>": case "<FreqOpts>": break; } } } } private void SetTableExposure(NonterminalToken pT) { //inputVariableList.Add("EXPOSURE_VARIABLE", this.GetCommandElement(pT.Tokens, 0)); this.Exposure = this.GetCommandElement(pT.Tokens, 0).Trim(new char[] {'[',']'}); } private void SetTableOutcome(NonterminalToken pT) { //inputVariableList.Add("OUTCOME_VARIABLE", this.GetCommandElement(pT.Tokens, 0)); this.Outcome = this.GetCommandElement(pT.Tokens, 0).Trim(new char[] { '[', ']' }); } private void SetFreqOpts(NonterminalToken pT) { // <FreqOpts> ::= <FreqOpts> <FreqOpt> | <FreqOpt> foreach (Token T in pT.Tokens) { if (T is NonterminalToken) { NonterminalToken NT = (NonterminalToken)T; switch (NT.Symbol.ToString()) { case "<FreqOpt>": this.SetFreqOpt(NT); break; case "<FreqOpts>": this.SetFreqOpt((NonterminalToken)NT.Tokens[0]); this.SetFreqOpt((NonterminalToken)NT.Tokens[1]); break; } } } } private void SetFreqOpt(NonterminalToken pT) { /* <FreqOpt> ::= <WeightOpt> | <FreqOptStrata> | <OutTableOpt> | <SetClause> | <FreqOptNoWrap> | <FreqOptColumnSize> | <FreqOptPsuvar> <WeightOpt> ::= WEIGHTVAR '=' Identifier <FreqOptStrata> ::= STRATAVAR '=' <IdentifierList> <FreqOptNoWrap> ::= NOWRAP <FreqOptColumnSize> ::= COLUMNSIZE '=' DecLiteral <FreqOptPsuvar> ::= PSUVAR '=' Identifier*/ switch (pT.Rule.Rhs[0].Name.ToString()) { case "WEIGHTVAR": this.WeightVar = this.GetCommandElement(pT.Tokens,2).Trim(new char[] { '[', ']' }); //inputVariableList.Add("WEIGHTVAR", this.GetCommandElement(pT.Tokens, 2).Trim(new char[] { '[', ']' })); break; case "STRATAVAR": //this.Stratvar = this.GetCommandElement(pT.Tokens, 2); this.Stratvar = AnalysisRule.SpliIdentifierList(this.GetCommandElement(pT.Tokens, 2)); //StringBuilder temp2 = new StringBuilder(); break; case "STATISTICS": if (this.GetCommandElement(pT.Tokens, 2).Equals("NONE")) { this.tablesShowStatistics = false; } break; case "OUTTABLE": this.OutTable = this.GetCommandElement(pT.Tokens, 2).Trim(new char[] { '[', ']' }); //inputVariableList.Add("OUTTABLE", this.GetCommandElement(pT.Tokens, 2).Trim(new char[] { '[', ']' })); break; case "<SetClause>": break; case "<FreqOptNoWrap>": //this.op break; case "<FreqOptColumnSize>": break; case "PSUVAR": this.PSUVar = this.GetCommandElement(pT.Tokens, 2).Trim(new char[] { '[', ']' }); //inputVariableList.Add("PSUVAR", this.GetCommandElement(pT.Tokens, 2).Trim(new char[] { '[', ']' })); break; } } public override object Execute() { object result = null; if (!this.HasRun) { //Configuration config = Configuration.GetNewInstance(); Dictionary<string, string> setProperties = this.Context.GetGlobalSettingProperties(); List<string> ExposureVariableList = new List<string>(); ExposureVariableList.Add(this.Exposure); bool isExceptionList = false; this.Context.ExpandGroupVariables(ExposureVariableList, ref isExceptionList); foreach (string EXPOSURE_VARIABLE in ExposureVariableList) { inputVariableList = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); inputVariableList.Add("EXPOSURE_VARIABLE", EXPOSURE_VARIABLE); inputVariableList.Add("OUTCOME_VARIABLE", this.Outcome); if (this.Stratvar != null) { StringBuilder temp = new StringBuilder(); foreach (string s in Stratvar) { temp.Append(s); temp.Append(','); } if (temp.Length > 0) { temp.Length = temp.Length - 1; } inputVariableList.Add("STRATAVAR", temp.ToString()); } if (!string.IsNullOrEmpty(OutTable)) { inputVariableList.Add("OutTable", OutTable); } if (!string.IsNullOrEmpty(WeightVar)) { inputVariableList.Add("WeightVar", WeightVar); } if (!tablesShowStatistics) { inputVariableList.Add("STATISTICS", "NONE"); } inputVariableList.Add("commandText", commandText); if (!string.IsNullOrEmpty(PSUVar)) { inputVariableList.Add("PSUVar", PSUVar); } if (this.Context.CurrentRead == null) { inputVariableList.Add("TableName", ""); } else { inputVariableList.Add("TableName", this.Context.CurrentRead.Identifier); } EpiInfo.Plugin.IDataSource DataSource = this.Context.GetDefaultIDataSource(); AnalysisStatisticExecuteHost statisticHost = new AnalysisStatisticExecuteHost(this.Context, setProperties, DataSource, inputVariableList, this.Context.CurrentSelect.ToString(), this.Context.AnalysisInterpreterHost); if (!inputVariableList.ContainsKey("PSUVAR")) { this.TablesStatistic = this.Context.GetStatistic("Tables", statisticHost); } else { this.TablesStatistic = this.Context.GetStatistic("ComplexSampleTables", statisticHost); } this.TablesStatistic.Execute(); this.TablesStatistic = null; } this.HasRun = true; } return result; } private string ConvertToPercent(double pValue) { return string.Format("{0: ##0.0}%", (100.0 * pValue)); } private string ConvertToPixelLength(double pValue) { return string.Format("{0: ##0}px", 1 * Math.Round((100.0 * pValue), MidpointRounding.AwayFromZero)); } private void SetTableOptions(NonterminalToken pToken) { for (int i = 0; i < pToken.Tokens.Length; i++) { NonterminalToken T = (NonterminalToken)pToken.Tokens[i]; switch (T.Rule.Rhs[0].ToString()) { case "<FreqOpts>": case "<WeightOpt>": case "<FreqOpt>": for (int j = 0; j < T.Tokens.Length; j++) { string temp = this.ExtractTokens(((NonterminalToken)T.Tokens[j]).Tokens); string[] tmp = temp.Split('='); switch (tmp[0].ToUpperInvariant().Trim()) { case "STRATAVAR": this.Stratvar = AnalysisRule.SpliIdentifierList(tmp[1].Trim()); break; case "WEIGHTVAR": this.WeightVar = tmp[1].Trim(); break; } } break; case "<OutTableOpt>": this.OutTable = this.GetCommandElement(T.Tokens, 2); break; case "<FreqOptPsuvar>": this.PSUVar = this.GetCommandElement(T.Tokens, 2); break; } } } /// <summary> /// performs execution of the TABLES command /// </summary> /// <returns>object</returns> public object Execute_old() { Dictionary<string, string> args = new Dictionary<string, string>(); args.Add("COMMANDNAME", CommandNames.TABLES); args.Add("parameter1", parameter1); if ((parameter2 != string.Empty)) { int i = parameter2.Length; args.Add("parameter2", parameter2); } if ((parameter3 != string.Empty)&& (parameter4 != null)) { args.Add("parameter3", parameter3); } if ((parameter4 != string.Empty) && (parameter4 != null)) { args.Add("parameter4", parameter4); } this.Context.AnalysisCheckCodeInterface.Display(args); return null; } } public static class HtmlRenderer { public static string RenderHtml(Rule_Context pContext, string commandName, string fileName, string tableName, int rowCount) { StringBuilder sb = new StringBuilder(); Epi.DataSets.Config.SettingsRow settings = Configuration.GetNewInstance().Settings; sb.Append(HTML.Italics(SharedStrings.CURRENT_VIEW + ":&nbsp;")); sb.Append(HTML.Bold(String.Format("{0}:{1}", fileName.Trim(new char[] { '\'' }), tableName))); if (pContext.CurrentRead.RelatedTables != null) { foreach (string table in pContext.CurrentRead.RelatedTables) { sb.Append(HTML.Tag("br")); sb.Append(HTML.Italics("&nbsp&nbsp&nbsp&nbspRelate:&nbsp;")); sb.Append(HTML.Bold(table)); } } if (pContext.DataInfo.SelectCriteria != String.Empty) { sb.Append(HTML.Tag("br")); sb.Append(HTML.Italics("Selection:&nbsp;&nbsp;")); sb.Append("&nbsp;"); sb.Append(HTML.Bold(EpiExpression(pContext, pContext.DataInfo.SelectCriteria))); } if (pContext.DataInfo.GetSqlStatementPartSortBy() != String.Empty) { sb.Append(HTML.Tag("br")); sb.Append(HTML.Italics("Sort By:&nbsp;&nbsp;")); sb.Append(HTML.Bold(EpiExpression(pContext, pContext.DataInfo.GetSqlStatementPartSortBy()))); } sb.Append(HTML.Tag("br")); sb.Append(HTML.Italics(SharedStrings.RECORD_COUNT + ":&nbsp;&nbsp;")); sb.Append(HTML.Bold(rowCount.ToString())); string scope = string.Empty; switch (settings.RecordProcessingScope) { case 1: scope = SharedStrings.DELETED_RECORDS_EXCLUDED; break; case 2: scope = SharedStrings.DELETED_RECORDS_ONLY; break; default: scope = SharedStrings.DELETED_RECORDS_INCLUDED; break; } sb.Append("&nbsp;"); sb.Append(HTML.Italics("(" + scope + ")&nbsp;&nbsp;&nbsp;")); sb.Append(HTML.Italics("Date:")); sb.Append("&nbsp;&nbsp;"); sb.Append(HTML.Bold(DateTime.Now.ToString())); sb.Append(HTML.Tag("br")); sb.Append(HTML.Tag("br")); return sb.ToString(); } private static bool IsBoolean(IVariable var) { return (var.DataType == DataType.Boolean || var.DataType == DataType.YesNo); } private static bool IsBoolean(Rule_Context pContext, string name) { return IsBoolean(pContext.MemoryRegion.GetVariable(name)); } private static string RepresentationOfValue(string val, bool isBoolean) { Configuration config = Configuration.GetNewInstance(); if (isBoolean) { return (val == "0") ? config.Settings.RepresentationOfNo : config.Settings.RepresentationOfYes; } else { return val; } } public static string TableHeadingHTML(Rule_Context pContext, DataTable distinct, string outcome, string exposure) { Configuration config = Configuration.GetNewInstance(); StringBuilder sb = new StringBuilder(); IMemoryRegion module = pContext.MemoryRegion; IVariable oVar = module.GetVariable(outcome); string outcomeWord = (config.Settings.ShowCompletePrompt) ? oVar.PromptText.ToString() : oVar.Name; IVariable eVar = module.GetVariable(exposure); string exposureWord = (config.Settings.ShowCompletePrompt) ? eVar.PromptText.ToString() : eVar.Name.ToString(); sb.Append("<caption> <b>").Append(outcomeWord).Append("</b></caption>"); sb.Append("<tr>"); sb.Append("<th nowrap>").Append(exposureWord).Append("</th>"); foreach (DataRow row in distinct.Rows) { foreach (DataColumn col in distinct.Columns) { IVariable var = module.GetVariable(col.ColumnName); DataType thisType = var.DataType; bool isBoolean = (thisType == DataType.Boolean || thisType == DataType.YesNo); sb.Append("<th>"); if (row[col.ColumnName] == null || string.IsNullOrEmpty(row[col.ColumnName].ToString())) { sb.Append(config.Settings.RepresentationOfMissing); } else { string val = RepresentationOfValue(row[col.ColumnName].ToString(), isBoolean); sb.Append(val); } sb.Append("</th>"); } } sb.Append("<th>TOTAL</th>"); sb.Append("</tr>"); return sb.ToString(); } public static string TableRowHTML(string row, string col, int rowCount, int colCount, bool isBooleanField) // exposure is going to have to be the word { StringBuilder sb = new StringBuilder(); string rowWord = row; if (isBooleanField) { rowWord = RepresentationOfValue(row, true); } sb.Append("<tr>"); sb.Append("<td align=right><b>"); sb.Append(row); sb.Append("</b><br>row %<br>col %</td>"); //foreach() //{ // sb.Append("<td align=right>"); // sb.Append(count).Append("<br>"); // double rowPct = ((double)count / (double)rowTotal) * 100; // sb.Append(rowPct.ToString("##.#")).Append("<br>"); // double colPct = ((double)count / count) * 100; // sb.Append(colPct.ToString("##.#")); // sb.Append("</td>"); //} sb.Append("<td align=right>").Append(rowCount).Append("<br>100.0<br>100.0").Append("</td>"); sb.Append("</tr>"); return sb.ToString(); } // This is for the whole table. public static string TableDataHTML(string exposureField, string outcomeField, DataTable table2x2, int colCount) { StringBuilder sb = new StringBuilder(); Dictionary<string, Dictionary<string, int>> exposureList = new Dictionary<string, Dictionary<string, int>>(); Dictionary<string, int> exposureTotals = new Dictionary<string, int>(); Dictionary<string, int> outcomeTotals = new Dictionary<string, int>(); int grandTotal = 0; //calulate totals foreach (DataRow r in table2x2.Rows) { string currExposure = r[ColumnNames.EXPOSURE].ToString(); string currOutcome = r[ColumnNames.OUTCOME].ToString(); int currCount = (int)r[ColumnNames.COUNT]; grandTotal += currCount; bool isBoolOutcome = false;//(table2x2.Columns[colIndex].GetType() == typeof(bool)); bool isBoolExposure = false; int outcomeCount = currCount; int exposureCount = currCount; if (isBoolExposure) { if (exposureCount == 1) { currExposure += "#TRUE"; AddToTotal(exposureTotals, currExposure, exposureCount); } else { currExposure += "#FALSE"; exposureCount = 1; AddToTotal(exposureTotals, currExposure, exposureCount); } } else { AddToTotal(exposureTotals, currExposure, exposureCount); } if (isBoolOutcome) { if (outcomeCount == 1) { currOutcome += "#TRUE"; AddToTotal(outcomeTotals, currOutcome, outcomeCount); } else { currOutcome += "#FALSE"; outcomeCount = 1; AddToTotal(outcomeTotals, currOutcome, outcomeCount); } } else { AddToTotal(outcomeTotals, currOutcome, outcomeCount); } } string[] keys = new string[outcomeTotals.Keys.Count]; outcomeTotals.Keys.CopyTo(keys, 0); sb.Append("<table>"); sb.AppendFormat("<tr><td>&nbsp;</td><td align=center colspan={0}><b>{1}</b></td></tr>", keys.Length, outcomeField); sb.Append(HeaderHtml(keys, exposureField)); StringBuilder rowBuilder = new StringBuilder(); int exposureTotal = 0; foreach (DataRow row in table2x2.Rows) { //create new html row string exposure = row[0].ToString(); rowBuilder = new StringBuilder(); exposureTotal = (int)row[1]; rowBuilder.Append(RowHtml(exposure)); for (int colIndex = 2; colIndex < table2x2.Columns.Count; colIndex++) { string outcome = table2x2.Columns[colIndex].ColumnName; int currCount = 0; int.TryParse(row[colIndex].ToString(), out currCount); bool isBoolField = (table2x2.Columns[colIndex].GetType() == typeof(bool)); if (isBoolField) { if (currCount == 1) { outcome += "#TRUE"; int outcomeTotal = outcomeTotals[outcome]; rowBuilder.Append(ColumnHtml(currCount, exposureTotal, outcomeTotal)); } else { outcome += "#FALSE"; currCount = 1; int outcomeTotal = outcomeTotals[outcome]; rowBuilder.Append(ColumnHtml(currCount, exposureTotal, outcomeTotal)); } } else { //add the next outcome int outcomeTotal = outcomeTotals[outcome]; rowBuilder.Append(ColumnHtml(currCount, exposureTotal, outcomeTotal)); } } //add the last exposure info to the row rowBuilder.Append(ColumnHtml(exposureTotal, exposureTotal, grandTotal)); rowBuilder.Append("</tr>"); sb.Append(rowBuilder.ToString()); } StringBuilder tr = new StringBuilder(); tr.Append("<tr><td><b><i>Total</i></b><br/>Row %<br/>Col %</td>"); for (int colIndex = 2; colIndex < table2x2.Columns.Count; colIndex++) { string currentOutcome = table2x2.Columns[colIndex].ColumnName; int colTotal = outcomeTotals[currentOutcome]; tr.Append(ColumnHtml(colTotal, colTotal, grandTotal)); } tr.Append(ColumnHtml(grandTotal, grandTotal, grandTotal)); tr.Append("</tr>"); sb.Append(tr.ToString()); sb.Append("</table>"); return sb.ToString(); } private static void AddToTotal(Dictionary<string, int> totals, string key, int count) { if (totals.ContainsKey(key)) { totals[key] += count; } else { totals.Add(key, count); } } public static string HeaderHtml(string[] columns, string exposureField) { StringBuilder sb = new StringBuilder(); sb.Append("<tr>"); sb.AppendFormat("<td align=center><b>{0}</b></td>", exposureField); for (int i = 0; i < columns.Length; i++) { sb.AppendFormat("<td align=center><b>{0}</b></td>", columns[i]); } sb.Append("<td align=center><b>Total</b></td>"); sb.Append("</tr>"); return sb.ToString(); } public static string ColumnHtml(int colCount, int rowTotal, int colTotal) { StringBuilder sb = new StringBuilder(); sb.Append("<td align=right>"); sb.Append(colCount).Append("<br>"); double rowPct = ((double)colCount / (double)rowTotal) * 100; sb.Append(rowPct.ToString("#0.0")).Append("<br>"); double colPct = ((double)colCount / colTotal) * 100; sb.Append(colPct.ToString("#0.0")); sb.Append("</td>"); return sb.ToString(); } public static string RowHtml(string rowName) { StringBuilder sb = new StringBuilder(); sb.Append("<tr><td align=right><b>"); sb.Append(rowName); sb.Append("</b><br/>"); sb.Append("Row %"); sb.Append("<br/>"); sb.Append("Col %"); sb.Append("</td>"); return sb.ToString(); } public static string TotalsHTML(DataTable table2x2) { StringBuilder sb = new StringBuilder(); return sb.ToString(); } public static string TotalsHTML(int colCount, ulong rowTotal) { StringBuilder sb = new StringBuilder(); sb.Append("<tr>"); sb.Append("<td align=right><b>").Append(SharedStrings.TOTAL); sb.Append("</b><br>Row %<br>Col %").Append("</td>"); for (int i = 0; i < colCount; i++) { sb.Append("<td align=right>").Append("count").Append(i.ToString()); sb.Append("<br>pct").Append(i.ToString()); sb.Append("<br>").Append("100").Append("</td>"); } sb.Append("<td align=right>").Append(rowTotal).Append("<br>100.0<br>100.0</td>"); sb.Append("</tr>"); return sb.ToString(); } public static string TableHTML(Rule_Context pContext, string outcomeName, string exposureName) { StringBuilder sb = new StringBuilder(); try { // Generate the table DataSet ds = pContext.DataInfo.GetDataSet2x2(pContext, outcomeName, exposureName); sb.Append("<table border align=left>"); sb.Append(TableHeadingHTML(pContext, ds.Tables["DistinctOutcomes"], outcomeName, exposureName)); sb.Append(TableDataHTML(outcomeName, exposureName, ds.Tables["Table2x2"], ds.Tables["DistinctOutcomes"].Rows.Count)); sb.Append("</table>"); return sb.ToString(); } catch (Exception ex) { throw new GeneralException(SharedStrings.DATA_TABLE_NOT_CREATED, ex); } } private static string EpiExpression(Rule_Context pContext, string whereClause) { string expression = string.Empty; if (!string.IsNullOrEmpty(whereClause)) { string where = whereClause.Replace("is null", " = (.)").Replace("is not null", " <> (.)"); bool isBoolean = false; int result = 0; string s = string.Empty; string[] expStrings = where.Split(new char[] { ' ' }); for (int i = 0; i < expStrings.Length; i++) { if (string.IsNullOrEmpty(expStrings[i])) { s = string.Empty; } else if (Regex.IsMatch(expStrings[i], @"[()=]")) { s = expStrings[i]; } else if (expStrings[i] == "<>") { s = expStrings[i]; } else if (expStrings[i].Equals("and", StringComparison.CurrentCultureIgnoreCase) || expStrings[i].Equals("or", StringComparison.CurrentCultureIgnoreCase)) { s = expStrings[i]; } else if (!int.TryParse(expStrings[i], out result)) // Maybe it's a variable? { s = expStrings[i]; IVariable var = null; try { var = pContext.MemoryRegion.GetVariable(s); } catch { var = null; } if (var != null) // It really is a variable { isBoolean = (var.DataType == DataType.Boolean || var.DataType == DataType.YesNo); } else { s = expStrings[i].ToString(); } } else if (isBoolean && int.TryParse(expStrings[i], out result)) { if (result == 0) { s = "(-)"; } if (result == 1) { s = "(+)"; } isBoolean = false; } else { s = expStrings[i].ToString(); } if (!string.IsNullOrEmpty(expression)) { expression += " "; } expression += s; } } return expression; } } }
/* * 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.IO; using System.IO.Compression; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using System.Xml.Linq; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The maximum major version of archive that we can read. Minor versions shouldn't need a max number since version /// bumps here should be compatible. /// </summary> public static int MAX_MAJOR_VERSION = 1; protected TarArchiveReader archive; private UserAccount m_userInfo; private string m_invPath; /// <summary> /// Do we want to merge this load with existing inventory? /// </summary> protected bool m_merge; /// <value> /// We only use this to request modules /// </value> protected Scene m_scene; /// <value> /// The stream from which the inventory archive will be loaded. /// </value> private Stream m_loadStream; /// <summary> /// Has the control file been loaded for this archive? /// </summary> public bool ControlFileLoaded { get; private set; } /// <summary> /// Do we want to enforce the check. IAR versions before 0.2 and 1.1 do not guarantee this order, so we can't /// enforce. /// </summary> public bool EnforceControlFileCheck { get; private set; } protected bool m_assetsLoaded; protected bool m_inventoryNodesLoaded; protected int m_successfulAssetRestores; protected int m_failedAssetRestores; protected int m_successfulItemRestores; /// <summary> /// Root destination folder for the IAR load. /// </summary> protected InventoryFolderBase m_rootDestinationFolder; /// <summary> /// Inventory nodes loaded from the iar. /// </summary> protected HashSet<InventoryNodeBase> m_loadedNodes = new HashSet<InventoryNodeBase>(); /// <summary> /// In order to load identically named folders, we need to keep track of the folders that we have already /// resolved. /// </summary> Dictionary <string, InventoryFolderBase> m_resolvedFolders = new Dictionary<string, InventoryFolderBase>(); /// <summary> /// Record the creator id that should be associated with an asset. This is used to adjust asset creator ids /// after OSP resolution (since OSP creators are only stored in the item /// </summary> protected Dictionary<UUID, UUID> m_creatorIdForAssetId = new Dictionary<UUID, UUID>(); public InventoryArchiveReadRequest( Scene scene, UserAccount userInfo, string invPath, string loadPath, bool merge) : this( scene, userInfo, invPath, new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress), merge) { } public InventoryArchiveReadRequest( Scene scene, UserAccount userInfo, string invPath, Stream loadStream, bool merge) { m_scene = scene; m_merge = merge; m_userInfo = userInfo; m_invPath = invPath; m_loadStream = loadStream; // FIXME: Do not perform this check since older versions of OpenSim do save the control file after other things // (I thought they weren't). We will need to bump the version number and perform this check on all // subsequent IAR versions only ControlFileLoaded = true; } /// <summary> /// Execute the request /// </summary> /// <remarks> /// Only call this once. To load another IAR, construct another request object. /// </remarks> /// <returns> /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are /// returned /// </returns> /// <exception cref="System.Exception">Thrown if load fails.</exception> public HashSet<InventoryNodeBase> Execute() { try { string filePath = "ERROR"; List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFoldersByPath( m_scene.InventoryService, m_userInfo.PrincipalID, m_invPath); if (folderCandidates.Count == 0) { // Possibly provide an option later on to automatically create this folder if it does not exist m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); return m_loadedNodes; } m_rootDestinationFolder = folderCandidates[0]; archive = new TarArchiveReader(m_loadStream); byte[] data; TarArchiveReader.TarEntryType entryType; while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { LoadAssetFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) { LoadInventoryFile(filePath, entryType, data); } } archive.Close(); m_log.DebugFormat( "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", m_successfulAssetRestores, m_failedAssetRestores); m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", m_successfulItemRestores); return m_loadedNodes; } finally { m_loadStream.Close(); } } public void Close() { if (m_loadStream != null) m_loadStream.Close(); } /// <summary> /// Replicate the inventory paths in the archive to the user's inventory as necessary. /// </summary> /// <param name="iarPath">The item archive path to replicate</param> /// <param name="rootDestinationFolder">The root folder for the inventory load</param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// This method will add more folders if necessary /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> /// <returns>The last user inventory folder created or found for the archive path</returns> public InventoryFolderBase ReplicateArchivePathToUserInventory( string iarPath, InventoryFolderBase rootDestFolder, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string iarPathExisting = iarPath; // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID); InventoryFolderBase destFolder = ResolveDestinationFolder(rootDestFolder, ref iarPathExisting, resolvedFolders); // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: originalArchivePath [{0}], section already loaded [{1}]", // iarPath, iarPathExisting); string iarPathToCreate = iarPath.Substring(iarPathExisting.Length); CreateFoldersForPath(destFolder, iarPathExisting, iarPathToCreate, resolvedFolders, loadedNodes); return destFolder; } /// <summary> /// Resolve a destination folder /// </summary> /// /// We require here a root destination folder (usually the root of the user's inventory) and the archive /// path. We also pass in a list of previously resolved folders in case we've found this one previously. /// /// <param name="archivePath"> /// The item archive path to resolve. The portion of the path passed back is that /// which corresponds to the resolved desintation folder. /// <param name="rootDestinationFolder"> /// The root folder for the inventory load /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <returns> /// The folder in the user's inventory that matches best the archive path given. If no such folder was found /// then the passed in root destination folder is returned. /// </returns> protected InventoryFolderBase ResolveDestinationFolder( InventoryFolderBase rootDestFolder, ref string archivePath, Dictionary <string, InventoryFolderBase> resolvedFolders) { // string originalArchivePath = archivePath; while (archivePath.Length > 0) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Trying to resolve destination folder {0}", archivePath); if (resolvedFolders.ContainsKey(archivePath)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath); return resolvedFolders[archivePath]; } else { if (m_merge) { // TODO: Using m_invPath is totally wrong - what we need to do is strip the uuid from the // iar name and try to find that instead. string plainPath = ArchiveConstants.ExtractPlainPathFromIarPath(archivePath); List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFoldersByPath( m_scene.InventoryService, m_userInfo.PrincipalID, plainPath); if (folderCandidates.Count != 0) { InventoryFolderBase destFolder = folderCandidates[0]; resolvedFolders[archivePath] = destFolder; return destFolder; } } // Don't include the last slash so find the penultimate one int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2); if (penultimateSlashIndex >= 0) { // Remove the last section of path so that we can see if we've already resolved the parent archivePath = archivePath.Remove(penultimateSlashIndex + 1); } else { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}", // originalArchivePath); archivePath = string.Empty; return rootDestFolder; } } } return rootDestFolder; } /// <summary> /// Create a set of folders for the given path. /// </summary> /// <param name="destFolder"> /// The root folder from which the creation will take place. /// </param> /// <param name="iarPathExisting"> /// the part of the iar path that already exists /// </param> /// <param name="iarPathToReplicate"> /// The path to replicate in the user's inventory from iar /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> protected void CreateFoldersForPath( InventoryFolderBase destFolder, string iarPathExisting, string iarPathToReplicate, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string[] rawDirsToCreate = iarPathToReplicate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < rawDirsToCreate.Length; i++) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0} from IAR", rawDirsToCreate[i]); if (!rawDirsToCreate[i].Contains(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR)) continue; int identicalNameIdentifierIndex = rawDirsToCreate[i].LastIndexOf( ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR); string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex); newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName); UUID newFolderId = UUID.Random(); // Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be // deleted once the client has relogged. // The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client) // even though there is a AssetType.RootCategory destFolder = new InventoryFolderBase( newFolderId, newFolderName, m_userInfo.PrincipalID, (short)AssetType.Unknown, destFolder.ID, 1); m_scene.InventoryService.AddFolder(destFolder); // Record that we have now created this folder iarPathExisting += rawDirsToCreate[i] + "/"; m_log.DebugFormat("[INVENTORY ARCHIVER]: Created folder {0} from IAR", iarPathExisting); resolvedFolders[iarPathExisting] = destFolder; if (0 == i) loadedNodes.Add(destFolder); } } /// <summary> /// Load an item from the archive /// </summary> /// <param name="filePath">The archive path for the item</param> /// <param name="data">The raw item data</param> /// <param name="rootDestinationFolder">The root destination folder for loaded items</param> /// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param> protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder) { InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data); // Don't use the item ID that's in the file item.ID = UUID.Random(); UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.UserAccountService); if (UUID.Zero != ospResolvedId) // The user exists in this grid { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId); // item.CreatorIdAsUuid = ospResolvedId; // Don't preserve the OSPA in the creator id (which actually gets persisted to the // database). Instead, replace with the UUID that we found. item.CreatorId = ospResolvedId.ToString(); item.CreatorData = string.Empty; } else if (item.CreatorData == null || item.CreatorData == String.Empty) { item.CreatorId = m_userInfo.PrincipalID.ToString(); // item.CreatorIdAsUuid = new UUID(item.CreatorId); } item.Owner = m_userInfo.PrincipalID; // Reset folder ID to the one in which we want to load it item.Folder = loadFolder.ID; // Record the creator id for the item's asset so that we can use it later, if necessary, when the asset // is loaded. // FIXME: This relies on the items coming before the assets in the TAR file. Need to create stronger // checks for this, and maybe even an external tool for creating OARs which enforces this, rather than // relying on native tar tools. m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid; m_scene.AddInventoryItem(item); return item; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>(); // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string rawUuid = filename.Remove(filename.Length - extension.Length); UUID assetId = new UUID(rawUuid); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; if (assetType == (sbyte)AssetType.Unknown) { m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, assetId); } else if (assetType == (sbyte)AssetType.Object) { if (m_creatorIdForAssetId.ContainsKey(assetId)) { string xmlData = Utils.BytesToString(data); List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); CoalescedSceneObjects coa = null; if (CoalescedSceneObjectsSerializer.TryFromXml(xmlData, out coa)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loaded coalescence {0} has {1} objects", assetId, coa.Count); if (coa.Objects.Count == 0) { m_log.WarnFormat( "[INVENTORY ARCHIVE READ REQUEST]: Aborting load of coalesced object from asset {0} as it has zero loaded components", assetId); return false; } sceneObjects.AddRange(coa.Objects); } else { SceneObjectGroup deserializedObject = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); if (deserializedObject != null) { sceneObjects.Add(deserializedObject); } else { m_log.WarnFormat( "[INVENTORY ARCHIVE READ REQUEST]: Aborting load of object from asset {0} as deserialization failed", assetId); return false; } } foreach (SceneObjectGroup sog in sceneObjects) foreach (SceneObjectPart sop in sog.Parts) if (sop.CreatorData == null || sop.CreatorData == "") sop.CreatorID = m_creatorIdForAssetId[assetId]; if (coa != null) data = Utils.StringToBytes(CoalescedSceneObjectsSerializer.ToXml(coa)); else data = Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(sceneObjects[0])); } } //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString()); asset.Data = data; m_scene.AssetService.Store(asset); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; } } /// <summary> /// Load control file /// </summary> /// <param name="path"></param> /// <param name="data"></param> public void LoadControlFile(string path, byte[] data) { XDocument doc = XDocument.Parse(Encoding.ASCII.GetString(data)); XElement archiveElement = doc.Element("archive"); int majorVersion = int.Parse(archiveElement.Attribute("major_version").Value); int minorVersion = int.Parse(archiveElement.Attribute("minor_version").Value); string version = string.Format("{0}.{1}", majorVersion, minorVersion); if (majorVersion > MAX_MAJOR_VERSION) { throw new Exception( string.Format( "The IAR you are trying to load has major version number of {0} but this version of OpenSim can only load IARs with major version number {1} and below", majorVersion, MAX_MAJOR_VERSION)); } ControlFileLoaded = true; m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version); } /// <summary> /// Load inventory file /// </summary> /// <param name="path"></param> /// <param name="entryType"></param> /// <param name="data"></param> protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.INVENTORY_PATH)); if (m_assetsLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); path = path.Substring(ArchiveConstants.INVENTORY_PATH.Length); // Trim off the file portion if we aren't already dealing with a directory path if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) path = path.Remove(path.LastIndexOf("/") + 1); InventoryFolderBase foundFolder = ReplicateArchivePathToUserInventory( path, m_rootDestinationFolder, m_resolvedFolders, m_loadedNodes); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) { InventoryItemBase item = LoadItem(data, foundFolder); if (item != null) { m_successfulItemRestores++; // If we aren't loading the folder containing the item then well need to update the // viewer separately for that item. if (!m_loadedNodes.Contains(foundFolder)) m_loadedNodes.Add(item); } } m_inventoryNodesLoaded = true; } /// <summary> /// Load asset file /// </summary> /// <param name="path"></param> /// <param name="data"></param> protected void LoadAssetFile(string path, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.ASSETS_PATH)); if (!m_inventoryNodesLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); if (LoadAsset(path, data)) m_successfulAssetRestores++; else m_failedAssetRestores++; if ((m_successfulAssetRestores) % 50 == 0) m_log.DebugFormat( "[INVENTORY ARCHIVER]: Loaded {0} assets...", m_successfulAssetRestores); m_assetsLoaded = true; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Implementation.Outlining; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal partial class VisualStudioSymbolNavigationService : ForegroundThreadAffinitizedObject, ISymbolNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory; private readonly ITextEditorFactoryService _textEditorFactoryService; private readonly ITextDocumentFactoryService _textDocumentFactoryService; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; private readonly OutliningTaggerProvider _outliningTaggerProvider; public VisualStudioSymbolNavigationService( SVsServiceProvider serviceProvider, OutliningTaggerProvider outliningTaggerProvider) { _serviceProvider = serviceProvider; _outliningTaggerProvider = outliningTaggerProvider; var componentModel = _serviceProvider.GetService<SComponentModel, IComponentModel>(); _editorAdaptersFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _textEditorFactoryService = componentModel.GetService<ITextEditorFactoryService>(); _textDocumentFactoryService = componentModel.GetService<ITextDocumentFactoryService>(); _metadataAsSourceFileService = componentModel.GetService<IMetadataAsSourceFileService>(); } public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken) { if (project == null || symbol == null) { return false; } options = options ?? project.Solution.Workspace.Options; symbol = symbol.OriginalDefinition; // Prefer visible source locations if possible. var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource); var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation()); var sourceLocation = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault(); if (sourceLocation != null) { var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree); if (targetDocument != null) { var editorWorkspace = targetDocument.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options); } } // We don't have a source document, so show the Metadata as Source view in a preview tab. var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault(); if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { return false; } // Should we prefer navigating to the Object Browser over metadata-as-source? if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language)) { var libraryService = project.LanguageServices.GetService<ILibraryService>(); if (libraryService == null) { return false; } var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation); if (navInfo == null) { navInfo = libraryService.NavInfoFactory.CreateForProject(project); } if (navInfo != null) { var navigationTool = _serviceProvider.GetService<SVsObjBrowser, IVsNavigationTool>(); return navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK; } // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen. } // Generate new source or retrieve existing source for the symbol in question var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken); var vsRunningDocumentTable4 = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>(); var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath); var openDocumentService = _serviceProvider.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(); IVsUIHierarchy hierarchy; uint itemId; IOleServiceProvider localServiceProvider; IVsWindowFrame windowFrame; openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame); var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath); var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie); var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer); if (!fileAlreadyOpen) { ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true)); ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle)); ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip)); } windowFrame.Show(); var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault(); if (openedDocument != null) { var editorWorkspace = openedDocument.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); return navigationService.TryNavigateToSpan( workspace: editorWorkspace, documentId: openedDocument.Id, textSpan: result.IdentifierLocation.SourceSpan, options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true)); } return true; } public bool TrySymbolNavigationNotify(ISymbol symbol, Solution solution) { return TryNotifyForSpecificSymbol(symbol, solution); } private bool TryNotifyForSpecificSymbol(ISymbol symbol, Solution solution) { AssertIsForeground(); IVsHierarchy hierarchy; IVsSymbolicNavigationNotify navigationNotify; string rqname; uint itemID; if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname)) { return false; } int navigationHandled; int returnCode = navigationNotify.OnBeforeNavigateToSymbol( hierarchy, itemID, rqname, out navigationHandled); if (returnCode == VSConstants.S_OK && navigationHandled == 1) { return true; } return false; } public bool WouldNavigateToSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset) { if (WouldNotifyToSpecificSymbol(symbol, solution, out filePath, out lineNumber, out charOffset)) { return true; } // If the symbol being considered is a constructor and no third parties choose to // navigate to the constructor, then try the constructor's containing type. if (symbol.IsConstructor() && WouldNotifyToSpecificSymbol(symbol.ContainingType, solution, out filePath, out lineNumber, out charOffset)) { return true; } filePath = null; lineNumber = 0; charOffset = 0; return false; } public bool WouldNotifyToSpecificSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset) { AssertIsForeground(); filePath = null; lineNumber = 0; charOffset = 0; IVsHierarchy hierarchy; IVsSymbolicNavigationNotify navigationNotify; string rqname; uint itemID; if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname)) { return false; } IVsHierarchy navigateToHierarchy; uint navigateToItem; int wouldNavigate; var navigateToTextSpan = new Microsoft.VisualStudio.TextManager.Interop.TextSpan[1]; int queryNavigateStatusCode = navigationNotify.QueryNavigateToSymbol( hierarchy, itemID, rqname, out navigateToHierarchy, out navigateToItem, navigateToTextSpan, out wouldNavigate); if (queryNavigateStatusCode == VSConstants.S_OK && wouldNavigate == 1) { navigateToHierarchy.GetCanonicalName(navigateToItem, out filePath); lineNumber = navigateToTextSpan[0].iStartLine; charOffset = navigateToTextSpan[0].iStartIndex; return true; } return false; } private bool TryGetNavigationAPIRequiredArguments( ISymbol symbol, Solution solution, out IVsHierarchy hierarchy, out uint itemID, out IVsSymbolicNavigationNotify navigationNotify, out string rqname) { AssertIsForeground(); hierarchy = null; navigationNotify = null; rqname = null; itemID = (uint)VSConstants.VSITEMID.Nil; if (!symbol.Locations.Any()) { return false; } var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource); if (!sourceLocations.Any()) { return false; } var documents = sourceLocations.Select(loc => solution.GetDocument(loc.SourceTree)).WhereNotNull(); if (!documents.Any()) { return false; } // We can only pass one itemid to IVsSymbolicNavigationNotify, so prefer itemids from // documents we consider to be "generated" to give external language services the best // chance of participating. var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>(); var generatedDocuments = documents.Where(d => generatedCodeRecognitionService.IsGeneratedCode(d)); var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First(); if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID)) { return false; } navigationNotify = hierarchy as IVsSymbolicNavigationNotify; if (navigationNotify == null) { return false; } rqname = LanguageServices.RQName.From(symbol); return rqname != null; } private bool TryGetVsHierarchyAndItemId(Document document, out IVsHierarchy hierarchy, out uint itemID) { AssertIsForeground(); var visualStudioWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (visualStudioWorkspace != null) { var hostProject = visualStudioWorkspace.GetHostProject(document.Project.Id); hierarchy = hostProject.Hierarchy; itemID = hostProject.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); return true; } hierarchy = null; itemID = (uint)VSConstants.VSITEMID.Nil; return false; } private IVsRunningDocumentTable GetRunningDocumentTable() { var runningDocumentTable = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable>(); Debug.Assert(runningDocumentTable != null); return runningDocumentTable; } } }
//------------------------------------------------------------------------------ // <copyright file="PageSetupDialog.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using Microsoft.Win32; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Printing; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Globalization; /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog"]/*' /> /// <devdoc> /// <para> Represents /// a dialog box that allows users to manipulate page settings, including margins and paper orientation.</para> /// </devdoc> [DefaultProperty("Document")] [SRDescription(SR.DescriptionPageSetupDialog)] // The only event this dialog has is HelpRequested, which isn't very useful public sealed class PageSetupDialog : CommonDialog { // If PrintDocument != null, pageSettings == printDocument.PageSettings private PrintDocument printDocument = null; private PageSettings pageSettings = null; private PrinterSettings printerSettings = null; private bool allowMargins; private bool allowOrientation; private bool allowPaper; private bool allowPrinter; private Margins minMargins; private bool showHelp; private bool showNetwork; private bool enableMetric; /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.PageSetupDialog"]/*' /> /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.PageSetupDialog'/> class.</para> /// </devdoc> public PageSetupDialog() { Reset(); } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.AllowMargins"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the margins section of the dialog box is enabled. /// /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.PSDallowMarginsDescr) ] public bool AllowMargins { get { return allowMargins; } set { allowMargins = value; } } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.AllowOrientation"]/*' /> /// <devdoc> /// <para> Gets or sets a value indicating whether the orientation section of the dialog box (landscape vs. portrait) /// is enabled. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.PSDallowOrientationDescr) ] public bool AllowOrientation { get { return allowOrientation;} set { allowOrientation = value;} } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.AllowPaper"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the paper section of the dialog box (paper size and paper source) /// is enabled. /// /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.PSDallowPaperDescr) ] public bool AllowPaper { get { return allowPaper;} set { allowPaper = value;} } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.AllowPrinter"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the Printer button is enabled. /// /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.PSDallowPrinterDescr) ] public bool AllowPrinter { get { return allowPrinter;} set { allowPrinter = value;} } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.Document"]/*' /> /// <devdoc> /// <para>Gets or sets a value indicating the <see cref='System.Drawing.Printing.PrintDocument'/> /// to get page settings from. /// </para> /// </devdoc> [ SRCategory(SR.CatData), DefaultValue(null), SRDescription(SR.PDdocumentDescr) ] public PrintDocument Document { get { return printDocument;} set { printDocument = value; if (printDocument != null) { pageSettings = printDocument.DefaultPageSettings; printerSettings = printDocument.PrinterSettings; } } } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.EnableMetric"]/*' /> /// <devdoc> /// This allows the user to override the current behavior where the Metric is converted to ThousandOfInch even for METRIC MEASUREMENTSYSTEM /// which returns a HUNDREDSOFMILLIMETER value. /// </devdoc> [ DefaultValue(false), SRDescription(SR.PSDenableMetricDescr), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] public bool EnableMetric { get { return enableMetric;} set { enableMetric = value;} } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.MinMargins"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating the minimum margins the /// user is allowed to select, in hundredths of an inch. /// /// </para> /// </devdoc> [ SRCategory(SR.CatData), SRDescription(SR.PSDminMarginsDescr) ] public Margins MinMargins { get { return minMargins;} set { if (value == null) value = new Margins(0, 0, 0, 0); minMargins = value; } } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.PageSettings"]/*' /> /// <devdoc> /// <para> /// Gets /// or sets /// a value indicating /// the page settings modified by the dialog box. /// /// </para> /// </devdoc> [ SRCategory(SR.CatData), DefaultValue(null), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(SR.PSDpageSettingsDescr) ] public PageSettings PageSettings { get { return pageSettings;} set { pageSettings = value; printDocument = null; } } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.PrinterSettings"]/*' /> /// <devdoc> /// <para> /// Gets /// or sets the printer /// settings the dialog box will modify if the user clicks the Printer button. /// </para> /// </devdoc> [ SRCategory(SR.CatData), DefaultValue(null), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(SR.PSDprinterSettingsDescr) ] public PrinterSettings PrinterSettings { get { return printerSettings;} set { printerSettings = value; printDocument = null; } } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.ShowHelp"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the Help button is visible. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(false), SRDescription(SR.PSDshowHelpDescr) ] public bool ShowHelp { get { return showHelp;} set { showHelp = value;} } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.ShowNetwork"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the Network button is visible. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.PSDshowNetworkDescr) ] public bool ShowNetwork { get { return showNetwork;} set { showNetwork = value;} } private int GetFlags() { int flags = 0; flags |= NativeMethods.PSD_ENABLEPAGESETUPHOOK; if (!allowMargins) flags |= NativeMethods.PSD_DISABLEMARGINS; if (!allowOrientation) flags |= NativeMethods.PSD_DISABLEORIENTATION; if (!allowPaper) flags |= NativeMethods.PSD_DISABLEPAPER; if (!allowPrinter || printerSettings == null) flags |= NativeMethods.PSD_DISABLEPRINTER; if (showHelp) flags |= NativeMethods.PSD_SHOWHELP; if (!showNetwork) flags |= NativeMethods.PSD_NONETWORKBUTTON; if (minMargins != null) flags |= NativeMethods.PSD_MINMARGINS; if (pageSettings.Margins != null) flags |= NativeMethods.PSD_MARGINS; // return flags; } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.Reset"]/*' /> /// <devdoc> /// <para> /// Resets all options to their default values. /// </para> /// </devdoc> public override void Reset() { allowMargins = true; allowOrientation = true; allowPaper = true; allowPrinter = true; MinMargins = null; // turns into Margin with all zeros pageSettings = null; printDocument = null; printerSettings = null; showHelp = false; showNetwork = true; } private void ResetMinMargins() { MinMargins = null; } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.ShouldSerializeMinMargins"]/*' /> /// <devdoc> /// <para> /// Indicates whether the <see cref='System.Windows.Forms.PageSetupDialog.MinMargins'/> /// property should be /// persisted. /// </para> /// </devdoc> private bool ShouldSerializeMinMargins() { return minMargins.Left != 0 || minMargins.Right != 0 || minMargins.Top != 0 || minMargins.Bottom != 0; } private static void UpdateSettings(NativeMethods.PAGESETUPDLG data, PageSettings pageSettings, PrinterSettings printerSettings) { // SetHDevMode demands AllPrintingAndUnmanagedCode Permission : Since we are calling that function we should Assert the permision, IntSecurity.AllPrintingAndUnmanagedCode.Assert(); try { pageSettings.SetHdevmode(data.hDevMode); if (printerSettings != null) { printerSettings.SetHdevmode(data.hDevMode); printerSettings.SetHdevnames(data.hDevNames); } } finally { CodeAccessPermission.RevertAssert(); } Margins newMargins = new Margins(); newMargins.Left = data.marginLeft; newMargins.Top = data.marginTop; newMargins.Right = data.marginRight; newMargins.Bottom = data.marginBottom; PrinterUnit fromUnit = ((data.Flags & NativeMethods.PSD_INHUNDREDTHSOFMILLIMETERS) != 0) ? PrinterUnit.HundredthsOfAMillimeter : PrinterUnit.ThousandthsOfAnInch; pageSettings.Margins = PrinterUnitConvert.Convert(newMargins, fromUnit, PrinterUnit.Display); } /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.RunDialog"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> protected override bool RunDialog(IntPtr hwndOwner) { IntSecurity.SafePrinting.Demand(); NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); if (pageSettings == null) throw new ArgumentException(SR.GetString(SR.PSDcantShowWithoutPage)); NativeMethods.PAGESETUPDLG data = new NativeMethods.PAGESETUPDLG(); data.lStructSize = Marshal.SizeOf(data); data.Flags = GetFlags(); data.hwndOwner = hwndOwner; data.lpfnPageSetupHook = hookProcPtr; PrinterUnit toUnit = PrinterUnit.ThousandthsOfAnInch; // Refer VSWhidbey: 331160. Below was a breaking change from RTM and EVERETT even though this was a correct FIX. // EnableMetric is a new Whidbey property which we allow the users to choose between the AutoConversion or not. if (EnableMetric) { //take the Units of Measurement while determining the PrinterUnits... //bug (121347)... StringBuilder sb = new StringBuilder(2); int result = UnsafeNativeMethods.GetLocaleInfo(NativeMethods.LOCALE_USER_DEFAULT,NativeMethods.LOCALE_IMEASURE, sb,sb.Capacity); if (result > 0 && Int32.Parse(sb.ToString(), CultureInfo.InvariantCulture) == 0) { toUnit = PrinterUnit.HundredthsOfAMillimeter; } } if (MinMargins != null) { Margins margins = PrinterUnitConvert.Convert(MinMargins, PrinterUnit.Display, toUnit); data.minMarginLeft = margins.Left; data.minMarginTop = margins.Top; data.minMarginRight = margins.Right; data.minMarginBottom = margins.Bottom; } if (pageSettings.Margins != null) { Margins margins = PrinterUnitConvert.Convert(pageSettings.Margins, PrinterUnit.Display, toUnit); data.marginLeft = margins.Left; data.marginTop = margins.Top; data.marginRight = margins.Right; data.marginBottom = margins.Bottom; } // Ensure that the margins are >= minMargins. // This is a requirement of the PAGESETUPDLG structure. // data.marginLeft = Math.Max(data.marginLeft, data.minMarginLeft); data.marginTop = Math.Max(data.marginTop, data.minMarginTop); data.marginRight = Math.Max(data.marginRight, data.minMarginRight); data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom); PrinterSettings printer = (printerSettings == null) ? pageSettings.PrinterSettings : printerSettings; // GetHDevmode demands AllPrintingAndUnmanagedCode Permission : Since we are calling that function we should Assert the permision, IntSecurity.AllPrintingAndUnmanagedCode.Assert(); try { data.hDevMode = printer.GetHdevmode(pageSettings); data.hDevNames = printer.GetHdevnames(); } finally { CodeAccessPermission.RevertAssert(); } try { bool status = UnsafeNativeMethods.PageSetupDlg(data); if (!status) { // Debug.WriteLine(Windows.CommonDialogErrorToString(Windows.CommDlgExtendedError())); return false; } UpdateSettings(data, pageSettings, printerSettings); // yes, printerSettings, not printer return true; } finally { UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode)); UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames)); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// FunctionResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Serverless.V1.Service { public class FunctionResource : Resource { private static Request BuildReadRequest(ReadFunctionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Serverless, "/v1/Services/" + options.PathServiceSid + "/Functions", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Functions. /// </summary> /// <param name="options"> Read Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static ResourceSet<FunctionResource> Read(ReadFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<FunctionResource>.FromJson("functions", response.Content); return new ResourceSet<FunctionResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Functions. /// </summary> /// <param name="options"> Read Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<ResourceSet<FunctionResource>> ReadAsync(ReadFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<FunctionResource>.FromJson("functions", response.Content); return new ResourceSet<FunctionResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Functions. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the Function resources from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static ResourceSet<FunctionResource> Read(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadFunctionOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Functions. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the Function resources from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<ResourceSet<FunctionResource>> ReadAsync(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadFunctionOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<FunctionResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<FunctionResource>.FromJson("functions", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<FunctionResource> NextPage(Page<FunctionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Serverless) ); var response = client.Request(request); return Page<FunctionResource>.FromJson("functions", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<FunctionResource> PreviousPage(Page<FunctionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Serverless) ); var response = client.Request(request); return Page<FunctionResource>.FromJson("functions", response.Content); } private static Request BuildFetchRequest(FetchFunctionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Serverless, "/v1/Services/" + options.PathServiceSid + "/Functions/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a specific Function resource. /// </summary> /// <param name="options"> Fetch Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static FunctionResource Fetch(FetchFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Retrieve a specific Function resource. /// </summary> /// <param name="options"> Fetch Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<FunctionResource> FetchAsync(FetchFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Retrieve a specific Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static FunctionResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchFunctionOptions(pathServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Retrieve a specific Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<FunctionResource> FetchAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchFunctionOptions(pathServiceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteFunctionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Serverless, "/v1/Services/" + options.PathServiceSid + "/Functions/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a Function resource. /// </summary> /// <param name="options"> Delete Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static bool Delete(DeleteFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a Function resource. /// </summary> /// <param name="options"> Delete Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteFunctionOptions(pathServiceSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteFunctionOptions(pathServiceSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateFunctionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Serverless, "/v1/Services/" + options.PathServiceSid + "/Functions", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new Function resource. /// </summary> /// <param name="options"> Create Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static FunctionResource Create(CreateFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new Function resource. /// </summary> /// <param name="options"> Create Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<FunctionResource> CreateAsync(CreateFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the Function resource under </param> /// <param name="friendlyName"> A string to describe the Function resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static FunctionResource Create(string pathServiceSid, string friendlyName, ITwilioRestClient client = null) { var options = new CreateFunctionOptions(pathServiceSid, friendlyName); return Create(options, client); } #if !NET35 /// <summary> /// Create a new Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the Function resource under </param> /// <param name="friendlyName"> A string to describe the Function resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<FunctionResource> CreateAsync(string pathServiceSid, string friendlyName, ITwilioRestClient client = null) { var options = new CreateFunctionOptions(pathServiceSid, friendlyName); return await CreateAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateFunctionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Serverless, "/v1/Services/" + options.PathServiceSid + "/Functions/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update a specific Function resource. /// </summary> /// <param name="options"> Update Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static FunctionResource Update(UpdateFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update a specific Function resource. /// </summary> /// <param name="options"> Update Function parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<FunctionResource> UpdateAsync(UpdateFunctionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update a specific Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to update </param> /// <param name="friendlyName"> A string to describe the Function resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Function </returns> public static FunctionResource Update(string pathServiceSid, string pathSid, string friendlyName, ITwilioRestClient client = null) { var options = new UpdateFunctionOptions(pathServiceSid, pathSid, friendlyName); return Update(options, client); } #if !NET35 /// <summary> /// Update a specific Function resource. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to update </param> /// <param name="friendlyName"> A string to describe the Function resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Function </returns> public static async System.Threading.Tasks.Task<FunctionResource> UpdateAsync(string pathServiceSid, string pathSid, string friendlyName, ITwilioRestClient client = null) { var options = new UpdateFunctionOptions(pathServiceSid, pathSid, friendlyName); return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a FunctionResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> FunctionResource object represented by the provided JSON </returns> public static FunctionResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<FunctionResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the Function resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the Function resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the Function resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The string that you assigned to describe the Function resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the Function resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the Function resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the Function resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of nested resources of the Function resource /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private FunctionResource() { } } }
using System; using System.IO; using System.Text; using System.Windows.Forms; using mk.Logic; using ScintillaNET; namespace zenQuery { public partial class frmMdi : Form { /// <summary> /// Initialize /// </summary> public frmMdi() { System.Threading.Thread.CurrentThread.Name = "Main Thread"; // to ease debugging // I personally really dislike the OfficeXP look on Windows XP with the blue. ToolStripManager.RenderMode = ToolStripManagerRenderMode.Professional; ((ToolStripProfessionalRenderer)ToolStripManager.Renderer).ColorTable.UseSystemColors = true; // ToolStripComboBox tsx = (ToolStripComboBox)ts.Items["tsResult"]; InitializeComponent(); } #region Resizing Forms // Variables having to do with the resizing code follow protected bool bSizeMode = false; /// <summary> /// Windows Constants for WndProc call in BeginResize/EndResize events /// </summary> protected const int WM_SIZING = 0x214, WM_ENTERSIZEMOVE = 0x231, WM_EXITSIZEMOVE = 0x232, WM_SYSCOMMAND = 0x112, SC_SIZE = 0xF000; /// <summary> /// Fires once at the beginning of a resizing drag. /// </summary> public event EventHandler BeginResize; /// <summary> /// Fires once at the end of a resizing drag. /// </summary> public event EventHandler EndResize; /// <summary> /// Process Windows messages (in this case to provide Begin/EndResize events /// </summary> /// <param name="m"></param> //protected override void WndProc(ref Message m) //{ // simpleDebug.dump(); // switch (m.Msg) // { // case WM_SIZING: // // Resize event already provided // break; // case WM_SYSCOMMAND: // bSizeMode = ((m.WParam.ToInt32() & 0xFFF0) == SC_SIZE); // break; // case WM_ENTERSIZEMOVE: // if (bSizeMode) // { // OnBeginResize(EventArgs.Empty); // } // break; // case WM_EXITSIZEMOVE: // { // if (bSizeMode) // { // OnEndResize(EventArgs.Empty); // } // break; // } // } // end switch // base.WndProc(ref m); //} /// <summary> /// Wylaczone Raise BeginResize event wylaczone /// </summary> /// <param name="e"></param> protected virtual void OnBeginResize(System.EventArgs e) { simpleDebug.dump(); if (BeginResize != null) BeginResize(this, e); } /// <summary> /// Raise EndResize event /// </summary> /// <param name="e"></param> protected virtual void OnEndResize(System.EventArgs e) { simpleDebug.dump(); if (EndResize != null) EndResize(this, e); } private void frmMdi_ResizeBegin(object sender, EventArgs e) { simpleDebug.dump(); OnBeginResize(e); } private void frmMdi_ResizeEnd(object sender, EventArgs e) { simpleDebug.dump(); OnEndResize(e); } #endregion #region mkObslugaFormularzy: isFormAlreadyLoaded, Laduj Formularz x /// <summary> /// czy zaladowany formularz /// </summary> /// <param name="formToLoadName"></param> /// <returns></returns> private bool isFormAlreadyLoaded(string formToLoadName) { foreach (Form frmChild in this.MdiChildren) { if (frmChild.Name == formToLoadName) { frmChild.Activate(); return true; } } return false; } /// <summary>Laduj frmHistory</summary> private void tsQueryHistory_Click(object sender, EventArgs e) { simpleDebug.dump(); if (!isFormAlreadyLoaded("frmHistory")) { frmHistory c = new frmHistory(); c.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; c.Text = "zenQuery History"; c.Show(dockPanel); } setFrmDocumentMenu(); } /// <summary>Laduj frmsnippets</summary> private void tsSnippets_Click(object sender, EventArgs e) { if (!isFormAlreadyLoaded("frmaction")) { frmaction c = new frmaction(); c.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; c.Text = "Actions"; c.Show(dockPanel); //refresh akcji } setFrmDocumentMenu(); } #endregion #region Menu menuStripMain , czyli pasek menu u gory standardowe opcje private void closeToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Close(); } private void printToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Printing.Print(); } private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Printing.PrintPreview(); } private void frmMdi_Load(object sender, EventArgs e) { simpleDebug.dump(); DoConnect(); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Save(); } private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.SaveAs(); } private void saveAllStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); foreach (frmDocument doc in dockPanel.Documents) { doc.Activate(); doc.Save(); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); Close(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); OpenFile(); } public bool OpenFile() { if (IsChildActive()) { //wroc jesli nie wybrales ok if (openFileDialog.ShowDialog() != DialogResult.OK) return false; byte[] data = null; using (FileStream fs = File.Open(openFileDialog.FileName, FileMode.Open)) { data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); } UTF8Encoding temp = new UTF8Encoding(true); GetQueryChild().setText(temp.GetString(data)); return true; } return false; } private void undoToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.UndoRedo.Undo(); } private void redoToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.UndoRedo.Redo(); } private void cutToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Clipboard.Cut(); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Clipboard.Copy(); ActiveDocument.Document.AutoComplete.List.Insert(0, "asdasd"); ActiveDocument.Document.AutoComplete.Show(); } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Clipboard.Paste(); } private void selectAllToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Selection.SelectAll(); } private void findToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.FindReplace.ShowFind(); } private void replaceToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.FindReplace.ShowReplace(); } private void goToToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.GoTo.ShowGoToDialog(); } private void toggleBookmarkToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Lines.Current.AddMarker(0); } private void previosBookmarkToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); // I've got to redo this whole FindNextMarker/FindPreviousMarker Scheme Line l = ActiveDocument.Document.Lines.Current.FindPreviousMarker(1); if (l != null) l.Goto(); } private void nextBookmarkToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); // I've got to redo this whole FindNextMarker/FindPreviousMarker Scheme Line l = ActiveDocument.Document.Lines.Current.FindNextMarker(1); if (l != null) l.Goto(); } private void clearBookmarsToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Markers.DeleteAll(0); } private void collectToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.DropMarkers.Collect(); } private void makeUpperCaseToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Commands.Execute(BindableCommand.UpperCase); } private void makeLowerCaseToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Commands.Execute(BindableCommand.LowerCase); } private void commentStreamToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Commands.Execute(BindableCommand.StreamComment); } private void commentLineToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Commands.Execute(BindableCommand.LineComment); } private void uncommentLineToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Commands.Execute(BindableCommand.LineUncomment); } private void insertSnippetToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Snippets.ShowSnippetList(); } private void surroundWithToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Snippets.ShowSurroundWithList(); } private void whiteSpaceToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); whiteSpaceToolStripMenuItem.Checked = !whiteSpaceToolStripMenuItem.Checked; //if (whiteSpaceToolStripMenuItem.Checked) //{ // ActiveDocument.Document.WhiteSpace.Mode = WhiteSpaceMode.VisibleAlways; //} //else //{ // ActiveDocument.Document.WhiteSpace.Mode = WhiteSpaceMode.Invisible; //} } private void wordWrapToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); wordWrapToolStripMenuItem.Checked = !wordWrapToolStripMenuItem.Checked; //TODO find new method //if (wordWrapToolStripMenuItem.Checked) //{ // ActiveDocument.Document.LineWrapping.Mode = LineWrapping.Word; //} //else //{ // ActiveDocument.Document.LineWrap.Mode = WrapMode.None; //} } private void endOfLineToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); endOfLineToolStripMenuItem.Checked = !endOfLineToolStripMenuItem.Checked; ActiveDocument.Document.EndOfLine.IsVisible = endOfLineToolStripMenuItem.Checked; } private void zoomInToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ZoomIn(); } private void zoomOutToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ZoomOut(); } private void resetZoomToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ZoomFactor = 0; } private void foldLevelToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Lines.Current.FoldExpanded = true; } private void unfoldLevelToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.Lines.Current.FoldExpanded = false; } private void foldAllToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); foreach (Line l in ActiveDocument.Document.Lines) { l.FoldExpanded = true; } } private void unfoldAllToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); foreach (Line l in ActiveDocument.Document.Lines) { l.FoldExpanded = true; } } private void cToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ConfigurationManager.Language = "cs"; ActiveDocument.Document.Indentation.SmartIndentType = SmartIndent.CPP; } private void plainTextToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ConfigurationManager.Language = ""; } private void hTMLToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ConfigurationManager.Language = "html"; } private void mSSQLToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ConfigurationManager.Language = "mssql"; } private void vBScriptToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ConfigurationManager.Language = "vbscript"; } private void pythonToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ConfigurationManager.Language = "python"; } private void xMLToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.ConfigurationManager.Language = "xml"; } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); new frmAbout().ShowDialog(this); } private void lineNumbersToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); lineNumbersToolStripMenuItem.Checked = !lineNumbersToolStripMenuItem.Checked; if (lineNumbersToolStripMenuItem.Checked) ActiveDocument.Document.Margins.Margin0.Width = 20; else ActiveDocument.Document.Margins.Margin0.Width = 0; } private void navigateForwardToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.DocumentNavigation.NavigateForward(); } private void navigateBackwardToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); ActiveDocument.Document.DocumentNavigation.NavigateBackward(); } private void newToolStripMenuItem_Click(object sender, EventArgs e) { simpleDebug.dump(); //NewDocument(); } #endregion #region SCIDE /// <summary> /// Numer dokumentu w programie /// </summary> public int _newDocumentCount = 0; /// <summary> /// Aktywny dokument w mdi /// </summary> public frmDocument ActiveDocument { get { return dockPanel.ActiveDocument as frmDocument; } } #endregion /// <summary> /// Uruchamijac sprawdza jaki typ okna jest czy jest to dokument /// czy nie i ukrywa menu etc /// </summary> private void setFrmDocumentMenu() { if (ActiveMdiChild == null || ActiveMdiChild.Name != "frmDocument") { frmDocumentMenu(false); } else { frmDocumentMenu(true); } } private void frmDocumentMenu(bool _enabled) { tsDisconnect.Enabled = _enabled; tsNew.Enabled = _enabled; tsOpen.Enabled = _enabled; tsSave.Enabled = _enabled; tsExecute.Enabled = _enabled; tsCancel.Enabled = _enabled; tsResult.Enabled = _enabled; tsHideResults.Enabled = _enabled; tsHideBrowser.Enabled = _enabled; tsBeautyCode.Enabled = _enabled; editToolStripMenu.Enabled = _enabled; viewStripMenuItem.Enabled = _enabled; newToolStripMenuItem.Enabled = _enabled; openToolStripMenuItem.Enabled = _enabled; saveToolStripMenuItem.Enabled = _enabled; saveAsToolStripMenuItem.Enabled = _enabled; saveAllStripMenuItem.Enabled = _enabled; printToolStripMenuItem.Enabled = _enabled; printPreviewToolStripMenuItem.Enabled = _enabled; } /// <summary> /// Wywolanie polaczenia /// </summary> private void tsConnect_Click(object sender, EventArgs e) { DoConnect(); } private void DoConnect() { simpleDebug.dump(); ConnectForm cf = new ConnectForm(); if (cf.ShowDialog() == DialogResult.OK) { //MK frmDocument qf = new frmDocument(cf.DbClient, cf.Browser, cf.LowBandwidth, "MSSQL"); qf.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; qf.Text = "Query" + ++_newDocumentCount; qf.Show(dockPanel); } } /// <summary>Sprzawdza czy biezacy formularz to frmDocument</summary> bool IsChildActive() { if (ActiveMdiChild != null) { if (ActiveMdiChild.Name == "frmDocument") return true; } return false; } /// <summary> /// biezacy aktywny dokument /// </summary> /// <returns></returns> frmDocument GetQueryChild() { return (frmDocument)ActiveMdiChild; } private void tsDisconnect_Click(object sender, EventArgs e) { if (IsChildActive()) GetQueryChild().Close(); } private void tsOpen_Click(object sender, EventArgs e) { simpleDebug.dump(); //TODO: openfile if (IsChildActive()) OpenFile(); } private void tsSave_Click(object sender, EventArgs e) { simpleDebug.dump(); if (IsChildActive()) GetQueryChild().Save(); } private void tsExecute_Click(object sender, EventArgs e) { simpleDebug.dump(); if (IsChildActive()) GetQueryChild().Execute(tsResult.Text); } private void tsCancel_Click(object sender, EventArgs e) { simpleDebug.dump(); if (IsChildActive()) GetQueryChild().Cancel(); } private void tsHideResults_Click(object sender, EventArgs e) { simpleDebug.dump(); if (IsChildActive()) GetQueryChild().HideResults = !GetQueryChild().HideResults; } private void tsHideBrowser_Click(object sender, EventArgs e) { simpleDebug.dump(); if (IsChildActive()) GetQueryChild().HideBrowser = !GetQueryChild().HideBrowser; } private void tsBeautyCode_Click(object sender, EventArgs e) { simpleDebug.dump(); try { if (IsChildActive()) GetQueryChild().Formatt(); } catch (Exception) { MessageBox.Show(this, "Nothing to beauty or engine error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } #region Output result /// <summary> /// Wybranie output text lub grid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tsResult_SelectedIndexChanged(object sender, EventArgs e) { if (tsResult.SelectedItem.ToString() == "Result Grid" || tsResult.SelectedItem.ToString() == "Result Grid Trans.") { DoResultsInGrid(); } else { DoResultsInText(); } globals._resultType = tsResult.SelectedItem.ToString(); } private void DoResultsInText() { // Changing the value of this property will automatically invoke the QueryForm's // PropertyChanged event, which we've wired to EnableControls(). if (IsChildActive()) { GetQueryChild().ResultsInText = true; GetQueryChild().ResultType = tsResult.SelectedItem.ToString(); } } private void DoResultsInGrid() { // Changing the value of this property will automatically invoke the QueryForm's // PropertyChanged event, which we've wired to EnableControls(). if (IsChildActive()) { GetQueryChild().ResultType = tsResult.SelectedItem.ToString(); GetQueryChild().ResultsInText = false; } } #endregion private void tsNew_Click(object sender, EventArgs e) { simpleDebug.dump(); if (IsChildActive()) { // Change the cursor to an hourglass while we're doing this, in case establishing the // new connection takes some time. Cursor oldCursor = Cursor; Cursor = Cursors.WaitCursor; frmDocument newQF = GetQueryChild().Clone(); if (newQF != null) // could be null if new connection failed { newQF.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; newQF.Text = "Query" + ++_newDocumentCount; newQF.Show(dockPanel); // This is so that we can update the toolbar and menu as the state of the QueryForm changes. //newQF.PropertyChanged += new EventHandler(ChildPropertyChanged); } Cursor = oldCursor; } } private void btnsearch_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtsearch.Text.Trim())) { MessageBox.Show(this, "You must provide search string.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); txtsearch.Focus(); return; } foreach (Form frmChild in this.MdiChildren) { if (frmChild.Name == "frmDocument") { frmDocument y = (frmDocument)frmChild; TreeView treeView = y.tree; treeView.BeginUpdate(); treeView.Nodes.Clear(); y.PopulateBrowser(); if (this.txtsearch.Text != string.Empty) { foreach (TreeNode _parentNode in treeView.Nodes) { int nodescount = _parentNode.Nodes.Count; for (int i = 0; i < nodescount; i++) { if (nodescount == 0) break; TreeNode x = _parentNode.Nodes[i]; if (x == null) break; if (x.Text.IndexOf(this.txtsearch.Text, StringComparison.InvariantCultureIgnoreCase) == -1) { _parentNode.Nodes[i].Remove(); i--; nodescount--; } } } } //enables redrawing tree after all objects have been added treeView.EndUpdate(); } } Cursor oldCursor = Cursor; Cursor = Cursors.WaitCursor; //frmDocument qf = new frmDocument(cf.DbClient, cf.Browser, cf.LowBandwidth, "MSSQL"); //qf.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; //qf.Text = "Query" + ++_newDocumentCount; //qf.Show(dockPanel); frmSearch c = new frmSearch(chkobjecttext.Checked, txtsearch.Text, GetQueryChild().DbClient); c.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; c.Text = "Search Result" + ++_newDocumentCount; c.Show(dockPanel); //c.Show(); Cursor = oldCursor; } private void chkobjectname_CheckedChanged(object sender, EventArgs e) { chkobjecttext.Checked = false; } private void chkobjecttext_CheckedChanged(object sender, EventArgs e) { chkobjectname.Checked = false; } private void dockPanel_ActiveDocumentChanged_1(object sender, EventArgs e) { simpleDebug.dump(); setFrmDocumentMenu(); } //private void DoNew() //{ // if (IsChildActive()) // { // // Change the cursor to an hourglass while we're doing this, in case establishing the // // new connection takes some time. // Cursor oldCursor = Cursor; // Cursor = Cursors.WaitCursor; // frmDocument newQF = GetQueryChild().Clone(); // if (newQF != null) // could be null if new connection failed // { // ((Form)newQF).MdiParent = this; // newQF.PropertyChanged += new EventHandler<EventArgs>(PropertyChanged); // ((Form)newQF).Show(); // } // Cursor = oldCursor; // } // else // DoConnect(); //} } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="GlobalLB.VirtualServerBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBVirtualServerDefinition))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBVirtualServerVirtualServerStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBVirtualServerVirtualServerMetricLimit))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBVirtualServerMonitorAssociation))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonObjectStatus))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonIPPortDefinition))] public partial class GlobalLBVirtualServer : iControlInterface { public GlobalLBVirtualServer() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_dependency //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void add_dependency( GlobalLBVirtualServerDefinition [] virtual_servers, GlobalLBVirtualServerDefinition [] [] dependencies ) { this.Invoke("add_dependency", new object [] { virtual_servers, dependencies}); } public System.IAsyncResult Beginadd_dependency(GlobalLBVirtualServerDefinition [] virtual_servers,GlobalLBVirtualServerDefinition [] [] dependencies, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_dependency", new object[] { virtual_servers, dependencies}, callback, asyncState); } public void Endadd_dependency(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void create( GlobalLBVirtualServerDefinition [] virtual_servers, string [] servers ) { this.Invoke("create", new object [] { virtual_servers, servers}); } public System.IAsyncResult Begincreate(GlobalLBVirtualServerDefinition [] virtual_servers,string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { virtual_servers, servers}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_virtual_servers //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void delete_all_virtual_servers( ) { this.Invoke("delete_all_virtual_servers", new object [0]); } public System.IAsyncResult Begindelete_all_virtual_servers(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_virtual_servers", new object[0], callback, asyncState); } public void Enddelete_all_virtual_servers(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_virtual_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void delete_virtual_server( GlobalLBVirtualServerDefinition [] virtual_servers ) { this.Invoke("delete_virtual_server", new object [] { virtual_servers}); } public System.IAsyncResult Begindelete_virtual_server(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_virtual_server", new object[] { virtual_servers}, callback, asyncState); } public void Enddelete_virtual_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBVirtualServerVirtualServerStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((GlobalLBVirtualServerVirtualServerStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public GlobalLBVirtualServerVirtualServerStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBVirtualServerVirtualServerStatistics)(results[0])); } //----------------------------------------------------------------------- // get_dependency //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBVirtualServerDefinition [] [] get_dependency( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_dependency", new object [] { virtual_servers}); return ((GlobalLBVirtualServerDefinition [] [])(results[0])); } public System.IAsyncResult Beginget_dependency(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dependency", new object[] { virtual_servers}, callback, asyncState); } public GlobalLBVirtualServerDefinition [] [] Endget_dependency(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBVirtualServerDefinition [] [])(results[0])); } //----------------------------------------------------------------------- // get_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_enabled_state( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_enabled_state", new object [] { virtual_servers}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_enabled_state(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_enabled_state", new object[] { virtual_servers}, callback, asyncState); } public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_limit //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBVirtualServerVirtualServerMetricLimit [] get_limit( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_limit", new object [] { virtual_servers}); return ((GlobalLBVirtualServerVirtualServerMetricLimit [])(results[0])); } public System.IAsyncResult Beginget_limit(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_limit", new object[] { virtual_servers}, callback, asyncState); } public GlobalLBVirtualServerVirtualServerMetricLimit [] Endget_limit(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBVirtualServerVirtualServerMetricLimit [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBVirtualServerDefinition [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((GlobalLBVirtualServerDefinition [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public GlobalLBVirtualServerDefinition [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBVirtualServerDefinition [])(results[0])); } //----------------------------------------------------------------------- // get_monitor_association //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBVirtualServerMonitorAssociation [] get_monitor_association( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_monitor_association", new object [] { virtual_servers}); return ((GlobalLBVirtualServerMonitorAssociation [])(results[0])); } public System.IAsyncResult Beginget_monitor_association(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_monitor_association", new object[] { virtual_servers}, callback, asyncState); } public GlobalLBVirtualServerMonitorAssociation [] Endget_monitor_association(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBVirtualServerMonitorAssociation [])(results[0])); } //----------------------------------------------------------------------- // get_object_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonObjectStatus [] get_object_status( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_object_status", new object [] { virtual_servers}); return ((CommonObjectStatus [])(results[0])); } public System.IAsyncResult Beginget_object_status(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_object_status", new object[] { virtual_servers}, callback, asyncState); } public CommonObjectStatus [] Endget_object_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonObjectStatus [])(results[0])); } //----------------------------------------------------------------------- // get_parent_link //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_parent_link( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_parent_link", new object [] { virtual_servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_parent_link(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_parent_link", new object[] { virtual_servers}, callback, asyncState); } public string [] Endget_parent_link(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_server( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_server", new object [] { virtual_servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_server(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_server", new object[] { virtual_servers}, callback, asyncState); } public string [] Endget_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBVirtualServerVirtualServerStatistics get_statistics( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_statistics", new object [] { virtual_servers}); return ((GlobalLBVirtualServerVirtualServerStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { virtual_servers}, callback, asyncState); } public GlobalLBVirtualServerVirtualServerStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBVirtualServerVirtualServerStatistics)(results[0])); } //----------------------------------------------------------------------- // get_translation //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonIPPortDefinition [] get_translation( GlobalLBVirtualServerDefinition [] virtual_servers ) { object [] results = this.Invoke("get_translation", new object [] { virtual_servers}); return ((CommonIPPortDefinition [])(results[0])); } public System.IAsyncResult Beginget_translation(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_translation", new object[] { virtual_servers}, callback, asyncState); } public CommonIPPortDefinition [] Endget_translation(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonIPPortDefinition [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // remove_all_dependencies //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void remove_all_dependencies( GlobalLBVirtualServerDefinition [] virtual_servers ) { this.Invoke("remove_all_dependencies", new object [] { virtual_servers}); } public System.IAsyncResult Beginremove_all_dependencies(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_dependencies", new object[] { virtual_servers}, callback, asyncState); } public void Endremove_all_dependencies(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_dependency //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void remove_dependency( GlobalLBVirtualServerDefinition [] virtual_servers, GlobalLBVirtualServerDefinition [] [] dependencies ) { this.Invoke("remove_dependency", new object [] { virtual_servers, dependencies}); } public System.IAsyncResult Beginremove_dependency(GlobalLBVirtualServerDefinition [] virtual_servers,GlobalLBVirtualServerDefinition [] [] dependencies, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_dependency", new object[] { virtual_servers, dependencies}, callback, asyncState); } public void Endremove_dependency(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_monitor_association //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void remove_monitor_association( GlobalLBVirtualServerDefinition [] virtual_servers ) { this.Invoke("remove_monitor_association", new object [] { virtual_servers}); } public System.IAsyncResult Beginremove_monitor_association(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_monitor_association", new object[] { virtual_servers}, callback, asyncState); } public void Endremove_monitor_association(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void reset_statistics( GlobalLBVirtualServerDefinition [] virtual_servers ) { this.Invoke("reset_statistics", new object [] { virtual_servers}); } public System.IAsyncResult Beginreset_statistics(GlobalLBVirtualServerDefinition [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { virtual_servers}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void set_enabled_state( GlobalLBVirtualServerDefinition [] virtual_servers, CommonEnabledState [] states ) { this.Invoke("set_enabled_state", new object [] { virtual_servers, states}); } public System.IAsyncResult Beginset_enabled_state(GlobalLBVirtualServerDefinition [] virtual_servers,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_enabled_state", new object[] { virtual_servers, states}, callback, asyncState); } public void Endset_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_limit //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void set_limit( GlobalLBVirtualServerVirtualServerMetricLimit [] limits ) { this.Invoke("set_limit", new object [] { limits}); } public System.IAsyncResult Beginset_limit(GlobalLBVirtualServerVirtualServerMetricLimit [] limits, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_limit", new object[] { limits}, callback, asyncState); } public void Endset_limit(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_monitor_association //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void set_monitor_association( GlobalLBVirtualServerMonitorAssociation [] monitor_associations ) { this.Invoke("set_monitor_association", new object [] { monitor_associations}); } public System.IAsyncResult Beginset_monitor_association(GlobalLBVirtualServerMonitorAssociation [] monitor_associations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_monitor_association", new object[] { monitor_associations}, callback, asyncState); } public void Endset_monitor_association(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void set_server( GlobalLBVirtualServerDefinition [] virtual_servers, string [] servers ) { this.Invoke("set_server", new object [] { virtual_servers, servers}); } public System.IAsyncResult Beginset_server(GlobalLBVirtualServerDefinition [] virtual_servers,string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_server", new object[] { virtual_servers, servers}, callback, asyncState); } public void Endset_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_translation //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/VirtualServer", RequestNamespace="urn:iControl:GlobalLB/VirtualServer", ResponseNamespace="urn:iControl:GlobalLB/VirtualServer")] public void set_translation( GlobalLBVirtualServerDefinition [] virtual_servers, CommonIPPortDefinition [] translations ) { this.Invoke("set_translation", new object [] { virtual_servers, translations}); } public System.IAsyncResult Beginset_translation(GlobalLBVirtualServerDefinition [] virtual_servers,CommonIPPortDefinition [] translations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_translation", new object[] { virtual_servers, translations}, callback, asyncState); } public void Endset_translation(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.VirtualServer.MonitorAssociation", Namespace = "urn:iControl")] public partial class GlobalLBVirtualServerMonitorAssociation { private GlobalLBVirtualServerDefinition virtual_serverField; public GlobalLBVirtualServerDefinition virtual_server { get { return this.virtual_serverField; } set { this.virtual_serverField = value; } } private GlobalLBMonitorRule monitor_ruleField; public GlobalLBMonitorRule monitor_rule { get { return this.monitor_ruleField; } set { this.monitor_ruleField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.VirtualServer.VirtualServerMetricLimit", Namespace = "urn:iControl")] public partial class GlobalLBVirtualServerVirtualServerMetricLimit { private GlobalLBVirtualServerDefinition virtual_serverField; public GlobalLBVirtualServerDefinition virtual_server { get { return this.virtual_serverField; } set { this.virtual_serverField = value; } } private GlobalLBMetricLimit [] metric_limitsField; public GlobalLBMetricLimit [] metric_limits { get { return this.metric_limitsField; } set { this.metric_limitsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.VirtualServer.VirtualServerStatisticEntry", Namespace = "urn:iControl")] public partial class GlobalLBVirtualServerVirtualServerStatisticEntry { private GlobalLBVirtualServerDefinition virtual_serverField; public GlobalLBVirtualServerDefinition virtual_server { get { return this.virtual_serverField; } set { this.virtual_serverField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.VirtualServer.VirtualServerStatistics", Namespace = "urn:iControl")] public partial class GlobalLBVirtualServerVirtualServerStatistics { private GlobalLBVirtualServerVirtualServerStatisticEntry [] statisticsField; public GlobalLBVirtualServerVirtualServerStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
//------------------------------------------------------------------------------ // <copyright file="SqlGuid.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">junfang</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ //************************************************************************** // @File: SqlGuid.cs // // Create by: JunFang // // Purpose: Implementation of SqlGuid which is equivalent to // data type "uniqueidentifier" in SQL Server // // Notes: // // History: // // 11/1/99 JunFang Created. // // @EndHeader@ //************************************************************************** using System; using System.Data.Common; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <devdoc> /// <para> /// Represents a globally unique identifier to be stored in /// or retrieved from a database. /// </para> /// </devdoc> [Serializable] [XmlSchemaProvider("GetXsdType")] public struct SqlGuid : INullable, IComparable, IXmlSerializable { private static readonly int SizeOfGuid = 16; // Comparison orders. private static readonly int[] x_rgiGuidOrder = new int[16] {10, 11, 12, 13, 14, 15, 8, 9, 6, 7, 4, 5, 0, 1, 2, 3}; private byte[] m_value; // the SqlGuid is null if m_value is null // constructor // construct a SqlGuid.Null private SqlGuid(bool fNull) { m_value = null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlGuid(byte[] value) { if (value == null || value.Length != SizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); m_value = new byte[SizeOfGuid]; value.CopyTo(m_value, 0); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal SqlGuid(byte[] value, bool ignored) { if (value == null || value.Length != SizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); m_value = value; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlGuid(String s) { m_value = (new Guid(s)).ToByteArray(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlGuid(Guid g) { m_value = g.ToByteArray(); } public SqlGuid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) : this(new Guid(a, b, c, d, e, f, g, h, i, j, k)) { } // INullable /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsNull { get { return(m_value == null);} } // property: Value /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Guid Value { get { if (IsNull) throw new SqlNullValueException(); else return new Guid(m_value); } } // Implicit conversion from Guid to SqlGuid /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static implicit operator SqlGuid(Guid x) { return new SqlGuid(x); } // Explicit conversion from SqlGuid to Guid. Throw exception if x is Null. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator Guid(SqlGuid x) { return x.Value; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public byte[] ToByteArray() { byte[] ret = new byte[SizeOfGuid]; m_value.CopyTo(ret, 0); return ret; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override String ToString() { if (IsNull) return SQLResource.NullString; Guid g = new Guid(m_value); return g.ToString(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlGuid Parse(String s) { if (s == SQLResource.NullString) return SqlGuid.Null; else return new SqlGuid(s); } // Comparison operators private static EComparison Compare(SqlGuid x, SqlGuid y) { //Swap to the correct order to be compared for (int i = 0; i < SizeOfGuid; i++) { byte b1, b2; b1 = x.m_value [x_rgiGuidOrder[i]]; b2 = y.m_value [x_rgiGuidOrder[i]]; if (b1 != b2) return(b1 < b2) ? EComparison.LT : EComparison.GT; } return EComparison.EQ; } // Implicit conversions // Explicit conversions // Explicit conversion from SqlString to SqlGuid /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlGuid(SqlString x) { return x.IsNull ? Null : new SqlGuid(x.Value); } // Explicit conversion from SqlBinary to SqlGuid /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlGuid(SqlBinary x) { return x.IsNull ? Null : new SqlGuid(x.Value); } // Overloading comparison operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator==(SqlGuid x, SqlGuid y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.EQ); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator!=(SqlGuid x, SqlGuid y) { return ! (x == y); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator<(SqlGuid x, SqlGuid y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.LT); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator>(SqlGuid x, SqlGuid y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.GT); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator<=(SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmp = Compare(x, y); return new SqlBoolean(cmp == EComparison.LT || cmp == EComparison.EQ); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator>=(SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmp = Compare(x, y); return new SqlBoolean(cmp == EComparison.GT || cmp == EComparison.EQ); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator == public static SqlBoolean Equals(SqlGuid x, SqlGuid y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlGuid x, SqlGuid y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlGuid x, SqlGuid y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlGuid x, SqlGuid y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlGuid x, SqlGuid y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlGuid x, SqlGuid y) { return (x >= y); } // Alternative method for conversions. public SqlString ToSqlString() { return (SqlString)this; } public SqlBinary ToSqlBinary() { return (SqlBinary)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int CompareTo(Object value) { if (value is SqlGuid) { SqlGuid i = (SqlGuid)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlGuid)); } public int CompareTo(SqlGuid value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool Equals(Object value) { if (!(value is SqlGuid)) { return false; } SqlGuid i = (SqlGuid)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // VSTFDevDiv# 479603 - SqlTypes read null value infinitely and never read the next value. Fix - Read the next value. reader.ReadElementString(); m_value = null; } else { m_value = new Guid(reader.ReadElementString()).ToByteArray(); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(new Guid(m_value))); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("string", XmlSchema.Namespace); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly SqlGuid Null = new SqlGuid(true); } // SqlGuid } // namespace System.Data.SqlTypes
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Diagnostics; using System.IO; using CoinSharp.Collections.Generic; using CoinSharp.IO; using Org.BouncyCastle.Math; using log4net; namespace CoinSharp.Store { /// <summary> /// Stores the block chain to disk. /// </summary> /// <remarks> /// This implementation is designed to have constant memory usage, regardless of the size of the block chain being /// stored. It exploits operating system level buffering and the fact that get() requests are, in normal usage, /// localized in chain space.<p/> /// Blocks are stored sequentially. Most blocks are fetched out of a small in-memory cache. The slowest part is /// traversing difficulty transition points, which requires seeking backwards over around 2000 blocks. On a Google /// Nexus S phone this takes a couple of seconds. On a MacBook Pro it takes around 50msec.<p/> /// The store has much room for optimization. Expanding the size of the cache will likely allow us to traverse /// difficulty transitions without using too much memory and without hitting the disk at all, for the case of initial /// block chain download. Storing the hashes on disk would allow us to avoid deserialization and hashing which is /// expensive on Android. /// </remarks> public class BoundedOverheadBlockStore : IBlockStore { private static readonly ILog Log = Common.Logger.GetLoggerForDeclaringType(); private const byte _fileFormatVersion = 1; // We keep some recently found blocks in the blockCache. It can help to optimize some cases where we are // looking up blocks we recently stored or requested. When the cache gets too big older entries are deleted. private readonly OrderedDictionary<Sha256Hash, StoredBlock> _blockCache = new OrderedDictionary<Sha256Hash, StoredBlock>(); // Use a separate cache to track get() misses. This is to efficiently handle the case of an unconnected block // during chain download. Each new block will do a get() on the unconnected block so if we haven't seen it yet we // must efficiently respond. // // We don't care about the value in this cache. It is always notFoundMarker. Unfortunately LinkedHashSet does not // provide the removeEldestEntry control. private readonly StoredBlock _notFoundMarker = new StoredBlock(null, null, uint.MaxValue); private readonly OrderedDictionary<Sha256Hash, StoredBlock> _notFoundCache = new OrderedDictionary<Sha256Hash, StoredBlock>(); private Sha256Hash _chainHead; private readonly NetworkParameters _params; private FileStream _channel; private class Record { // A BigInteger representing the total amount of work done so far on this chain. As of May 2011 it takes 8 // bytes to represent this field, so 16 bytes should be plenty for a long time. private const int _chainWorkBytes = 16; private static readonly byte[] _emptyBytes = new byte[_chainWorkBytes]; private uint _height; // 4 bytes private readonly byte[] _chainWork; // 16 bytes private readonly byte[] _blockHeader; // 80 bytes public const int Size = 4 + _chainWorkBytes + Block.HeaderSize; public Record() { _height = 0; _chainWork = new byte[_chainWorkBytes]; _blockHeader = new byte[Block.HeaderSize]; } /// <exception cref="IOException"/> public static void Write(Stream channel, StoredBlock block) { using (var buf = ByteBuffer.Allocate(Size)) { buf.PutInt((int) block.Height); var chainWorkBytes = block.ChainWork.ToByteArray(); Debug.Assert(chainWorkBytes.Length <= _chainWorkBytes, "Ran out of space to store chain work!"); if (chainWorkBytes.Length < _chainWorkBytes) { // Pad to the right size. buf.Put(_emptyBytes, 0, _chainWorkBytes - chainWorkBytes.Length); } buf.Put(chainWorkBytes); buf.Put(block.Header.BitcoinSerialize()); buf.Position = 0; channel.Position = channel.Length; channel.Write(buf.ToArray()); channel.Position = channel.Length - Size; } } /// <exception cref="IOException"/> public bool Read(Stream channel, long position, ByteBuffer buffer) { buffer.Position = 0; var originalPos = channel.Position; channel.Position = position; var data = new byte[buffer.Length]; var bytesRead = channel.Read(data); buffer.Clear(); buffer.Write(data); channel.Position = originalPos; if (bytesRead < Size) return false; buffer.Position = 0; _height = (uint) buffer.GetInt(); buffer.Get(_chainWork); buffer.Get(_blockHeader); return true; } public BigInteger ChainWork { get { return new BigInteger(1, _chainWork); } } /// <exception cref="ProtocolException"/> public Block GetHeader(NetworkParameters networkParams) { return new Block(networkParams, _blockHeader); } public uint Height { get { return _height; } } /// <exception cref="ProtocolException"/> public StoredBlock ToStoredBlock(NetworkParameters networkParams) { return new StoredBlock(GetHeader(networkParams), ChainWork, Height); } } /// <exception cref="BlockStoreException"/> public BoundedOverheadBlockStore(NetworkParameters networkParams, FileInfo file) { _params = networkParams; try { Load(file); } catch (IOException e) { Log.Error("failed to load block store from file", e); CreateNewStore(networkParams, file); } } /// <exception cref="BlockStoreException"/> private void CreateNewStore(NetworkParameters networkParams, FileInfo file) { // Create a new block store if the file wasn't found or anything went wrong whilst reading. _blockCache.Clear(); try { if (_channel != null) { _channel.Dispose(); _channel = null; } if (file.Exists) { try { file.Delete(); } catch (IOException) { throw new BlockStoreException("Could not delete old store in order to recreate it"); } } _channel = file.Create(); // Create fresh. _channel.WriteByte(_fileFormatVersion); } catch (IOException e1) { // We could not load a block store nor could we create a new one! throw new BlockStoreException(e1); } try { // Set up the genesis block. When we start out fresh, it is by definition the top of the chain. var genesis = networkParams.GenesisBlock.CloneAsHeader(); var storedGenesis = new StoredBlock(genesis, genesis.GetWork(), 0); _chainHead = storedGenesis.Header.Hash; _channel.Write(_chainHead.Bytes); Put(storedGenesis); } catch (IOException e) { throw new BlockStoreException(e); } } /// <exception cref="IOException"/> /// <exception cref="BlockStoreException"/> private void Load(FileInfo file) { Log.InfoFormat("Reading block store from {0}", file); if (_channel != null) { _channel.Dispose(); } _channel = file.OpenRead(); try { // Read a version byte. var version = _channel.ReadByte(); if (version == -1) { // No such file or the file was empty. throw new FileNotFoundException(file.Name + " does not exist or is empty"); } if (version != _fileFormatVersion) { throw new BlockStoreException("Bad version number: " + version); } // Chain head pointer is the first thing in the file. var chainHeadHash = new byte[32]; if (_channel.Read(chainHeadHash) < chainHeadHash.Length) throw new BlockStoreException("Truncated store: could not read chain head hash."); _chainHead = new Sha256Hash(chainHeadHash); Log.InfoFormat("Read chain head from disk: {0}", _chainHead); _channel.Position = _channel.Length - Record.Size; } catch (IOException) { _channel.Close(); throw; } catch (BlockStoreException) { _channel.Close(); throw; } } /// <exception cref="BlockStoreException"/> public void Put(StoredBlock block) { lock (this) { try { var hash = block.Header.Hash; // Append to the end of the file. Record.Write(_channel, block); _blockCache[hash] = block; while (_blockCache.Count > 2050) { _blockCache.RemoveAt(0); } } catch (IOException e) { throw new BlockStoreException(e); } } } /// <exception cref="BlockStoreException"/> public StoredBlock Get(Sha256Hash hash) { lock (this) { // Check the memory cache first. StoredBlock fromMem; if (_blockCache.TryGetValue(hash, out fromMem)) { return fromMem; } if (_notFoundCache.TryGetValue(hash, out fromMem) && fromMem == _notFoundMarker) { return null; } try { var fromDisk = GetRecord(hash); StoredBlock block = null; if (fromDisk == null) { _notFoundCache[hash] = _notFoundMarker; while (_notFoundCache.Count > 2050) { _notFoundCache.RemoveAt(0); } } else { block = fromDisk.ToStoredBlock(_params); _blockCache[hash] = block; while (_blockCache.Count > 2050) { _blockCache.RemoveAt(0); } } return block; } catch (IOException e) { throw new BlockStoreException(e); } catch (ProtocolException e) { throw new BlockStoreException(e); } } } private ByteBuffer _buf = ByteBuffer.Allocate(Record.Size); /// <exception cref="BlockStoreException"/> /// <exception cref="IOException"/> /// <exception cref="ProtocolException"/> private Record GetRecord(Sha256Hash hash) { var startPos = _channel.Position; // Use our own file pointer within the tight loop as updating channel positions is really expensive. var pos = startPos; var record = new Record(); do { if (!record.Read(_channel, pos, _buf)) throw new IOException("Failed to read buffer"); if (record.GetHeader(_params).Hash.Equals(hash)) { // Found it. Update file position for next time. _channel.Position = pos; return record; } // Did not find it. if (pos == 1 + 32) { // At the start so wrap around to the end. pos = _channel.Length - Record.Size; } else { // Move backwards. pos = pos - Record.Size; Debug.Assert(pos >= 1 + 32, pos.ToString()); } } while (pos != startPos); // Was never stored. _channel.Position = pos; return null; } /// <exception cref="BlockStoreException"/> public StoredBlock GetChainHead() { lock (this) { var head = Get(_chainHead); if (head == null) throw new BlockStoreException("Corrupted block store: chain head not found"); return head; } } /// <exception cref="BlockStoreException"/> public void SetChainHead(StoredBlock chainHead) { lock (this) { try { _chainHead = chainHead.Header.Hash; // Write out new hash to the first 32 bytes of the file past one (first byte is version number). var originalPos = _channel.Position; _channel.Position = 1; var bytes = _chainHead.Bytes; _channel.Write(bytes, 0, bytes.Length); _channel.Position = originalPos; } catch (IOException e) { throw new BlockStoreException(e); } } } #region IDisposable Members public void Dispose() { if (_channel != null) { _channel.Dispose(); _channel = null; } if (_buf != null) { _buf.Dispose(); _buf = null; } } #endregion } }
// // UserJobTile.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Unix; using Gtk; using Hyena.Jobs; using Hyena.Gui; using Banshee.Base; using Banshee.ServiceStack; namespace Banshee.Gui.Widgets { public class UserJobTile : Table { private Job job; private string [] icon_names; private string title; private string status; private Image icon; private Gdk.Pixbuf icon_pixbuf; private Label title_label; private Label status_label; private ProgressBar progress_bar; private Button cancel_button; private uint update_delay_id; private uint progress_bounce_id; private object tooltips; Banshee.Widgets.HigMessageDialog cancel_dialog; public UserJobTile (Job job) : base (3, 2, false) { this.job = job; this.job.Updated += OnJobUpdated; BuildWidget (); UpdateFromJob (); } private void BuildWidget () { ThreadAssist.AssertInMainThread (); ColumnSpacing = 5; RowSpacing = 2; icon = new Image (); tooltips = TooltipSetter.CreateHost (); title_label = new Label (); title_label.Xalign = 0.0f; title_label.Ellipsize = Pango.EllipsizeMode.End; status_label = new Label (); status_label.Xalign = 0.0f; status_label.Ellipsize = Pango.EllipsizeMode.End; progress_bar = new ProgressBar (); progress_bar.SetSizeRequest (0, -1); progress_bar.Text = " "; progress_bar.Show (); cancel_button = new Button (new Image (Stock.Stop, IconSize.Menu)); cancel_button.Relief = ReliefStyle.None; cancel_button.ShowAll (); cancel_button.Clicked += OnCancelClicked; Attach (title_label, 0, 3, 0, 1, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Expand | AttachOptions.Fill, 0, 0); Attach (status_label, 0, 3, 1, 2, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Expand | AttachOptions.Fill, 0, 0); Attach (icon, 0, 1, 2, 3, AttachOptions.Shrink | AttachOptions.Fill, AttachOptions.Shrink | AttachOptions.Fill, 0, 0); Attach (progress_bar, 1, 2, 2, 3, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Shrink, 0, 0); Attach (cancel_button, 2, 3, 2, 3, AttachOptions.Shrink | AttachOptions.Fill, AttachOptions.Shrink | AttachOptions.Fill, 0, 0); } protected override void OnStyleSet (Style style) { base.OnStyleSet (style); UpdateIcons (); } private void OnCancelClicked (object o, EventArgs args) { if (cancel_dialog != null) { return; } Window parent = null; if (ServiceManager.Contains<GtkElementsService> ()) { parent = ServiceManager.Get<GtkElementsService> ().PrimaryWindow; } cancel_dialog = new Banshee.Widgets.HigMessageDialog (parent, DialogFlags.Modal, MessageType.Question, ButtonsType.None, job.Title == null ? Catalog.GetString ("Stop Operation") : String.Format (Catalog.GetString ("Stop {0}"), job.Title), job.CancelMessage == null ? (job.Title == null ? Catalog.GetString ("This operation is still performing work. Would you like to stop it?") : String.Format (Catalog.GetString ( "The '{0}' operation is still performing work. Would you like to stop it?"), job.Title)) : job.CancelMessage); cancel_dialog.AddButton (job.Title == null ? Catalog.GetString ("Continue") : String.Format (Catalog.GetString ("Continue {0}"), job.Title), ResponseType.No, true); cancel_dialog.AddButton (Stock.Stop, ResponseType.Yes, false); cancel_dialog.DefaultResponse = ResponseType.Cancel; if (cancel_dialog.Run () == (int)ResponseType.Yes) { if (job.CanCancel) { ServiceManager.JobScheduler.Cancel (job); } } cancel_dialog.Destroy (); cancel_dialog = null; } private void SetTitle (string new_title) { if (String.IsNullOrEmpty (new_title)) { title_label.Hide (); } else { title_label.Markup = String.Format ("<small><b>{0}</b></small>", GLib.Markup.EscapeText (new_title)); title_label.Show (); } title = new_title; } private bool never_had_status = true; private void UpdateFromJob () { ThreadAssist.AssertInMainThread (); if (cancel_dialog != null && !job.CanCancel) { cancel_dialog.Respond (Gtk.ResponseType.Cancel); } if (job.IsCancelRequested) { SetTitle (Catalog.GetString ("Stopping...")); } else if (title != job.Title) { SetTitle (job.Title); } if (status != job.Status) { // If we've ever had the status in this job, don't hide it b/c that'll make // the tile change width, possibly repeatedly and annoyingly if (String.IsNullOrEmpty (job.Status) && never_had_status) { status_label.Hide (); } else { never_had_status = false; status_label.Markup = String.Format ("<small>{0}</small>", GLib.Markup.EscapeText (job.Status ?? String.Empty)); TooltipSetter.Set (tooltips, status_label, job.Status ?? String.Empty); status_label.Show (); } status = job.Status; } if (icon_names == null || icon_names.Length != job.IconNames.Length) { UpdateIcons (); } else { for (int i = 0; i < job.IconNames.Length; i++) { if (icon_names[i] != job.IconNames[i]) { UpdateIcons (); break; } } } cancel_button.Sensitive = job.CanCancel && !job.IsCancelRequested; if (job.Progress == 0 && progress_bounce_id > 0) { return; } progress_bar.Fraction = job.Progress; if (job.Progress == 0.0 && progress_bounce_id == 0) { progress_bounce_id = GLib.Timeout.Add (100, delegate { progress_bar.Text = " "; progress_bar.Pulse (); return true; }); } else if (job.Progress > 0.0) { if (progress_bounce_id > 0) { GLib.Source.Remove (progress_bounce_id); progress_bounce_id = 0; } progress_bar.Text = String.Format("{0}%", (int)(job.Progress * 100.0)); } } private void UpdateIcons () { icon_names = job.IconNames; if (icon_pixbuf != null) { icon_pixbuf.Dispose (); icon_pixbuf = null; } if (icon_names == null || icon_names.Length == 0) { icon.Hide (); return; } icon_pixbuf = IconThemeUtils.LoadIcon (22, icon_names); if (icon_pixbuf != null) { icon.Pixbuf = icon_pixbuf; icon.Show (); return; } icon_pixbuf = new Gdk.Pixbuf (icon_names[0]); if (icon_pixbuf != null) { Gdk.Pixbuf scaled = icon_pixbuf.ScaleSimple (22, 22, Gdk.InterpType.Bilinear); icon_pixbuf.Dispose (); icon.Pixbuf = scaled; icon.Show (); } } private void OnJobUpdated (object o, EventArgs args) { if (update_delay_id == 0) { GLib.Timeout.Add (100, UpdateFromJobTimeout); } } private bool UpdateFromJobTimeout () { UpdateFromJob (); update_delay_id = 0; return false; } } }
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGBorderTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGBorderTest { [Test] public void Test_border_no_size() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.BorderLeftWidth = 10; root.BorderTopWidth = 10; root.BorderRightWidth = 10; root.BorderBottomWidth = 10; root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(20f, root.LayoutWidth); Assert.AreEqual(20f, root.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(20f, root.LayoutWidth); Assert.AreEqual(20f, root.LayoutHeight); } [Test] public void Test_border_container_match_child() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.BorderLeftWidth = 10; root.BorderTopWidth = 10; root.BorderRightWidth = 10; root.BorderBottomWidth = 10; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(30f, root.LayoutWidth); Assert.AreEqual(30f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(30f, root.LayoutWidth); Assert.AreEqual(30f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_border_flex_child() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.BorderLeftWidth = 10; root.BorderTopWidth = 10; root.BorderRightWidth = 10; root.BorderBottomWidth = 10; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.Width = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(80f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); } [Test] public void Test_border_stretch_child() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.BorderLeftWidth = 10; root.BorderTopWidth = 10; root.BorderRightWidth = 10; root.BorderBottomWidth = 10; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(80f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(80f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_border_center_child() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.BorderStartWidth = 10; root.BorderEndWidth = 20; root.BorderBottomWidth = 20; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(40f, root_child0.LayoutX); Assert.AreEqual(35f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(35f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.Extensions.ObjectExtensions; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Spectator; using osu.Game.Replays; using osu.Game.Rulesets; using osu.Game.Scoring; using Realms; namespace osu.Game.Screens.Spectate { /// <summary> /// A <see cref="OsuScreen"/> which spectates one or more users. /// </summary> public abstract class SpectatorScreen : OsuScreen { protected IReadOnlyList<int> Users => users; private readonly List<int> users = new List<int>(); [Resolved] private BeatmapManager beatmaps { get; set; } [Resolved] private RulesetStore rulesets { get; set; } [Resolved] private SpectatorClient spectatorClient { get; set; } [Resolved] private UserLookupCache userLookupCache { get; set; } private readonly IBindableDictionary<int, SpectatorState> userStates = new BindableDictionary<int, SpectatorState>(); private readonly Dictionary<int, APIUser> userMap = new Dictionary<int, APIUser>(); private readonly Dictionary<int, SpectatorGameplayState> gameplayStates = new Dictionary<int, SpectatorGameplayState>(); /// <summary> /// Creates a new <see cref="SpectatorScreen"/>. /// </summary> /// <param name="users">The users to spectate.</param> protected SpectatorScreen(params int[] users) { this.users.AddRange(users); } [Resolved] private RealmAccess realm { get; set; } private IDisposable realmSubscription; protected override void LoadComplete() { base.LoadComplete(); userLookupCache.GetUsersAsync(users.ToArray()).ContinueWith(task => Schedule(() => { var foundUsers = task.GetResultSafely(); foreach (var u in foundUsers) { if (u == null) continue; userMap[u.Id] = u; } userStates.BindTo(spectatorClient.WatchedUserStates); userStates.BindCollectionChanged(onUserStatesChanged, true); realmSubscription = realm.RegisterForNotifications( realm => realm.All<BeatmapSetInfo>().Where(s => !s.DeletePending), beatmapsChanged); foreach ((int id, var _) in userMap) spectatorClient.WatchUser(id); })); } private void beatmapsChanged(IRealmCollection<BeatmapSetInfo> items, ChangeSet changes, Exception ___) { if (changes?.InsertedIndices == null) return; foreach (int c in changes.InsertedIndices) beatmapUpdated(items[c]); } private void beatmapUpdated(BeatmapSetInfo beatmapSet) { foreach ((int userId, _) in userMap) { if (!userStates.TryGetValue(userId, out var userState)) continue; if (beatmapSet.Beatmaps.Any(b => b.OnlineID == userState.BeatmapID)) startGameplay(userId); } } private void onUserStatesChanged(object sender, NotifyDictionaryChangedEventArgs<int, SpectatorState> e) { switch (e.Action) { case NotifyDictionaryChangedAction.Add: case NotifyDictionaryChangedAction.Replace: foreach ((int userId, var state) in e.NewItems.AsNonNull()) onUserStateChanged(userId, state); break; case NotifyDictionaryChangedAction.Remove: foreach ((int userId, SpectatorState state) in e.OldItems.AsNonNull()) onUserStateRemoved(userId, state); break; } } private void onUserStateChanged(int userId, SpectatorState newState) { if (newState.RulesetID == null || newState.BeatmapID == null) return; if (!userMap.ContainsKey(userId)) return; switch (newState.State) { case SpectatedUserState.Passed: // Make sure that gameplay completes to the end. if (gameplayStates.TryGetValue(userId, out var gameplayState)) gameplayState.Score.Replay.HasReceivedAllFrames = true; break; case SpectatedUserState.Playing: Schedule(() => OnNewPlayingUserState(userId, newState)); startGameplay(userId); break; } } private void onUserStateRemoved(int userId, SpectatorState state) { if (!userMap.ContainsKey(userId)) return; if (!gameplayStates.TryGetValue(userId, out var gameplayState)) return; gameplayState.Score.Replay.HasReceivedAllFrames = true; gameplayStates.Remove(userId); Schedule(() => EndGameplay(userId, state)); } private void startGameplay(int userId) { Debug.Assert(userMap.ContainsKey(userId)); var user = userMap[userId]; var spectatorState = userStates[userId]; var resolvedRuleset = rulesets.AvailableRulesets.FirstOrDefault(r => r.OnlineID == spectatorState.RulesetID)?.CreateInstance(); if (resolvedRuleset == null) return; var resolvedBeatmap = beatmaps.QueryBeatmap(b => b.OnlineID == spectatorState.BeatmapID); if (resolvedBeatmap == null) return; var score = new Score { ScoreInfo = new ScoreInfo { BeatmapInfo = resolvedBeatmap, User = user, Mods = spectatorState.Mods.Select(m => m.ToMod(resolvedRuleset)).ToArray(), Ruleset = resolvedRuleset.RulesetInfo, }, Replay = new Replay { HasReceivedAllFrames = false }, }; var gameplayState = new SpectatorGameplayState(score, resolvedRuleset, beatmaps.GetWorkingBeatmap(resolvedBeatmap)); gameplayStates[userId] = gameplayState; Schedule(() => StartGameplay(userId, gameplayState)); } /// <summary> /// Invoked when a spectated user's state has changed to a new state indicating the player is currently playing. /// </summary> /// <param name="userId">The user whose state has changed.</param> /// <param name="spectatorState">The new state.</param> protected abstract void OnNewPlayingUserState(int userId, [NotNull] SpectatorState spectatorState); /// <summary> /// Starts gameplay for a user. /// </summary> /// <param name="userId">The user to start gameplay for.</param> /// <param name="spectatorGameplayState">The gameplay state.</param> protected abstract void StartGameplay(int userId, [NotNull] SpectatorGameplayState spectatorGameplayState); /// <summary> /// Ends gameplay for a user. /// </summary> /// <param name="userId">The user to end gameplay for.</param> /// <param name="state">The final user state.</param> protected abstract void EndGameplay(int userId, SpectatorState state); /// <summary> /// Stops spectating a user. /// </summary> /// <param name="userId">The user to stop spectating.</param> protected void RemoveUser(int userId) { if (!userStates.TryGetValue(userId, out var state)) return; onUserStateRemoved(userId, state); users.Remove(userId); userMap.Remove(userId); spectatorClient.StopWatchingUser(userId); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (spectatorClient != null) { foreach ((int userId, var _) in userMap) spectatorClient.StopWatchingUser(userId); } realmSubscription?.Dispose(); } } }
using J2N.Text; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using FieldsConsumer = Lucene.Net.Codecs.FieldsConsumer; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using PostingsConsumer = Lucene.Net.Codecs.PostingsConsumer; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using TermsConsumer = Lucene.Net.Codecs.TermsConsumer; using TermStats = Lucene.Net.Codecs.TermStats; // TODO: break into separate freq and prox writers as // codecs; make separate container (tii/tis/skip/*) that can // be configured as any number of files 1..N internal sealed class FreqProxTermsWriterPerField : TermsHashConsumerPerField, IComparable<FreqProxTermsWriterPerField> { internal readonly FreqProxTermsWriter parent; internal readonly TermsHashPerField termsHashPerField; internal readonly FieldInfo fieldInfo; internal readonly DocumentsWriterPerThread.DocState docState; internal readonly FieldInvertState fieldState; private bool hasFreq; private bool hasProx; private bool hasOffsets; internal IPayloadAttribute payloadAttribute; internal IOffsetAttribute offsetAttribute; public FreqProxTermsWriterPerField(TermsHashPerField termsHashPerField, FreqProxTermsWriter parent, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.parent = parent; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; SetIndexOptions(fieldInfo.IndexOptions); } internal override int StreamCount { get { if (!hasProx) { return 1; } else { return 2; } } } internal override void Finish() { if (hasPayloads) { fieldInfo.SetStorePayloads(); } } internal bool hasPayloads; [ExceptionToNetNumericConvention] internal override void SkippingLongTerm() { } public int CompareTo(FreqProxTermsWriterPerField other) { return fieldInfo.Name.CompareToOrdinal(other.fieldInfo.Name); } // Called after flush internal void Reset() { // Record, up front, whether our in-RAM format will be // with or without term freqs: SetIndexOptions(fieldInfo.IndexOptions); payloadAttribute = null; } private void SetIndexOptions(IndexOptions indexOptions) { if (indexOptions == IndexOptions.NONE) { // field could later be updated with indexed=true, so set everything on hasFreq = hasProx = hasOffsets = true; } else { hasFreq = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; hasProx = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; hasOffsets = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; } } internal override bool Start(IIndexableField[] fields, int count) { for (int i = 0; i < count; i++) { if (fields[i].IndexableFieldType.IsIndexed) { return true; } } return false; } internal override void Start(IIndexableField f) { if (fieldState.AttributeSource.HasAttribute<IPayloadAttribute>()) { payloadAttribute = fieldState.AttributeSource.GetAttribute<IPayloadAttribute>(); } else { payloadAttribute = null; } if (hasOffsets) { offsetAttribute = fieldState.AttributeSource.AddAttribute<IOffsetAttribute>(); } else { offsetAttribute = null; } } internal void WriteProx(int termID, int proxCode) { //System.out.println("writeProx termID=" + termID + " proxCode=" + proxCode); if (Debugging.AssertsEnabled) Debugging.Assert(hasProx); BytesRef payload; if (payloadAttribute == null) { payload = null; } else { payload = payloadAttribute.Payload; } if (payload != null && payload.Length > 0) { termsHashPerField.WriteVInt32(1, (proxCode << 1) | 1); termsHashPerField.WriteVInt32(1, payload.Length); termsHashPerField.WriteBytes(1, payload.Bytes, payload.Offset, payload.Length); hasPayloads = true; } else { termsHashPerField.WriteVInt32(1, proxCode << 1); } FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; postings.lastPositions[termID] = fieldState.Position; } internal void WriteOffsets(int termID, int offsetAccum) { if (Debugging.AssertsEnabled) Debugging.Assert(hasOffsets); int startOffset = offsetAccum + offsetAttribute.StartOffset; int endOffset = offsetAccum + offsetAttribute.EndOffset; FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; if (Debugging.AssertsEnabled) Debugging.Assert(startOffset - postings.lastOffsets[termID] >= 0); termsHashPerField.WriteVInt32(1, startOffset - postings.lastOffsets[termID]); termsHashPerField.WriteVInt32(1, endOffset - startOffset); postings.lastOffsets[termID] = startOffset; } internal override void NewTerm(int termID) { // First time we're seeing this term since the last // flush if (Debugging.AssertsEnabled) Debugging.Assert(docState.TestPoint("FreqProxTermsWriterPerField.newTerm start")); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; postings.lastDocIDs[termID] = docState.docID; if (!hasFreq) { postings.lastDocCodes[termID] = docState.docID; } else { postings.lastDocCodes[termID] = docState.docID << 1; postings.termFreqs[termID] = 1; if (hasProx) { WriteProx(termID, fieldState.Position); if (hasOffsets) { WriteOffsets(termID, fieldState.Offset); } } else { if (Debugging.AssertsEnabled) Debugging.Assert(!hasOffsets); } } fieldState.MaxTermFrequency = Math.Max(1, fieldState.MaxTermFrequency); fieldState.UniqueTermCount++; } internal override void AddTerm(int termID) { if (Debugging.AssertsEnabled) Debugging.Assert(docState.TestPoint("FreqProxTermsWriterPerField.addTerm start")); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; if (Debugging.AssertsEnabled) Debugging.Assert(!hasFreq || postings.termFreqs[termID] > 0); if (!hasFreq) { if (Debugging.AssertsEnabled) Debugging.Assert(postings.termFreqs == null); if (docState.docID != postings.lastDocIDs[termID]) { if (Debugging.AssertsEnabled) Debugging.Assert(docState.docID > postings.lastDocIDs[termID]); termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID]); postings.lastDocCodes[termID] = docState.docID - postings.lastDocIDs[termID]; postings.lastDocIDs[termID] = docState.docID; fieldState.UniqueTermCount++; } } else if (docState.docID != postings.lastDocIDs[termID]) { if (Debugging.AssertsEnabled) Debugging.Assert(docState.docID > postings.lastDocIDs[termID], () => "id: " + docState.docID + " postings ID: " + postings.lastDocIDs[termID] + " termID: " + termID); // Term not yet seen in the current doc but previously // seen in other doc(s) since the last flush // Now that we know doc freq for previous doc, // write it & lastDocCode if (1 == postings.termFreqs[termID]) { termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID] | 1); } else { termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID]); termsHashPerField.WriteVInt32(0, postings.termFreqs[termID]); } postings.termFreqs[termID] = 1; fieldState.MaxTermFrequency = Math.Max(1, fieldState.MaxTermFrequency); postings.lastDocCodes[termID] = (docState.docID - postings.lastDocIDs[termID]) << 1; postings.lastDocIDs[termID] = docState.docID; if (hasProx) { WriteProx(termID, fieldState.Position); if (hasOffsets) { postings.lastOffsets[termID] = 0; WriteOffsets(termID, fieldState.Offset); } } else { if (Debugging.AssertsEnabled) Debugging.Assert(!hasOffsets); } fieldState.UniqueTermCount++; } else { fieldState.MaxTermFrequency = Math.Max(fieldState.MaxTermFrequency, ++postings.termFreqs[termID]); if (hasProx) { WriteProx(termID, fieldState.Position - postings.lastPositions[termID]); } if (hasOffsets) { WriteOffsets(termID, fieldState.Offset); } } } internal override ParallelPostingsArray CreatePostingsArray(int size) { return new FreqProxPostingsArray(size, hasFreq, hasProx, hasOffsets); } internal sealed class FreqProxPostingsArray : ParallelPostingsArray { public FreqProxPostingsArray(int size, bool writeFreqs, bool writeProx, bool writeOffsets) : base(size) { if (writeFreqs) { termFreqs = new int[size]; } lastDocIDs = new int[size]; lastDocCodes = new int[size]; if (writeProx) { lastPositions = new int[size]; if (writeOffsets) { lastOffsets = new int[size]; } } else { if (Debugging.AssertsEnabled) Debugging.Assert(!writeOffsets); } //System.out.println("PA init freqs=" + writeFreqs + " pos=" + writeProx + " offs=" + writeOffsets); } internal int[] termFreqs; // # times this term occurs in the current doc internal int[] lastDocIDs; // Last docID where this term occurred internal int[] lastDocCodes; // Code for prior doc internal int[] lastPositions; // Last position where this term occurred internal int[] lastOffsets; // Last endOffset where this term occurred internal override ParallelPostingsArray NewInstance(int size) { return new FreqProxPostingsArray(size, termFreqs != null, lastPositions != null, lastOffsets != null); } internal override void CopyTo(ParallelPostingsArray toArray, int numToCopy) { if (Debugging.AssertsEnabled) Debugging.Assert(toArray is FreqProxPostingsArray); FreqProxPostingsArray to = (FreqProxPostingsArray)toArray; base.CopyTo(toArray, numToCopy); Array.Copy(lastDocIDs, 0, to.lastDocIDs, 0, numToCopy); Array.Copy(lastDocCodes, 0, to.lastDocCodes, 0, numToCopy); if (lastPositions != null) { if (Debugging.AssertsEnabled) Debugging.Assert(to.lastPositions != null); Array.Copy(lastPositions, 0, to.lastPositions, 0, numToCopy); } if (lastOffsets != null) { if (Debugging.AssertsEnabled) Debugging.Assert(to.lastOffsets != null); Array.Copy(lastOffsets, 0, to.lastOffsets, 0, numToCopy); } if (termFreqs != null) { if (Debugging.AssertsEnabled) Debugging.Assert(to.termFreqs != null); Array.Copy(termFreqs, 0, to.termFreqs, 0, numToCopy); } } internal override int BytesPerPosting() { int bytes = ParallelPostingsArray.BYTES_PER_POSTING + 2 * RamUsageEstimator.NUM_BYTES_INT32; if (lastPositions != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } if (lastOffsets != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } if (termFreqs != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } return bytes; } } [MethodImpl(MethodImplOptions.NoInlining)] public void Abort() { } internal BytesRef payload; /// <summary> /// Walk through all unique text tokens (Posting /// instances) found in this field and serialize them /// into a single RAM segment. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal void Flush(string fieldName, FieldsConsumer consumer, SegmentWriteState state) { if (!fieldInfo.IsIndexed) { return; // nothing to flush, don't bother the codec with the unindexed field } TermsConsumer termsConsumer = consumer.AddField(fieldInfo); IComparer<BytesRef> termComp = termsConsumer.Comparer; // CONFUSING: this.indexOptions holds the index options // that were current when we first saw this field. But // it's possible this has changed, eg when other // documents are indexed that cause a "downgrade" of the // IndexOptions. So we must decode the in-RAM buffer // according to this.indexOptions, but then write the // new segment to the directory according to // currentFieldIndexOptions: IndexOptions currentFieldIndexOptions = fieldInfo.IndexOptions; if (Debugging.AssertsEnabled) Debugging.Assert(currentFieldIndexOptions != IndexOptions.NONE); bool writeTermFreq = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; bool writePositions = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; bool writeOffsets = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; bool readTermFreq = this.hasFreq; bool readPositions = this.hasProx; bool readOffsets = this.hasOffsets; //System.out.println("flush readTF=" + readTermFreq + " readPos=" + readPositions + " readOffs=" + readOffsets); // Make sure FieldInfo.update is working correctly!: if (Debugging.AssertsEnabled) { Debugging.Assert(!writeTermFreq || readTermFreq); Debugging.Assert(!writePositions || readPositions); Debugging.Assert(!writeOffsets || readOffsets); Debugging.Assert(!writeOffsets || writePositions); } IDictionary<Term, int?> segDeletes; if (state.SegUpdates != null && state.SegUpdates.terms.Count > 0) { segDeletes = state.SegUpdates.terms; } else { segDeletes = null; } int[] termIDs = termsHashPerField.SortPostings(termComp); int numTerms = termsHashPerField.bytesHash.Count; BytesRef text = new BytesRef(); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; ByteSliceReader freq = new ByteSliceReader(); ByteSliceReader prox = new ByteSliceReader(); FixedBitSet visitedDocs = new FixedBitSet(state.SegmentInfo.DocCount); long sumTotalTermFreq = 0; long sumDocFreq = 0; Term protoTerm = new Term(fieldName); for (int i = 0; i < numTerms; i++) { int termID = termIDs[i]; // Get BytesRef int textStart = postings.textStarts[termID]; termsHashPerField.bytePool.SetBytesRef(text, textStart); termsHashPerField.InitReader(freq, termID, 0); if (readPositions || readOffsets) { termsHashPerField.InitReader(prox, termID, 1); } // TODO: really TermsHashPerField should take over most // of this loop, including merge sort of terms from // multiple threads and interacting with the // TermsConsumer, only calling out to us (passing us the // DocsConsumer) to handle delivery of docs/positions PostingsConsumer postingsConsumer = termsConsumer.StartTerm(text); int? delDocLimit; if (segDeletes != null) { protoTerm.Bytes = text; int? docIDUpto; segDeletes.TryGetValue(protoTerm, out docIDUpto); if (docIDUpto != null) { delDocLimit = docIDUpto; } else { delDocLimit = 0; } } else { delDocLimit = 0; } // Now termStates has numToMerge FieldMergeStates // which all share the same term. Now we must // interleave the docID streams. int docFreq = 0; long totalTermFreq = 0; int docID = 0; while (true) { //System.out.println(" cycle"); int termFreq; if (freq.Eof()) { if (postings.lastDocCodes[termID] != -1) { // Return last doc docID = postings.lastDocIDs[termID]; if (readTermFreq) { termFreq = postings.termFreqs[termID]; } else { termFreq = -1; } postings.lastDocCodes[termID] = -1; } else { // EOF break; } } else { int code = freq.ReadVInt32(); if (!readTermFreq) { docID += code; termFreq = -1; } else { docID += (int)((uint)code >> 1); if ((code & 1) != 0) { termFreq = 1; } else { termFreq = freq.ReadVInt32(); } } if (Debugging.AssertsEnabled) Debugging.Assert(docID != postings.lastDocIDs[termID]); } docFreq++; if (Debugging.AssertsEnabled) Debugging.Assert(docID < state.SegmentInfo.DocCount, () => "doc=" + docID + " maxDoc=" + state.SegmentInfo.DocCount); // NOTE: we could check here if the docID was // deleted, and skip it. However, this is somewhat // dangerous because it can yield non-deterministic // behavior since we may see the docID before we see // the term that caused it to be deleted. this // would mean some (but not all) of its postings may // make it into the index, which'd alter the docFreq // for those terms. We could fix this by doing two // passes, ie first sweep marks all del docs, and // 2nd sweep does the real flush, but I suspect // that'd add too much time to flush. visitedDocs.Set(docID); postingsConsumer.StartDoc(docID, writeTermFreq ? termFreq : -1); if (docID < delDocLimit) { // Mark it deleted. TODO: we could also skip // writing its postings; this would be // deterministic (just for this Term's docs). // TODO: can we do this reach-around in a cleaner way???? if (state.LiveDocs == null) { state.LiveDocs = docState.docWriter.codec.LiveDocsFormat.NewLiveDocs(state.SegmentInfo.DocCount); } if (state.LiveDocs.Get(docID)) { state.DelCountOnFlush++; state.LiveDocs.Clear(docID); } } totalTermFreq += termFreq; // Carefully copy over the prox + payload info, // changing the format to match Lucene's segment // format. if (readPositions || readOffsets) { // we did record positions (& maybe payload) and/or offsets int position = 0; int offset = 0; for (int j = 0; j < termFreq; j++) { BytesRef thisPayload; if (readPositions) { int code = prox.ReadVInt32(); position += (int)((uint)code >> 1); if ((code & 1) != 0) { // this position has a payload int payloadLength = prox.ReadVInt32(); if (payload == null) { payload = new BytesRef(); payload.Bytes = new byte[payloadLength]; } else if (payload.Bytes.Length < payloadLength) { payload.Grow(payloadLength); } prox.ReadBytes(payload.Bytes, 0, payloadLength); payload.Length = payloadLength; thisPayload = payload; } else { thisPayload = null; } if (readOffsets) { int startOffset = offset + prox.ReadVInt32(); int endOffset = startOffset + prox.ReadVInt32(); if (writePositions) { if (writeOffsets) { if (Debugging.AssertsEnabled) Debugging.Assert(startOffset >= 0 && endOffset >= startOffset, () => "startOffset=" + startOffset + ",endOffset=" + endOffset + ",offset=" + offset); postingsConsumer.AddPosition(position, thisPayload, startOffset, endOffset); } else { postingsConsumer.AddPosition(position, thisPayload, -1, -1); } } offset = startOffset; } else if (writePositions) { postingsConsumer.AddPosition(position, thisPayload, -1, -1); } } } } postingsConsumer.FinishDoc(); } termsConsumer.FinishTerm(text, new TermStats(docFreq, writeTermFreq ? totalTermFreq : -1)); sumTotalTermFreq += totalTermFreq; sumDocFreq += docFreq; } termsConsumer.Finish(writeTermFreq ? sumTotalTermFreq : -1, sumDocFreq, visitedDocs.Cardinality()); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Shouldly; using Xunit; namespace Baseline.Testing { public class FileSetTester : IDisposable { private readonly TestDirectory _testDirectory; private FileSet theFileSet; public FileSetTester() { _testDirectory = new TestDirectory(); _testDirectory.ChangeDirectory(); if (Directory.Exists("target")) { Directory.Delete("target", true); } Directory.CreateDirectory("target"); theFileSet = new FileSet(); } [Fact] public void append_include() { theFileSet.Include.ShouldBe("*.*"); theFileSet.AppendInclude("*.config"); theFileSet.Include.ShouldBe("*.config"); theFileSet.AppendInclude("*.as*x"); theFileSet.Include.ShouldBe("*.config;*.as*x"); } private void writeFile(string name) { name = Path.Combine(Directory.GetCurrentDirectory(), "target", name).ToFullPath(); var directory = Path.GetDirectoryName(name); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (File.Exists(name)) { File.Delete(name); } File.WriteAllText(name, ""); } public IEnumerable<string> includedFiles() { return theFileSet.IncludedFilesFor("target").Select(Path.GetFileName).OrderBy(x => x); } public IEnumerable<string> excludedFiles() { return theFileSet.ExcludedFilesFor("target").Select(Path.GetFileName).OrderBy(x => x); } [Fact] public void find_includes_directoy_as_part_of_include_pattern_with_one() { writeFile("config/zee.config"); theFileSet.Include = "config/*.config"; includedFiles().ShouldHaveTheSameElementsAs("zee.config"); } [Fact] public void find_includes_directoy_as_part_of_include_pattern_with_many() { writeFile("config/a.config"); writeFile("config/b.config"); writeFile("config/zeppelin.yaml"); writeFile("hitchhiker.config"); theFileSet.Include = "config/*.config;config/zeppelin.yaml"; includedFiles().ShouldHaveTheSameElementsAs("a.config", "b.config", "zeppelin.yaml"); } [Fact] public void find_does_not_wig_out_when_the_exclude_pattern_is_an_invalid_directory() { writeFile("config/a.config"); writeFile("config/b.config"); writeFile("config/zeppelin.yaml"); writeFile("hitchhiker.config"); new FileSystem().DeleteDirectory("data"); theFileSet = new FileSet() { Include = "*.as*x;*.master;Content{0}*.*;*.config".ToFormat(Path.DirectorySeparatorChar), Exclude = "data/*" }; includedFiles().ShouldHaveTheSameElementsAs("a.config", "b.config", "hitchhiker.config"); } [Fact] public void a_null_include_finds_everything() { writeFile("a.txt"); writeFile("a.xml"); writeFile("b.txt"); theFileSet.Include = null; includedFiles().ShouldHaveTheSameElementsAs("a.txt", "a.xml", "b.txt"); } [Fact] public void find_includes_in_flat_directory_with_only_one_include() { writeFile("a.txt"); writeFile("a.xml"); writeFile("b.txt"); writeFile("b.xml"); writeFile("c.txt"); writeFile("c.xml"); theFileSet.Include = "*.txt"; includedFiles().ShouldHaveTheSameElementsAs("a.txt", "b.txt", "c.txt"); } [Fact] public void find_includes_in_flat_directory_with_multiple_includes() { writeFile("a.txt"); writeFile("a.xml"); writeFile("b.txt"); writeFile("b.xml"); writeFile("c.txt"); writeFile("c.xml"); theFileSet.Include = "*.txt;c.xml"; includedFiles().ShouldHaveTheSameElementsAs("a.txt", "b.txt", "c.txt", "c.xml"); } [Fact] public void find_includes_in_flat_directory_with_overlapping_includes_returns_distinct() { writeFile("a.txt"); writeFile("a.xml"); writeFile("b.txt"); writeFile("b.xml"); writeFile("c.txt"); writeFile("c.xml"); theFileSet.Include = "*.txt;c.*"; includedFiles().ShouldHaveTheSameElementsAs("a.txt", "b.txt", "c.txt", "c.xml"); } [Fact] public void find_includes_in_deep_directory_with_one_filter() { writeFile("a.txt"); writeFile("a.xml"); writeFile("f1/b.txt"); writeFile("b.xml"); writeFile("f1/f2/c.txt"); writeFile("c.xml"); theFileSet.Include = "*.txt"; includedFiles().ShouldHaveTheSameElementsAs("a.txt", "b.txt", "c.txt"); } [Fact] public void a_null_exclude_does_nothing() { writeFile("a.txt"); writeFile("a.xml"); writeFile("f1/b.txt"); writeFile("b.xml"); writeFile("f1/f2/c.txt"); writeFile("c.xml"); theFileSet.Exclude = null; excludedFiles().Any().ShouldBeFalse(); } [Fact] public void mixed_include_and_exclude() { writeFile("a.txt"); writeFile("a.xml"); writeFile("f1/b.txt"); writeFile("b.xml"); writeFile("f1/f2/c.txt"); writeFile("c.xml"); theFileSet.Include = "*.xml"; theFileSet.Exclude = "a.xml"; new FileSystem().FindFiles("target", theFileSet).Select(x => Path.GetFileName(x)).ShouldHaveTheSameElementsAs("b.xml", "c.xml"); } [Fact] public void get_fileset_for_assembly_names() { var names = new string[]{"a", "b", "c", "d"}; var set = FileSet.ForAssemblyNames(names); set.Exclude.ShouldBeNull(); set.Include.ShouldBe("a.dll;a.exe;b.dll;b.exe;c.dll;c.exe;d.dll;d.exe"); } [Fact] public void get_fileset_for_assembly_debug_files() { var names = new string[] { "a", "b", "c", "d" }; var set = FileSet.ForAssemblyDebugFiles(names); set.Exclude.ShouldBeNull(); set.Include.ShouldBe("a.pdb;b.pdb;c.pdb;d.pdb"); } public void Dispose() { _testDirectory.Dispose(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace GurlFeed.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace Internal.Cryptography.Pal.Native { /// <summary> /// Base class for safe handles representing NULL-based pointers. /// </summary> internal abstract class SafePointerHandle<T> : SafeHandle where T : SafeHandle, new() { protected SafePointerHandle() : base(IntPtr.Zero, true) { } public sealed override bool IsInvalid { get { return handle == IntPtr.Zero; } } public static T InvalidHandle { get { return SafeHandleCache<T>.GetInvalidHandle(() => new T()); } } protected override void Dispose(bool disposing) { if (!SafeHandleCache<T>.IsCachedInvalidHandle(this)) { base.Dispose(disposing); } } } /// <summary> /// SafeHandle for the CERT_CONTEXT structure defined by crypt32. /// </summary> internal class SafeCertContextHandle : SafePointerHandle<SafeCertContextHandle> { private SafeCertContextHandle _parent; public SafeCertContextHandle() { } public SafeCertContextHandle(SafeCertContextHandle parent) { if (parent == null) throw new ArgumentNullException(nameof(parent)); Debug.Assert(!parent.IsInvalid); Debug.Assert(!parent.IsClosed); bool ignored = false; parent.DangerousAddRef(ref ignored); _parent = parent; SetHandle(_parent.handle); } protected override bool ReleaseHandle() { if (_parent != null) { _parent.DangerousRelease(); _parent = null; } else { Interop.crypt32.CertFreeCertificateContext(handle); } SetHandle(IntPtr.Zero); return true; } public unsafe CERT_CONTEXT* CertContext { get { return (CERT_CONTEXT*)handle; } } // Extract the raw CERT_CONTEXT* pointer and reset the SafeHandle to the invalid state so it no longer auto-destroys the CERT_CONTEXT. public unsafe CERT_CONTEXT* Disconnect() { CERT_CONTEXT* pCertContext = (CERT_CONTEXT*)handle; SetHandle(IntPtr.Zero); return pCertContext; } public bool HasPersistedPrivateKey { get { return CertHasProperty(CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID); } } public bool HasEphemeralPrivateKey { get { return CertHasProperty(CertContextPropId.CERT_KEY_CONTEXT_PROP_ID); } } public bool ContainsPrivateKey { get { return HasPersistedPrivateKey || HasEphemeralPrivateKey; } } public SafeCertContextHandle Duplicate() { return Interop.crypt32.CertDuplicateCertificateContext(handle); } private bool CertHasProperty(CertContextPropId propertyId) { int cb = 0; bool hasProperty = Interop.crypt32.CertGetCertificateContextProperty( this, propertyId, null, ref cb); return hasProperty; } } /// <summary> /// SafeHandle for the CERT_CONTEXT structure defined by crypt32. Unlike SafeCertContextHandle, disposition already deletes any associated key containers. /// </summary> internal sealed class SafeCertContextHandleWithKeyContainerDeletion : SafeCertContextHandle { protected sealed override bool ReleaseHandle() { using (SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(handle)) { DeleteKeyContainer(certContext); } base.ReleaseHandle(); return true; } public static void DeleteKeyContainer(SafeCertContextHandle pCertContext) { if (pCertContext.IsInvalid) return; int cb = 0; bool containsPrivateKey = Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cb); if (!containsPrivateKey) return; byte[] provInfoAsBytes = new byte[cb]; if (!Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, provInfoAsBytes, ref cb)) return; unsafe { fixed (byte* pProvInfoAsBytes = provInfoAsBytes) { CRYPT_KEY_PROV_INFO* pProvInfo = (CRYPT_KEY_PROV_INFO*)pProvInfoAsBytes; if (pProvInfo->dwProvType == 0) { // dwProvType being 0 indicates that the key is stored in CNG. // dwProvType being non-zero indicates that the key is stored in CAPI. string providerName = Marshal.PtrToStringUni((IntPtr)(pProvInfo->pwszProvName)); string keyContainerName = Marshal.PtrToStringUni((IntPtr)(pProvInfo->pwszContainerName)); try { using (CngKey cngKey = CngKey.Open(keyContainerName, new CngProvider(providerName))) { cngKey.Delete(); } } catch (CryptographicException) { // While leaving the file on disk is undesirable, an inability to perform this cleanup // should not manifest itself to a user. } } else { #if !uap // For UWP, CryptAcquireContext() is a disallowed api, even when being used for cleanup. CAPI keys should not exist on that platform, however... CryptAcquireContextFlags flags = (pProvInfo->dwFlags & CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) | CryptAcquireContextFlags.CRYPT_DELETEKEYSET; IntPtr hProv; bool success = Interop.cryptoapi.CryptAcquireContext(out hProv, pProvInfo->pwszContainerName, pProvInfo->pwszProvName, pProvInfo->dwProvType, flags); // Called CryptAcquireContext solely for the side effect of deleting the key containers. When called with these flags, no actual // hProv is returned (so there's nothing to clean up.) Debug.Assert(hProv == IntPtr.Zero); #endif } } } } } /// <summary> /// SafeHandle for the HCERTSTORE handle defined by crypt32. /// </summary> internal sealed class SafeCertStoreHandle : SafePointerHandle<SafeCertStoreHandle> { protected sealed override bool ReleaseHandle() { bool success = Interop.crypt32.CertCloseStore(handle, 0); return success; } } /// <summary> /// SafeHandle for the HCRYPTMSG handle defined by crypt32. /// </summary> internal sealed class SafeCryptMsgHandle : SafePointerHandle<SafeCryptMsgHandle> { protected sealed override bool ReleaseHandle() { bool success = Interop.crypt32.CryptMsgClose(handle); return success; } } /// <summary> /// SafeHandle for LocalAlloc'd memory. /// </summary> internal sealed class SafeLocalAllocHandle : SafePointerHandle<SafeLocalAllocHandle> { public static SafeLocalAllocHandle Create(int cb) { var h = new SafeLocalAllocHandle(); h.SetHandle(Marshal.AllocHGlobal(cb)); return h; } protected sealed override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: api@oanda.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// An OrderFillTransaction represents the filling of an Order in the client&#39;s Account. /// </summary> [DataContract] public partial class OrderFillTransaction : IEquatable<OrderFillTransaction>, IValidatableObject { /// <summary> /// The Type of the Transaction. Always set to \"ORDER_FILL\" for an OrderFillTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"ORDER_FILL\" for an OrderFillTransaction.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { /// <summary> /// Enum CREATE for "CREATE" /// </summary> [EnumMember(Value = "CREATE")] CREATE, /// <summary> /// Enum CLOSE for "CLOSE" /// </summary> [EnumMember(Value = "CLOSE")] CLOSE, /// <summary> /// Enum REOPEN for "REOPEN" /// </summary> [EnumMember(Value = "REOPEN")] REOPEN, /// <summary> /// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE")] CLIENTCONFIGURE, /// <summary> /// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE_REJECT")] CLIENTCONFIGUREREJECT, /// <summary> /// Enum TRANSFERFUNDS for "TRANSFER_FUNDS" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS")] TRANSFERFUNDS, /// <summary> /// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS_REJECT")] TRANSFERFUNDSREJECT, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_ORDER_REJECT")] MARKETORDERREJECT, /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "LIMIT_ORDER_REJECT")] LIMITORDERREJECT, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum STOPORDERREJECT for "STOP_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_ORDER_REJECT")] STOPORDERREJECT, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")] MARKETIFTOUCHEDORDERREJECT, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")] TAKEPROFITORDERREJECT, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER_REJECT")] STOPLOSSORDERREJECT, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")] TRAILINGSTOPLOSSORDERREJECT, /// <summary> /// Enum ORDERFILL for "ORDER_FILL" /// </summary> [EnumMember(Value = "ORDER_FILL")] ORDERFILL, /// <summary> /// Enum ORDERCANCEL for "ORDER_CANCEL" /// </summary> [EnumMember(Value = "ORDER_CANCEL")] ORDERCANCEL, /// <summary> /// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT" /// </summary> [EnumMember(Value = "ORDER_CANCEL_REJECT")] ORDERCANCELREJECT, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")] ORDERCLIENTEXTENSIONSMODIFY, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")] ORDERCLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")] TRADECLIENTEXTENSIONSMODIFY, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")] TRADECLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER" /// </summary> [EnumMember(Value = "MARGIN_CALL_ENTER")] MARGINCALLENTER, /// <summary> /// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXTEND")] MARGINCALLEXTEND, /// <summary> /// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXIT")] MARGINCALLEXIT, /// <summary> /// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE" /// </summary> [EnumMember(Value = "DELAYED_TRADE_CLOSURE")] DELAYEDTRADECLOSURE, /// <summary> /// Enum DAILYFINANCING for "DAILY_FINANCING" /// </summary> [EnumMember(Value = "DAILY_FINANCING")] DAILYFINANCING, /// <summary> /// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL" /// </summary> [EnumMember(Value = "RESET_RESETTABLE_PL")] RESETRESETTABLEPL } /// <summary> /// The reason that an Order was filled /// </summary> /// <value>The reason that an Order was filled</value> [JsonConverter(typeof(StringEnumConverter))] public enum ReasonEnum { /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERTRADECLOSE for "MARKET_ORDER_TRADE_CLOSE" /// </summary> [EnumMember(Value = "MARKET_ORDER_TRADE_CLOSE")] MARKETORDERTRADECLOSE, /// <summary> /// Enum MARKETORDERPOSITIONCLOSEOUT for "MARKET_ORDER_POSITION_CLOSEOUT" /// </summary> [EnumMember(Value = "MARKET_ORDER_POSITION_CLOSEOUT")] MARKETORDERPOSITIONCLOSEOUT, /// <summary> /// Enum MARKETORDERMARGINCLOSEOUT for "MARKET_ORDER_MARGIN_CLOSEOUT" /// </summary> [EnumMember(Value = "MARKET_ORDER_MARGIN_CLOSEOUT")] MARKETORDERMARGINCLOSEOUT, /// <summary> /// Enum MARKETORDERDELAYEDTRADECLOSE for "MARKET_ORDER_DELAYED_TRADE_CLOSE" /// </summary> [EnumMember(Value = "MARKET_ORDER_DELAYED_TRADE_CLOSE")] MARKETORDERDELAYEDTRADECLOSE } /// <summary> /// The Type of the Transaction. Always set to \"ORDER_FILL\" for an OrderFillTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"ORDER_FILL\" for an OrderFillTransaction.</value> [DataMember(Name="type", EmitDefaultValue=false)] public TypeEnum? Type { get; set; } /// <summary> /// The reason that an Order was filled /// </summary> /// <value>The reason that an Order was filled</value> [DataMember(Name="reason", EmitDefaultValue=false)] public ReasonEnum? Reason { get; set; } /// <summary> /// Initializes a new instance of the <see cref="OrderFillTransaction" /> class. /// </summary> /// <param name="Id">The Transaction&#39;s Identifier..</param> /// <param name="Time">The date/time when the Transaction was created..</param> /// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param> /// <param name="AccountID">The ID of the Account the Transaction was created for..</param> /// <param name="BatchID">The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param> /// <param name="RequestID">The Request ID of the request which generated the transaction..</param> /// <param name="Type">The Type of the Transaction. Always set to \&quot;ORDER_FILL\&quot; for an OrderFillTransaction..</param> /// <param name="OrderID">The ID of the Order filled..</param> /// <param name="ClientOrderID">The client Order ID of the Order filled (only provided if the client has assigned one)..</param> /// <param name="Instrument">The name of the filled Order&#39;s instrument..</param> /// <param name="Units">The number of units filled by the Order..</param> /// <param name="Price">The average market price that the Order was filled at..</param> /// <param name="Reason">The reason that an Order was filled.</param> /// <param name="Pl">The profit or loss incurred when the Order was filled..</param> /// <param name="Financing">The financing paid or collected when the Order was filled..</param> /// <param name="AccountBalance">The Account&#39;s balance after the Order was filled..</param> /// <param name="TradeOpened">TradeOpened.</param> /// <param name="TradesClosed">The Trades that were closed when the Order was filled (only provided if filling the Order resulted in a closing open Trades)..</param> /// <param name="TradeReduced">TradeReduced.</param> public OrderFillTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?), string OrderID = default(string), string ClientOrderID = default(string), string Instrument = default(string), string Units = default(string), string Price = default(string), ReasonEnum? Reason = default(ReasonEnum?), string Pl = default(string), string Financing = default(string), string AccountBalance = default(string), TradeOpen TradeOpened = default(TradeOpen), List<TradeReduce> TradesClosed = default(List<TradeReduce>), TradeReduce TradeReduced = default(TradeReduce)) { this.Id = Id; this.Time = Time; this.UserID = UserID; this.AccountID = AccountID; this.BatchID = BatchID; this.RequestID = RequestID; this.Type = Type; this.OrderID = OrderID; this.ClientOrderID = ClientOrderID; this.Instrument = Instrument; this.Units = Units; this.Price = Price; this.Reason = Reason; this.Pl = Pl; this.Financing = Financing; this.AccountBalance = AccountBalance; this.TradeOpened = TradeOpened; this.TradesClosed = TradesClosed; this.TradeReduced = TradeReduced; } /// <summary> /// The Transaction&#39;s Identifier. /// </summary> /// <value>The Transaction&#39;s Identifier.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// The date/time when the Transaction was created. /// </summary> /// <value>The date/time when the Transaction was created.</value> [DataMember(Name="time", EmitDefaultValue=false)] public string Time { get; set; } /// <summary> /// The ID of the user that initiated the creation of the Transaction. /// </summary> /// <value>The ID of the user that initiated the creation of the Transaction.</value> [DataMember(Name="userID", EmitDefaultValue=false)] public int? UserID { get; set; } /// <summary> /// The ID of the Account the Transaction was created for. /// </summary> /// <value>The ID of the Account the Transaction was created for.</value> [DataMember(Name="accountID", EmitDefaultValue=false)] public string AccountID { get; set; } /// <summary> /// The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously. /// </summary> /// <value>The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value> [DataMember(Name="batchID", EmitDefaultValue=false)] public string BatchID { get; set; } /// <summary> /// The Request ID of the request which generated the transaction. /// </summary> /// <value>The Request ID of the request which generated the transaction.</value> [DataMember(Name="requestID", EmitDefaultValue=false)] public string RequestID { get; set; } /// <summary> /// The ID of the Order filled. /// </summary> /// <value>The ID of the Order filled.</value> [DataMember(Name="orderID", EmitDefaultValue=false)] public string OrderID { get; set; } /// <summary> /// The client Order ID of the Order filled (only provided if the client has assigned one). /// </summary> /// <value>The client Order ID of the Order filled (only provided if the client has assigned one).</value> [DataMember(Name="clientOrderID", EmitDefaultValue=false)] public string ClientOrderID { get; set; } /// <summary> /// The name of the filled Order&#39;s instrument. /// </summary> /// <value>The name of the filled Order&#39;s instrument.</value> [DataMember(Name="instrument", EmitDefaultValue=false)] public string Instrument { get; set; } /// <summary> /// The number of units filled by the Order. /// </summary> /// <value>The number of units filled by the Order.</value> [DataMember(Name="units", EmitDefaultValue=false)] public string Units { get; set; } /// <summary> /// The average market price that the Order was filled at. /// </summary> /// <value>The average market price that the Order was filled at.</value> [DataMember(Name="price", EmitDefaultValue=false)] public string Price { get; set; } /// <summary> /// The profit or loss incurred when the Order was filled. /// </summary> /// <value>The profit or loss incurred when the Order was filled.</value> [DataMember(Name="pl", EmitDefaultValue=false)] public string Pl { get; set; } /// <summary> /// The financing paid or collected when the Order was filled. /// </summary> /// <value>The financing paid or collected when the Order was filled.</value> [DataMember(Name="financing", EmitDefaultValue=false)] public string Financing { get; set; } /// <summary> /// The Account&#39;s balance after the Order was filled. /// </summary> /// <value>The Account&#39;s balance after the Order was filled.</value> [DataMember(Name="accountBalance", EmitDefaultValue=false)] public string AccountBalance { get; set; } /// <summary> /// Gets or Sets TradeOpened /// </summary> [DataMember(Name="tradeOpened", EmitDefaultValue=false)] public TradeOpen TradeOpened { get; set; } /// <summary> /// The Trades that were closed when the Order was filled (only provided if filling the Order resulted in a closing open Trades). /// </summary> /// <value>The Trades that were closed when the Order was filled (only provided if filling the Order resulted in a closing open Trades).</value> [DataMember(Name="tradesClosed", EmitDefaultValue=false)] public List<TradeReduce> TradesClosed { get; set; } /// <summary> /// Gets or Sets TradeReduced /// </summary> [DataMember(Name="tradeReduced", EmitDefaultValue=false)] public TradeReduce TradeReduced { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderFillTransaction {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Time: ").Append(Time).Append("\n"); sb.Append(" UserID: ").Append(UserID).Append("\n"); sb.Append(" AccountID: ").Append(AccountID).Append("\n"); sb.Append(" BatchID: ").Append(BatchID).Append("\n"); sb.Append(" RequestID: ").Append(RequestID).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" OrderID: ").Append(OrderID).Append("\n"); sb.Append(" ClientOrderID: ").Append(ClientOrderID).Append("\n"); sb.Append(" Instrument: ").Append(Instrument).Append("\n"); sb.Append(" Units: ").Append(Units).Append("\n"); sb.Append(" Price: ").Append(Price).Append("\n"); sb.Append(" Reason: ").Append(Reason).Append("\n"); sb.Append(" Pl: ").Append(Pl).Append("\n"); sb.Append(" Financing: ").Append(Financing).Append("\n"); sb.Append(" AccountBalance: ").Append(AccountBalance).Append("\n"); sb.Append(" TradeOpened: ").Append(TradeOpened).Append("\n"); sb.Append(" TradesClosed: ").Append(TradesClosed).Append("\n"); sb.Append(" TradeReduced: ").Append(TradeReduced).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as OrderFillTransaction); } /// <summary> /// Returns true if OrderFillTransaction instances are equal /// </summary> /// <param name="other">Instance of OrderFillTransaction to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderFillTransaction other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Time == other.Time || this.Time != null && this.Time.Equals(other.Time) ) && ( this.UserID == other.UserID || this.UserID != null && this.UserID.Equals(other.UserID) ) && ( this.AccountID == other.AccountID || this.AccountID != null && this.AccountID.Equals(other.AccountID) ) && ( this.BatchID == other.BatchID || this.BatchID != null && this.BatchID.Equals(other.BatchID) ) && ( this.RequestID == other.RequestID || this.RequestID != null && this.RequestID.Equals(other.RequestID) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.OrderID == other.OrderID || this.OrderID != null && this.OrderID.Equals(other.OrderID) ) && ( this.ClientOrderID == other.ClientOrderID || this.ClientOrderID != null && this.ClientOrderID.Equals(other.ClientOrderID) ) && ( this.Instrument == other.Instrument || this.Instrument != null && this.Instrument.Equals(other.Instrument) ) && ( this.Units == other.Units || this.Units != null && this.Units.Equals(other.Units) ) && ( this.Price == other.Price || this.Price != null && this.Price.Equals(other.Price) ) && ( this.Reason == other.Reason || this.Reason != null && this.Reason.Equals(other.Reason) ) && ( this.Pl == other.Pl || this.Pl != null && this.Pl.Equals(other.Pl) ) && ( this.Financing == other.Financing || this.Financing != null && this.Financing.Equals(other.Financing) ) && ( this.AccountBalance == other.AccountBalance || this.AccountBalance != null && this.AccountBalance.Equals(other.AccountBalance) ) && ( this.TradeOpened == other.TradeOpened || this.TradeOpened != null && this.TradeOpened.Equals(other.TradeOpened) ) && ( this.TradesClosed == other.TradesClosed || this.TradesClosed != null && this.TradesClosed.SequenceEqual(other.TradesClosed) ) && ( this.TradeReduced == other.TradeReduced || this.TradeReduced != null && this.TradeReduced.Equals(other.TradeReduced) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Time != null) hash = hash * 59 + this.Time.GetHashCode(); if (this.UserID != null) hash = hash * 59 + this.UserID.GetHashCode(); if (this.AccountID != null) hash = hash * 59 + this.AccountID.GetHashCode(); if (this.BatchID != null) hash = hash * 59 + this.BatchID.GetHashCode(); if (this.RequestID != null) hash = hash * 59 + this.RequestID.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.OrderID != null) hash = hash * 59 + this.OrderID.GetHashCode(); if (this.ClientOrderID != null) hash = hash * 59 + this.ClientOrderID.GetHashCode(); if (this.Instrument != null) hash = hash * 59 + this.Instrument.GetHashCode(); if (this.Units != null) hash = hash * 59 + this.Units.GetHashCode(); if (this.Price != null) hash = hash * 59 + this.Price.GetHashCode(); if (this.Reason != null) hash = hash * 59 + this.Reason.GetHashCode(); if (this.Pl != null) hash = hash * 59 + this.Pl.GetHashCode(); if (this.Financing != null) hash = hash * 59 + this.Financing.GetHashCode(); if (this.AccountBalance != null) hash = hash * 59 + this.AccountBalance.GetHashCode(); if (this.TradeOpened != null) hash = hash * 59 + this.TradeOpened.GetHashCode(); if (this.TradesClosed != null) hash = hash * 59 + this.TradesClosed.GetHashCode(); if (this.TradeReduced != null) hash = hash * 59 + this.TradeReduced.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Copyright 2016 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. // The controller is not available for versions of Unity without the // // GVR native integration. #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) using UnityEngine; using UnityEngine.VR; using System.Collections; using Gvr.Internal; /// Represents the controller's current connection state. public enum GvrConnectionState { /// Indicates that the controller is disconnected. Disconnected, /// Indicates that the device is scanning for controllers. Scanning, /// Indicates that the device is connecting to a controller. Connecting, /// Indicates that the device is connected to a controller. Connected, /// Indicates that an error has occurred. Error, }; /// Main entry point for the Daydream controller API. /// /// To use this API, add this behavior to a GameObject in your scene, or use the /// GvrControllerMain prefab. There can only be one object with this behavior on your scene. /// /// This is a singleton object. /// /// To access the controller state, simply read the static properties of this class. For example, /// to know the controller's current orientation, use GvrController.Orientation. public class GvrController : MonoBehaviour { private static GvrController instance; private static IControllerProvider controllerProvider; private ControllerState controllerState = new ControllerState(); private IEnumerator controllerUpdate; private WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); /// If true, enable gyroscope on the controller. [Tooltip("If enabled, the controller will report gyroscope readings.")] public bool enableGyro = false; /// If true, enable accelerometer on the controller. [Tooltip("If enabled, the controller will report accelerometer readings.")] public bool enableAccel = false; public enum EmulatorConnectionMode { OFF, USB, WIFI, } /// Indicates how we connect to the controller emulator. [Tooltip("How to connect to the emulator: USB cable (recommended) or WIFI.")] public EmulatorConnectionMode emulatorConnectionMode = EmulatorConnectionMode.USB; /// Returns the controller's current connection state. public static GvrConnectionState State { get { return instance != null ? instance.controllerState.connectionState : GvrConnectionState.Error; } } /// Returns the controller's current orientation in space, as a quaternion. /// The space in which the orientation is represented is the usual Unity space, with /// X pointing to the right, Y pointing up and Z pointing forward. Therefore, to make an /// object in your scene have the same orientation as the controller, simply assign this /// quaternion to the GameObject's transform.rotation. public static Quaternion Orientation { get { return instance != null ? instance.controllerState.orientation : Quaternion.identity; } } /// Returns the controller's gyroscope reading. The gyroscope indicates the angular /// about each of its local axes. The controller's axes are: X points to the right, /// Y points perpendicularly up from the controller's top surface and Z lies /// along the controller's body, pointing towards the front. The angular speed is given /// in radians per second, using the right-hand rule (positive means a right-hand rotation /// about the given axis). public static Vector3 Gyro { get { return instance != null ? instance.controllerState.gyro : Vector3.zero; } } /// Returns the controller's accelerometer reading. The accelerometer indicates the /// effect of acceleration and gravity in the direction of each of the controller's local /// axes. The controller's local axes are: X points to the right, Y points perpendicularly /// up from the controller's top surface and Z lies along the controller's body, pointing /// towards the front. The acceleration is measured in meters per second squared. Note that /// gravity is combined with acceleration, so when the controller is resting on a table top, /// it will measure an acceleration of 9.8 m/s^2 on the Y axis. The accelerometer reading /// will be zero on all three axes only if the controller is in free fall, or if the user /// is in a zero gravity environment like a space station. public static Vector3 Accel { get { return instance != null ? instance.controllerState.accel : Vector3.zero; } } /// If true, the user is currently touching the controller's touchpad. public static bool IsTouching { get { return instance != null ? instance.controllerState.isTouching : false; } } /// If true, the user just started touching the touchpad. This is an event flag (it is true /// for only one frame after the event happens, then reverts to false). public static bool TouchDown { get { return instance != null ? instance.controllerState.touchDown : false; } } /// If true, the user just stopped touching the touchpad. This is an event flag (it is true /// for only one frame after the event happens, then reverts to false). public static bool TouchUp { get { return instance != null ? instance.controllerState.touchUp : false; } } public static Vector2 TouchPos { get { return instance != null ? instance.controllerState.touchPos : Vector2.zero; } } /// If true, the user is currently performing the recentering gesture. Most apps will want /// to pause the interaction while this remains true. public static bool Recentering { get { return instance != null ? instance.controllerState.recentering : false; } } /// If true, the user just completed the recenter gesture. The controller's orientation is /// now being reported in the new recentered coordinate system (the controller's orientation /// when recentering was completed was remapped to mean "forward"). This is an event flag /// (it is true for only one frame after the event happens, then reverts to false). /// The headset is recentered together with the controller. public static bool Recentered { get { return instance != null ? instance.controllerState.recentered : false; } } /// If true, the click button (touchpad button) is currently being pressed. This is not /// an event: it represents the button's state (it remains true while the button is being /// pressed). public static bool ClickButton { get { return instance != null ? instance.controllerState.clickButtonState : false; } } /// If true, the click button (touchpad button) was just pressed. This is an event flag: /// it will be true for only one frame after the event happens. public static bool ClickButtonDown { get { return instance != null ? instance.controllerState.clickButtonDown : false; } } /// If true, the click button (touchpad button) was just released. This is an event flag: /// it will be true for only one frame after the event happens. public static bool ClickButtonUp { get { return instance != null ? instance.controllerState.clickButtonUp : false; } } /// If true, the app button (touchpad button) is currently being pressed. This is not /// an event: it represents the button's state (it remains true while the button is being /// pressed). public static bool AppButton { get { return instance != null ? instance.controllerState.appButtonState : false; } } /// If true, the app button was just pressed. This is an event flag: it will be true for /// only one frame after the event happens. public static bool AppButtonDown { get { return instance != null ? instance.controllerState.appButtonDown : false; } } /// If true, the app button was just released. This is an event flag: it will be true for /// only one frame after the event happens. public static bool AppButtonUp { get { return instance != null ? instance.controllerState.appButtonUp : false; } } /// If State == GvrConnectionState.Error, this contains details about the error. public static string ErrorDetails { get { if (instance != null) { return instance.controllerState.connectionState == GvrConnectionState.Error ? instance.controllerState.errorDetails : ""; } else { return "GvrController instance not found in scene. It may be missing, or it might " + "not have initialized yet."; } } } void Awake() { if (instance != null) { Debug.LogError("More than one GvrController instance was found in your scene. " + "Ensure that there is only one GvrController."); this.enabled = false; return; } instance = this; if (controllerProvider == null) { controllerProvider = ControllerProviderFactory.CreateControllerProvider(this); } } void OnDestroy() { instance = null; } private void UpdateController() { controllerProvider.ReadState(controllerState); // If the controller was recentered, also recenter the headset. if (controllerState.recentered) { #if UNITY_EDITOR GvrViewer sdk = GvrViewer.Instance; if (sdk) { sdk.Recenter(); } #else InputTracking.Recenter(); #endif // UNITY_EDITOR } } void OnApplicationPause(bool paused) { Debug.Log("GvrController: application " + (paused ? "paused" : "resumed")); if (null == controllerProvider) return; if (paused) { controllerProvider.OnPause(); } else { controllerProvider.OnResume(); } } void OnEnable() { controllerUpdate = EndOfFrame(); StartCoroutine(controllerUpdate); } void OnDisable() { StopCoroutine(controllerUpdate); } IEnumerator EndOfFrame() { while (true) { // This must be done at the end of the frame to ensure that all GameObjects had a chance // to read transient controller state (e.g. events, etc) for the current frame before // it gets reset. yield return waitForEndOfFrame; UpdateController(); } } } #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
/*************************************************************************** * Rdf.cs * * Copyright (C) 2005 Novell * Written by Aaron Bockover (aaron@aaronbock.net) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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 MusicBrainz { public sealed class Rdf { public static readonly string MBI_VARIOUS_ARTIST_ID = "89ad4ac3-39f7-470e-963a-56509c546377", MBS_Rewind = "[REWIND]", MBS_Back = "[BACK]", MBS_SelectArtist = "http://musicbrainz.org/mm/mm-2.1#artistList []", MBS_SelectAlbum = "http://musicbrainz.org/mm/mm-2.1#albumList []", MBS_SelectTrack = "http://musicbrainz.org/mm/mm-2.1#trackList []", MBS_SelectTrackArtist = "http://purl.org/dc/elements/1.1/creator", MBS_SelectTrackAlbum = "http://musicbrainz.org/mm/mq-1.1#album", MBS_SelectTrmid = "http://musicbrainz.org/mm/mm-2.1#trmidList []", MBS_SelectCdindexid = "http://musicbrainz.org/mm/mm-2.1#cdindexidList []", MBS_SelectReleaseDate = "http://musicbrainz.org/mm/mm-2.1#releaseDateList []", MBS_SelectLookupResult = "http://musicbrainz.org/mm/mq-1.1#lookupResultList []", MBS_SelectLookupResultArtist = "http://musicbrainz.org/mm/mq-1.1#artist", MBS_SelectLookupResultAlbum = "http://musicbrainz.org/mm/mq-1.1#album", MBS_SelectLookupResultTrack = "http://musicbrainz.org/mm/mq-1.1#track", MBE_GetStatus = "http://musicbrainz.org/mm/mq-1.1#status", MBE_GetNumArtists = "http://musicbrainz.org/mm/mm-2.1#artistList [COUNT]", MBE_GetNumAlbums = "http://musicbrainz.org/mm/mm-2.1#albumList [COUNT]", MBE_GetNumTracks = "http://musicbrainz.org/mm/mm-2.1#trackList [COUNT]", MBE_GetNumTrmids = "http://musicbrainz.org/mm/mm-2.1#trmidList [COUNT]", MBE_GetNumLookupResults = "http://musicbrainz.org/mm/mm-2.1#lookupResultList [COUNT]", MBE_ArtistGetArtistName = "http://purl.org/dc/elements/1.1/title", MBE_ArtistGetArtistSortName = "http://musicbrainz.org/mm/mm-2.1#sortName", MBE_ArtistGetArtistId = "", MBE_ArtistGetAlbumName = "http://musicbrainz.org/mm/mm-2.1#albumList [] http://purl.org/dc/elements/1.1/title", MBE_ArtistGetAlbumId = "http://musicbrainz.org/mm/mm-2.1#albumList []", MBE_AlbumGetAlbumName = "http://purl.org/dc/elements/1.1/title", MBE_AlbumGetAlbumId = "", MBE_AlbumGetAlbumStatus = "http://musicbrainz.org/mm/mm-2.1#releaseStatus", MBE_AlbumGetAlbumType = "http://musicbrainz.org/mm/mm-2.1#releaseType", MBE_AlbumGetAmazonAsin = "http://www.amazon.com/gp/aws/landing.html#Asin", MBE_AlbumGetAmazonCoverartURL = "http://musicbrainz.org/mm/mm-2.1#coverart", MBE_AlbumGetNumCdindexIds = "http://musicbrainz.org/mm/mm-2.1#cdindexidList [COUNT]", MBE_AlbumGetNumReleaseDates = "http://musicbrainz.org/mm/mm-2.1#releaseDateList [COUNT]", MBE_AlbumGetAlbumArtistId = "http://purl.org/dc/elements/1.1/creator", MBE_AlbumGetNumTracks = "http://musicbrainz.org/mm/mm-2.1#trackList [COUNT]", MBE_AlbumGetTrackId = "http://musicbrainz.org/mm/mm-2.1#trackList [] ", MBE_AlbumGetTrackList = "http://musicbrainz.org/mm/mm-2.1#trackList", MBE_AlbumGetTrackNum = "http://musicbrainz.org/mm/mm-2.1#trackList [?] http://musicbrainz.org/mm/mm-2.1#trackNum", MBE_AlbumGetTrackName = "http://musicbrainz.org/mm/mm-2.1#trackList [] http://purl.org/dc/elements/1.1/title", MBE_AlbumGetTrackDuration = "http://musicbrainz.org/mm/mm-2.1#trackList [] http://musicbrainz.org/mm/mm-2.1#duration", MBE_AlbumGetArtistName = "http://musicbrainz.org/mm/mm-2.1#trackList [] http://purl.org/dc/elements/1.1/creator http://purl.org/dc/elements/1.1/title", MBE_AlbumGetArtistSortName = "http://musicbrainz.org/mm/mm-2.1#trackList [] http://purl.org/dc/elements/1.1/creator http://musicbrainz.org/mm/mm-2.1#sortName", MBE_AlbumGetArtistId = "http://musicbrainz.org/mm/mm-2.1#trackList [] http://purl.org/dc/elements/1.1/creator", MBE_TrackGetTrackName = "http://purl.org/dc/elements/1.1/title", MBE_TrackGetTrackId = "", MBE_TrackGetTrackNum = "http://musicbrainz.org/mm/mm-2.1#trackNum", MBE_TrackGetTrackDuration = "http://musicbrainz.org/mm/mm-2.1#duration", MBE_TrackGetArtistName = "http://purl.org/dc/elements/1.1/creator http://purl.org/dc/elements/1.1/title", MBE_TrackGetArtistSortName = "http://purl.org/dc/elements/1.1/creator http://musicbrainz.org/mm/mm-2.1#sortName", MBE_TrackGetArtistId = "http://purl.org/dc/elements/1.1/creator", MBE_QuickGetArtistName = "http://musicbrainz.org/mm/mq-1.1#artistName", MBE_QuickGetArtistSortName = "http://musicbrainz.org/mm/mm-2.1#sortName", MBE_QuickGetArtistId = "http://musicbrainz.org/mm/mm-2.1#artistid", MBE_QuickGetAlbumName = "http://musicbrainz.org/mm/mq-1.1#albumName", MBE_QuickGetTrackName = "http://musicbrainz.org/mm/mq-1.1#trackName", MBE_QuickGetTrackNum = "http://musicbrainz.org/mm/mm-2.1#trackNum", MBE_QuickGetTrackId = "http://musicbrainz.org/mm/mm-2.1#trackid", MBE_QuickGetTrackDuration = "http://musicbrainz.org/mm/mm-2.1#duration", MBE_ReleaseGetDate = "http://purl.org/dc/elements/1.1/date", MBE_ReleaseGetCountry = "http://musicbrainz.org/mm/mm-2.1#country", MBE_LookupGetType = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", MBE_LookupGetRelevance = "http://musicbrainz.org/mm/mq-1.1#relevance", MBE_LookupGetArtistId = "http://musicbrainz.org/mm/mq-1.1#artist", MBE_LookupGetAlbumId = "http://musicbrainz.org/mm/mq-1.1#album", MBE_LookupGetAlbumArtistId = "http://musicbrainz.org/mm/mq-1.1#album " + "http://purl.org/dc/elements/1.1/creator", MBE_LookupGetTrackId = "http://musicbrainz.org/mm/mq-1.1#track", MBE_LookupGetTrackArtistId = "http://musicbrainz.org/mm/mq-1.1#track " + "http://purl.org/dc/elements/1.1/creator", MBE_TOCGetCDIndexId = "http://musicbrainz.org/mm/mm-2.1#cdindexid", MBE_TOCGetFirstTrack = "http://musicbrainz.org/mm/mm-2.1#firstTrack", MBE_TOCGetLastTrack = "http://musicbrainz.org/mm/mm-2.1#lastTrack", MBE_TOCGetTrackSectorOffset = "http://musicbrainz.org/mm/mm-2.1#toc [] http://musicbrainz.org/mm/mm-2.1#sectorOffset", MBE_TOCGetTrackNumSectors = "http://musicbrainz.org/mm/mm-2.1#toc [] http://musicbrainz.org/mm/mm-2.1#numSectors", MBE_AuthGetSessionId = "http://musicbrainz.org/mm/mq-1.1#sessionId", MBE_AuthGetChallenge = "http://musicbrainz.org/mm/mq-1.1#authChallenge", MBQ_GetCDInfo = "@CDINFO@", MBQ_GetCDTOC = "@LOCALCDINFO@", MBQ_AssociateCD = "@CDINFOASSOCIATECD@", MBQ_Authenticate = "<mq:AuthenticateQuery>\n" + " <mq:username>@1@</mq:username>\n" + "</mq:AuthenticateQuery>\n", MBQ_GetCDInfoFromCDIndexId = "<mq:GetCDInfo>\n" + " <mq:depth>@DEPTH@</mq:depth>\n" + " <mm:cdindexid>@1@</mm:cdindexid>\n" + "</mq:GetCDInfo>\n", MBQ_TrackInfoFromTRMId = "<mq:TrackInfoFromTRMId>\n" + " <mm:trmid>@1@</mm:trmid>\n" + " <mq:artistName>@2@</mq:artistName>\n" + " <mq:albumName>@3@</mq:albumName>\n" + " <mq:trackName>@4@</mq:trackName>\n" + " <mm:trackNum>@5@</mm:trackNum>\n" + " <mm:duration>@6@</mm:duration>\n" + "</mq:TrackInfoFromTRMId>\n", MBQ_QuickTrackInfoFromTrackId = "<mq:QuickTrackInfoFromTrackId>\n" + " <mm:trackid>@1@</mm:trackid>\n" + " <mm:albumid>@2@</mm:albumid>\n" + "</mq:QuickTrackInfoFromTrackId>\n", MBQ_FindArtistByName = "<mq:FindArtist>\n" + " <mq:depth>@DEPTH@</mq:depth>\n" + " <mq:artistName>@1@</mq:artistName>\n" + " <mq:maxItems>@MAX_ITEMS@</mq:maxItems>\n" + "</mq:FindArtist>\n", MBQ_FindAlbumByName = "<mq:FindAlbum>\n" + " <mq:depth>@DEPTH@</mq:depth>\n" + " <mq:maxItems>@MAX_ITEMS@</mq:maxItems>\n" + " <mq:albumName>@1@</mq:albumName>\n" + "</mq:FindAlbum>\n", MBQ_FindTrackByName = "<mq:FindTrack>\n" + " <mq:depth>@DEPTH@</mq:depth>\n" + " <mq:maxItems>@MAX_ITEMS@</mq:maxItems>\n" + " <mq:trackName>@1@</mq:trackName>\n" + "</mq:FindTrack>\n", MBQ_FindDistinctTRMId = "<mq:FindDistinctTRMID>\n" + " <mq:depth>@DEPTH@</mq:depth>\n" + " <mq:artistName>@1@</mq:artistName>\n" + " <mq:trackName>@2@</mq:trackName>\n" + "</mq:FindDistinctTRMID>\n", MBQ_GetArtistById = "http://@URL@/mm-2.1/artist/@1@/@DEPTH@", MBQ_GetAlbumById = "http://@URL@/mm-2.1/album/@1@/@DEPTH@", MBQ_GetTrackById = "http://@URL@/mm-2.1/track/@1@/@DEPTH@", MBQ_GetTrackByTRMId = "http://@URL@/mm-2.1/trmid/@1@/@DEPTH@", MBQ_SubmitTrackTRMId = "<mq:SubmitTRMList>\n" + " <mm:trmidList>\n" + " <rdf:Bag>\n" + " <rdf:li>\n" + " <mq:trmTrackPair>\n" + " <mm:trackid>@1@</mm:trackid>\n" + " <mm:trmid>@2@</mm:trmid>\n" + " </mq:trmTrackPair>\n" + " </rdf:li>\n" + " </rdf:Bag>\n" + " </mm:trmidList>\n" + " <mq:sessionId>@SESSID@</mq:sessionId>\n" + " <mq:sessionKey>@SESSKEY@</mq:sessionKey>\n" + " <mq:clientVersion>@CLIENTVER@</mq:clientVersion>\n" + "</mq:SubmitTRMList>\n", MBQ_FileInfoLookup = "<mq:FileInfoLookup>\n" + " <mm:trmid>@1@</mm:trmid>\n" + " <mq:artistName>@2@</mq:artistName>\n" + " <mq:albumName>@3@</mq:albumName>\n" + " <mq:trackName>@4@</mq:trackName>\n" + " <mm:trackNum>@5@</mm:trackNum>\n" + " <mm:duration>@6@</mm:duration>\n" + " <mq:fileName>@7@</mq:fileName>\n" + " <mm:artistid>@8@</mm:artistid>\n" + " <mm:albumid>@9@</mm:albumid>\n" + " <mm:trackid>@10@</mm:trackid>\n" + " <mq:maxItems>@MAX_ITEMS@</mq:maxItems>\n" + "</mq:FileInfoLookup>\n"; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Requests/Messages/UseItemCaptureMessage.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 POGOProtos.Networking.Requests.Messages { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/UseItemCaptureMessage.proto</summary> public static partial class UseItemCaptureMessageReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/UseItemCaptureMessage.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UseItemCaptureMessageReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkNQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvVXNl", "SXRlbUNhcHR1cmVNZXNzYWdlLnByb3RvEidQT0dPUHJvdG9zLk5ldHdvcmtp", "bmcuUmVxdWVzdHMuTWVzc2FnZXMaJlBPR09Qcm90b3MvSW52ZW50b3J5L0l0", "ZW0vSXRlbUlkLnByb3RvInkKFVVzZUl0ZW1DYXB0dXJlTWVzc2FnZRIyCgdp", "dGVtX2lkGAEgASgOMiEuUE9HT1Byb3Rvcy5JbnZlbnRvcnkuSXRlbS5JdGVt", "SWQSFAoMZW5jb3VudGVyX2lkGAIgASgGEhYKDnNwYXduX3BvaW50X2lkGAMg", "ASgJYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Inventory.Item.ItemIdReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.UseItemCaptureMessage), global::POGOProtos.Networking.Requests.Messages.UseItemCaptureMessage.Parser, new[]{ "ItemId", "EncounterId", "SpawnPointId" }, null, null, null) })); } #endregion } #region Messages public sealed partial class UseItemCaptureMessage : pb::IMessage<UseItemCaptureMessage> { private static readonly pb::MessageParser<UseItemCaptureMessage> _parser = new pb::MessageParser<UseItemCaptureMessage>(() => new UseItemCaptureMessage()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UseItemCaptureMessage> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Requests.Messages.UseItemCaptureMessageReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UseItemCaptureMessage() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UseItemCaptureMessage(UseItemCaptureMessage other) : this() { itemId_ = other.itemId_; encounterId_ = other.encounterId_; spawnPointId_ = other.spawnPointId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UseItemCaptureMessage Clone() { return new UseItemCaptureMessage(this); } /// <summary>Field number for the "item_id" field.</summary> public const int ItemIdFieldNumber = 1; private global::POGOProtos.Inventory.Item.ItemId itemId_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Inventory.Item.ItemId ItemId { get { return itemId_; } set { itemId_ = value; } } /// <summary>Field number for the "encounter_id" field.</summary> public const int EncounterIdFieldNumber = 2; private ulong encounterId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong EncounterId { get { return encounterId_; } set { encounterId_ = value; } } /// <summary>Field number for the "spawn_point_id" field.</summary> public const int SpawnPointIdFieldNumber = 3; private string spawnPointId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SpawnPointId { get { return spawnPointId_; } set { spawnPointId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UseItemCaptureMessage); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UseItemCaptureMessage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ItemId != other.ItemId) return false; if (EncounterId != other.EncounterId) return false; if (SpawnPointId != other.SpawnPointId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ItemId != 0) hash ^= ItemId.GetHashCode(); if (EncounterId != 0UL) hash ^= EncounterId.GetHashCode(); if (SpawnPointId.Length != 0) hash ^= SpawnPointId.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 (ItemId != 0) { output.WriteRawTag(8); output.WriteEnum((int) ItemId); } if (EncounterId != 0UL) { output.WriteRawTag(17); output.WriteFixed64(EncounterId); } if (SpawnPointId.Length != 0) { output.WriteRawTag(26); output.WriteString(SpawnPointId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ItemId != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ItemId); } if (EncounterId != 0UL) { size += 1 + 8; } if (SpawnPointId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SpawnPointId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UseItemCaptureMessage other) { if (other == null) { return; } if (other.ItemId != 0) { ItemId = other.ItemId; } if (other.EncounterId != 0UL) { EncounterId = other.EncounterId; } if (other.SpawnPointId.Length != 0) { SpawnPointId = other.SpawnPointId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { itemId_ = (global::POGOProtos.Inventory.Item.ItemId) input.ReadEnum(); break; } case 17: { EncounterId = input.ReadFixed64(); break; } case 26: { SpawnPointId = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections.Generic; using System.Linq; using Sce.Atf; using Sce.Atf.Adaptation; using Sce.Atf.Applications; using Sce.Atf.Dom; namespace Sce.Sled.Shared.Dom { /// <summary> /// Complex Type for a list of profile info items /// </summary> public class SledProfileInfoListType : DomNodeAdapter, IItemView, ITreeListView, IObservableContext { /// <summary> /// Types enumeration /// </summary> public enum Display { /// <summary> /// Function calls, times, etc. /// </summary> Normal, /// <summary> /// Function call graph /// </summary> CallGraph, } /// <summary> /// Get or set display mode /// </summary> public Display DisplayMode { get; set; } /// <summary> /// Get or set the name attribute /// </summary> public string Name { get { return GetAttribute<string>(SledSchema.SledProfileInfoListType.nameAttribute); } set { SetAttribute(SledSchema.SledProfileInfoListType.nameAttribute, value); } } /// <summary> /// Gets the ProfileInfo sequence /// </summary> public IList<SledProfileInfoType> ProfileInfo { get { return GetChildList<SledProfileInfoType>(SledSchema.SledProfileInfoListType.ProfileInfoChild); } } #region IItemView Interface /// <summary> /// Fills in or modifies the given display info for the item</summary> /// <param name="item">Item</param> /// <param name="info">Display info to update</param> public void GetInfo(object item, ItemInfo info) { if (item.Is<SledProfileInfoListType>()) { info.Label = Name; info.ImageIndex = info.GetImageIndex(Atf.Resources.FolderImage); return; } var itemView = item.As<IItemView>(); if ((itemView == null) || ReferenceEquals(itemView, this)) return; itemView.GetInfo(item, info); } #endregion #region ITreeListView Interface /// <summary> /// Get children for a parent /// </summary> /// <param name="parent">Parent object</param> /// <returns>Enumeration of the children of the parent object</returns> public IEnumerable<object> GetChildren(object parent) { if (DisplayMode == Display.Normal) yield break; var pi = parent.As<SledProfileInfoType>(); if (pi == null) yield break; foreach (var child in pi.ProfileInfo) yield return child; } /// <summary> /// Get root level items /// </summary> public IEnumerable<object> Roots { get { return ProfileInfo; } } /// <summary> /// Get columns /// </summary> public string[] ColumnNames { get { return DisplayMode == Display.Normal ? SledProfileInfoType.NormalColumnNames : SledProfileInfoType.CallGraphColumnNames; } } #endregion #region IObservableContext Interface /// <summary> /// Event fired when item added /// </summary> public event EventHandler<ItemInsertedEventArgs<object>> ItemInserted; /// <summary> /// Event fired when item removed /// </summary> public event EventHandler<ItemRemovedEventArgs<object>> ItemRemoved; /// <summary> /// Event fired when item changed /// </summary> public event EventHandler<ItemChangedEventArgs<object>> ItemChanged; /// <summary> /// Event fired when reloaded /// </summary> public event EventHandler Reloaded { add { } remove { } } // Cheap way to stop compile warning #endregion /// <summary> /// Performs one-time initialization when this adapter's DomNode property is set. /// The DomNode property is only ever set once for the lifetime of this adapter.</summary> protected override void OnNodeSet() { DomNode.AttributeChanged += DomNodeAttributeChanged; DomNode.ChildInserted += DomNodeChildInserted; DomNode.ChildRemoving += DomNodeChildRemoving; base.OnNodeSet(); } private void DomNodeAttributeChanged(object sender, AttributeEventArgs e) { if (!e.DomNode.Is<SledProfileInfoType>()) return; ItemChanged.Raise( this, new ItemChangedEventArgs<object>( e.DomNode.As<SledProfileInfoType>())); } private void DomNodeChildInserted(object sender, ChildEventArgs e) { if (!e.Child.Is<SledProfileInfoType>()) return; ItemInserted.Raise( this, new ItemInsertedEventArgs<object>( e.Index, e.Child.As<SledProfileInfoType>(), e.Parent.As<SledProfileInfoType>())); } private void DomNodeChildRemoving(object sender, ChildEventArgs e) { if (!e.Child.Is<SledProfileInfoType>()) return; ItemRemoved.Raise( this, new ItemRemovedEventArgs<object>( e.Index, e.Child.As<SledProfileInfoType>(), e.Parent.As<SledProfileInfoType>())); } } }
//----------------------------------------------------------------------- // <copyright file="JsonSchemaValidator.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NJsonSchema.Validation.FormatValidators; namespace NJsonSchema.Validation { /// <summary>Class to validate a JSON schema against a given <see cref="JToken"/>. </summary> public class JsonSchemaValidator { private readonly IEnumerable<IFormatValidator> _formatValidators = new IFormatValidator[] { new DateTimeFormatValidator(), new DateFormatValidator(), new EmailFormatValidator(), new GuidFormatValidator(), new HostnameFormatValidator(), new IpV4FormatValidator(), new IpV6FormatValidator(), new TimeFormatValidator(), new TimeSpanFormatValidator(), new UriFormatValidator(), new ByteFormatValidator(), new Base64FormatValidator(), new UuidFormatValidator() }; private readonly IDictionary<string, IFormatValidator[]> _formatValidatorsMap; /// <summary> /// Initializes JsonSchemaValidator /// </summary> public JsonSchemaValidator(params IFormatValidator[] customValidators) { _formatValidatorsMap = _formatValidators.Union(customValidators).GroupBy(x => x.Format).ToDictionary(v => v.Key, v => v.ToArray()); } /// <summary>Validates the given JSON data.</summary> /// <param name="jsonData">The json data.</param> /// <param name="schema">The schema.</param> /// <exception cref="JsonReaderException">Could not deserialize the JSON data.</exception> /// <returns>The list of validation errors.</returns> public ICollection<ValidationError> Validate(string jsonData, JsonSchema schema) { using (var reader = new StringReader(jsonData)) using (var jsonReader = new JsonTextReader(reader) { DateParseHandling = DateParseHandling.None }) { var jsonObject = JToken.ReadFrom(jsonReader); return Validate(jsonObject, schema); } } /// <summary>Validates the given JSON token.</summary> /// <param name="token">The token.</param> /// <param name="schema">The schema.</param> /// <returns>The list of validation errors.</returns> public ICollection<ValidationError> Validate(JToken token, JsonSchema schema) { return Validate(token, schema.ActualSchema, null, token.Path); } /// <summary>Validates the given JSON token.</summary> /// <param name="token">The token.</param> /// <param name="schema">The schema.</param> /// <param name="propertyName">The current property name.</param> /// <param name="propertyPath">The current property path.</param> /// <returns>The list of validation errors.</returns> protected virtual ICollection<ValidationError> Validate(JToken token, JsonSchema schema, string propertyName, string propertyPath) { var errors = new List<ValidationError>(); ValidateAnyOf(token, schema, propertyName, propertyPath, errors); ValidateAllOf(token, schema, propertyName, propertyPath, errors); ValidateOneOf(token, schema, propertyName, propertyPath, errors); ValidateNot(token, schema, propertyName, propertyPath, errors); ValidateType(token, schema, propertyName, propertyPath, errors); ValidateEnum(token, schema, propertyName, propertyPath, errors); ValidateProperties(token, schema, propertyName, propertyPath, errors); return errors; } private void ValidateType(JToken token, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { var types = GetTypes(schema).ToDictionary(t => t, t => (ICollection<ValidationError>)new List<ValidationError>()); if (types.Count > 1) { foreach (var type in types) { ValidateArray(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value); ValidateString(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value); ValidateNumber(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value); ValidateInteger(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value); ValidateBoolean(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value); ValidateNull(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value); ValidateObject(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value); } // just one has to validate when multiple types are defined if (types.All(t => t.Value.Count > 0)) { errors.Add(new MultiTypeValidationError( ValidationErrorKind.NoTypeValidates, propertyName, propertyPath, types, token, schema)); } } else { ValidateArray(token, schema, schema.Type, propertyName, propertyPath, errors); ValidateString(token, schema, schema.Type, propertyName, propertyPath, errors); ValidateNumber(token, schema, schema.Type, propertyName, propertyPath, errors); ValidateInteger(token, schema, schema.Type, propertyName, propertyPath, errors); ValidateBoolean(token, schema, schema.Type, propertyName, propertyPath, errors); ValidateNull(token, schema, schema.Type, propertyName, propertyPath, errors); ValidateObject(token, schema, schema.Type, propertyName, propertyPath, errors); } } private static readonly IEnumerable<JsonObjectType> JsonObjectTypes = Enum .GetValues(typeof(JsonObjectType)) .Cast<JsonObjectType>() .Where(t => t != JsonObjectType.None) .ToList(); private IEnumerable<JsonObjectType> GetTypes(JsonSchema schema) { return JsonObjectTypes.Where(t => schema.Type.HasFlag(t)); } private void ValidateAnyOf(JToken token, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.AnyOf.Count > 0) { var propertyErrors = schema.AnyOf.ToDictionary(s => s, s => Validate(token, s)); if (propertyErrors.All(s => s.Value.Count != 0)) { errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotAnyOf, propertyName, propertyPath, propertyErrors, token, schema)); } } } private void ValidateAllOf(JToken token, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.AllOf.Count > 0) { var propertyErrors = schema.AllOf.ToDictionary(s => s, s => Validate(token, s)); if (propertyErrors.Any(s => s.Value.Count != 0)) { errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotAllOf, propertyName, propertyPath, propertyErrors, token, schema)); } } } private void ValidateOneOf(JToken token, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.OneOf.Count > 0) { var propertyErrors = schema.OneOf.ToDictionary(s => s, s => Validate(token, s)); if (propertyErrors.Count(s => s.Value.Count == 0) != 1) { errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotOneOf, propertyName, propertyPath, propertyErrors, token, schema)); } } } private void ValidateNot(JToken token, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.Not != null && Validate(token, schema.Not).Count == 0) { errors.Add(new ValidationError(ValidationErrorKind.ExcludedSchemaValidates, propertyName, propertyPath, token, schema)); } } private void ValidateNull(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List<ValidationError> errors) { if (type.HasFlag(JsonObjectType.Null) && token != null && token.Type != JTokenType.Null) { errors.Add(new ValidationError(ValidationErrorKind.NullExpected, propertyName, propertyPath, token, schema)); } } private void ValidateEnum(JToken token, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.Enumeration.Contains(null) && token?.Type == JTokenType.Null) { return; } if (schema.Enumeration.Count > 0 && schema.Enumeration.All(v => v?.ToString() != token?.ToString())) { errors.Add(new ValidationError(ValidationErrorKind.NotInEnumeration, propertyName, propertyPath, token, schema)); } } private void ValidateString(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List<ValidationError> errors) { var isString = token.Type == JTokenType.String || token.Type == JTokenType.Date || token.Type == JTokenType.Guid || token.Type == JTokenType.TimeSpan || token.Type == JTokenType.Uri; if (isString) { var value = token.Type == JTokenType.Date ? (token as JValue).ToString("yyyy-MM-ddTHH:mm:ssK") : token.Value<string>(); if (value != null) { if (!string.IsNullOrEmpty(schema.Pattern)) { if (!Regex.IsMatch(value, schema.Pattern)) { errors.Add(new ValidationError(ValidationErrorKind.PatternMismatch, propertyName, propertyPath, token, schema)); } } if (schema.MinLength.HasValue && value.Length < schema.MinLength) { errors.Add(new ValidationError(ValidationErrorKind.StringTooShort, propertyName, propertyPath, token, schema)); } if (schema.MaxLength.HasValue && value.Length > schema.MaxLength) { errors.Add(new ValidationError(ValidationErrorKind.StringTooLong, propertyName, propertyPath, token, schema)); } if (!string.IsNullOrEmpty(schema.Format) && _formatValidatorsMap.TryGetValue(schema.Format, out var formatValidators) && !formatValidators.Any(x => x.IsValid(value, token.Type))) { errors.AddRange(formatValidators.Select(x => x.ValidationErrorKind).Distinct() .Select(validationErrorKind => new ValidationError(validationErrorKind, propertyName, propertyPath, token, schema))); } } } else if (type.HasFlag(JsonObjectType.String)) { errors.Add(new ValidationError(ValidationErrorKind.StringExpected, propertyName, propertyPath, token, schema)); } } private void ValidateNumber(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List<ValidationError> errors) { if (type.HasFlag(JsonObjectType.Number) && token.Type != JTokenType.Float && token.Type != JTokenType.Integer) { errors.Add(new ValidationError(ValidationErrorKind.NumberExpected, propertyName, propertyPath, token, schema)); } if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer) { try { var value = token.Value<decimal>(); if (schema.Minimum.HasValue && (schema.IsExclusiveMinimum ? value <= schema.Minimum : value < schema.Minimum)) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooSmall, propertyName, propertyPath, token, schema)); } if (schema.Maximum.HasValue && (schema.IsExclusiveMaximum ? value >= schema.Maximum : value > schema.Maximum)) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooBig, propertyName, propertyPath, token, schema)); } if (schema.ExclusiveMinimum.HasValue && value <= schema.ExclusiveMinimum) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooSmall, propertyName, propertyPath, token, schema)); } if (schema.ExclusiveMaximum.HasValue && value >= schema.ExclusiveMaximum) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooBig, propertyName, propertyPath, token, schema)); } if (schema.MultipleOf.HasValue && value % schema.MultipleOf != 0) { errors.Add(new ValidationError(ValidationErrorKind.NumberNotMultipleOf, propertyName, propertyPath, token, schema)); } } catch (OverflowException) { var value = token.Value<double>(); if (schema.Minimum.HasValue && (schema.IsExclusiveMinimum ? value <= (double)schema.Minimum : value < (double)schema.Minimum)) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooSmall, propertyName, propertyPath, token, schema)); } if (schema.Maximum.HasValue && (schema.IsExclusiveMaximum ? value >= (double)schema.Maximum : value > (double)schema.Maximum)) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooBig, propertyName, propertyPath, token, schema)); } if (schema.ExclusiveMinimum.HasValue && value <= (double)schema.ExclusiveMinimum) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooSmall, propertyName, propertyPath, token, schema)); } if (schema.ExclusiveMaximum.HasValue && value >= (double)schema.ExclusiveMaximum) { errors.Add(new ValidationError(ValidationErrorKind.NumberTooBig, propertyName, propertyPath, token, schema)); } if (schema.MultipleOf.HasValue && value % (double)schema.MultipleOf != 0) { errors.Add(new ValidationError(ValidationErrorKind.NumberNotMultipleOf, propertyName, propertyPath, token, schema)); } } } } private void ValidateInteger(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List<ValidationError> errors) { if (type.HasFlag(JsonObjectType.Integer) && token.Type != JTokenType.Integer) { errors.Add(new ValidationError(ValidationErrorKind.IntegerExpected, propertyName, propertyPath, token, schema)); } } private void ValidateBoolean(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List<ValidationError> errors) { if (type.HasFlag(JsonObjectType.Boolean) && token.Type != JTokenType.Boolean) { errors.Add(new ValidationError(ValidationErrorKind.BooleanExpected, propertyName, propertyPath, token, schema)); } } private void ValidateObject(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List<ValidationError> errors) { if (type.HasFlag(JsonObjectType.Object) && !(token is JObject)) { errors.Add(new ValidationError(ValidationErrorKind.ObjectExpected, propertyName, propertyPath, token, schema)); } } private void ValidateProperties(JToken token, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { var obj = token as JObject; if (obj == null && schema.Type.HasFlag(JsonObjectType.Null)) { return; } foreach (var propertyInfo in schema.Properties) { var newPropertyPath = GetPropertyPath(propertyPath, propertyInfo.Key); var property = obj?.Property(propertyInfo.Key); if (property != null) { var propertyErrors = Validate(property.Value, propertyInfo.Value.ActualSchema, propertyInfo.Key, newPropertyPath); errors.AddRange(propertyErrors); } else if (propertyInfo.Value.IsRequired) { errors.Add(new ValidationError(ValidationErrorKind.PropertyRequired, propertyInfo.Key, newPropertyPath, token, schema)); } } // Properties may be required in a schema without being specified as a property. foreach (var requiredProperty in schema.RequiredProperties) { if (schema.Properties.ContainsKey(requiredProperty)) { // The property has already been checked. continue; } var newPropertyPath = GetPropertyPath(propertyPath, requiredProperty); if (obj?.Property(requiredProperty) == null) { errors.Add(new ValidationError(ValidationErrorKind.PropertyRequired, requiredProperty, newPropertyPath, token, schema)); } } if (obj != null) { var properties = obj.Properties().ToList(); ValidateMaxProperties(token, properties, schema, propertyName, propertyPath, errors); ValidateMinProperties(token, properties, schema, propertyName, propertyPath, errors); var additionalProperties = properties.Where(p => !schema.Properties.ContainsKey(p.Name)).ToList(); ValidatePatternProperties(additionalProperties, schema, errors); ValidateAdditionalProperties(token, additionalProperties, schema, propertyName, propertyPath, errors); } } private string GetPropertyPath(string propertyPath, string propertyName) { return !string.IsNullOrEmpty(propertyPath) ? propertyPath + "." + propertyName : propertyName; } private void ValidateMaxProperties(JToken token, IList<JProperty> properties, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.MaxProperties > 0 && properties.Count() > schema.MaxProperties) { errors.Add(new ValidationError(ValidationErrorKind.TooManyProperties, propertyName, propertyPath, token, schema)); } } private void ValidateMinProperties(JToken token, IList<JProperty> properties, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.MinProperties > 0 && properties.Count() < schema.MinProperties) { errors.Add(new ValidationError(ValidationErrorKind.TooFewProperties, propertyName, propertyPath, token, schema)); } } private void ValidatePatternProperties(List<JProperty> additionalProperties, JsonSchema schema, List<ValidationError> errors) { foreach (var property in additionalProperties.ToArray()) { var patternPropertySchema = schema.PatternProperties.FirstOrDefault(p => Regex.IsMatch(property.Name, p.Key)); if (patternPropertySchema.Value != null) { var error = TryCreateChildSchemaError(property.Value, patternPropertySchema.Value, ValidationErrorKind.AdditionalPropertiesNotValid, property.Name, property.Path); if (error != null) { errors.Add(error); } additionalProperties.Remove(property); } } } private void ValidateAdditionalProperties(JToken token, List<JProperty> additionalProperties, JsonSchema schema, string propertyName, string propertyPath, List<ValidationError> errors) { if (schema.AdditionalPropertiesSchema != null) { foreach (var property in additionalProperties) { var error = TryCreateChildSchemaError(property.Value, schema.AdditionalPropertiesSchema, ValidationErrorKind.AdditionalPropertiesNotValid, property.Name, property.Path); if (error != null) { errors.Add(error); } } } else if (!schema.AllowAdditionalProperties && additionalProperties.Any()) { foreach (var property in additionalProperties) { var newPropertyPath = !string.IsNullOrEmpty(propertyPath) ? propertyPath + "." + property.Name : property.Name; errors.Add(new ValidationError(ValidationErrorKind.NoAdditionalPropertiesAllowed, property.Name, newPropertyPath, property, schema)); } } } private void ValidateArray(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List<ValidationError> errors) { if (token is JArray array) { if (schema.MinItems > 0 && array.Count < schema.MinItems) { errors.Add(new ValidationError(ValidationErrorKind.TooFewItems, propertyName, propertyPath, token, schema)); } if (schema.MaxItems > 0 && array.Count > schema.MaxItems) { errors.Add(new ValidationError(ValidationErrorKind.TooManyItems, propertyName, propertyPath, token, schema)); } if (schema.UniqueItems && array.Count != array.Select(a => a.ToString()).Distinct().Count()) { errors.Add(new ValidationError(ValidationErrorKind.ItemsNotUnique, propertyName, propertyPath, token, schema)); } for (var index = 0; index < array.Count; index++) { var item = array[index]; var propertyIndex = string.Format("[{0}]", index); var itemPath = !string.IsNullOrEmpty(propertyPath) ? propertyPath + propertyIndex : propertyIndex; if (schema.Item != null) { var error = TryCreateChildSchemaError(item, schema.Item, ValidationErrorKind.ArrayItemNotValid, propertyIndex, itemPath); if (error != null) { errors.Add(error); } } ValidateAdditionalItems(item, schema, index, propertyPath, errors); } } else if (type.HasFlag(JsonObjectType.Array)) { errors.Add(new ValidationError(ValidationErrorKind.ArrayExpected, propertyName, propertyPath, token, schema)); } } private void ValidateAdditionalItems(JToken item, JsonSchema schema, int index, string propertyPath, List<ValidationError> errors) { if (schema.Items.Count > 0) { var propertyIndex = string.Format("[{0}]", index); if (schema.Items.Count > index) { var error = TryCreateChildSchemaError(item, schema.Items.ElementAt(index), ValidationErrorKind.ArrayItemNotValid, propertyIndex, propertyPath + propertyIndex); if (error != null) { errors.Add(error); } } else if (schema.AdditionalItemsSchema != null) { var error = TryCreateChildSchemaError(item, schema.AdditionalItemsSchema, ValidationErrorKind.AdditionalItemNotValid, propertyIndex, propertyPath + propertyIndex); if (error != null) { errors.Add(error); } } else if (!schema.AllowAdditionalItems) { errors.Add(new ValidationError(ValidationErrorKind.TooManyItemsInTuple, propertyIndex, propertyPath + propertyIndex, item, schema)); } } } private ChildSchemaValidationError TryCreateChildSchemaError(JToken token, JsonSchema schema, ValidationErrorKind errorKind, string property, string path) { var errors = Validate(token, schema.ActualSchema, null, path); if (errors.Count == 0) { return null; } var errorDictionary = new Dictionary<JsonSchema, ICollection<ValidationError>>(); errorDictionary.Add(schema, errors); return new ChildSchemaValidationError(errorKind, property, path, errorDictionary, token, schema); } } }
using CommandLineParser.Arguments; using CommandLineParser.Exceptions; using System.Collections.Generic; using Xunit; namespace Tests { public partial class Tests { #pragma warning disable CS0649 enum OptionsFlag { O1, O2, O3 } class ValueArgumentParsingTarget { [ValueArgument(typeof(int), 'i', AllowMultiple = true)] public List<int> Numbers; [ValueArgument(typeof(int), 'v', DefaultValue = 2, ForcedDefaultValue = 1, ValueOptional = true)] public int Version; [ValueArgument(typeof(int?), 'n', Optional = true)] public int? NullableInt; [ValueArgument(typeof(bool?), 'b', Optional = true)] public bool? NullableBool; [ValueArgument(typeof(int), 'l', DefaultValue = 0)] public int Length; [ValueArgument(typeof(int), 'd', DefaultValue = 9, ValueOptional = true)] public int Duration; [ValueArgument(typeof(OptionsFlag), 'f', "flag", DefaultValue = OptionsFlag.O3)] public OptionsFlag Flag; } #pragma warning restore CS0649 ValueArgumentParsingTarget valueArgumentTarget; public CommandLineParser.CommandLineParser InitValueArgument() { var commandLineParser = new CommandLineParser.CommandLineParser(); valueArgumentTarget = new ValueArgumentParsingTarget(); commandLineParser.ExtractArgumentAttributes(valueArgumentTarget); return commandLineParser; } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnDefaultEnumValue_whenParameterNotPassed_andForcedDefaultValueNotSet() { // Arrange string[] args = { " " }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(OptionsFlag.O3, valueArgumentTarget.Flag); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnDefaultValue_whenParameterNotPassed_andForcedDefaultValueNotSet() { // Arrange string[] args = { " " }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(9, valueArgumentTarget.Duration); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnDefaultValue_whenParameterPassedWithoutValue_andForcedDefaultValueNotSet() { // Arrange string[] args = { "-d" }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(9, valueArgumentTarget.Duration); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnValue_whenParameterPassedWithValue_andForcedDefaultValueNotSet() { // Arrange string[] args = { "-d", "7" }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(7, valueArgumentTarget.Duration); } [Fact] public void ArgumentBoundToCollection_shouldCreateInstanceOfTheCollection() { // Arrange string[] args = { "-i", "1", "-i", "2", "-i", "3" }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(new List<int> { 1, 2, 3 }, valueArgumentTarget.Numbers); } [Fact] public void ValueArgumentWithOptionalNullableValue_shouldReturnDefaultValue_whenValueNotSpecified() { // Arrange string[] args = { }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(null, valueArgumentTarget.NullableInt); Assert.Equal(null, valueArgumentTarget.NullableBool); } [Fact] public void ValueArgumentWithOptionalNullableValue_shouldReturnCorrectValue_whenValueIsSpecified() { // Arrange string[] args = { "-n", "42", "-b", "true" }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(42, valueArgumentTarget.NullableInt); Assert.Equal(true, valueArgumentTarget.NullableBool); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnDefaultValue_whenValueNotUsed_valueArgumentIsInTheMiddle() { // Arrange string[] args = { "-v", "-i", "1" }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(2 /*default*/ , valueArgumentTarget.Version); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnDefaultValue_whenValueNotUsed_valueArgumentIsAtTheEnd() { // Arrange string[] args = { "-i", "1", "-v" }; var commandLineParser = InitValueArgument(); // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(2 /*default*/ , valueArgumentTarget.Version); } [Fact] public void ValueArgumentWithMandatoryValue_shouldFailParsing_whenValueNotFound_lastArgument() { // Arrange string[] args = { "-l" }; var commandLineParser = InitValueArgument(); // Act var e = Assert.Throws<CommandLineArgumentException>(() => commandLineParser.ParseCommandLine(args)); Assert.Equal(e.Message, "Value argument l must be followed by a value."); } [Fact] public void ValueArgumentWithMandatoryValue_shouldFailParsing_whenValueNotFound_argumentInTheMiddle() { // Arrange string[] args = { "-l", "-v", "1" }; var commandLineParser = InitValueArgument(); // Act var e = Assert.Throws<CommandLineArgumentException>(() => commandLineParser.ParseCommandLine(args)); Assert.Equal(e.Message, "Value argument l must be followed by a value, another argument(-v) found instead"); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnDefaultValue_andValueNotUsed_whenUsingEqualsSyntax_andValueArgumentIsInTheMiddle() { // Arrange string[] args = { "-v", "-i=\"1\"" }; var commandLineParser = InitValueArgument(); commandLineParser.AcceptEqualSignSyntaxForValueArguments = true; // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(2 /*default*/ , valueArgumentTarget.Version); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnStrongDefaultValue_andValueNotUsed_whenUsingEqualsSyntax_andValueArgumentDoesNotExist() { // Arrange string[] args = { "-i=\"1\"" }; var commandLineParser = InitValueArgument(); commandLineParser.AcceptEqualSignSyntaxForValueArguments = true; // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(1 /*strong default*/ , valueArgumentTarget.Version); } [Fact] public void ValueArgumentWithOptionalValue_shouldReturnDefaultValue_whenValueNotUsed_whenUsingEqualsSyntax_andValueArgumentIsAtTheEnd() { // Arrange string[] args = { "-i=\"1\"", "-v" }; var commandLineParser = InitValueArgument(); commandLineParser.AcceptEqualSignSyntaxForValueArguments = true; // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(2 /*default*/ , valueArgumentTarget.Version); } [Fact] public void ValueArgument_shouldHandleNegativeIntegers_whenUsingEqualsSyntax() { // Arrange string[] args = { "-v=\"-1\"" }; var commandLineParser = InitValueArgument(); commandLineParser.AcceptEqualSignSyntaxForValueArguments = true; // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(-1, valueArgumentTarget.Version); } [Fact] public void ValueArgument_shouldHandleNegativeIntegers_whenNotUsingEqualsSyntax() { // Arrange string[] args = { "-v", "-1" }; var commandLineParser = InitValueArgument(); commandLineParser.AcceptEqualSignSyntaxForValueArguments = false; // Act commandLineParser.ParseCommandLine(args); // Assert Assert.Equal(-1, valueArgumentTarget.Version); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Windows.Input; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.ServiceLocation; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using StockTraderRI.Infrastructure; using StockTraderRI.Infrastructure.Interfaces; using StockTraderRI.Modules.Position.Controllers; using StockTraderRI.Modules.Position.Interfaces; using StockTraderRI.Modules.Position.Models; using StockTraderRI.Modules.Position.Orders; using StockTraderRI.Modules.Position.Tests.Mocks; namespace StockTraderRI.Modules.Position.Tests.Controllers { [TestClass] public class OrdersControllerFixture { private MockRegionManager regionManager; private MockRegion ordersRegion; [TestInitialize] public void SetUp() { regionManager = new MockRegionManager(); regionManager.Regions.Add("ActionRegion", new MockRegion()); ordersRegion = new MockRegion(); regionManager.Regions.Add("OrdersRegion", ordersRegion); } [TestMethod] public void BuyAndSellCommandsInvokeController() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var buyOrderCompositeViewModel = new MockOrderCompositeViewModel(); var sellOrderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel orderCompositeViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(orderCompositeViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(buyOrderCompositeViewModel); controller.BuyCommand.Execute("STOCK01"); Assert.AreEqual("STOCK01", controller.StartOrderArgumentTickerSymbol); Assert.AreEqual(TransactionType.Buy, controller.StartOrderArgumentTransactionType); // Set new CompositeViewModel to simulate resolution of new instance. mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(sellOrderCompositeViewModel); controller.SellCommand.Execute("STOCK02"); Assert.AreEqual("STOCK02", controller.StartOrderArgumentTickerSymbol); Assert.AreEqual(TransactionType.Sell, controller.StartOrderArgumentTransactionType); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void ControllerAddsViewIfNotPresent() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); var collapsibleRegion = (MockRegion)regionManager.Regions["ActionRegion"]; Assert.AreEqual<int>(0, collapsibleRegion.AddedViews.Count); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.AreEqual<int>(1, collapsibleRegion.AddedViews.Count); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void ControllerAddsANewOrderOnStartOrder() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); Assert.AreEqual<int>(0, ordersRegion.AddedViews.Count); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.AreEqual<int>(1, ordersRegion.AddedViews.Count); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void NewOrderIsShownOrder() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); Assert.AreEqual<int>(0, ordersRegion.AddedViews.Count); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.AreSame(ordersRegion.SelectedItem, ordersRegion.AddedViews[0]); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void StartOrderHooksInstanceCommandsToGlobalSaveAllAndCancelAllCommands() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.IsFalse(orderCompositeViewModel.MockSubmitCommand.ExecuteCalled); commandProxy.SubmitAllOrdersCommand.Execute(null); Assert.IsTrue(orderCompositeViewModel.MockSubmitCommand.ExecuteCalled); Assert.IsFalse(orderCompositeViewModel.MockCancelCommand.ExecuteCalled); commandProxy.CancelAllOrdersCommand.Execute(null); Assert.IsTrue(orderCompositeViewModel.MockCancelCommand.ExecuteCalled); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void StartOrderHooksInstanceCommandsToGlobalSaveAndCancelCommands() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.IsFalse(orderCompositeViewModel.MockSubmitCommand.ExecuteCalled); commandProxy.SubmitOrderCommand.Execute(null); Assert.IsTrue(orderCompositeViewModel.MockSubmitCommand.ExecuteCalled); Assert.IsFalse(orderCompositeViewModel.MockCancelCommand.ExecuteCalled); commandProxy.CancelOrderCommand.Execute(null); Assert.IsTrue(orderCompositeViewModel.MockCancelCommand.ExecuteCalled); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void OnCloseViewRequestedTheControllerUnhooksGlobalCommands() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.AreEqual(1, ordersRegion.AddedViews.Count); // Act orderCompositeViewModel.RaiseCloseViewRequested(); // Verify Assert.AreEqual(0, ordersRegion.AddedViews.Count); commandProxy.SubmitAllOrdersCommand.Execute(null); Assert.IsFalse(orderCompositeViewModel.MockSubmitCommand.ExecuteCalled); commandProxy.CancelAllOrdersCommand.Execute(null); Assert.IsFalse(orderCompositeViewModel.MockCancelCommand.ExecuteCalled); commandProxy.SubmitOrderCommand.Execute(null); Assert.IsFalse(orderCompositeViewModel.MockSubmitCommand.ExecuteCalled); commandProxy.CancelOrderCommand.Execute(null); Assert.IsFalse(orderCompositeViewModel.MockCancelCommand.ExecuteCalled); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void StartOrderCreatesCompositePMAndPassesCorrectInitInfo() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, null); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.AreEqual("STOCK01", orderCompositeViewModel.TransactionInfo.TickerSymbol); Assert.AreEqual(TransactionType.Buy, orderCompositeViewModel.TransactionInfo.TransactionType); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void SubmitAllInstanceCommandHookedToGlobalSubmitAllCommands() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var accountPositionService = new MockAccountPositionService(); accountPositionService.AddPosition("STOCK01", 10.0M, 100); var controller = new TestableOrdersController(regionManager, commandProxy, accountPositionService); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.IsFalse(controller.SubmitAllCommandCalled); commandProxy.SubmitAllOrdersCommand.CanExecute(null); Assert.IsTrue(controller.SubmitAllCommandCalled); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void CannotSellMoreSharesThanAreOwned() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var accountPositionService = new MockAccountPositionService(); accountPositionService.AddPosition("STOCK01", 10.0M, 100); var controller = new TestableOrdersController(regionManager, commandProxy, accountPositionService); // Act var buyOrder = new MockOrderCompositeViewModel() { Shares = 100, }; mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(buyOrder); controller.InvokeStartOrder(TransactionType.Buy, "STOCK01"); Assert.IsTrue(controller.SubmitAllVoteOnlyCommand.CanExecute()); var sellOrder = new MockOrderCompositeViewModel() { Shares = 200 }; mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(sellOrder); controller.InvokeStartOrder(TransactionType.Sell, "STOCK01"); //Should not be able to sell even though owned shares==100, buy==100 and sell==200 Assert.IsFalse(controller.SubmitAllVoteOnlyCommand.CanExecute()); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void CannotSellMoreSharesThanAreOwnedInDifferentOrders() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var accountPositionService = new MockAccountPositionService(); accountPositionService.AddPosition("STOCK01", 10.0M, 100); var controller = new TestableOrdersController(regionManager, commandProxy, accountPositionService); var sellOrder1 = new MockOrderCompositeViewModel() { Shares = 100 }; mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(sellOrder1); controller.InvokeStartOrder(TransactionType.Sell, "STOCK01"); Assert.IsTrue(controller.SubmitAllVoteOnlyCommand.CanExecute()); var sellOrder2 = new MockOrderCompositeViewModel() { Shares = 100 }; mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(sellOrder2); controller.InvokeStartOrder(TransactionType.Sell, "stock01"); Assert.IsFalse(controller.SubmitAllVoteOnlyCommand.CanExecute()); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void CannotSellMoreSharesThatAreNotOwned() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel() { Shares = 1 }; var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, new MockStockTraderRICommandProxy(), new MockAccountPositionService()); controller.InvokeStartOrder(TransactionType.Sell, "NOTOWNED"); Assert.IsFalse(controller.SubmitAllVoteOnlyCommand.CanExecute()); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void CannotSubmitAllWhenNothingToSubmit() { var controller = new TestableOrdersController(new MockRegionManager(), new MockStockTraderRICommandProxy(), new MockAccountPositionService()); Assert.IsFalse(controller.SubmitAllVoteOnlyCommand.CanExecute()); } [TestMethod] public void AfterAllOrdersSubmittedSubmitAllCommandShouldBeDisabled() { try { Mock<IOrdersView> mockOrdersView = new Mock<IOrdersView>(); Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel(); var commandProxy = new MockStockTraderRICommandProxy(); IOrdersView orderCompositeView = mockOrdersView.Object; IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(orderCompositeView); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, new MockAccountPositionService()); var buyOrder = new MockOrderCompositeViewModel() { Shares = 100 }; mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(buyOrder); controller.InvokeStartOrder(TransactionType.Buy, "STOCK1"); bool canExecuteChangedCalled = false; bool canExecuteResult = false; commandProxy.SubmitAllOrdersCommand.CanExecuteChanged += delegate { canExecuteChangedCalled = true; canExecuteResult = controller.SubmitAllVoteOnlyCommand.CanExecute(); }; buyOrder.RaiseCloseViewRequested(); Assert.IsTrue(canExecuteChangedCalled); Assert.IsFalse(canExecuteResult); } finally { ServiceLocator.SetLocatorProvider(() => null); } } [TestMethod] public void ShouldRemoveOrdersViewWhenClosingLastOrder() { try { Mock<IOrdersViewModel> mockOrdersViewModel = new Mock<IOrdersViewModel>(); Mock<ServiceLocatorImplBase> mockServiceLocator = new Mock<ServiceLocatorImplBase>(); var orderCompositeViewModel = new MockOrderCompositeViewModel() { Shares = 100 }; var commandProxy = new MockStockTraderRICommandProxy(); IOrdersViewModel ordersViewModel = mockOrdersViewModel.Object; mockServiceLocator.Setup(x => x.GetInstance<IOrdersView>()).Returns(new Mock<IOrdersView>().Object); mockServiceLocator.Setup(x => x.GetInstance<IOrdersViewModel>()).Returns(ordersViewModel); mockServiceLocator.Setup(x => x.GetInstance<IOrderCompositeViewModel>()).Returns(orderCompositeViewModel); ServiceLocator.SetLocatorProvider(() => mockServiceLocator.Object); var controller = new TestableOrdersController(regionManager, commandProxy, new MockAccountPositionService()); var region = (MockRegion)regionManager.Regions["ActionRegion"]; controller.InvokeStartOrder(TransactionType.Buy, "STOCK1"); Assert.AreEqual<int>(1, region.AddedViews.Count); orderCompositeViewModel.RaiseCloseViewRequested(); Assert.AreEqual<int>(0, region.AddedViews.Count); } finally { ServiceLocator.SetLocatorProvider(() => null); } } } internal class TestableOrdersController : OrdersController { public TestableOrdersController(IRegionManager regionManager, MockStockTraderRICommandProxy commandProxy, IAccountPositionService accountPositionService) : base(regionManager, commandProxy, accountPositionService) { } public string StartOrderArgumentTickerSymbol { get; set; } public TransactionType StartOrderArgumentTransactionType { get; set; } protected override void StartOrder(string tickerSymbol, TransactionType transactionType) { base.StartOrder(tickerSymbol, transactionType); StartOrderArgumentTickerSymbol = tickerSymbol; StartOrderArgumentTransactionType = transactionType; } public void InvokeStartOrder(TransactionType transactionType, string symbol) { StartOrder(symbol, transactionType); } public bool SubmitAllCommandCalled = false; protected override bool SubmitAllCanExecute() { SubmitAllCommandCalled = true; return base.SubmitAllCanExecute(); } } public class MockOrdersViewModel : IOrdersViewModel { public string HeaderInfo { get { throw new NotImplementedException(); } } } class MockOrderCompositeViewModel : IOrderCompositeViewModel { public MockCommand MockSubmitCommand = new MockCommand(); public MockCommand MockCancelCommand = new MockCommand(); public event EventHandler CloseViewRequested; public ICommand SubmitCommand { get { return MockSubmitCommand; } } public ICommand CancelCommand { get { return MockCancelCommand; } } public TransactionInfo TransactionInfo { get; set; } public int Shares { get; set; } internal void RaiseCloseViewRequested() { CloseViewRequested(this, EventArgs.Empty); } } internal class MockCommand : ICommand { public bool ExecuteCalled; public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { ExecuteCalled = true; } } }
// Copyright 2007 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using DBus; using org.freedesktop.DBus; public class ManagedDBusTestExport { public static void Main () { Bus bus = Bus.Session; string bus_name = "org.ndesk.test"; ObjectPath path = new ObjectPath ("/org/ndesk/test"); IDemoOne demo; if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) { //create a new instance of the object to be exported demo = new Demo (); bus.Register (path, demo); //run the main loop while (true) bus.Iterate (); } else { //import a remote to a local proxy demo = bus.GetObject<IDemo> (bus_name, path); //demo = bus.GetObject<DemoProx> (bus_name, path); } Console.WriteLine (); demo.SomeEvent += HandleSomeEventA; demo.FireOffSomeEvent (); Console.WriteLine (); demo.SomeEvent -= HandleSomeEventA; demo.FireOffSomeEvent (); Console.WriteLine (); demo.SomeEvent += delegate (string arg1, object arg2, double arg3, MyTuple mt) {Console.WriteLine ("SomeEvent handler: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B);}; demo.SomeEvent += delegate (string arg1, object arg2, double arg3, MyTuple mt) {Console.WriteLine ("SomeEvent handler two: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B);}; demo.FireOffSomeEvent (); Console.WriteLine (); Console.WriteLine (demo.GetSomeVariant ()); Console.WriteLine (); demo.Say2 ("demo.Say2"); ((IDemoTwo)demo).Say2 ("((IDemoTwo)demo).Say2"); demo.SayEnum (DemoEnum.Bar, DemoEnum.Foo); uint n; string ostr; demo.WithOutParameters (out n, "21", out ostr); Console.WriteLine ("n: " + n); Console.WriteLine ("ostr: " + ostr); uint[] a1, a2, a3; demo.WithOutParameters2 (out a1, out a2, out a3); Console.WriteLine ("oparam2: " + a2[1]); uint[] @contacts = new uint[] { 2 }; IDictionary<uint,SimplePresence> presence; demo.GetPresences (contacts, out presence); Console.WriteLine ("pres: " + presence[2].Status); MyTuple2 cpx = new MyTuple2 (); cpx.A = "a"; cpx.B = "b"; cpx.C = new Dictionary<int,MyTuple> (); cpx.C[3] = new MyTuple("foo", "bar"); object cpxRet = demo.ComplexAsVariant (cpx, 12); MyTuple2 mt2ret = (MyTuple2)Convert.ChangeType (cpxRet, typeof (MyTuple2)); Console.WriteLine ("mt2ret.C[3].B " + mt2ret.C[3].B); /* IDemoOne[] objs = demo.GetObjArr (); foreach (IDemoOne obj in objs) obj.Say ("Some obj"); */ Console.WriteLine("SomeProp: " + demo.SomeProp); demo.SomeProp = 321; DemoProx demoProx = demo as DemoProx; if (demoProx != null) demoProx.SayRepeatedly(5, "Repetition"); demo.ThrowSomeException (); } public static void HandleSomeEventA (string arg1, object arg2, double arg3, MyTuple mt) { Console.WriteLine ("SomeEvent handler A: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B); } public static void HandleSomeEventB (string arg1, object arg2, double arg3, MyTuple mt) { Console.WriteLine ("SomeEvent handler B: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B); } } [Interface ("org.ndesk.test")] public interface IDemoOne { event SomeEventHandler SomeEvent; void FireOffSomeEvent (); void Say (object var); void SayEnum (DemoEnum a, DemoEnum b); void Say2 (string str); object GetSomeVariant (); void ThrowSomeException (); void WithOutParameters (out uint n, string str, out string ostr); void WithOutParameters2 (out uint[] a1, out uint[] a2, out uint[] a3); void GetPresences (uint[] @contacts, out IDictionary<uint,SimplePresence> @presence); object ComplexAsVariant (object v, int num); IDemoOne[] GetEmptyObjArr (); IDemoOne[] GetObjArr (); int SomeProp { get; set; } } [Interface ("org.ndesk.test2")] public interface IDemoTwo { int Say (string str); void Say2 (string str); } public interface IDemo : IDemoOne, IDemoTwo { } public abstract class DemoProx : DemoBase { public virtual void SayRepeatedly (int count, string str) { for (int i = 0 ; i != count ; i++) Say2(str); } } public class Demo : DemoBase { public override void Say2 (string str) { Console.WriteLine ("Subclassed IDemoOne.Say2: " + str); } } public class DemoBase : IDemo { public event SomeEventHandler SomeEvent; public void Say (object var) { Console.WriteLine ("variant: " + var); } public int Say (string str) { Console.WriteLine ("string: " + str); return str.Length; } public void SayEnum (DemoEnum a, DemoEnum b) { Console.WriteLine ("SayEnum: " + a + ", " + b); } public virtual void Say2 (string str) { Console.WriteLine ("IDemoOne.Say2: " + str); } void IDemoTwo.Say2 (string str) { Console.WriteLine ("IDemoTwo.Say2: " + str); } public void FireOffSomeEvent () { Console.WriteLine ("Asked to fire off SomeEvent"); MyTuple mt; mt.A = "a"; mt.B = "b"; if (SomeEvent != null) { SomeEvent ("some string", 21, 19.84, mt); Console.WriteLine ("Fired off SomeEvent"); } } public object GetSomeVariant () { Console.WriteLine ("GetSomeVariant()"); return new byte[0]; } public void ThrowSomeException () { throw new Exception ("Some exception"); } public void WithOutParameters (out uint n, string str, out string ostr) { n = UInt32.Parse (str); ostr = "." + str + "."; } public void WithOutParameters2 (out uint[] a1, out uint[] a2, out uint[] a3) { a1 = new uint[] { }; a2 = new uint[] { 21, 23, 16 }; a3 = new uint[] { 21, 23 }; } public void GetPresences (uint[] @contacts, out IDictionary<uint,SimplePresence> @presence) { Dictionary<uint,SimplePresence> presences = new Dictionary<uint,SimplePresence>(); presences[2] = new SimplePresence { Type = ConnectionPresenceType.Offline, Status = "offline", StatusMessage = "" }; presence = presences; } public object ComplexAsVariant (object v, int num) { Console.WriteLine ("v: " + v); Console.WriteLine ("v null? " + (v == null)); MyTuple2 mt2 = (MyTuple2)Convert.ChangeType (v, typeof (MyTuple2)); Console.WriteLine ("mt2.C[3].B " + mt2.C[3].B); Console.WriteLine ("num: " + num); return v; } public IDemoOne[] GetEmptyObjArr () { return new Demo[] {}; } public IDemoOne[] GetObjArr () { return new IDemoOne[] {this}; } public int SomeProp { get { return 123; } set { Console.WriteLine ("Set SomeProp: " + value); } } } public enum DemoEnum : byte { Foo, Bar, } public struct MyTuple { public MyTuple (string a, string b) { A = a; B = b; } public string A; public string B; } public struct MyTuple2 { public string A; public string B; public IDictionary<int,MyTuple> C; } public delegate void SomeEventHandler (string arg1, object arg2, double arg3, MyTuple mt); public enum ConnectionPresenceType : uint { Unset = 0, Offline = 1, Available = 2, Away = 3, ExtendedAway = 4, Hidden = 5, Busy = 6, Unknown = 7, Error = 8, } public struct SimplePresence { public ConnectionPresenceType Type; public string Status; public string StatusMessage; }
using System; using System.Collections.Generic; using System.ComponentModel; namespace Htc.Vita.Core.Auth { /// <summary> /// Class OAuth2. /// </summary> public static partial class OAuth2 { /// <summary> /// Class AuthorizationCodeClientConfig. /// </summary> public class AuthorizationCodeClientConfig { private Uri _accessTokenUri; private Uri _authorizationUri; private string _clientId; private string _clientSecret; private Uri _introspectTokenUri; private Uri _redirectUri; private Uri _refreshTokenUri; private ISet<string> _tokenScope = new HashSet<string>(); /// <summary> /// Gets or sets the access token URI. /// </summary> /// <value>The access token URI.</value> public Uri AccessTokenUri { get { return _accessTokenUri; } set { if (value == null) { return; } _accessTokenUri = value; } } /// <summary> /// Gets or sets the authorization URI. /// </summary> /// <value>The authorization URI.</value> public Uri AuthorizationUri { get { return _authorizationUri; } set { if (value == null) { return; } _authorizationUri = value; } } /// <summary> /// Gets or sets the client identifier. /// </summary> /// <value>The client identifier.</value> public string ClientId { get { return _clientId; } set { if (string.IsNullOrWhiteSpace(value)) { return; } _clientId = value; } } /// <summary> /// Gets or sets the client secret. /// </summary> /// <value>The client secret.</value> public string ClientSecret { get { return _clientSecret; } set { if (string.IsNullOrWhiteSpace(value)) { return; } _clientSecret = value; } } /// <summary> /// Gets or sets the introspect token URI. /// </summary> /// <value>The introspect token URI.</value> public Uri IntrospectTokenUri { get { return _introspectTokenUri; } set { if (value == null) { return; } _introspectTokenUri = value; } } /// <summary> /// Gets the options. /// </summary> /// <value>The options.</value> public Dictionary<string, object> Options { get; } = new Dictionary<string, object>(); /// <summary> /// Gets or sets the redirect URI. /// </summary> /// <value>The redirect URI.</value> public Uri RedirectUri { get { return _redirectUri; } set { if (value == null) { return; } _redirectUri = value; } } /// <summary> /// Gets or sets the refresh token URI. /// </summary> /// <value>The refresh token URI.</value> public Uri RefreshTokenUri { get { return _refreshTokenUri; } set { if (value == null) { return; } _refreshTokenUri = value; } } /// <summary> /// Gets the token scope. /// </summary> /// <value>The token scope.</value> public ISet<string> TokenScope { get { return _tokenScope; } set { if (value == null) { return; } _tokenScope = value; } } } /// <summary> /// Class ClientTokenInfo. /// </summary> public class ClientTokenInfo { private int _expiresInSec; private Dictionary<string, string> _options = new Dictionary<string, string>(); private ISet<string> _tokenScope = new HashSet<string>(); /// <summary> /// Gets or sets the access token. /// </summary> /// <value>The access token.</value> public string AccessToken { get; set; } /// <summary> /// Gets or sets the expires in sec. /// </summary> /// <value>The expires in sec.</value> public int ExpiresInSec { get { return _expiresInSec; } set { if (value < 0) { return; } _expiresInSec = value; } } /// <summary> /// Gets the options. /// </summary> /// <value>The options.</value> public Dictionary<string, string> Options { get { return _options; } set { if (value == null) { return; } _options = value; } } /// <summary> /// Gets or sets the refresh token. /// </summary> /// <value>The refresh token.</value> public string RefreshToken { get; set; } /// <summary> /// Gets the token scope. /// </summary> /// <value>The token scope.</value> public ISet<string> TokenScope { get { return _tokenScope; } set { if (value == null) { return; } _tokenScope = value; } } /// <summary> /// Gets or sets the type. /// </summary> /// <value>The type.</value> public TokenType Type { get; set; } = TokenType.Unknown; /// <summary> /// Fills the empty properties with another token. /// </summary> /// <param name="another">Another token.</param> /// <returns>ClientTokenInfo.</returns> public ClientTokenInfo FillEmptyPropertiesWith(ClientTokenInfo another) { if (another == null) { return this; } if (string.IsNullOrWhiteSpace(AccessToken)) { var anotherAccessToken = another.AccessToken; if (!string.IsNullOrWhiteSpace(anotherAccessToken)) { AccessToken = anotherAccessToken; } } if (ExpiresInSec <= 0) { var anotherExpiresInSec = another.ExpiresInSec; if (anotherExpiresInSec > 0) { ExpiresInSec = anotherExpiresInSec; } } if (Options == null || Options.Count <= 0) { var anotherOptions = another.Options; if (anotherOptions != null && anotherOptions.Count > 0) { Options = anotherOptions; } } if (string.IsNullOrWhiteSpace(RefreshToken)) { var anotherRefreshToken = another.RefreshToken; if (!string.IsNullOrWhiteSpace(anotherRefreshToken)) { RefreshToken = anotherRefreshToken; } } if (TokenScope == null) { var anotherTokenScope = another.TokenScope; if (anotherTokenScope != null) { TokenScope = anotherTokenScope; } } if (Type == TokenType.Unknown) { var anotherType = another.Type; if (anotherType != TokenType.Unknown) { Type = anotherType; } } return this; } } /// <summary> /// Enum GrantType /// </summary> public enum GrantType { /// <summary> /// The grant type for authorization code /// </summary> [Description("authorization_code")] AuthorizationCode, /// <summary> /// The grant type for client credentials /// </summary> [Description("client_credentials")] ClientCredentials, /// <summary> /// The grant type for device code /// </summary> [Description("urn:ietf:params:oauth:grant-type:device_code")] DeviceCode, /// <summary> /// The grant type for password /// </summary> [Description("password")] Password, /// <summary> /// The grant type for refresh token /// </summary> [Description("refresh_token")] RefreshToken } /// <summary> /// Enum Key /// </summary> public enum Key { /// <summary> /// The key for access token /// </summary> [Description("access_token")] AccessToken, /// <summary> /// The key for client identifier /// </summary> [Description("client_id")] ClientId, /// <summary> /// The key for client secret /// </summary> [Description("client_secret")] ClientSecret, /// <summary> /// The key for code /// </summary> [Description("code")] Code, /// <summary> /// The key for expires-in /// </summary> [Description("expires_in")] ExpiresIn, /// <summary> /// The key for grant type /// </summary> [Description("grant_type")] GrantType, /// <summary> /// The key for redirect URI /// </summary> [Description("redirection_uri")] RedirectUri, /// <summary> /// The key for refresh token /// </summary> [Description("refresh_token")] RefreshToken, /// <summary> /// The key for response type /// </summary> [Description("response_type")] ResponseType, /// <summary> /// The key for scope /// </summary> [Description("scope")] Scope, /// <summary> /// The key for token type /// </summary> [Description("token_type")] TokenType } /// <summary> /// Enum ResponseType /// </summary> public enum ResponseType { /// <summary> /// The response is code /// </summary> [Description("code")] Code, /// <summary> /// The response is token /// </summary> [Description("token")] Token } /// <summary> /// Enum TokenType /// </summary> public enum TokenType { /// <summary> /// Token type is unknown /// </summary> [Description("Unknown")] Unknown, /// <summary> /// Bearer token /// </summary> [Description("Bearer")] Bearer } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.BinaryAuthorization.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedBinauthzManagementServiceV1Beta1ClientTest { [xunit::FactAttribute] public void GetPolicyRequestObject() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.GetPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy response = client.GetPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPolicyRequestObjectAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.GetPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPolicy() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.GetPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy response = client.GetPolicy(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPolicyAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.GetPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetPolicyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPolicyResourceNames() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.GetPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy response = client.GetPolicy(request.PolicyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPolicyResourceNamesAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.GetPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetPolicyAsync(request.PolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetPolicyAsync(request.PolicyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdatePolicyRequestObject() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdatePolicyRequest request = new UpdatePolicyRequest { Policy = new Policy(), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.UpdatePolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy response = client.UpdatePolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdatePolicyRequestObjectAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdatePolicyRequest request = new UpdatePolicyRequest { Policy = new Policy(), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.UpdatePolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.UpdatePolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.UpdatePolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdatePolicy() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdatePolicyRequest request = new UpdatePolicyRequest { Policy = new Policy(), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.UpdatePolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy response = client.UpdatePolicy(request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdatePolicyAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdatePolicyRequest request = new UpdatePolicyRequest { Policy = new Policy(), }; Policy expectedResponse = new Policy { PolicyName = PolicyName.FromProject("[PROJECT]"), AdmissionWhitelistPatterns = { new AdmissionWhitelistPattern(), }, ClusterAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, DefaultAdmissionRule = new AdmissionRule(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable, KubernetesServiceAccountAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, IstioServiceIdentityAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, KubernetesNamespaceAdmissionRules = { { "key8a0b6e3c", new AdmissionRule() }, }, }; mockGrpcClient.Setup(x => x.UpdatePolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.UpdatePolicyAsync(request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.UpdatePolicyAsync(request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAttestorRequestObject() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), AttestorId = "attestor_id76a3ccd6", Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.CreateAttestor(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAttestorRequestObjectAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), AttestorId = "attestor_id76a3ccd6", Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.CreateAttestorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.CreateAttestorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAttestor() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), AttestorId = "attestor_id76a3ccd6", Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.CreateAttestor(request.Parent, request.AttestorId, request.Attestor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAttestorAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), AttestorId = "attestor_id76a3ccd6", Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.CreateAttestorAsync(request.Parent, request.AttestorId, request.Attestor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.CreateAttestorAsync(request.Parent, request.AttestorId, request.Attestor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAttestorResourceNames() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), AttestorId = "attestor_id76a3ccd6", Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.CreateAttestor(request.ParentAsProjectName, request.AttestorId, request.Attestor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAttestorResourceNamesAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), AttestorId = "attestor_id76a3ccd6", Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.CreateAttestorAsync(request.ParentAsProjectName, request.AttestorId, request.Attestor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.CreateAttestorAsync(request.ParentAsProjectName, request.AttestorId, request.Attestor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAttestorRequestObject() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.GetAttestor(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAttestorRequestObjectAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.GetAttestorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.GetAttestorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAttestor() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.GetAttestor(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAttestorAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.GetAttestorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.GetAttestorAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAttestorResourceNames() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.GetAttestor(request.AttestorName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAttestorResourceNamesAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.GetAttestorAsync(request.AttestorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.GetAttestorAsync(request.AttestorName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateAttestorRequestObject() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdateAttestorRequest request = new UpdateAttestorRequest { Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.UpdateAttestor(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateAttestorRequestObjectAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdateAttestorRequest request = new UpdateAttestorRequest { Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.UpdateAttestorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.UpdateAttestorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateAttestor() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdateAttestorRequest request = new UpdateAttestorRequest { Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor response = client.UpdateAttestor(request.Attestor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateAttestorAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); UpdateAttestorRequest request = new UpdateAttestorRequest { Attestor = new Attestor(), }; Attestor expectedResponse = new Attestor { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), UserOwnedDrydockNote = new UserOwnedDrydockNote(), UpdateTime = new wkt::Timestamp(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Attestor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); Attestor responseCallSettings = await client.UpdateAttestorAsync(request.Attestor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Attestor responseCancellationToken = await client.UpdateAttestorAsync(request.Attestor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAttestorRequestObject() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); client.DeleteAttestor(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAttestorRequestObjectAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); await client.DeleteAttestorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAttestorAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAttestor() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); client.DeleteAttestor(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAttestorAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); await client.DeleteAttestorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAttestorAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAttestorResourceNames() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAttestor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); client.DeleteAttestor(request.AttestorName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAttestorResourceNamesAsync() { moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client> mockGrpcClient = new moq::Mock<BinauthzManagementServiceV1Beta1.BinauthzManagementServiceV1Beta1Client>(moq::MockBehavior.Strict); DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAttestorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BinauthzManagementServiceV1Beta1Client client = new BinauthzManagementServiceV1Beta1ClientImpl(mockGrpcClient.Object, null); await client.DeleteAttestorAsync(request.AttestorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAttestorAsync(request.AttestorName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using PcapDotNet.Base; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.IpV6 { /// <summary> /// RFC 6554. /// <pre> /// +-----+-------+-------+------+------------------+--------------+---------------+ /// | Bit | 0-3 | 4-7 | 8-11 | 12-15 | 16-23 | 24-31 | /// +-----+-------+-------+------+------------------+--------------+---------------+ /// | 0 | Next Header | Header Extension Length | Routing Type | Segments Left | /// +-----+-------+-------+------+------------------+--------------+---------------+ /// | 32 | CmprI | CmprE | Pad | Reserved | /// +-----+-------+-------+------+-------------------------------------------------+ /// | 64 | Address[1] | /// | ... | | /// +-----+------------------------------------------------------------------------+ /// | | Address[2] | /// | ... | | /// +-----+------------------------------------------------------------------------+ /// | . | . | /// | . | . | /// | . | . | /// +-----+------------------------------------------------------------------------+ /// | | Address[n] | /// | ... | | /// +-----+------------------------------------------------------------------------+ /// | | Padding | /// | ... | | /// +-----+------------------------------------------------------------------------+ /// </pre> /// </summary> public sealed class IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks : IpV6ExtensionHeaderRouting { private static class RoutingDataOffset { public const int CommonPrefixLengthForNonLastAddresses = 0; public const int CommonPrefixLengthForLastAddress = CommonPrefixLengthForNonLastAddresses; public const int PadSize = CommonPrefixLengthForLastAddress + sizeof(byte); public const int Reserved = PadSize; public const int Addresses = Reserved + UInt24.SizeOf; } private static class RoutingDataMask { public const byte CommonPrefixLengthForNonLastAddresses = 0xF0; public const byte CommonPrefixLengthForLastAddress = 0x0F; public const byte PadSize = 0xF0; } private static class RoutingDataShift { public const int CommonPrefixLengthForNonLastAddresses = 4; public const int PadSize = 4; } /// <summary> /// The minimum number of bytes the routing data takes. /// </summary> public const int RoutingDataMinimumLength = RoutingDataOffset.Addresses; /// <summary> /// The maximum common prefix length. /// </summary> public const byte MaxCommonPrefixLength = IpV6Address.SizeOf - 1; /// <summary> /// The maximum padding size. /// </summary> public const byte MaxPadSize = IpV6Address.SizeOf - 1; /// <summary> /// Creates an instance from next header, segments left, common prefix length for non last addresses, common prefix length for last address and addresses. /// </summary> /// <param name="nextHeader">Identifies the type of header immediately following this extension header.</param> /// <param name="segmentsLeft"> /// Number of route segments remaining, i.e., number of explicitly listed intermediate nodes still to be visited before reaching the final destination. /// </param> /// <param name="commonPrefixLengthForNonLastAddresses"> /// Number of prefix octets from each segment, except than the last segment, (i.e., segments 1 through n-1) that are elided. /// For example, a header carrying full IPv6 addresses in Addresses[1..n-1] sets this to 0. /// </param> /// <param name="commonPrefixLengthForLastAddress"> /// Number of prefix octets from the last segment (i.e., segment n) that are elided. /// For example, a header carrying a full IPv6 address in Addresses[n] sets this to 0. /// </param> /// <param name="addresses">Routing addresses.</param> public IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks(IpV4Protocol? nextHeader, byte segmentsLeft, byte commonPrefixLengthForNonLastAddresses, byte commonPrefixLengthForLastAddress, params IpV6Address[] addresses) : base(nextHeader, segmentsLeft) { if (addresses == null) throw new ArgumentNullException("addresses"); if (commonPrefixLengthForNonLastAddresses > MaxCommonPrefixLength) { throw new ArgumentOutOfRangeException("commonPrefixLengthForNonLastAddresses", commonPrefixLengthForNonLastAddresses, string.Format(CultureInfo.InvariantCulture, "Maximum value is {0}", MaxCommonPrefixLength)); } CommonPrefixLengthForNonLastAddresses = commonPrefixLengthForNonLastAddresses; if (commonPrefixLengthForLastAddress > MaxCommonPrefixLength) { throw new ArgumentOutOfRangeException("commonPrefixLengthForLastAddress", commonPrefixLengthForLastAddress, string.Format(CultureInfo.InvariantCulture, "Maximum value is {0}", MaxCommonPrefixLength)); } CommonPrefixLengthForLastAddress = commonPrefixLengthForLastAddress; if (addresses.Any()) { if (commonPrefixLengthForNonLastAddresses != 0) { for (int i = 0; i != addresses.Length - 1; ++i) ValidateCommonPrefixForAddress(addresses, i, commonPrefixLengthForNonLastAddresses); } if (commonPrefixLengthForLastAddress != 0) ValidateCommonPrefixForAddress(addresses, addresses.Length - 1, commonPrefixLengthForLastAddress); } Addresses = addresses.AsReadOnly(); PadSize = (byte)((8 - Length % 8) % 8); } private static void ValidateCommonPrefixForAddress(IpV6Address[] addresses, int addressIndex, byte commonPrefixLength) { IpV6Address address = addresses[addressIndex]; if (address.ToValue() >> (8 * (IpV6Address.SizeOf - commonPrefixLength)) != 0) { throw new ArgumentOutOfRangeException("addresses", address, string.Format(CultureInfo.InvariantCulture, "When an address has {0} common bytes, it should start with {0} zero bytes.", commonPrefixLength)); } } /// <summary> /// Identifier of a particular Routing header variant. /// </summary> public override IpV6RoutingType RoutingType { get { return IpV6RoutingType.RoutingProtocolLowPowerAndLossyNetworksSourceRouteHeader; } } /// <summary> /// Number of prefix octets from each segment, except than the last segment, (i.e., segments 1 through n-1) that are elided. /// For example, a header carrying full IPv6 addresses in Addresses[1..n-1] sets this to 0. /// </summary> public byte CommonPrefixLengthForNonLastAddresses { get; private set; } /// <summary> /// Number of prefix octets from the last segment (i.e., segment n) that are elided. /// For example, a header carrying a full IPv6 address in Addresses[n] sets this to 0. /// </summary> public byte CommonPrefixLengthForLastAddress { get; private set; } /// <summary> /// Number of octets that are used for padding after Address[n] at the end of the header. /// </summary> public byte PadSize { get; private set; } /// <summary> /// Routing addresses. /// </summary> public ReadOnlyCollection<IpV6Address> Addresses { get; private set; } internal override int RoutingDataLength { get { return RoutingDataMinimumLength + (Addresses.Any() ? Addresses.Count * IpV6Address.SizeOf - (Addresses.Count - 1) * CommonPrefixLengthForNonLastAddresses - CommonPrefixLengthForLastAddress : 0) + PadSize; } } internal static IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks ParseRoutingData(IpV4Protocol nextHeader, byte segmentsLeft, DataSegment routingData) { if (routingData.Length < RoutingDataMinimumLength) return null; byte commonPrefixLengthForNonLastAddresses = (byte)((routingData[RoutingDataOffset.CommonPrefixLengthForNonLastAddresses] & RoutingDataMask.CommonPrefixLengthForNonLastAddresses) >> RoutingDataShift.CommonPrefixLengthForNonLastAddresses); if (commonPrefixLengthForNonLastAddresses > MaxCommonPrefixLength) return null; byte commonPrefixLengthForLastAddress = (byte)(routingData[RoutingDataOffset.CommonPrefixLengthForLastAddress] & RoutingDataMask.CommonPrefixLengthForLastAddress); if (commonPrefixLengthForLastAddress > MaxCommonPrefixLength) return null; byte padSize = (byte)((routingData[RoutingDataOffset.PadSize] & RoutingDataMask.PadSize) >> RoutingDataShift.PadSize); if (padSize > MaxPadSize) return null; int addressesLength = routingData.Length - RoutingDataOffset.Addresses - padSize; int numAddresses = addressesLength == 0 ? 0 : (addressesLength - (IpV6Address.SizeOf - commonPrefixLengthForLastAddress)) / (IpV6Address.SizeOf - commonPrefixLengthForNonLastAddresses) + 1; if (numAddresses < 0) return null; IpV6Address[] addresses = new IpV6Address[numAddresses]; if (numAddresses > 0) { byte[] addressBytes = new byte[IpV6Address.SizeOf]; for (int i = 0; i < numAddresses - 1; ++i) { DataSegment addressSegment = routingData.Subsegment(RoutingDataOffset.Addresses + i * (IpV6Address.SizeOf - commonPrefixLengthForNonLastAddresses), IpV6Address.SizeOf - commonPrefixLengthForNonLastAddresses); addressSegment.Write(addressBytes, commonPrefixLengthForNonLastAddresses); addresses[i] = addressBytes.ReadIpV6Address(0, Endianity.Big); } addressBytes = new byte[IpV6Address.SizeOf]; DataSegment lastAddressSegment = routingData.Subsegment(RoutingDataOffset.Addresses + (numAddresses - 1) * (IpV6Address.SizeOf - commonPrefixLengthForNonLastAddresses), IpV6Address.SizeOf - commonPrefixLengthForLastAddress); lastAddressSegment.Write(addressBytes, commonPrefixLengthForLastAddress); addresses[numAddresses - 1] = addressBytes.ReadIpV6Address(0, Endianity.Big); } return new IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks(nextHeader, segmentsLeft, commonPrefixLengthForNonLastAddresses, commonPrefixLengthForLastAddress, addresses); } internal override bool EqualsRoutingData(IpV6ExtensionHeaderRouting other) { return EqualsRoutingData(other as IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks); } internal override int GetRoutingDataHashCode() { return Sequence.GetHashCode(BitSequence.Merge(CommonPrefixLengthForNonLastAddresses, CommonPrefixLengthForLastAddress, PadSize), Addresses.SequenceGetHashCode()); } internal override void WriteRoutingData(byte[] buffer, int offset) { buffer.Write(offset + RoutingDataOffset.CommonPrefixLengthForNonLastAddresses, (byte)((CommonPrefixLengthForNonLastAddresses << RoutingDataShift.CommonPrefixLengthForNonLastAddresses) | CommonPrefixLengthForLastAddress)); buffer.Write(offset + RoutingDataOffset.PadSize, (byte)(PadSize << RoutingDataShift.PadSize)); if (Addresses.Any()) { int addressOffset = offset + RoutingDataOffset.Addresses; byte[] addressBytes = new byte[IpV6Address.SizeOf]; for (int i = 0; i != Addresses.Count - 1; ++i) { addressBytes.Write(0, Addresses[i], Endianity.Big); addressBytes.Subsegment(CommonPrefixLengthForNonLastAddresses, IpV6Address.SizeOf - CommonPrefixLengthForNonLastAddresses).Write(buffer, ref addressOffset); } addressBytes.Write(0, Addresses[Addresses.Count - 1], Endianity.Big); addressBytes.Subsegment(CommonPrefixLengthForLastAddress, IpV6Address.SizeOf - CommonPrefixLengthForLastAddress).Write(buffer, ref addressOffset); } } private bool EqualsRoutingData(IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks other) { return other != null && CommonPrefixLengthForNonLastAddresses == other.CommonPrefixLengthForNonLastAddresses && CommonPrefixLengthForLastAddress == other.CommonPrefixLengthForLastAddress && PadSize == other.PadSize && Addresses.SequenceEqual(other.Addresses); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: conformance.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 Conformance { /// <summary>Holder for reflection information generated from conformance.proto</summary> public static partial class ConformanceReflection { #region Descriptor /// <summary>File descriptor for conformance.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ConformanceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFjb25mb3JtYW5jZS5wcm90bxILY29uZm9ybWFuY2UijQEKEkNvbmZvcm1h", "bmNlUmVxdWVzdBIaChBwcm90b2J1Zl9wYXlsb2FkGAEgASgMSAASFgoManNv", "bl9wYXlsb2FkGAIgASgJSAASOAoXcmVxdWVzdGVkX291dHB1dF9mb3JtYXQY", "AyABKA4yFy5jb25mb3JtYW5jZS5XaXJlRm9ybWF0QgkKB3BheWxvYWQisQEK", "E0NvbmZvcm1hbmNlUmVzcG9uc2USFQoLcGFyc2VfZXJyb3IYASABKAlIABIZ", "Cg9zZXJpYWxpemVfZXJyb3IYBiABKAlIABIXCg1ydW50aW1lX2Vycm9yGAIg", "ASgJSAASGgoQcHJvdG9idWZfcGF5bG9hZBgDIAEoDEgAEhYKDGpzb25fcGF5", "bG9hZBgEIAEoCUgAEhEKB3NraXBwZWQYBSABKAlIAEIICgZyZXN1bHQqNQoK", "V2lyZUZvcm1hdBIPCgtVTlNQRUNJRklFRBAAEgwKCFBST1RPQlVGEAESCAoE", "SlNPThACQiEKH2NvbS5nb29nbGUucHJvdG9idWYuY29uZm9ybWFuY2ViBnBy", "b3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Conformance.WireFormat), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceRequest), global::Conformance.ConformanceRequest.Parser, new[]{ "ProtobufPayload", "JsonPayload", "RequestedOutputFormat" }, new[]{ "Payload" }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceResponse), global::Conformance.ConformanceResponse.Parser, new[]{ "ParseError", "SerializeError", "RuntimeError", "ProtobufPayload", "JsonPayload", "Skipped" }, new[]{ "Result" }, null, null) })); } #endregion } #region Enums public enum WireFormat { [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, [pbr::OriginalName("PROTOBUF")] Protobuf = 1, [pbr::OriginalName("JSON")] Json = 2, } #endregion #region Messages /// <summary> /// Represents a single test case's input. The testee should: /// /// 1. parse this proto (which should always succeed) /// 2. parse the protobuf or JSON payload in "payload" (which may fail) /// 3. if the parse succeeded, serialize the message in the requested format. /// </summary> public sealed partial class ConformanceRequest : pb::IMessage<ConformanceRequest> { private static readonly pb::MessageParser<ConformanceRequest> _parser = new pb::MessageParser<ConformanceRequest>(() => new ConformanceRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConformanceRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Conformance.ConformanceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceRequest(ConformanceRequest other) : this() { requestedOutputFormat_ = other.requestedOutputFormat_; switch (other.PayloadCase) { case PayloadOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case PayloadOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceRequest Clone() { return new ConformanceRequest(this); } /// <summary>Field number for the "protobuf_payload" field.</summary> public const int ProtobufPayloadFieldNumber = 1; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString ProtobufPayload { get { return payloadCase_ == PayloadOneofCase.ProtobufPayload ? (pb::ByteString) payload_ : pb::ByteString.Empty; } set { payload_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); payloadCase_ = PayloadOneofCase.ProtobufPayload; } } /// <summary>Field number for the "json_payload" field.</summary> public const int JsonPayloadFieldNumber = 2; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JsonPayload { get { return payloadCase_ == PayloadOneofCase.JsonPayload ? (string) payload_ : ""; } set { payload_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); payloadCase_ = PayloadOneofCase.JsonPayload; } } /// <summary>Field number for the "requested_output_format" field.</summary> public const int RequestedOutputFormatFieldNumber = 3; private global::Conformance.WireFormat requestedOutputFormat_ = 0; /// <summary> /// Which format should the testee serialize its message to? /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Conformance.WireFormat RequestedOutputFormat { get { return requestedOutputFormat_; } set { requestedOutputFormat_ = value; } } private object payload_; /// <summary>Enum of possible cases for the "payload" oneof.</summary> public enum PayloadOneofCase { None = 0, ProtobufPayload = 1, JsonPayload = 2, } private PayloadOneofCase payloadCase_ = PayloadOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PayloadOneofCase PayloadCase { get { return payloadCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearPayload() { payloadCase_ = PayloadOneofCase.None; payload_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConformanceRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConformanceRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ProtobufPayload != other.ProtobufPayload) return false; if (JsonPayload != other.JsonPayload) return false; if (RequestedOutputFormat != other.RequestedOutputFormat) return false; if (PayloadCase != other.PayloadCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (payloadCase_ == PayloadOneofCase.ProtobufPayload) hash ^= ProtobufPayload.GetHashCode(); if (payloadCase_ == PayloadOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode(); if (RequestedOutputFormat != 0) hash ^= RequestedOutputFormat.GetHashCode(); hash ^= (int) payloadCase_; 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 (payloadCase_ == PayloadOneofCase.ProtobufPayload) { output.WriteRawTag(10); output.WriteBytes(ProtobufPayload); } if (payloadCase_ == PayloadOneofCase.JsonPayload) { output.WriteRawTag(18); output.WriteString(JsonPayload); } if (RequestedOutputFormat != 0) { output.WriteRawTag(24); output.WriteEnum((int) RequestedOutputFormat); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (payloadCase_ == PayloadOneofCase.ProtobufPayload) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(ProtobufPayload); } if (payloadCase_ == PayloadOneofCase.JsonPayload) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonPayload); } if (RequestedOutputFormat != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) RequestedOutputFormat); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConformanceRequest other) { if (other == null) { return; } if (other.RequestedOutputFormat != 0) { RequestedOutputFormat = other.RequestedOutputFormat; } switch (other.PayloadCase) { case PayloadOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case PayloadOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; } } [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: { ProtobufPayload = input.ReadBytes(); break; } case 18: { JsonPayload = input.ReadString(); break; } case 24: { requestedOutputFormat_ = (global::Conformance.WireFormat) input.ReadEnum(); break; } } } } } /// <summary> /// Represents a single test case's output. /// </summary> public sealed partial class ConformanceResponse : pb::IMessage<ConformanceResponse> { private static readonly pb::MessageParser<ConformanceResponse> _parser = new pb::MessageParser<ConformanceResponse>(() => new ConformanceResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConformanceResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Conformance.ConformanceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceResponse(ConformanceResponse other) : this() { switch (other.ResultCase) { case ResultOneofCase.ParseError: ParseError = other.ParseError; break; case ResultOneofCase.SerializeError: SerializeError = other.SerializeError; break; case ResultOneofCase.RuntimeError: RuntimeError = other.RuntimeError; break; case ResultOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case ResultOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; case ResultOneofCase.Skipped: Skipped = other.Skipped; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceResponse Clone() { return new ConformanceResponse(this); } /// <summary>Field number for the "parse_error" field.</summary> public const int ParseErrorFieldNumber = 1; /// <summary> /// This string should be set to indicate parsing failed. The string can /// provide more information about the parse error if it is available. /// /// Setting this string does not necessarily mean the testee failed the /// test. Some of the test cases are intentionally invalid input. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ParseError { get { return resultCase_ == ResultOneofCase.ParseError ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.ParseError; } } /// <summary>Field number for the "serialize_error" field.</summary> public const int SerializeErrorFieldNumber = 6; /// <summary> /// If the input was successfully parsed but errors occurred when /// serializing it to the requested output format, set the error message in /// this field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SerializeError { get { return resultCase_ == ResultOneofCase.SerializeError ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.SerializeError; } } /// <summary>Field number for the "runtime_error" field.</summary> public const int RuntimeErrorFieldNumber = 2; /// <summary> /// This should be set if some other error occurred. This will always /// indicate that the test failed. The string can provide more information /// about the failure. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string RuntimeError { get { return resultCase_ == ResultOneofCase.RuntimeError ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.RuntimeError; } } /// <summary>Field number for the "protobuf_payload" field.</summary> public const int ProtobufPayloadFieldNumber = 3; /// <summary> /// If the input was successfully parsed and the requested output was /// protobuf, serialize it to protobuf and set it in this field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString ProtobufPayload { get { return resultCase_ == ResultOneofCase.ProtobufPayload ? (pb::ByteString) result_ : pb::ByteString.Empty; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.ProtobufPayload; } } /// <summary>Field number for the "json_payload" field.</summary> public const int JsonPayloadFieldNumber = 4; /// <summary> /// If the input was successfully parsed and the requested output was JSON, /// serialize to JSON and set it in this field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JsonPayload { get { return resultCase_ == ResultOneofCase.JsonPayload ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.JsonPayload; } } /// <summary>Field number for the "skipped" field.</summary> public const int SkippedFieldNumber = 5; /// <summary> /// For when the testee skipped the test, likely because a certain feature /// wasn't supported, like JSON input/output. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Skipped { get { return resultCase_ == ResultOneofCase.Skipped ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.Skipped; } } private object result_; /// <summary>Enum of possible cases for the "result" oneof.</summary> public enum ResultOneofCase { None = 0, ParseError = 1, SerializeError = 6, RuntimeError = 2, ProtobufPayload = 3, JsonPayload = 4, Skipped = 5, } private ResultOneofCase resultCase_ = ResultOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ResultOneofCase ResultCase { get { return resultCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearResult() { resultCase_ = ResultOneofCase.None; result_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConformanceResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConformanceResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ParseError != other.ParseError) return false; if (SerializeError != other.SerializeError) return false; if (RuntimeError != other.RuntimeError) return false; if (ProtobufPayload != other.ProtobufPayload) return false; if (JsonPayload != other.JsonPayload) return false; if (Skipped != other.Skipped) return false; if (ResultCase != other.ResultCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (resultCase_ == ResultOneofCase.ParseError) hash ^= ParseError.GetHashCode(); if (resultCase_ == ResultOneofCase.SerializeError) hash ^= SerializeError.GetHashCode(); if (resultCase_ == ResultOneofCase.RuntimeError) hash ^= RuntimeError.GetHashCode(); if (resultCase_ == ResultOneofCase.ProtobufPayload) hash ^= ProtobufPayload.GetHashCode(); if (resultCase_ == ResultOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode(); if (resultCase_ == ResultOneofCase.Skipped) hash ^= Skipped.GetHashCode(); hash ^= (int) resultCase_; 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 (resultCase_ == ResultOneofCase.ParseError) { output.WriteRawTag(10); output.WriteString(ParseError); } if (resultCase_ == ResultOneofCase.RuntimeError) { output.WriteRawTag(18); output.WriteString(RuntimeError); } if (resultCase_ == ResultOneofCase.ProtobufPayload) { output.WriteRawTag(26); output.WriteBytes(ProtobufPayload); } if (resultCase_ == ResultOneofCase.JsonPayload) { output.WriteRawTag(34); output.WriteString(JsonPayload); } if (resultCase_ == ResultOneofCase.Skipped) { output.WriteRawTag(42); output.WriteString(Skipped); } if (resultCase_ == ResultOneofCase.SerializeError) { output.WriteRawTag(50); output.WriteString(SerializeError); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (resultCase_ == ResultOneofCase.ParseError) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ParseError); } if (resultCase_ == ResultOneofCase.SerializeError) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SerializeError); } if (resultCase_ == ResultOneofCase.RuntimeError) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RuntimeError); } if (resultCase_ == ResultOneofCase.ProtobufPayload) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(ProtobufPayload); } if (resultCase_ == ResultOneofCase.JsonPayload) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonPayload); } if (resultCase_ == ResultOneofCase.Skipped) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Skipped); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConformanceResponse other) { if (other == null) { return; } switch (other.ResultCase) { case ResultOneofCase.ParseError: ParseError = other.ParseError; break; case ResultOneofCase.SerializeError: SerializeError = other.SerializeError; break; case ResultOneofCase.RuntimeError: RuntimeError = other.RuntimeError; break; case ResultOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case ResultOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; case ResultOneofCase.Skipped: Skipped = other.Skipped; break; } } [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: { ParseError = input.ReadString(); break; } case 18: { RuntimeError = input.ReadString(); break; } case 26: { ProtobufPayload = input.ReadBytes(); break; } case 34: { JsonPayload = input.ReadString(); break; } case 42: { Skipped = input.ReadString(); break; } case 50: { SerializeError = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.IO; using Fake; using Machine.Specifications; using Microsoft.FSharp.Core; namespace Test.FAKECore { public class when_accessing_internals { It should_have_access_to_FAKE_internals = () => AssemblyInfoFile.getDependencies(new List<AssemblyInfoFile.Attribute>()); } public class when_using_fsharp_task_with_default_config { It should_use_system_namespace_and_emit_a_version_module = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateFSharpAssemblyInfo(infoFile, attributes); const string expected = "namespace System\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\nmodule internal AssemblyVersionInformation =\r\n let [<Literal>] Version = \"1.0.0.0\"\r\n let [<Literal>] InformationalVersion = \"1.0.0.0\"\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_fs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".fs"); const string original = "namespace System\r\nopen System.Reflection\r\n\r\n" + "[<assembly: AssemblyProduct(\"TestLib\")>]\r\n" + "[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "namespace System\r\nopen System.Reflection\r\n\r\n" + "[<assembly: AssemblyProduct(\"TestLibNew\")>]\r\n" + "[<assembly: AssemblyVersionAttribute(\"2.0.0.0\")>]\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_fs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".fs"); const string original = "namespace System\r\nopen System.Reflection\r\n\r\n" + "[<assembly: AssemblyProduct(\"TestLib\")>]\r\n" + "[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; // Assert productAttr.Value.ShouldEqual("\"TestLib\""); versionAttr.Value.ShouldEqual("\"1.0.0.0\""); }; } public class when_using_fsharp_task_with_custom_config { It should_use_custom_namespace_and_not_emit_a_version_module = () => { var customConfig = new AssemblyInfoFile.AssemblyInfoFileConfig(false, new FSharpOption<string>("Custom")); string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateFSharpAssemblyInfoWithConfig(infoFile, attributes, customConfig); const string expected = "namespace Custom\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; } public class when_using_csharp_task_with_default_config { It should_use_system_namespace_and_emit_a_version_module = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateCSharpAssemblyInfo(infoFile, attributes); const string expected = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n[assembly: AssemblyProductAttribute(\"TestLib\")]\r\n[assembly: AssemblyVersionAttribute(\"1.0.0.0\")]\r\nnamespace System {\r\n internal static class AssemblyVersionInformation {\r\n internal const string Version = \"1.0.0.0\";\r\n internal const string InformationalVersion = \"1.0.0.0\";\r\n }\r\n}\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_cs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cs"); const string original = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n" + "[assembly: AssemblyProduct(\"TestLib\")]\r\n" + "[assembly: AssemblyVersionAttribute(\"1.0.0.0\")]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n" + "[assembly: AssemblyProduct(\"TestLibNew\")]\r\n" + "[assembly: AssemblyVersionAttribute(\"2.0.0.0\")]\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_cs_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cs"); const string original = "// <auto-generated/>\r\nusing System.Reflection;\r\n\r\n" + "[assembly: AssemblyProduct(\"TestLib\")]\r\n" + "[assembly: AssemblyVersionAttribute(\"1.0.0.0\")]\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; // Assert productAttr.Value.ShouldEqual("\"TestLib\""); versionAttr.Value.ShouldEqual("\"1.0.0.0\""); }; } public class when_using_cppcli_task_with_default_config { It should_emit_valid_syntax = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateCppCliAssemblyInfo(infoFile, attributes); const string expected = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n[assembly:AssemblyProductAttribute(\"TestLib\")];\r\n[assembly:AssemblyVersionAttribute(\"1.0.0.0\")];\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_cpp_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cpp"); const string original = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n" + "[assembly:AssemblyProduct(\"TestLib\")];\r\n" + "[assembly:AssemblyVersionAttribute(\"1.0.0.0\")];\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n" + "[assembly:AssemblyProduct(\"TestLibNew\")];\r\n" + "[assembly:AssemblyVersionAttribute(\"2.0.0.0\")];\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_cpp_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".cpp"); const string original = "// <auto-generated/>\r\nusing namespace System::Reflection;\r\n\r\n" + "[assembly:AssemblyProduct(\"TestLib\")];\r\n" + "[assembly:AssemblyVersionAttribute(\"1.0.0.0\")];\r\n"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; // Assert productAttr.Value.ShouldEqual("\"TestLib\""); versionAttr.Value.ShouldEqual("\"1.0.0.0\""); }; } public class when_using_vb_task_with_default_config { It should_emit_valid_syntax = () => { string infoFile = Path.GetTempFileName(); var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLib"), AssemblyInfoFile.Attribute.Version("1.0.0.0") }; AssemblyInfoFile.CreateVisualBasicAssemblyInfo(infoFile, attributes); const string expected = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n<assembly: AssemblyProductAttribute(\"TestLib\")>\r\n<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>\r\nFriend NotInheritable Class AssemblyVersionInformation\r\n Friend Const Version As String = \"1.0.0.0\"\r\n Friend Const InformationalVersion As String = \"1.0.0.0\"\r\nEnd Class\r\n"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It update_attributes_should_update_attributes_in_vb_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".vb"); const string original = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n" + "<assembly: AssemblyProduct(\"TestLib\")>\r\n" + "<Assembly: AssemblyCompany(\"TestCompany\")>\r\n" + "<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>\r\n" + "<Assembly: ComVisibleAttribute(false)>"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var attributes = new[] { AssemblyInfoFile.Attribute.Product("TestLibNew"), AssemblyInfoFile.Attribute.Company("TestCompanyNew"), AssemblyInfoFile.Attribute.Version("2.0.0.0") }; AssemblyInfoFile.UpdateAttributes(infoFile, attributes); // Assert const string expected = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n" + "<assembly: AssemblyProduct(\"TestLibNew\")>\r\n" + "<Assembly: AssemblyCompany(\"TestCompanyNew\")>\r\n" + "<assembly: AssemblyVersionAttribute(\"2.0.0.0\")>\r\n" + "<Assembly: ComVisibleAttribute(false)>"; File.ReadAllText(infoFile) .ShouldEqual(expected.Replace("\r\n", Environment.NewLine)); }; It get_attribute_should_read_attribute_from_vb_file = () => { // Arrange. Create attribute both with and without "Attribute" at the end, and also // case-insensitive attributes string infoFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".vb"); const string original = "' <auto-generated/>\r\nImports System.Reflection\r\n\r\n" + "<assembly: AssemblyProduct(\"TestLib\")>\r\n" + "<Assembly: AssemblyCompany(\"TestCompany\")>\r\n" + "<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>\r\n" + "<Assembly: ComVisibleAttribute(false)>"; File.WriteAllText(infoFile, original.Replace("\r\n", Environment.NewLine)); // Act var productAttr = AssemblyInfoFile.GetAttribute("AssemblyProduct", infoFile).Value; var companyAttr = AssemblyInfoFile.GetAttribute("AssemblyCompany", infoFile).Value; var versionAttr = AssemblyInfoFile.GetAttribute("AssemblyVersion", infoFile).Value; var comVisibleAttr = AssemblyInfoFile.GetAttribute("ComVisible", infoFile).Value; // Assert productAttr.Value.ShouldEqual("\"TestLib\""); companyAttr.Value.ShouldEqual("\"TestCompany\""); versionAttr.Value.ShouldEqual("\"1.0.0.0\""); comVisibleAttr.Value.ShouldEqual("false"); }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Threading; using Windows.Foundation; using Windows.Storage.Streams; namespace System.IO { #region class StreamOperationAsyncResult internal abstract partial class StreamOperationAsyncResult : IAsyncResult { private AsyncCallback _userCompletionCallback = null; private Object _userAsyncStateInfo = null; private IAsyncInfo _asyncStreamOperation = null; private volatile bool _completed = false; private volatile bool _callbackInvoked = false; private volatile ManualResetEvent _waitHandle = null; private Int64 _bytesCompleted = 0; private ExceptionDispatchInfo _errorInfo = null; private readonly bool _processCompletedOperationInCallback; private IAsyncInfo _completedOperation = null; protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation, AsyncCallback userCompletionCallback, Object userAsyncStateInfo, bool processCompletedOperationInCallback) { if (asyncStreamOperation == null) throw new ArgumentNullException("asyncReadOperation"); _userCompletionCallback = userCompletionCallback; _userAsyncStateInfo = userAsyncStateInfo; _asyncStreamOperation = asyncStreamOperation; _completed = false; _callbackInvoked = false; _bytesCompleted = 0; _errorInfo = null; _processCompletedOperationInCallback = processCompletedOperationInCallback; } public object AsyncState { get { return _userAsyncStateInfo; } } internal bool ProcessCompletedOperationInCallback { get { return _processCompletedOperationInCallback; } } #pragma warning disable 420 // "a reference to a volatile field will not be treated as volatile" public WaitHandle AsyncWaitHandle { get { ManualResetEvent wh = _waitHandle; if (wh != null) return wh; // What if someone calls this public property and decides to wait on it? // > Use 'completed' in the ctor - this way the handle wait will return as appropriate. wh = new ManualResetEvent(_completed); ManualResetEvent otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null); // We lost the race. Dispose OUR handle and return OTHER handle: if (otherHandle != null) { wh.Dispose(); return otherHandle; } // We won the race. Return OUR new handle: return wh; } } #pragma warning restore 420 // "a reference to a volatile field will not be treated as volatile" public bool CompletedSynchronously { get { return false; } } public bool IsCompleted { get { return _completed; } } internal void Wait() { if (_completed) return; WaitHandle wh = AsyncWaitHandle; while (_completed == false) wh.WaitOne(); } internal Int64 BytesCompleted { get { return _bytesCompleted; } } internal bool HasError { get { return _errorInfo != null; } } internal void ThrowCachedError() { if (_errorInfo == null) return; _errorInfo.Throw(); } internal bool CancelStreamOperation() { if (_callbackInvoked) return false; _asyncStreamOperation.Cancel(); return true; } internal void CloseStreamOperation() { try { if (_asyncStreamOperation != null) _asyncStreamOperation.Close(); } catch { } _asyncStreamOperation = null; } ~StreamOperationAsyncResult() { // This finalisation is not critical, but we can still make an effort to notify the underlying WinRT stream // that we are not any longer interested in the results: CancelStreamOperation(); } internal abstract void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted); private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo errInfo, String errMsg) { Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException; if (errInfoSrc == null) throw new InvalidOperationException(errMsg); else throw new InvalidOperationException(errMsg, errInfoSrc); } internal void ProcessCompletedOperation() { // The error handling is slightly tricky here: // Before processing the IO results, we are verifying some basic assumptions and if they do not hold, we are // throwing InvalidOperation. However, by the time this method is called, we might have already stored something // into errorInfo, e.g. if an error occurred in StreamOperationCompletedCallback. If that is the case, then that // previous exception might include some important info relevant for detecting the problem. So, we take that // previous exception and attach it as the inner exception to the InvalidOperationException being thrown. // In cases where we have a good understanding of the previously saved errorInfo, and we know for sure that it // the immediate reason for the state validation to fail, we can avoid throwing InvalidOperation altogether // and only rethrow the errorInfo. if (!_callbackInvoked) ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState); if (!_processCompletedOperationInCallback && !_completed) ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState); if (_completedOperation == null) { ExceptionDispatchInfo errInfo = _errorInfo; Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException; // See if errorInfo is set because we observed completedOperation == null previously (being slow is Ok on error path): if (errInfoSrc != null && errInfoSrc is NullReferenceException && SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo.Equals(errInfoSrc.Message)) { errInfo.Throw(); } else { throw new InvalidOperationException(SR.InvalidOperation_CannotCallThisMethodInCurrentState); } } if (_completedOperation.Id != _asyncStreamOperation.Id) ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_UnexpectedAsyncOperationID); if (_completedOperation.Status == AsyncStatus.Error) { _bytesCompleted = 0; ThrowWithIOExceptionDispatchInfo(_completedOperation.ErrorCode); } ProcessConcreteCompletedOperation(_completedOperation, out _bytesCompleted); } internal void StreamOperationCompletedCallback(IAsyncInfo completedOperation, AsyncStatus unusedCompletionStatus) { try { if (_callbackInvoked) throw new InvalidOperationException(SR.InvalidOperation_MultipleIOCompletionCallbackInvocation); _callbackInvoked = true; // This happens in rare stress cases in Console mode and the WinRT folks said they are unlikely to fix this in Dev11. // Moreover, this can happen if the underlying WinRT stream has a faulty user implementation. // If we did not do this check, we would either get the same exception without the explaining message when dereferencing // completedOperation later, or we will get an InvalidOperation when processing the Op. With the check, they will be // aggregated and the user will know what went wrong. if (completedOperation == null) throw new NullReferenceException(SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo); _completedOperation = completedOperation; // processCompletedOperationInCallback == false indicates that the stream is doing a blocking wait on the waitHandle of this IAsyncResult. // In that case calls on completedOperation may deadlock if completedOperation is not free threaded. // By setting processCompletedOperationInCallback to false the stream that created this IAsyncResult indicated that it // will call ProcessCompletedOperation after the waitHandle is signalled to fetch the results. if (_processCompletedOperationInCallback) ProcessCompletedOperation(); } catch (Exception ex) { _bytesCompleted = 0; _errorInfo = ExceptionDispatchInfo.Capture(ex); } finally { _completed = true; Interlocked.MemoryBarrier(); // From this point on, AsyncWaitHandle would create a handle that is readily set, // so we do not need to check if it is being produced asynchronously. if (_waitHandle != null) _waitHandle.Set(); } if (_userCompletionCallback != null) _userCompletionCallback(this); } } // class StreamOperationAsyncResult #endregion class StreamOperationAsyncResult #region class StreamReadAsyncResult internal class StreamReadAsyncResult : StreamOperationAsyncResult { private IBuffer _userBuffer = null; internal StreamReadAsyncResult(IAsyncOperationWithProgress<IBuffer, UInt32> asyncStreamReadOperation, IBuffer buffer, AsyncCallback userCompletionCallback, Object userAsyncStateInfo, bool processCompletedOperationInCallback) : base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback) { if (buffer == null) throw new ArgumentNullException("buffer"); _userBuffer = buffer; asyncStreamReadOperation.Completed = this.StreamOperationCompletedCallback; } internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted) { ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<IBuffer, UInt32>)completedOperation, out bytesCompleted); } private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<IBuffer, UInt32> completedOperation, out Int64 bytesCompleted) { IBuffer resultBuffer = completedOperation.GetResults(); Debug.Assert(resultBuffer != null); WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer); bytesCompleted = _userBuffer.Length; } } // class StreamReadAsyncResult #endregion class StreamReadAsyncResult #region class StreamWriteAsyncResult internal class StreamWriteAsyncResult : StreamOperationAsyncResult { internal StreamWriteAsyncResult(IAsyncOperationWithProgress<UInt32, UInt32> asyncStreamWriteOperation, AsyncCallback userCompletionCallback, Object userAsyncStateInfo, bool processCompletedOperationInCallback) : base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback) { asyncStreamWriteOperation.Completed = this.StreamOperationCompletedCallback; } internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted) { ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<UInt32, UInt32>)completedOperation, out bytesCompleted); } private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<UInt32, UInt32> completedOperation, out Int64 bytesCompleted) { UInt32 bytesWritten = completedOperation.GetResults(); bytesCompleted = bytesWritten; } } // class StreamWriteAsyncResult #endregion class StreamWriteAsyncResult #region class StreamFlushAsyncResult internal class StreamFlushAsyncResult : StreamOperationAsyncResult { internal StreamFlushAsyncResult(IAsyncOperation<Boolean> asyncStreamFlushOperation, bool processCompletedOperationInCallback) : base(asyncStreamFlushOperation, null, null, processCompletedOperationInCallback) { asyncStreamFlushOperation.Completed = this.StreamOperationCompletedCallback; } internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted) { ProcessConcreteCompletedOperation((IAsyncOperation<Boolean>)completedOperation, out bytesCompleted); } private void ProcessConcreteCompletedOperation(IAsyncOperation<Boolean> completedOperation, out Int64 bytesCompleted) { Boolean success = completedOperation.GetResults(); bytesCompleted = (success ? 0 : -1); } } // class StreamFlushAsyncResult #endregion class StreamFlushAsyncResult } // namespace // StreamOperationAsyncResult.cs
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Net; using System.Web; using ServiceStack.Common; using ServiceStack.MiniProfiler.UI; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Extensions; using ServiceStack.WebHost.Endpoints.Support; using HttpRequestWrapper = ServiceStack.WebHost.Endpoints.Extensions.HttpRequestWrapper; namespace ServiceStack.WebHost.Endpoints { public class ServiceStackHttpHandlerFactory : IHttpHandlerFactory { static readonly List<string> WebHostRootFileNames = new List<string>(); static private readonly string WebHostPhysicalPath = null; static private readonly string DefaultRootFileName = null; static private string ApplicationBaseUrl = null; static private readonly IHttpHandler DefaultHttpHandler = null; static private readonly RedirectHttpHandler NonRootModeDefaultHttpHandler = null; static private readonly IHttpHandler ForbiddenHttpHandler = null; static private readonly IHttpHandler NotFoundHttpHandler = null; static private readonly IHttpHandler StaticFileHandler = new StaticFileHandler(); private static readonly bool IsIntegratedPipeline = false; private static readonly bool ServeDefaultHandler = false; private static readonly bool AutoRedirectsDirs = false; private static Func<IHttpRequest, IHttpHandler>[] RawHttpHandlers; [ThreadStatic] public static string DebugLastHandlerArgs; static ServiceStackHttpHandlerFactory() { //MONO doesn't implement this property var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline"); if (pi != null) { IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, new object[0]); } var config = EndpointHost.Config; if (config == null) { throw new ConfigurationErrorsException( "ServiceStack: AppHost does not exist or has not been initialized. " + "Make sure you have created an AppHost and started it with 'new AppHost().Init();' in your Global.asax Application_Start()", new ArgumentNullException("EndpointHost.Config")); } var isAspNetHost = HttpListenerBase.Instance == null || HttpContext.Current != null; WebHostPhysicalPath = config.WebHostPhysicalPath; AutoRedirectsDirs = isAspNetHost && !Env.IsMono; //Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources var hostedAtRootPath = config.ServiceStackHandlerFactoryPath == null; //DefaultHttpHandler not supported in IntegratedPipeline mode if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono) DefaultHttpHandler = new DefaultHttpHandler(); ServeDefaultHandler = hostedAtRootPath || Env.IsMono; if (ServeDefaultHandler) { foreach (var filePath in Directory.GetFiles(WebHostPhysicalPath)) { var fileNameLower = Path.GetFileName(filePath).ToLower(); if (DefaultRootFileName == null && config.DefaultDocuments.Contains(fileNameLower)) { //Can't serve Default.aspx pages when hostedAtRootPath so ignore and allow for next default document if (!(hostedAtRootPath && fileNameLower.EndsWith(".aspx"))) { DefaultRootFileName = fileNameLower; ((StaticFileHandler)StaticFileHandler).SetDefaultFile(filePath); if (DefaultHttpHandler == null) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = DefaultRootFileName }; } } WebHostRootFileNames.Add(Path.GetFileName(fileNameLower)); } foreach (var dirName in Directory.GetDirectories(WebHostPhysicalPath)) { var dirNameLower = Path.GetFileName(dirName).ToLower(); WebHostRootFileNames.Add(Path.GetFileName(dirNameLower)); } } if (!string.IsNullOrEmpty(config.DefaultRedirectPath)) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.DefaultRedirectPath }; if (DefaultHttpHandler == null && !string.IsNullOrEmpty(config.MetadataRedirectPath)) DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath }; if (!string.IsNullOrEmpty(config.MetadataRedirectPath)) NonRootModeDefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath }; if (DefaultHttpHandler == null) DefaultHttpHandler = NotFoundHttpHandler; var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler; var debugDefaultHandler = defaultRedirectHanlder != null ? defaultRedirectHanlder.RelativeUrl : typeof(DefaultHttpHandler).Name; SetApplicationBaseUrl(config.WebHostUrl); ForbiddenHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden); if (ForbiddenHttpHandler == null) { ForbiddenHttpHandler = new ForbiddenHttpHandler { IsIntegratedPipeline = IsIntegratedPipeline, WebHostPhysicalPath = WebHostPhysicalPath, WebHostRootFileNames = WebHostRootFileNames, ApplicationBaseUrl = ApplicationBaseUrl, DefaultRootFileName = DefaultRootFileName, DefaultHandler = debugDefaultHandler, }; } NotFoundHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.NotFound); if (NotFoundHttpHandler == null) { NotFoundHttpHandler = new NotFoundHttpHandler { IsIntegratedPipeline = IsIntegratedPipeline, WebHostPhysicalPath = WebHostPhysicalPath, WebHostRootFileNames = WebHostRootFileNames, ApplicationBaseUrl = ApplicationBaseUrl, DefaultRootFileName = DefaultRootFileName, DefaultHandler = debugDefaultHandler, }; } var rawHandlers = config.RawHttpHandlers; rawHandlers.Add(ReturnRequestInfo); rawHandlers.Add(MiniProfilerHandler.MatchesRequest); RawHttpHandlers = rawHandlers.ToArray(); } // Entry point for ASP.NET public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated; var httpReq = new HttpRequestWrapper(pathTranslated, context.Request); foreach (var rawHttpHandler in RawHttpHandlers) { var reqInfo = rawHttpHandler(httpReq); if (reqInfo != null) return reqInfo; } var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath; var pathInfo = context.Request.GetPathInfo(); //WebDev Server auto requests '/default.aspx' so recorrect path to different default document if (mode == null && (url == "/default.aspx" || url == "/Default.aspx")) pathInfo = "/"; //Default Request / if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { //Exception calling context.Request.Url on Apache+mod_mono if (ApplicationBaseUrl == null) { var absoluteUrl = Env.IsMono ? url.ToParentPath() : context.Request.GetApplicationUrl(); SetApplicationBaseUrl(absoluteUrl); } //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath()); if (catchAllHandler != null) return catchAllHandler; return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler; } if (mode != null && pathInfo.EndsWith("/" + mode)) { return ReturnDefaultHandler(httpReq); } return GetHandlerForPathInfo( httpReq.HttpMethod, pathInfo, context.Request.FilePath, pathTranslated) ?? NotFoundHttpHandler; } private static void SetApplicationBaseUrl(string absoluteUrl) { if (absoluteUrl == null) return; ApplicationBaseUrl = absoluteUrl; var defaultRedirectUrl = DefaultHttpHandler as RedirectHttpHandler; if (defaultRedirectUrl != null && defaultRedirectUrl.AbsoluteUrl == null) defaultRedirectUrl.AbsoluteUrl = ApplicationBaseUrl.CombineWith( defaultRedirectUrl.RelativeUrl); if (NonRootModeDefaultHttpHandler != null && NonRootModeDefaultHttpHandler.AbsoluteUrl == null) NonRootModeDefaultHttpHandler.AbsoluteUrl = ApplicationBaseUrl.CombineWith( NonRootModeDefaultHttpHandler.RelativeUrl); } public static string GetBaseUrl() { return EndpointHost.Config.WebHostUrl ?? ApplicationBaseUrl; } // Entry point for HttpListener public static IHttpHandler GetHandler(IHttpRequest httpReq) { foreach (var rawHttpHandler in RawHttpHandlers) { var reqInfo = rawHttpHandler(httpReq); if (reqInfo != null) return reqInfo; } var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath; var pathInfo = httpReq.PathInfo; //Default Request / if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { if (ApplicationBaseUrl == null) SetApplicationBaseUrl(httpReq.GetPathUrl()); //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath()); if (catchAllHandler != null) return catchAllHandler; return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler; } if (mode != null && pathInfo.EndsWith(mode)) { var requestPath = pathInfo; if (requestPath == "/" + mode || requestPath == mode || requestPath == mode + "/") { //TODO: write test for this if (httpReq.GetPhysicalPath() != WebHostPhysicalPath || !File.Exists(Path.Combine(httpReq.ApplicationFilePath, DefaultRootFileName ?? ""))) { return new IndexPageHttpHandler(); } } var okToServe = ShouldAllow(httpReq.GetPhysicalPath()); return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler; } return GetHandlerForPathInfo(httpReq.HttpMethod, pathInfo, pathInfo, httpReq.GetPhysicalPath()) ?? NotFoundHttpHandler; } /// <summary> /// If enabled, just returns the Request Info as it understands /// </summary> /// <param name="context"></param> /// <returns></returns> private static IHttpHandler ReturnRequestInfo(HttpRequest httpReq) { if (EndpointHost.Config.DebugOnlyReturnRequestInfo || (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo"))) { var reqInfo = RequestInfoHandler.GetRequestInfo( new HttpRequestWrapper(typeof(RequestInfo).Name, httpReq)); reqInfo.Host = EndpointHost.Config.DebugAspNetHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName; //reqInfo.FactoryUrl = url; //Just RawUrl without QueryString //reqInfo.FactoryPathTranslated = pathTranslated; //Local path on filesystem reqInfo.PathInfo = httpReq.PathInfo; reqInfo.Path = httpReq.Path; reqInfo.ApplicationPath = httpReq.ApplicationPath; return new RequestInfoHandler { RequestInfo = reqInfo }; } return null; } private static IHttpHandler ReturnDefaultHandler(IHttpRequest httpReq) { var pathProvider = EndpointHost.VirtualPathProvider; var defaultDoc = pathProvider.GetFile(DefaultRootFileName ?? ""); if (httpReq.GetPhysicalPath() != WebHostPhysicalPath || defaultDoc == null) { return new IndexPageHttpHandler(); } var okToServe = ShouldAllow(httpReq.GetPhysicalPath()); return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler; } private static IHttpHandler ReturnRequestInfo(IHttpRequest httpReq) { if (EndpointHost.Config.DebugOnlyReturnRequestInfo || (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo"))) { var reqInfo = RequestInfoHandler.GetRequestInfo(httpReq); reqInfo.Host = EndpointHost.Config.DebugHttpListenerHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName; reqInfo.PathInfo = httpReq.PathInfo; reqInfo.Path = httpReq.GetPathUrl(); return new RequestInfoHandler { RequestInfo = reqInfo }; } return null; } // no handler registered // serve the file from the filesystem, restricting to a safelist of extensions private static bool ShouldAllow(string filePath) { var fileExt = Path.GetExtension(filePath); if (string.IsNullOrEmpty(fileExt)) return false; return EndpointHost.Config.AllowFileExtensions.Contains(fileExt.Substring(1)); } public static IHttpHandler GetHandlerForPathInfo(string httpMethod, string pathInfo, string requestPath, string filePath) { var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) return NotFoundHttpHandler; string contentType; var restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType); if (restPath != null) return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType }; var existingFile = pathParts[0].ToLower(); if (WebHostRootFileNames.Contains(existingFile)) { var fileExt = Path.GetExtension(filePath); var isFileRequest = !string.IsNullOrEmpty(fileExt); if (!isFileRequest && !AutoRedirectsDirs) { //If pathInfo is for Directory try again with redirect including '/' suffix if (!pathInfo.EndsWith("/")) { var appFilePath = filePath.Substring(0, filePath.Length - requestPath.Length); var redirect = Support.StaticFileHandler.DirectoryExists(filePath, appFilePath); if (redirect) { return new RedirectHttpHandler { RelativeUrl = pathInfo + "/", }; } } } //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath); if (catchAllHandler != null) return catchAllHandler; if (!isFileRequest) return NotFoundHttpHandler; return ShouldAllow(requestPath) ? StaticFileHandler : ForbiddenHttpHandler; } var handler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath); if (handler != null) return handler; if (EndpointHost.Config.FallbackRestPath != null) { restPath = EndpointHost.Config.FallbackRestPath(httpMethod, pathInfo, filePath); if (restPath != null) { return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType }; } } return null; } private static IHttpHandler GetCatchAllHandlerIfAny(string httpMethod, string pathInfo, string filePath) { if (EndpointHost.CatchAllHandlers != null) { foreach (var httpHandlerResolver in EndpointHost.CatchAllHandlers) { var httpHandler = httpHandlerResolver(httpMethod, pathInfo, filePath); if (httpHandler != null) return httpHandler; } } return null; } public void ReleaseHandler(IHttpHandler handler) { } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; // Include Silverlight's managed resources #if SILVERLIGHT using System.Core; #endif //SILVERLIGHT namespace System.Linq.Expressions { // internal abstract class OldExpressionVisitor { internal OldExpressionVisitor() { } internal virtual Expression Visit(Expression exp) { if (exp == null) return exp; switch (exp.NodeType) { case ExpressionType.UnaryPlus: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: return this.VisitUnary((UnaryExpression)exp); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.Power: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return this.VisitBinary((BinaryExpression)exp); case ExpressionType.TypeIs: return this.VisitTypeIs((TypeBinaryExpression)exp); case ExpressionType.Conditional: return this.VisitConditional((ConditionalExpression)exp); case ExpressionType.Constant: return this.VisitConstant((ConstantExpression)exp); case ExpressionType.Parameter: return this.VisitParameter((ParameterExpression)exp); case ExpressionType.MemberAccess: return this.VisitMemberAccess((MemberExpression)exp); case ExpressionType.Call: return this.VisitMethodCall((MethodCallExpression)exp); case ExpressionType.Lambda: return this.VisitLambda((LambdaExpression)exp); case ExpressionType.New: return this.VisitNew((NewExpression)exp); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return this.VisitNewArray((NewArrayExpression)exp); case ExpressionType.Invoke: return this.VisitInvocation((InvocationExpression)exp); case ExpressionType.MemberInit: return this.VisitMemberInit((MemberInitExpression)exp); case ExpressionType.ListInit: return this.VisitListInit((ListInitExpression)exp); default: throw Error.UnhandledExpressionType(exp.NodeType); } } internal virtual MemberBinding VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return this.VisitMemberAssignment((MemberAssignment)binding); case MemberBindingType.MemberBinding: return this.VisitMemberMemberBinding((MemberMemberBinding)binding); case MemberBindingType.ListBinding: return this.VisitMemberListBinding((MemberListBinding)binding); default: throw Error.UnhandledBindingType(binding.BindingType); } } internal virtual ElementInit VisitElementInitializer(ElementInit initializer) { ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments); if (arguments != initializer.Arguments) { return Expression.ElementInit(initializer.AddMethod, arguments); } return initializer; } internal virtual Expression VisitUnary(UnaryExpression u) { Expression operand = this.Visit(u.Operand); if (operand != u.Operand) { return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); } return u; } internal virtual Expression VisitBinary(BinaryExpression b) { Expression left = this.Visit(b.Left); Expression right = this.Visit(b.Right); Expression conversion = this.Visit(b.Conversion); if (left != b.Left || right != b.Right || conversion != b.Conversion) { if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) return Expression.Coalesce(left, right, conversion as LambdaExpression); else return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } return b; } internal virtual Expression VisitTypeIs(TypeBinaryExpression b) { Expression expr = this.Visit(b.Expression); if (expr != b.Expression) { return Expression.TypeIs(expr, b.TypeOperand); } return b; } internal virtual Expression VisitConstant(ConstantExpression c) { return c; } internal virtual Expression VisitConditional(ConditionalExpression c) { Expression test = this.Visit(c.Test); Expression ifTrue = this.Visit(c.IfTrue); Expression ifFalse = this.Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; } internal virtual Expression VisitParameter(ParameterExpression p) { return p; } internal virtual Expression VisitMemberAccess(MemberExpression m) { Expression exp = this.Visit(m.Expression); if (exp != m.Expression) { return Expression.MakeMemberAccess(exp, m.Member); } return m; } internal virtual Expression VisitMethodCall(MethodCallExpression m) { Expression obj = this.Visit(m.Object); IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments); if (obj != m.Object || args != m.Arguments) { return Expression.Call(obj, m.Method, args); } return m; } internal virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original) { List<Expression> list = null; for (int i = 0, n = original.Count; i < n; i++) { Expression p = this.Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<Expression>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) return list.ToReadOnlyCollection(); return original; } internal virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { Expression e = this.Visit(assignment.Expression); if (e != assignment.Expression) { return Expression.Bind(assignment.Member, e); } return assignment; } internal virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings); if (bindings != binding.Bindings) { return Expression.MemberBind(binding.Member, bindings); } return binding; } internal virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) { IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers); if (initializers != binding.Initializers) { return Expression.ListBind(binding.Member, initializers); } return binding; } internal virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { List<MemberBinding> list = null; for (int i = 0, n = original.Count; i < n; i++) { MemberBinding b = this.VisitBinding(original[i]); if (list != null) { list.Add(b); } else if (b != original[i]) { list = new List<MemberBinding>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(b); } } if (list != null) return list; return original; } internal virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { List<ElementInit> list = null; for (int i = 0, n = original.Count; i < n; i++) { ElementInit init = this.VisitElementInitializer(original[i]); if (list != null) { list.Add(init); } else if (init != original[i]) { list = new List<ElementInit>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(init); } } if (list != null) return list; return original; } internal virtual Expression VisitLambda(LambdaExpression lambda) { Expression body = this.Visit(lambda.Body); if (body != lambda.Body) { return Expression.Lambda(lambda.Type, body, lambda.Parameters); } return lambda; } internal virtual NewExpression VisitNew(NewExpression nex) { IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments); if (args != nex.Arguments) { if(nex.Members != null) return Expression.New(nex.Constructor, args, nex.Members); else return Expression.New(nex.Constructor, args); } return nex; } internal virtual Expression VisitMemberInit(MemberInitExpression init) { NewExpression n = this.VisitNew(init.NewExpression); IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings); if (n != init.NewExpression || bindings != init.Bindings) { return Expression.MemberInit(n, bindings); } return init; } internal virtual Expression VisitListInit(ListInitExpression init) { NewExpression n = this.VisitNew(init.NewExpression); IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || initializers != init.Initializers) { return Expression.ListInit(n, initializers); } return init; } internal virtual Expression VisitNewArray(NewArrayExpression na) { IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions); if (exprs != na.Expressions) { if (na.NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(na.Type.GetElementType(), exprs); } else { return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); } } return na; } internal virtual Expression VisitInvocation(InvocationExpression iv) { IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments); Expression expr = this.Visit(iv.Expression); if (args != iv.Arguments || expr != iv.Expression) { return Expression.Invoke(expr, args); } return iv; } } // internal static class ReadOnlyCollectionExtensions { internal static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> sequence) { if (sequence == null) return DefaultReadOnlyCollection<T>.Empty; ReadOnlyCollection<T> col = sequence as ReadOnlyCollection<T>; if (col != null) return col; return new ReadOnlyCollection<T>(sequence.ToArray()); } private static class DefaultReadOnlyCollection<T> { private static volatile ReadOnlyCollection<T> _defaultCollection; internal static ReadOnlyCollection<T> Empty { get { if (_defaultCollection == null) _defaultCollection = new ReadOnlyCollection<T>(new T[] { }); return _defaultCollection; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Win32; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Reflection; using System.Threading; /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter"]/*' /> /// <devdoc> /// ColorConverter is a class that can be used to convert /// colors from one data type to another. Access this /// class through the TypeDescriptor. /// </devdoc> public class ColorConverter : TypeConverter { private static string ColorConstantsLock = "colorConstants"; private static Hashtable colorConstants; private static string SystemColorConstantsLock = "systemColorConstants"; private static Hashtable systemColorConstants; private static string ValuesLock = "values"; private static StandardValuesCollection values; /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ColorConverter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ColorConverter() { } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.Colors"]/*' /> /// <devdoc> /// Hashtable of color / value pairs (color name is key) /// for standard colors. /// </devdoc> private static Hashtable Colors { get { if (colorConstants == null) { lock(ColorConstantsLock) { if (colorConstants == null) { Hashtable tempHash = new Hashtable(StringComparer.OrdinalIgnoreCase); FillConstants(tempHash, typeof(Color)); colorConstants = tempHash; } } } return colorConstants; } } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.SystemColors"]/*' /> /// <devdoc> /// Hashtable of color / value pairs (color name is key) /// for system colors. /// </devdoc> private static Hashtable SystemColors { get { if (systemColorConstants == null) { lock (SystemColorConstantsLock) { if (systemColorConstants == null) { Hashtable tempHash = new Hashtable(StringComparer.OrdinalIgnoreCase); FillConstants(tempHash, typeof(System.Drawing.SystemColors)); systemColorConstants = tempHash; } } } return systemColorConstants; } } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.CanConvertFrom"]/*' /> /// <devdoc> /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// </devdoc> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.CanConvertTo"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether this converter can /// convert an object to the given destination type using the context.</para> /// </devdoc> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } internal static object GetNamedColor(string name) { object color = null; // First, check to see if this is a standard name. // color = Colors[name]; if (color != null) { return color; } // Ok, how about a system color? // color = SystemColors[name]; return color; } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ConvertFrom"]/*' /> /// <devdoc> /// Converts the given object to the converter's native type. /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string strValue = value as string; if (strValue != null) { object obj = null; string text = strValue.Trim(); if (text.Length == 0) { obj = Color.Empty; } else { // First, check to see if this is a standard name. // obj = GetNamedColor(text); if (obj == null) { if (culture == null) { culture = CultureInfo.CurrentCulture; } char sep = culture.TextInfo.ListSeparator[0]; bool tryMappingToKnownColor = true; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); // If the value is a 6 digit hex number only, then // we want to treat the Alpha as 255, not 0 // if (text.IndexOf(sep) == -1) { // text can be '' (empty quoted string) if (text.Length >= 2 && (text[0] == '\'' || text[0] == '"') && text[0] == text[text.Length -1]) { // In quotes means a named value string colorName = text.Substring(1, text.Length - 2); obj = Color.FromName(colorName); tryMappingToKnownColor = false; } else if ((text.Length == 7 && text[0] == '#') || (text.Length == 8 && (text.StartsWith("0x") || text.StartsWith("0X"))) || (text.Length == 8 && (text.StartsWith("&h") || text.StartsWith("&H")))) { // Note: ConvertFromString will raise exception if value cannot be converted. obj = Color.FromArgb(unchecked((int)(0xFF000000 | (uint)(int)intConverter.ConvertFromString(context, culture, text)))); } } // Nope. Parse the RGBA from the text. // if (obj == null) { string[] tokens = text.Split(new char[] {sep}); int[] values = new int[tokens.Length]; for (int i = 0; i < values.Length; i++) { values[i] = unchecked((int)intConverter.ConvertFromString(context, culture, tokens[i])); } // We should now have a number of parsed integer values. // We support 1, 3, or 4 arguments: // // 1 -- full ARGB encoded // 3 -- RGB // 4 -- ARGB // switch (values.Length) { case 1: obj = Color.FromArgb(values[0]); break; case 3: obj = Color.FromArgb(values[0], values[1], values[2]); break; case 4: obj = Color.FromArgb(values[0], values[1], values[2], values[3]); break; } tryMappingToKnownColor = true; } if ((obj != null) && tryMappingToKnownColor) { // Now check to see if this color matches one of our known colors. // If it does, then substitute it. We can only do this for "Colors" // because system colors morph with user settings. // int targetARGB = ((Color)obj).ToArgb(); foreach (Color c in Colors.Values) { if (c.ToArgb() == targetARGB) { obj = c; break; } } } } if (obj == null) { throw new ArgumentException(SR.Format(SR.InvalidColor, text)); } } return obj; } return base.ConvertFrom(context, culture, value); } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ConvertTo"]/*' /> /// <devdoc> /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call /// to ToString on the object if the object is valid and if the destination /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// </devdoc> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if( value is Color ){ if (destinationType == typeof(string)) { Color c = (Color)value; if (c == Color.Empty) { return string.Empty; } else { // If this is a known color, then Color can provide its own // name. Otherwise, we fabricate an ARGB value for it. // if (c.IsKnownColor) { return c.Name; } else if (c.IsNamedColor) { return "'" + c.Name + "'"; } else { if (culture == null) { culture = CultureInfo.CurrentCulture; } string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args; int nArg = 0; if (c.A < 255) { args = new string[4]; args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.A); } else { args = new string[3]; } // Note: ConvertToString will raise exception if value cannot be converted. args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.R); args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.G); args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.B); // Now slam all of these together with the fantastic Join // method. // return string.Join(sep, args); } } } if (destinationType == typeof(InstanceDescriptor)) { MemberInfo member = null; object[] args = null; Color c = (Color)value; if (c.IsEmpty) { member = typeof(Color).GetField("Empty"); } else if (c.IsSystemColor) { member = typeof(SystemColors).GetProperty(c.Name); } else if (c.IsKnownColor) { member = typeof(Color).GetProperty(c.Name); } else if (c.A != 255) { member = typeof(Color).GetMethod("FromArgb", new Type[] {typeof(int), typeof(int), typeof(int), typeof(int)}); args = new object[] {c.A, c.R, c.G, c.B}; } else if (c.IsNamedColor) { member = typeof(Color).GetMethod("FromName", new Type[] {typeof(string)}); args = new object[] {c.Name}; } else { member = typeof(Color).GetMethod("FromArgb", new Type[] {typeof(int), typeof(int), typeof(int)}); args = new object[] {c.R, c.G, c.B}; } Debug.Assert(member != null, "Could not convert color to member. Did someone change method name / signature and not update Colorconverter?"); if (member != null) { return new InstanceDescriptor(member, args); } else { return null; } } } return base.ConvertTo(context, culture, value, destinationType); } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.FillConstants"]/*' /> /// <devdoc> /// Fills the given hashtable with field name / value pairs. It walks all public static /// properties of enumType that have a property type of Color. /// </devdoc> private static void FillConstants(Hashtable hash, Type enumType) { MethodAttributes attrs = MethodAttributes.Public | MethodAttributes.Static; PropertyInfo[] props = enumType.GetProperties(); for (int i = 0; i < props.Length; i++) { PropertyInfo prop = props[i]; if (prop.PropertyType == typeof(Color)) { MethodInfo method = prop.GetGetMethod(); if (method != null && (method.Attributes & attrs) == attrs) { object[] tempIndex = null; hash[prop.Name] = prop.GetValue(null, tempIndex); } } } } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.GetStandardValues"]/*' /> /// <devdoc> /// Retrieves a collection containing a set of standard values /// for the data type this validator is designed for. This /// will return null if the data type does not support a /// standard set of values. /// </devdoc> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (values == null) { lock (ValuesLock) { if (values == null) { // We must take the value from each hashtable and combine them. // ArrayList arrayValues = new ArrayList(); arrayValues.AddRange(Colors.Values); arrayValues.AddRange(SystemColors.Values); // Now, we have a couple of colors that have the same names but // are identical values. Look for these and remove them. Too // bad this is n^2. // int count = arrayValues.Count; for (int i = 0; i < count - 1; i++) { for (int j = i + 1; j < count; j++) { if (arrayValues[i].Equals(arrayValues[j])) { // Remove this item! // arrayValues.RemoveAt(j); count--; j--; } } } // Sort the array. // arrayValues.Sort(0, arrayValues.Count, new ColorComparer()); values = new StandardValuesCollection(arrayValues.ToArray()); } } } return values; } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.GetStandardValuesSupported"]/*' /> /// <devdoc> /// Determines if this object supports a standard set of values /// that can be picked from a list. /// </devdoc> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ColorComparer"]/*' /> /// <devdoc> /// IComparer for color values. This takes color values but compares their /// names. /// </devdoc> private class ColorComparer : IComparer { public int Compare(object left, object right) { Color cLeft = (Color)left; Color cRight = (Color)right; return string.Compare(cLeft.Name, cRight.Name, false, CultureInfo.InvariantCulture); } } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class BTreeCursorTest { private string testFixtureName; private string testFixtureHome; private string testName; private string testHome; private DatabaseEnvironment paramEnv; private BTreeDatabase paramDB; private EventWaitHandle signal; private delegate void BTCursorMoveFuncDelegate( BTreeCursor cursor, LockingInfo lockingInfo); private BTCursorMoveFuncDelegate btCursorFunc; [TestFixtureSetUp] public void RunBeforeTests() { testFixtureName = "BTreeCursorTest"; testFixtureHome = "./TestOut/" + testFixtureName; } [Test] public void TestAddKeyFirst() { BTreeDatabase db; BTreeCursor cursor; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; testName = "TestAddKeyFirst"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); // Add record("key", "data") into database. CursorTest.GetCursorInBtreeDBWithoutEnv( testHome, testName, out db, out cursor); CursorTest.AddOneByCursor(db, cursor); // Add record("key","data1") as the first of the data item of "key". pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data1"))); cursor.Add(pair, Cursor.InsertLocation.FIRST); // Confirm the record is added as the first of the data item of "key". cursor.Move(new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), true); Assert.AreEqual(ASCIIEncoding.ASCII.GetBytes("data1"), cursor.Current.Value.Data); cursor.Close(); db.Close(); } [Test] public void TestAddKeyLast() { BTreeDatabase db; BTreeCursor cursor; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; testName = "TestAddKeyLast"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); // Add record("key", "data") into database. CursorTest.GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); CursorTest.AddOneByCursor(db, cursor); // Add new record("key","data1") as the last of the data item of "key". pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data1"))); cursor.Add(pair, Cursor.InsertLocation.LAST); // Confirm the record is added as the first of the data item of "key". cursor.Move(new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), true); Assert.AreNotEqual(ASCIIEncoding.ASCII.GetBytes("data1"), cursor.Current.Value.Data); cursor.Close(); db.Close(); } [Test] public void TestAddUnique() { BTreeDatabase db; BTreeCursor cursor; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; testName = "TestAddUnique"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); // Open a database and cursor. BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; // To put no duplicate data, the database should be set to be sorted. dbConfig.Duplicates = DuplicatesPolicy.SORTED; db = BTreeDatabase.Open(testHome + "/" + testName + ".db", dbConfig); cursor = db.Cursor(); // Add record("key", "data") into database. CursorTest.AddOneByCursor(db, cursor); // Fail to add duplicate record("key","data"). pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"))); try { cursor.AddUnique(pair); } catch (KeyExistException) { } finally { cursor.Close(); db.Close(); } } [Test] public void TestDuplicateWithSamePos() { BTreeDatabase db; BTreeDatabaseConfig dbConfig; BTreeCursor cursor, dupCursor; DatabaseEnvironment env; DatabaseEnvironmentConfig envConfig; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; Transaction txn; testName = "TestDuplicateWithSamePos"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; envConfig.UseTxns = true; envConfig.NoMMap = false; env = DatabaseEnvironment.Open(testHome, envConfig); txn = env.BeginTransaction(); dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; db = BTreeDatabase.Open(testName + ".db", dbConfig, txn); key = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); db.Put(key, data, txn); txn.Commit(); txn = env.BeginTransaction(); cursor = db.Cursor(txn); cursor.Move(key, true); //Duplicate a new cursor to the same position. dupCursor = cursor.Duplicate(true); // Overwrite the record. dupCursor.Overwrite(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("newdata"))); // Confirm that the original data doesn't exist. Assert.IsFalse(dupCursor.Move(pair, true)); dupCursor.Close(); cursor.Close(); txn.Commit(); db.Close(); env.Close(); } [Test, ExpectedException(typeof(ExpectedTestException))] public void TestDuplicateToDifferentPos() { BTreeDatabase db; BTreeDatabaseConfig dbConfig; BTreeCursor cursor, dupCursor; DatabaseEnvironment env; DatabaseEnvironmentConfig envConfig; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; Transaction txn; testName = "TestDuplicateToDifferentPos"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; envConfig.UseTxns = true; envConfig.NoMMap = false; env = DatabaseEnvironment.Open(testHome, envConfig); txn = env.BeginTransaction(); dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; db = BTreeDatabase.Open(testName + ".db", dbConfig, txn); key = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); db.Put(key, data, txn); txn.Commit(); txn = env.BeginTransaction(); cursor = db.Cursor(txn); cursor.Move(key, true); //Duplicate a new cursor to the same position. dupCursor = cursor.Duplicate(false); /* * The duplicate cursor points to nothing so overwriting the * record is not allowed. */ try { dupCursor.Overwrite(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("newdata"))); } catch (DatabaseException) { throw new ExpectedTestException(); } finally { dupCursor.Close(); cursor.Close(); txn.Commit(); db.Close(); env.Close(); } } [Test] public void TestInsertAfter() { BTreeDatabase db; BTreeCursor cursor; DatabaseEntry data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; testName = "TestInsertAfter"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); // Add record("key", "data") into database. CursorTest.GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); CursorTest.AddOneByCursor(db, cursor); // Insert the new record("key","data1") after the record("key", "data"). data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data1")); cursor.Insert(data, Cursor.InsertLocation.AFTER); /* * Move the cursor to the record("key", "data") and confirm that * the next record is the one just inserted. */ pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"))); Assert.IsTrue(cursor.Move(pair, true)); Assert.IsTrue(cursor.MoveNext()); Assert.AreEqual(ASCIIEncoding.ASCII.GetBytes("key"), cursor.Current.Key.Data); Assert.AreEqual(ASCIIEncoding.ASCII.GetBytes("data1"), cursor.Current.Value.Data); cursor.Close(); db.Close(); } [Test] public void TestMoveFirstMultipleAndMultipleKey() { testName = "TestMoveFirstMultipleAndMultipleKey"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> pair; MultipleKeyDatabaseEntry multiPair; int cnt; int[] size = new int[2]; size[0] = 0; size[1] = 1024; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); for (int i = 0; i < 2; i++) { cnt = 0; if (size[i] == 0) cursor.MoveFirstMultiple(); else cursor.MoveFirstMultiple(size[i]); pair = cursor.CurrentMultiple; foreach (DatabaseEntry dbt in pair.Value) cnt++; Assert.AreEqual(1, cnt); } for (int i = 0; i < 2; i++) { cnt = 0; if (size[i] == 0) cursor.MoveFirstMultipleKey(); else cursor.MoveFirstMultipleKey(size[i]); multiPair = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> dbt in multiPair) cnt++; Assert.Less(1, cnt); } cursor.Close(); db.Close(); } [Test] public void TestMoveMultiple() { testName = "TestMoveMultiple"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key; KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> pair; int cnt; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); // Move cursor to pairs with exact 99 as its key. cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)99)); cursor.MoveMultiple(key, true); pair = cursor.CurrentMultiple; Assert.AreEqual(99, BitConverter.ToInt32(pair.Key.Data, 0)); foreach (DatabaseEntry dbt in pair.Value) cnt++; Assert.AreEqual(2, cnt); // Move cursor to pairs with the smallest key larger than 100. cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)100)); cursor.MoveMultiple(key, false); pair = cursor.CurrentMultiple; Assert.AreEqual(101, BitConverter.ToInt32(pair.Key.Data, 0)); foreach (DatabaseEntry dbt in pair.Value) cnt++; Assert.AreEqual(1, cnt); cursor.Close(); db.Close(); } [Test] public void TestMoveMultipleKey() { testName = "TestMoveMultipleKey"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key; MultipleKeyDatabaseEntry mulPair; ; int cnt; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); /* * Bulk retrieve key/value pair from the pair whose key * is exact 99. */ cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)99)); cursor.MoveMultipleKey(key, true); mulPair = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> pair in mulPair) { Assert.GreaterOrEqual(3, BitConverter.ToInt32(pair.Key.Data, 0) - 98); cnt++; } Assert.AreEqual(3, cnt); /* * Bulk retrieve key/value pair from the pair whose key * is the smallest one larger than 100. */ cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)100)); cursor.MoveMultipleKey(key, false); mulPair = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> pair in mulPair) { Assert.AreEqual(101, BitConverter.ToInt32(pair.Key.Data, 0)); cnt++; } Assert.LessOrEqual(1, cnt); cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)100)); cursor.MoveMultipleKey(key, false, 1024); mulPair = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> pair in mulPair) { Assert.AreEqual(101, BitConverter.ToInt32(pair.Key.Data, 0)); Assert.AreEqual(101, BitConverter.ToInt32(pair.Value.Data, 0)); cnt++; } Assert.LessOrEqual(1, cnt); cursor.Close(); db.Close(); } [Test] public void TestMoveMultipleKeyWithRecno() { testName = "TestMoveMultipleKeyWithRecno"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; MultipleKeyDatabaseEntry multiDBT; int cnt; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.UseRecordNumbers = true; dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); cnt = 0; cursor.MoveMultipleKey(98); multiDBT = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> pair in multiDBT) cnt++; Assert.AreEqual(3, cnt); cnt = 0; cursor.MoveMultipleKey(98, 1024); multiDBT = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> pair in multiDBT) cnt++; Assert.AreEqual(3, cnt); cursor.Close(); db.Close(); } [Test] public void TestMoveMultiplePairs() { testName = "TestMoveMultiplePairs"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; MultipleKeyDatabaseEntry multiKeyDBTs1, multiKeyDBTs2; int cnt; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.SORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); /* * Bulk retrieve pairs from the pair whose key/data * is exact 99/99. */ cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)99)); data = new DatabaseEntry(BitConverter.GetBytes((int)99)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.MoveMultipleKey(pair, true); multiKeyDBTs1 = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> p in multiKeyDBTs1) cnt++; Assert.AreEqual(3, cnt); // Bulk retrieve pairs from the pair whose key is exact 99. cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)99)); data = new DatabaseEntry(BitConverter.GetBytes((int)98)); cursor.MoveMultipleKey(pair, true); multiKeyDBTs2 = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> dbts in multiKeyDBTs2) cnt++; Assert.AreEqual(3, cnt); /* * Bulk retrieve pairs from the pair whose key is * exact 99 in buffer size of 1024k. */ cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)99)); data = new DatabaseEntry(BitConverter.GetBytes((int)102)); cursor.MoveMultipleKey(pair, true, 1024); multiKeyDBTs2 = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> dbts in multiKeyDBTs2) cnt++; Assert.AreEqual(3, cnt); cursor.Close(); db.Close(); } [Test] public void TestMoveMultiplePairWithKey() { testName = "TestMoveMultiplePairWithKey"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> mulPair; int cnt; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); /* * Move the cursor to pairs with exact 99 as its key * and 99 as its data. */ cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)99)); data = new DatabaseEntry(BitConverter.GetBytes((int)99)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.MoveMultiple(pair, true); mulPair = cursor.CurrentMultiple; Assert.AreEqual(99, BitConverter.ToInt32(mulPair.Key.Data, 0)); foreach (DatabaseEntry dbt in mulPair.Value) { Assert.AreEqual(99, BitConverter.ToInt32(dbt.Data, 0)); cnt++; } Assert.AreEqual(1, cnt); // Move cursor to pairs with the smallest key larger than 100. cnt = 0; key = new DatabaseEntry(BitConverter.GetBytes((int)100)); data = new DatabaseEntry(BitConverter.GetBytes((int)100)); cursor.MoveMultiple(pair, false); mulPair = cursor.CurrentMultiple; Assert.AreEqual(99, BitConverter.ToInt32(mulPair.Key.Data, 0)); foreach (DatabaseEntry dbt in mulPair.Value) { Assert.GreaterOrEqual(1, BitConverter.ToInt32(dbt.Data, 0) - 99); cnt++; } Assert.AreEqual(1, cnt); cursor.Close(); db.Close(); } [Test] public void TestMoveMultipleWithRecno() { testName = "TestMoveMultipleWithRecno"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> pair; int cnt; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.PageSize = 1024; dbConfig.UseRecordNumbers = true; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); // Move cursor to the No.100 record. cnt = 0; cursor.MoveMultiple(100); pair = cursor.CurrentMultiple; Assert.AreEqual(100, BitConverter.ToInt32(pair.Key.Data, 0)); foreach (DatabaseEntry dbt in pair.Value) cnt++; Assert.AreEqual(1, cnt); // Move cursor to the No.100 record with buffer size of 1024k. cnt = 0; cursor.MoveMultiple(100, 1024); pair = cursor.CurrentMultiple; Assert.AreEqual(100, BitConverter.ToInt32(pair.Key.Data, 0)); foreach (DatabaseEntry dbt in pair.Value) cnt++; Assert.AreEqual(1, cnt); cursor.Close(); db.Close(); } [Test] public void TestMoveNextDuplicateMultipleAndMultipleKey() { testName = "TestMoveNextDuplicateMultipleAndMultipleKey"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> pairs; MultipleKeyDatabaseEntry multiPair; int cnt; int[] size = new int[2]; size[0] = 0; size[1] = 1024; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.SORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); key = new DatabaseEntry(BitConverter.GetBytes(99)); data = new DatabaseEntry(BitConverter.GetBytes(99)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); for (int j = 0; j < 2; j++) { for (int i = 0; i < 2; i++) { cnt = 0; cursor.Move(pair, true); if (j == 0) { if (size[i] == 0) Assert.IsTrue(cursor.MoveNextDuplicateMultiple()); else Assert.IsTrue(cursor.MoveNextDuplicateMultiple(size[i])); pairs = cursor.CurrentMultiple; foreach (DatabaseEntry dbt in pairs.Value) { Assert.AreEqual(100, BitConverter.ToInt32(dbt.Data, 0)); cnt++; } Assert.AreEqual(1, cnt); } else { if (size[i] == 0) Assert.IsTrue(cursor.MoveNextDuplicateMultipleKey()); else Assert.IsTrue(cursor.MoveNextDuplicateMultipleKey(size[i])); multiPair = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> p in multiPair) { Assert.AreEqual(100, BitConverter.ToInt32(p.Value.Data, 0)); cnt++; } Assert.AreEqual(1, cnt); } } } cursor.Close(); db.Close(); } [Test] public void TestMoveNextUniqueMultipleAndMultipleKey() { testName = "TestMoveNextUniqueMultipleAndMultipleKey"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> pairs; MultipleKeyDatabaseEntry multiPair; int cnt; int[] size = new int[2]; size[0] = 0; size[1] = 1024; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); key = new DatabaseEntry(BitConverter.GetBytes(99)); data = new DatabaseEntry(BitConverter.GetBytes(99)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); for (int j = 0; j < 2; j++) { for (int i = 0; i < 2; i++) { cnt = 0; cursor.Move(pair, true); if (j == 0) { if (size[i] == 0) Assert.IsTrue(cursor.MoveNextUniqueMultiple()); else Assert.IsTrue(cursor.MoveNextUniqueMultiple(size[i])); pairs = cursor.CurrentMultiple; foreach (DatabaseEntry dbt in pairs.Value) { Assert.AreEqual(101, BitConverter.ToInt32(dbt.Data, 0)); cnt++; } Assert.AreEqual(1, cnt); } else { if (size[i] == 0) Assert.IsTrue(cursor.MoveNextUniqueMultipleKey()); else Assert.IsTrue(cursor.MoveNextUniqueMultipleKey(size[i])); multiPair = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> p in multiPair) { Assert.AreEqual(101, BitConverter.ToInt32(p.Value.Data, 0)); cnt++; } Assert.AreEqual(1, cnt); } } } cursor.Close(); db.Close(); } [Test] public void TestRefreshMultipleAndMultipleKey() { testName = "TestRefreshMultipleAndMultipleKey"; testHome = testFixtureHome + "/" + testName; string btreeDBFileName = testHome + "/" + testName + ".db"; BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> pairs; MultipleKeyDatabaseEntry multiPair; int cnt; int[] size = new int[2]; size[0] = 0; size[1] = 1024; Configuration.ClearDir(testHome); BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; dbConfig.Duplicates = DuplicatesPolicy.SORTED; dbConfig.PageSize = 1024; GetMultipleDB(btreeDBFileName, dbConfig, out db, out cursor); key = new DatabaseEntry(BitConverter.GetBytes(99)); data = new DatabaseEntry(BitConverter.GetBytes(99)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); for (int j = 0; j < 2; j++) { for (int i = 0; i < 2; i++) { cnt = 0; cursor.Move(pair, true); if (j == 0) { if (size[i] == 0) Assert.IsTrue(cursor.RefreshMultiple()); else Assert.IsTrue(cursor.RefreshMultiple(size[i])); pairs = cursor.CurrentMultiple; foreach (DatabaseEntry dbt in pairs.Value) cnt++; Assert.AreEqual(2, cnt); } else { if (size[i] == 0) Assert.IsTrue(cursor.RefreshMultipleKey()); else Assert.IsTrue(cursor.RefreshMultipleKey(size[i])); multiPair = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> p in multiPair) cnt++; Assert.AreEqual(3, cnt); } } } cursor.Close(); db.Close(); } private void GetMultipleDB(string dbFileName, BTreeDatabaseConfig dbConfig, out BTreeDatabase db, out BTreeCursor cursor) { db = BTreeDatabase.Open(dbFileName, dbConfig); cursor = db.Cursor(); KeyValuePair<DatabaseEntry, DatabaseEntry> pair; DatabaseEntry key, data; for (int i = 1; i < 100; i++) { key = new DatabaseEntry(BitConverter.GetBytes(i)); data = new DatabaseEntry(BitConverter.GetBytes(i)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.Add(pair); } if (dbConfig.UseRecordNumbers == true) { byte[] bytes = new byte[512]; for (int i = 0; i < 512; i++) bytes[i] = (byte)i; key = new DatabaseEntry(BitConverter.GetBytes(100)); data = new DatabaseEntry(bytes); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.Add(pair); } else { if (dbConfig.Duplicates == DuplicatesPolicy.UNSORTED || dbConfig.Duplicates == DuplicatesPolicy.SORTED) { key = new DatabaseEntry(BitConverter.GetBytes(99)); data = new DatabaseEntry(BitConverter.GetBytes(100)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.Add(pair); } key = new DatabaseEntry(BitConverter.GetBytes(101)); data = new DatabaseEntry(BitConverter.GetBytes(101)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.Add(pair); } } [Test] public void TestInsertBefore() { BTreeDatabase db; BTreeCursor cursor; DatabaseEntry data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; testName = "TestInsertBefore"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); // Add record("key", "data") into database. CursorTest.GetCursorInBtreeDBWithoutEnv( testHome, testName, out db, out cursor); CursorTest.AddOneByCursor(db, cursor); // Insert the new record("key","data1") before the record("key", "data"). data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data1")); cursor.Insert(data, Cursor.InsertLocation.BEFORE); /* * Move the cursor to the record("key", "data") and confirm * that the previous record is the one just inserted. */ pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"))); Assert.IsTrue(cursor.Move(pair, true)); Assert.IsTrue(cursor.MovePrev()); Assert.AreEqual(ASCIIEncoding.ASCII.GetBytes("key"),cursor.Current.Key.Data); Assert.AreEqual(ASCIIEncoding.ASCII.GetBytes("data1"), cursor.Current.Value.Data); cursor.Close(); db.Close(); } [Test] public void TestMoveToRecno() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveToRecno"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); GetCursorInBtreeDBUsingRecno(testHome, testName, out db, out cursor); for (int i = 0; i < 10; i++) db.Put( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); MoveCursorToRecno(cursor, null); cursor.Close(); db.Close(); } [Test] public void TestMoveToRecnoWithRMW() { testName = "TestMoveToRecnoWithRMW"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); btCursorFunc = new BTCursorMoveFuncDelegate( MoveCursorToRecno); // Move to a specified key and a key/data pair. MoveWithRMW(testHome, testName); } [Test] public void TestRecno() { BTreeDatabase db; BTreeCursor cursor; testName = "TestRecno"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); GetCursorInBtreeDBUsingRecno(testHome, testName, out db, out cursor); for (int i = 0; i < 10; i++) db.Put( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); ReturnRecno(cursor, null); cursor.Close(); db.Close(); } [Test] public void TestRecnoWithRMW() { testName = "TestRecnoWithRMW"; testHome = testFixtureHome + "/" + testName; Configuration.ClearDir(testHome); // Use MoveCursorToRecno() as its move function. btCursorFunc = new BTCursorMoveFuncDelegate( ReturnRecno); // Move to a specified key and a key/data pair. MoveWithRMW(testHome, testName); } /* * Move the cursor according to recno. The recno * starts from 1 and is increased by 1. */ public void MoveCursorToRecno(BTreeCursor cursor, LockingInfo lck) { for (uint i = 1; i <= 5; i++) if (lck == null) Assert.IsTrue(cursor.Move(i)); else Assert.IsTrue(cursor.Move(i, lck)); } /*l * Move the cursor according to a given recno and * return the current record's recno. The given recno * and the one got from the cursor should be the same. */ public void ReturnRecno(BTreeCursor cursor, LockingInfo lck) { for (uint i = 1; i <= 5; i++) if (lck == null) { if (cursor.Move(i) == true) Assert.AreEqual(i, cursor.Recno()); } else { if (cursor.Move(i, lck) == true) Assert.AreEqual(i, cursor.Recno(lck)); } } public void GetCursorInBtreeDBUsingRecno(string home, string name, out BTreeDatabase db, out BTreeCursor cursor) { string dbFileName = home + "/" + name + ".db"; BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.UseRecordNumbers = true; dbConfig.Creation = CreatePolicy.IF_NEEDED; db = BTreeDatabase.Open(dbFileName, dbConfig); cursor = db.Cursor(); } public void RdMfWt() { Transaction txn = paramEnv.BeginTransaction(); BTreeCursor dbc = paramDB.Cursor(txn); try { LockingInfo lck = new LockingInfo(); lck.ReadModifyWrite = true; // Read record. btCursorFunc(dbc, lck); // Block the current thread until event is set. signal.WaitOne(); // Write new records into database. DatabaseEntry key = new DatabaseEntry(BitConverter.GetBytes(55)); DatabaseEntry data = new DatabaseEntry(BitConverter.GetBytes(55)); dbc.Add(new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data)); dbc.Close(); txn.Commit(); } catch (DeadlockException) { dbc.Close(); txn.Abort(); } } public void MoveWithRMW(string home, string name) { paramEnv = null; paramDB = null; // Open the environment. DatabaseEnvironmentConfig envCfg = new DatabaseEnvironmentConfig(); envCfg.Create = true; envCfg.FreeThreaded = true; envCfg.UseLocking = true; envCfg.UseLogging = true; envCfg.UseMPool = true; envCfg.UseTxns = true; paramEnv = DatabaseEnvironment.Open(home, envCfg); // Open database in transaction. Transaction openTxn = paramEnv.BeginTransaction(); BTreeDatabaseConfig cfg = new BTreeDatabaseConfig(); cfg.Creation = CreatePolicy.ALWAYS; cfg.Env = paramEnv; cfg.FreeThreaded = true; cfg.PageSize = 4096; // Use record number. cfg.UseRecordNumbers = true; paramDB = BTreeDatabase.Open(name + ".db", cfg, openTxn); openTxn.Commit(); /* * Put 10 different, 2 duplicate and another different * records into database. */ Transaction txn = paramEnv.BeginTransaction(); for (int i = 0; i < 13; i++) { DatabaseEntry key, data; if (i == 10 || i == 11) { key = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data")); } else { key = new DatabaseEntry(BitConverter.GetBytes(i)); data = new DatabaseEntry(BitConverter.GetBytes(i)); } paramDB.Put(key, data, txn); } txn.Commit(); // Get a event wait handle. signal = new EventWaitHandle(false, EventResetMode.ManualReset); /* * Start RdMfWt() in two threads. RdMfWt() reads * and writes data into database. */ Thread t1 = new Thread(new ThreadStart(RdMfWt)); Thread t2 = new Thread(new ThreadStart(RdMfWt)); t1.Start(); t2.Start(); // Give both threads time to read before signalling them to write. Thread.Sleep(1000); // Invoke the write operation in both threads. signal.Set(); // Return the number of deadlocks. while (t1.IsAlive || t2.IsAlive) { /* * Give both threads time to write before * counting the number of deadlocks. */ Thread.Sleep(1000); uint deadlocks = paramEnv.DetectDeadlocks(DeadlockPolicy.DEFAULT); // Confirm that there won't be any deadlock. Assert.AreEqual(0, deadlocks); } t1.Join(); t2.Join(); paramDB.Close(); paramEnv.Close(); } } }
// 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 Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PacketCapturesOperations operations. /// </summary> internal partial class PacketCapturesOperations : IServiceOperations<NetworkManagementClient>, IPacketCapturesOperations { /// <summary> /// Initializes a new instance of the PacketCapturesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PacketCapturesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PacketCaptureResult>> CreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<PacketCaptureResult> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a packet capture session by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PacketCaptureResult>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PacketCaptureResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginStopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> GetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<PacketCaptureQueryStatusResult> _response = await BeginGetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Lists all packet capture sessions within the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<PacketCaptureResult>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<PacketCaptureResult>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<PacketCaptureResult>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PacketCaptureResult>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PacketCaptureResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginStop", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> BeginGetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginGetStatus", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PacketCaptureQueryStatusResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel { using System.Collections.ObjectModel; using System.IdentityModel.Tokens; using System.Runtime; using System.Runtime.CompilerServices; using System.ServiceModel.Channels; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Xml; using System.ComponentModel; public sealed class FederatedMessageSecurityOverHttp { internal const bool DefaultNegotiateServiceCredential = true; internal const SecurityKeyType DefaultIssuedKeyType = SecurityKeyType.SymmetricKey; internal const bool DefaultEstablishSecurityContext = true; bool establishSecurityContext; bool negotiateServiceCredential; SecurityAlgorithmSuite algorithmSuite; EndpointAddress issuerAddress; EndpointAddress issuerMetadataAddress; Binding issuerBinding; Collection<ClaimTypeRequirement> claimTypeRequirements; string issuedTokenType; SecurityKeyType issuedKeyType; Collection<XmlElement> tokenRequestParameters; public FederatedMessageSecurityOverHttp() { negotiateServiceCredential = DefaultNegotiateServiceCredential; algorithmSuite = SecurityAlgorithmSuite.Default; issuedKeyType = DefaultIssuedKeyType; claimTypeRequirements = new Collection<ClaimTypeRequirement>(); tokenRequestParameters = new Collection<XmlElement>(); establishSecurityContext = DefaultEstablishSecurityContext; } public bool NegotiateServiceCredential { get { return this.negotiateServiceCredential; } set { this.negotiateServiceCredential = value; } } public SecurityAlgorithmSuite AlgorithmSuite { get { return this.algorithmSuite; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } this.algorithmSuite = value; } } public bool EstablishSecurityContext { get { return this.establishSecurityContext; } set { this.establishSecurityContext = value; } } [DefaultValue(null)] public EndpointAddress IssuerAddress { get { return this.issuerAddress; } set { this.issuerAddress = value; } } [DefaultValue(null)] public EndpointAddress IssuerMetadataAddress { get { return this.issuerMetadataAddress; } set { this.issuerMetadataAddress = value; } } [DefaultValue(null)] public Binding IssuerBinding { get { return this.issuerBinding; } set { this.issuerBinding = value; } } [DefaultValue(null)] public string IssuedTokenType { get { return this.issuedTokenType; } set { this.issuedTokenType = value; } } public SecurityKeyType IssuedKeyType { get { return this.issuedKeyType; } set { if (!SecurityKeyTypeHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } this.issuedKeyType = value; } } public Collection<ClaimTypeRequirement> ClaimTypeRequirements { get { return this.claimTypeRequirements; } } public Collection<XmlElement> TokenRequestParameters { get { return this.tokenRequestParameters; } } [MethodImpl(MethodImplOptions.NoInlining)] internal SecurityBindingElement CreateSecurityBindingElement(bool isSecureTransportMode, bool isReliableSession, MessageSecurityVersion version) { if ((this.IssuedKeyType == SecurityKeyType.BearerKey) && (version.TrustVersion == TrustVersion.WSTrustFeb2005)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.BearerKeyIncompatibleWithWSFederationHttpBinding))); } if (isReliableSession && !this.EstablishSecurityContext) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecureConversationRequiredByReliableSession))); } SecurityBindingElement result; bool emitBspAttributes = true; IssuedSecurityTokenParameters issuedParameters = new IssuedSecurityTokenParameters(this.IssuedTokenType, this.IssuerAddress, this.IssuerBinding); issuedParameters.IssuerMetadataAddress = this.issuerMetadataAddress; issuedParameters.KeyType = this.IssuedKeyType; if (this.IssuedKeyType == SecurityKeyType.SymmetricKey) { issuedParameters.KeySize = this.AlgorithmSuite.DefaultSymmetricKeyLength; } else { issuedParameters.KeySize = 0; } foreach (ClaimTypeRequirement c in this.claimTypeRequirements) { issuedParameters.ClaimTypeRequirements.Add(c); } foreach (XmlElement p in this.TokenRequestParameters) { issuedParameters.AdditionalRequestParameters.Add(p); } WSSecurityTokenSerializer versionSpecificSerializer = new WSSecurityTokenSerializer(version.SecurityVersion, version.TrustVersion, version.SecureConversationVersion, emitBspAttributes, null, null, null); SecurityStandardsManager versionSpecificStandardsManager = new SecurityStandardsManager(version, versionSpecificSerializer); issuedParameters.AddAlgorithmParameters(this.AlgorithmSuite, versionSpecificStandardsManager, this.issuedKeyType); SecurityBindingElement issuedTokenSecurity; if (isSecureTransportMode) { issuedTokenSecurity = SecurityBindingElement.CreateIssuedTokenOverTransportBindingElement(issuedParameters); } else { if (negotiateServiceCredential) { // We should have passed 'true' as RequireCancelation to be consistent with other standard bindings. // However, to limit the change for Orcas, we scope down to just newer version of WSSecurityPolicy. issuedTokenSecurity = SecurityBindingElement.CreateIssuedTokenForSslBindingElement(issuedParameters, version.SecurityPolicyVersion != SecurityPolicyVersion.WSSecurityPolicy11); } else { issuedTokenSecurity = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(issuedParameters); } } issuedTokenSecurity.MessageSecurityVersion = version; issuedTokenSecurity.DefaultAlgorithmSuite = this.AlgorithmSuite; if (this.EstablishSecurityContext) { result = SecurityBindingElement.CreateSecureConversationBindingElement(issuedTokenSecurity, true); } else { result = issuedTokenSecurity; } result.MessageSecurityVersion = version; result.DefaultAlgorithmSuite = this.AlgorithmSuite; result.IncludeTimestamp = true; if (!isReliableSession) { result.LocalServiceSettings.ReconnectTransportOnFailure = false; result.LocalClientSettings.ReconnectTransportOnFailure = false; } else { result.LocalServiceSettings.ReconnectTransportOnFailure = true; result.LocalClientSettings.ReconnectTransportOnFailure = true; } if (this.establishSecurityContext) { // issue the transition SCT for a short duration only issuedTokenSecurity.LocalServiceSettings.IssuedCookieLifetime = SpnegoTokenAuthenticator.defaultServerIssuedTransitionTokenLifetime; } return result; } internal static bool TryCreate(SecurityBindingElement sbe, bool isSecureTransportMode, bool isReliableSession, MessageSecurityVersion version, out FederatedMessageSecurityOverHttp messageSecurity) { Fx.Assert(null != sbe, string.Empty); messageSecurity = null; // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings if (!sbe.IncludeTimestamp) return false; if (sbe.SecurityHeaderLayout != SecurityProtocolFactory.defaultSecurityHeaderLayout) return false; bool emitBspAttributes = true; // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching() SecurityBindingElement bootstrapSecurity; bool establishSecurityContext = SecurityBindingElement.IsSecureConversationBinding(sbe, true, out bootstrapSecurity); bootstrapSecurity = establishSecurityContext ? bootstrapSecurity : sbe; if (isSecureTransportMode && !(bootstrapSecurity is TransportSecurityBindingElement)) return false; bool negotiateServiceCredential = DefaultNegotiateServiceCredential; IssuedSecurityTokenParameters issuedTokenParameters; if (isSecureTransportMode) { if (!SecurityBindingElement.IsIssuedTokenOverTransportBinding(bootstrapSecurity, out issuedTokenParameters)) return false; } else { // We should have passed 'true' as RequireCancelation to be consistent with other standard bindings. // However, to limit the change for Orcas, we scope down to just newer version of WSSecurityPolicy. if (SecurityBindingElement.IsIssuedTokenForSslBinding(bootstrapSecurity, version.SecurityPolicyVersion != SecurityPolicyVersion.WSSecurityPolicy11, out issuedTokenParameters)) negotiateServiceCredential = true; else if (SecurityBindingElement.IsIssuedTokenForCertificateBinding(bootstrapSecurity, out issuedTokenParameters)) negotiateServiceCredential = false; else return false; } if ((issuedTokenParameters.KeyType == SecurityKeyType.BearerKey) && (version.TrustVersion == TrustVersion.WSTrustFeb2005)) { return false; } Collection<XmlElement> nonAlgorithmRequestParameters; WSSecurityTokenSerializer versionSpecificSerializer = new WSSecurityTokenSerializer(version.SecurityVersion, version.TrustVersion, version.SecureConversationVersion, emitBspAttributes, null, null, null); SecurityStandardsManager versionSpecificStandardsManager = new SecurityStandardsManager(version, versionSpecificSerializer); if (!issuedTokenParameters.DoAlgorithmsMatch(sbe.DefaultAlgorithmSuite, versionSpecificStandardsManager, out nonAlgorithmRequestParameters)) { return false; } messageSecurity = new FederatedMessageSecurityOverHttp(); messageSecurity.AlgorithmSuite = sbe.DefaultAlgorithmSuite; messageSecurity.NegotiateServiceCredential = negotiateServiceCredential; messageSecurity.EstablishSecurityContext = establishSecurityContext; messageSecurity.IssuedTokenType = issuedTokenParameters.TokenType; messageSecurity.IssuerAddress = issuedTokenParameters.IssuerAddress; messageSecurity.IssuerBinding = issuedTokenParameters.IssuerBinding; messageSecurity.IssuerMetadataAddress = issuedTokenParameters.IssuerMetadataAddress; messageSecurity.IssuedKeyType = issuedTokenParameters.KeyType; foreach (ClaimTypeRequirement c in issuedTokenParameters.ClaimTypeRequirements) { messageSecurity.ClaimTypeRequirements.Add(c); } foreach (XmlElement p in nonAlgorithmRequestParameters) { messageSecurity.TokenRequestParameters.Add(p); } if (issuedTokenParameters.AlternativeIssuerEndpoints != null && issuedTokenParameters.AlternativeIssuerEndpoints.Count > 0) { return false; } return true; } internal bool InternalShouldSerialize() { return (this.ShouldSerializeAlgorithmSuite() || this.ShouldSerializeClaimTypeRequirements() || this.ShouldSerializeNegotiateServiceCredential() || this.ShouldSerializeEstablishSecurityContext() || this.ShouldSerializeIssuedKeyType() || this.ShouldSerializeTokenRequestParameters()); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeAlgorithmSuite() { return (this.AlgorithmSuite != SecurityAlgorithmSuite.Default); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeClaimTypeRequirements() { return (this.ClaimTypeRequirements.Count > 0); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeNegotiateServiceCredential() { return (this.NegotiateServiceCredential != DefaultNegotiateServiceCredential); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeEstablishSecurityContext() { return (this.EstablishSecurityContext != DefaultEstablishSecurityContext); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeIssuedKeyType() { return (this.IssuedKeyType != DefaultIssuedKeyType); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeTokenRequestParameters() { return (this.TokenRequestParameters.Count > 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { public partial class Process : IDisposable { private bool _haveMainWindow; private IntPtr _mainWindowHandle; private string _mainWindowTitle; private bool _haveResponding; private bool _responding; private bool StartCore(ProcessStartInfo startInfo) { return startInfo.UseShellExecute ? StartWithShellExecuteEx(startInfo) : StartWithCreateProcess(startInfo); } private unsafe bool StartWithShellExecuteEx(ProcessStartInfo startInfo) { if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password != null) throw new InvalidOperationException(SR.CantStartAsUser); if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) throw new InvalidOperationException(SR.CantRedirectStreams); if (startInfo.StandardErrorEncoding != null) throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); if (startInfo.StandardOutputEncoding != null) throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); if (startInfo._environmentVariables != null) throw new InvalidOperationException(SR.CantUseEnvVars); fixed (char* fileName = startInfo.FileName.Length > 0 ? startInfo.FileName : null) fixed (char* verb = startInfo.Verb.Length > 0 ? startInfo.Verb : null) fixed (char* parameters = startInfo.Arguments.Length > 0 ? startInfo.Arguments : null) fixed (char* directory = startInfo.WorkingDirectory.Length > 0 ? startInfo.WorkingDirectory : null) { Interop.Shell32.SHELLEXECUTEINFO shellExecuteInfo = new Interop.Shell32.SHELLEXECUTEINFO() { cbSize = (uint)sizeof(Interop.Shell32.SHELLEXECUTEINFO), lpFile = fileName, lpVerb = verb, lpParameters = parameters, lpDirectory = directory, fMask = Interop.Shell32.SEE_MASK_NOCLOSEPROCESS | Interop.Shell32.SEE_MASK_FLAG_DDEWAIT }; if (startInfo.ErrorDialog) shellExecuteInfo.hwnd = startInfo.ErrorDialogParentHandle; else shellExecuteInfo.fMask |= Interop.Shell32.SEE_MASK_FLAG_NO_UI; switch (startInfo.WindowStyle) { case ProcessWindowStyle.Hidden: shellExecuteInfo.nShow = Interop.Shell32.SW_HIDE; break; case ProcessWindowStyle.Minimized: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWMINIMIZED; break; case ProcessWindowStyle.Maximized: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWMAXIMIZED; break; default: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWNORMAL; break; } ShellExecuteHelper executeHelper = new ShellExecuteHelper(&shellExecuteInfo); if (!executeHelper.ShellExecuteOnSTAThread()) { int error = executeHelper.ErrorCode; if (error == 0) { error = GetShellError(shellExecuteInfo.hInstApp); } switch (error) { case Interop.Errors.ERROR_BAD_EXE_FORMAT: case Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH: throw new Win32Exception(error, SR.InvalidApplication); case Interop.Errors.ERROR_CALL_NOT_IMPLEMENTED: // This happens on Windows Nano throw new PlatformNotSupportedException(SR.UseShellExecuteNotSupported); default: throw new Win32Exception(error); } } if (shellExecuteInfo.hProcess != IntPtr.Zero) { SetProcessHandle(new SafeProcessHandle(shellExecuteInfo.hProcess)); return true; } } return false; } private int GetShellError(IntPtr error) { switch ((long)error) { case Interop.Shell32.SE_ERR_FNF: return Interop.Errors.ERROR_FILE_NOT_FOUND; case Interop.Shell32.SE_ERR_PNF: return Interop.Errors.ERROR_PATH_NOT_FOUND; case Interop.Shell32.SE_ERR_ACCESSDENIED: return Interop.Errors.ERROR_ACCESS_DENIED; case Interop.Shell32.SE_ERR_OOM: return Interop.Errors.ERROR_NOT_ENOUGH_MEMORY; case Interop.Shell32.SE_ERR_DDEFAIL: case Interop.Shell32.SE_ERR_DDEBUSY: case Interop.Shell32.SE_ERR_DDETIMEOUT: return Interop.Errors.ERROR_DDE_FAIL; case Interop.Shell32.SE_ERR_SHARE: return Interop.Errors.ERROR_SHARING_VIOLATION; case Interop.Shell32.SE_ERR_NOASSOC: return Interop.Errors.ERROR_NO_ASSOCIATION; case Interop.Shell32.SE_ERR_DLLNOTFOUND: return Interop.Errors.ERROR_DLL_NOT_FOUND; default: return (int)(long)error; } } internal unsafe class ShellExecuteHelper { private Interop.Shell32.SHELLEXECUTEINFO* _executeInfo; private bool _succeeded; private bool _notpresent; public ShellExecuteHelper(Interop.Shell32.SHELLEXECUTEINFO* executeInfo) { _executeInfo = executeInfo; } private void ShellExecuteFunction() { try { if (!(_succeeded = Interop.Shell32.ShellExecuteExW(_executeInfo))) ErrorCode = Marshal.GetLastWin32Error(); } catch (EntryPointNotFoundException) { _notpresent = true; } } public bool ShellExecuteOnSTAThread() { // ShellExecute() requires STA in order to work correctly. if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { ThreadStart threadStart = new ThreadStart(ShellExecuteFunction); Thread executionThread = new Thread(threadStart); executionThread.SetApartmentState(ApartmentState.STA); executionThread.Start(); executionThread.Join(); } else { ShellExecuteFunction(); } if (_notpresent) throw new PlatformNotSupportedException(SR.UseShellExecuteNotSupported); return _succeeded; } public int ErrorCode { get; private set; } } private string GetMainWindowTitle() { IntPtr handle = MainWindowHandle; if (handle == IntPtr.Zero) return string.Empty; int length = Interop.User32.GetWindowTextLengthW(handle); if (length == 0) { #if DEBUG // We never used to throw here, want to surface possible mistakes on our part int error = Marshal.GetLastWin32Error(); Debug.Assert(error == 0, $"Failed GetWindowTextLengthW(): { new Win32Exception(error).Message }"); #endif return string.Empty; } StringBuilder builder = new StringBuilder(length); length = Interop.User32.GetWindowTextW(handle, builder, builder.Capacity + 1); #if DEBUG if (length == 0) { // We never used to throw here, want to surface possible mistakes on our part int error = Marshal.GetLastWin32Error(); Debug.Assert(error == 0, $"Failed GetWindowTextW(): { new Win32Exception(error).Message }"); } #endif builder.Length = length; return builder.ToString(); } public IntPtr MainWindowHandle { get { if (!_haveMainWindow) { EnsureState(State.IsLocal | State.HaveId); _mainWindowHandle = ProcessManager.GetMainWindowHandle(_processId); _haveMainWindow = true; } return _mainWindowHandle; } } private bool CloseMainWindowCore() { const int GWL_STYLE = -16; // Retrieves the window styles. const int WS_DISABLED = 0x08000000; // WindowStyle disabled. A disabled window cannot receive input from the user. const int WM_CLOSE = 0x0010; // WindowMessage close. IntPtr mainWindowHandle = MainWindowHandle; if (mainWindowHandle == (IntPtr)0) { return false; } int style = Interop.User32.GetWindowLong(mainWindowHandle, GWL_STYLE); if ((style & WS_DISABLED) != 0) { return false; } Interop.User32.PostMessage(mainWindowHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); return true; } public string MainWindowTitle { get { if (_mainWindowTitle == null) { _mainWindowTitle = GetMainWindowTitle(); } return _mainWindowTitle; } } private bool IsRespondingCore() { const int WM_NULL = 0x0000; const int SMTO_ABORTIFHUNG = 0x0002; IntPtr mainWindow = MainWindowHandle; if (mainWindow == (IntPtr)0) { return true; } IntPtr result; return Interop.User32.SendMessageTimeout(mainWindow, WM_NULL, IntPtr.Zero, IntPtr.Zero, SMTO_ABORTIFHUNG, 5000, out result) != (IntPtr)0; } public bool Responding { get { if (!_haveResponding) { _responding = IsRespondingCore(); _haveResponding = true; } return _responding; } } private bool WaitForInputIdleCore(int milliseconds) { const int WAIT_OBJECT_0 = 0x00000000; const int WAIT_FAILED = unchecked((int)0xFFFFFFFF); const int WAIT_TIMEOUT = 0x00000102; bool idle; using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.SYNCHRONIZE | Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int ret = Interop.User32.WaitForInputIdle(handle, milliseconds); switch (ret) { case WAIT_OBJECT_0: idle = true; break; case WAIT_TIMEOUT: idle = false; break; case WAIT_FAILED: default: throw new InvalidOperationException(SR.InputIdleUnkownError); } } return idle; } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * 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 Microsoft.Exchange.WebServices.Data { using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents the schema for generic items. /// </summary> [Schema] public class ItemSchema : ServiceObjectSchema { /// <summary> /// Field URIs for Item. /// </summary> private static class FieldUris { public const string ItemId = "item:ItemId"; public const string ParentFolderId = "item:ParentFolderId"; public const string ItemClass = "item:ItemClass"; public const string MimeContent = "item:MimeContent"; public const string MimeContentUTF8 = "item:MimeContentUTF8"; public const string Attachments = "item:Attachments"; public const string Subject = "item:Subject"; public const string DateTimeReceived = "item:DateTimeReceived"; public const string Size = "item:Size"; public const string Categories = "item:Categories"; public const string HasAttachments = "item:HasAttachments"; public const string Importance = "item:Importance"; public const string InReplyTo = "item:InReplyTo"; public const string InternetMessageHeaders = "item:InternetMessageHeaders"; public const string IsAssociated = "item:IsAssociated"; public const string IsDraft = "item:IsDraft"; public const string IsFromMe = "item:IsFromMe"; public const string IsResend = "item:IsResend"; public const string IsSubmitted = "item:IsSubmitted"; public const string IsUnmodified = "item:IsUnmodified"; public const string DateTimeSent = "item:DateTimeSent"; public const string DateTimeCreated = "item:DateTimeCreated"; public const string Body = "item:Body"; public const string ResponseObjects = "item:ResponseObjects"; public const string Sensitivity = "item:Sensitivity"; public const string ReminderDueBy = "item:ReminderDueBy"; public const string ReminderIsSet = "item:ReminderIsSet"; public const string ReminderMinutesBeforeStart = "item:ReminderMinutesBeforeStart"; public const string DisplayTo = "item:DisplayTo"; public const string DisplayCc = "item:DisplayCc"; public const string Culture = "item:Culture"; public const string EffectiveRights = "item:EffectiveRights"; public const string LastModifiedName = "item:LastModifiedName"; public const string LastModifiedTime = "item:LastModifiedTime"; public const string WebClientReadFormQueryString = "item:WebClientReadFormQueryString"; public const string WebClientEditFormQueryString = "item:WebClientEditFormQueryString"; public const string ConversationId = "item:ConversationId"; public const string UniqueBody = "item:UniqueBody"; public const string StoreEntryId = "item:StoreEntryId"; public const string InstanceKey = "item:InstanceKey"; public const string NormalizedBody = "item:NormalizedBody"; public const string EntityExtractionResult = "item:EntityExtractionResult"; public const string Flag = "item:Flag"; public const string PolicyTag = "item:PolicyTag"; public const string ArchiveTag = "item:ArchiveTag"; public const string RetentionDate = "item:RetentionDate"; public const string Preview = "item:Preview"; public const string TextBody = "item:TextBody"; public const string IconIndex = "item:IconIndex"; } /// <summary> /// Defines the Id property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Id = new ComplexPropertyDefinition<ItemId>( XmlElementNames.ItemId, FieldUris.ItemId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, delegate() { return new ItemId(); }); /// <summary> /// Defines the Body property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Body = new ComplexPropertyDefinition<MessageBody>( XmlElementNames.Body, FieldUris.Body, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, delegate() { return new MessageBody(); }); /// <summary> /// Defines the ItemClass property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ItemClass = new StringPropertyDefinition( XmlElementNames.ItemClass, FieldUris.ItemClass, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the Subject property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Subject = new StringPropertyDefinition( XmlElementNames.Subject, FieldUris.Subject, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the MimeContent property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MimeContent = new ComplexPropertyDefinition<MimeContent>( XmlElementNames.MimeContent, FieldUris.MimeContent, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2007_SP1, delegate() { return new MimeContent(); }); /// <summary> /// Defines the MimeContentUTF8 property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MimeContentUTF8 = new ComplexPropertyDefinition<MimeContentUTF8>( XmlElementNames.MimeContentUTF8, FieldUris.MimeContentUTF8, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2013_SP1, delegate() { return new MimeContentUTF8(); }); /// <summary> /// Defines the ParentFolderId property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ParentFolderId = new ComplexPropertyDefinition<FolderId>( XmlElementNames.ParentFolderId, FieldUris.ParentFolderId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, delegate() { return new FolderId(); }); /// <summary> /// Defines the Sensitivity property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Sensitivity = new GenericPropertyDefinition<Sensitivity>( XmlElementNames.Sensitivity, FieldUris.Sensitivity, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the Attachments property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Attachments = new AttachmentsPropertyDefinition(); /// <summary> /// Defines the DateTimeReceived property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition DateTimeReceived = new DateTimePropertyDefinition( XmlElementNames.DateTimeReceived, FieldUris.DateTimeReceived, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the Size property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Size = new IntPropertyDefinition( XmlElementNames.Size, FieldUris.Size, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the Categories property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Categories = new ComplexPropertyDefinition<StringList>( XmlElementNames.Categories, FieldUris.Categories, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, delegate() { return new StringList(); }); /// <summary> /// Defines the Importance property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Importance = new GenericPropertyDefinition<Importance>( XmlElementNames.Importance, FieldUris.Importance, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the InReplyTo property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition InReplyTo = new StringPropertyDefinition( XmlElementNames.InReplyTo, FieldUris.InReplyTo, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the IsSubmitted property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsSubmitted = new BoolPropertyDefinition( XmlElementNames.IsSubmitted, FieldUris.IsSubmitted, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the IsAssociated property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsAssociated = new BoolPropertyDefinition( XmlElementNames.IsAssociated, FieldUris.IsAssociated, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010); /// <summary> /// Defines the IsDraft property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsDraft = new BoolPropertyDefinition( XmlElementNames.IsDraft, FieldUris.IsDraft, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the IsFromMe property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsFromMe = new BoolPropertyDefinition( XmlElementNames.IsFromMe, FieldUris.IsFromMe, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the IsResend property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsResend = new BoolPropertyDefinition( XmlElementNames.IsResend, FieldUris.IsResend, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the IsUnmodified property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsUnmodified = new BoolPropertyDefinition( XmlElementNames.IsUnmodified, FieldUris.IsUnmodified, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the InternetMessageHeaders property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition InternetMessageHeaders = new ComplexPropertyDefinition<InternetMessageHeaderCollection>( XmlElementNames.InternetMessageHeaders, FieldUris.InternetMessageHeaders, ExchangeVersion.Exchange2007_SP1, delegate() { return new InternetMessageHeaderCollection(); }); /// <summary> /// Defines the DateTimeSent property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition DateTimeSent = new DateTimePropertyDefinition( XmlElementNames.DateTimeSent, FieldUris.DateTimeSent, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the DateTimeCreated property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition DateTimeCreated = new DateTimePropertyDefinition( XmlElementNames.DateTimeCreated, FieldUris.DateTimeCreated, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the AllowedResponseActions property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AllowedResponseActions = new ResponseObjectsPropertyDefinition( XmlElementNames.ResponseObjects, FieldUris.ResponseObjects, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the ReminderDueBy property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ReminderDueBy = new ScopedDateTimePropertyDefinition( XmlElementNames.ReminderDueBy, FieldUris.ReminderDueBy, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, delegate(ExchangeVersion version) { return AppointmentSchema.StartTimeZone; }); /// <summary> /// Defines the IsReminderSet property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsReminderSet = new BoolPropertyDefinition( XmlElementNames.ReminderIsSet, // Note: server-side the name is ReminderIsSet FieldUris.ReminderIsSet, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the ReminderMinutesBeforeStart property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ReminderMinutesBeforeStart = new IntPropertyDefinition( XmlElementNames.ReminderMinutesBeforeStart, FieldUris.ReminderMinutesBeforeStart, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the DisplayCc property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition DisplayCc = new StringPropertyDefinition( XmlElementNames.DisplayCc, FieldUris.DisplayCc, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the DisplayTo property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition DisplayTo = new StringPropertyDefinition( XmlElementNames.DisplayTo, FieldUris.DisplayTo, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the HasAttachments property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition HasAttachments = new BoolPropertyDefinition( XmlElementNames.HasAttachments, FieldUris.HasAttachments, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the Culture property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Culture = new StringPropertyDefinition( XmlElementNames.Culture, FieldUris.Culture, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the EffectiveRights property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition EffectiveRights = new EffectiveRightsPropertyDefinition( XmlElementNames.EffectiveRights, FieldUris.EffectiveRights, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the LastModifiedName property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition LastModifiedName = new StringPropertyDefinition( XmlElementNames.LastModifiedName, FieldUris.LastModifiedName, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the LastModifiedTime property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition LastModifiedTime = new DateTimePropertyDefinition( XmlElementNames.LastModifiedTime, FieldUris.LastModifiedTime, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the WebClientReadFormQueryString property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition WebClientReadFormQueryString = new StringPropertyDefinition( XmlElementNames.WebClientReadFormQueryString, FieldUris.WebClientReadFormQueryString, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010); /// <summary> /// Defines the WebClientEditFormQueryString property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition WebClientEditFormQueryString = new StringPropertyDefinition( XmlElementNames.WebClientEditFormQueryString, FieldUris.WebClientEditFormQueryString, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010); /// <summary> /// Defines the ConversationId property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ConversationId = new ComplexPropertyDefinition<ConversationId>( XmlElementNames.ConversationId, FieldUris.ConversationId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010, delegate() { return new ConversationId(); }); /// <summary> /// Defines the UniqueBody property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition UniqueBody = new ComplexPropertyDefinition<UniqueBody>( XmlElementNames.UniqueBody, FieldUris.UniqueBody, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2010, delegate() { return new UniqueBody(); }); /// <summary> /// Defines the StoreEntryId property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition StoreEntryId = new ByteArrayPropertyDefinition( XmlElementNames.StoreEntryId, FieldUris.StoreEntryId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP2); /// <summary> /// Defines the InstanceKey property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition InstanceKey = new ByteArrayPropertyDefinition( XmlElementNames.InstanceKey, FieldUris.InstanceKey, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013); /// <summary> /// Defines the NormalizedBody property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition NormalizedBody = new ComplexPropertyDefinition<NormalizedBody>( XmlElementNames.NormalizedBody, FieldUris.NormalizedBody, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2013, delegate() { return new NormalizedBody(); }); /// <summary> /// Defines the EntityExtractionResult property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition EntityExtractionResult = new ComplexPropertyDefinition<EntityExtractionResult>( XmlElementNames.NlgEntityExtractionResult, FieldUris.EntityExtractionResult, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2013, delegate() { return new EntityExtractionResult(); }); /// <summary> /// Defines the InternetMessageHeaders property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Flag = new ComplexPropertyDefinition<Flag>( XmlElementNames.Flag, FieldUris.Flag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, delegate() { return new Flag(); }); /// <summary> /// Defines the PolicyTag property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition PolicyTag = new ComplexPropertyDefinition<PolicyTag>( XmlElementNames.PolicyTag, FieldUris.PolicyTag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, delegate() { return new PolicyTag(); }); /// <summary> /// Defines the ArchiveTag property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ArchiveTag = new ComplexPropertyDefinition<ArchiveTag>( XmlElementNames.ArchiveTag, FieldUris.ArchiveTag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, delegate() { return new ArchiveTag(); }); /// <summary> /// Defines the RetentionDate property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition RetentionDate = new DateTimePropertyDefinition( XmlElementNames.RetentionDate, FieldUris.RetentionDate, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, true); /// <summary> /// Defines the Preview property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Preview = new StringPropertyDefinition( XmlElementNames.Preview, FieldUris.Preview, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013); /// <summary> /// Defines the TextBody property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition TextBody = new ComplexPropertyDefinition<TextBody>( XmlElementNames.TextBody, FieldUris.TextBody, PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2013, delegate() { return new TextBody(); }); /// <summary> /// Defines the IconIndex property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IconIndex = new GenericPropertyDefinition<IconIndex>( XmlElementNames.IconIndex, FieldUris.IconIndex, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013); // This must be declared after the property definitions internal static readonly ItemSchema Instance = new ItemSchema(); /// <summary> /// Registers properties. /// </summary> /// <remarks> /// IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) /// </remarks> internal override void RegisterProperties() { base.RegisterProperties(); this.RegisterProperty(MimeContent); this.RegisterProperty(Id); this.RegisterProperty(ParentFolderId); this.RegisterProperty(ItemClass); this.RegisterProperty(Subject); this.RegisterProperty(Sensitivity); this.RegisterProperty(Body); this.RegisterProperty(Attachments); this.RegisterProperty(DateTimeReceived); this.RegisterProperty(Size); this.RegisterProperty(Categories); this.RegisterProperty(Importance); this.RegisterProperty(InReplyTo); this.RegisterProperty(IsSubmitted); this.RegisterProperty(IsDraft); this.RegisterProperty(IsFromMe); this.RegisterProperty(IsResend); this.RegisterProperty(IsUnmodified); this.RegisterProperty(InternetMessageHeaders); this.RegisterProperty(DateTimeSent); this.RegisterProperty(DateTimeCreated); this.RegisterProperty(AllowedResponseActions); this.RegisterProperty(ReminderDueBy); this.RegisterProperty(IsReminderSet); this.RegisterProperty(ReminderMinutesBeforeStart); this.RegisterProperty(DisplayCc); this.RegisterProperty(DisplayTo); this.RegisterProperty(HasAttachments); this.RegisterProperty(ServiceObjectSchema.ExtendedProperties); this.RegisterProperty(Culture); this.RegisterProperty(EffectiveRights); this.RegisterProperty(LastModifiedName); this.RegisterProperty(LastModifiedTime); this.RegisterProperty(IsAssociated); this.RegisterProperty(WebClientReadFormQueryString); this.RegisterProperty(WebClientEditFormQueryString); this.RegisterProperty(ConversationId); this.RegisterProperty(UniqueBody); this.RegisterProperty(Flag); this.RegisterProperty(StoreEntryId); this.RegisterProperty(InstanceKey); this.RegisterProperty(NormalizedBody); this.RegisterProperty(EntityExtractionResult); this.RegisterProperty(PolicyTag); this.RegisterProperty(ArchiveTag); this.RegisterProperty(RetentionDate); this.RegisterProperty(Preview); this.RegisterProperty(TextBody); this.RegisterProperty(IconIndex); this.RegisterProperty(MimeContentUTF8); } /// <summary> /// Initializes a new instance of the <see cref="ItemSchema"/> class. /// </summary> internal ItemSchema() : base() { } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.CrossDomainLibWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace System.Net.Http.Headers { // This type is used to store a collection of headers in 'headerStore': // - A header can have multiple values. // - A header can have an associated parser which is able to parse the raw string value into a strongly typed object. // - If a header has an associated parser and the provided raw value can't be parsed, the value is considered // invalid. Invalid values are stored if added using TryAddWithoutValidation(). If the value was added using Add(), // Add() will throw FormatException. // - Since parsing header values is expensive and users usually only care about a few headers, header values are // lazily initialized. // // Given the properties above, a header value can have three states: // - 'raw': The header value was added using TryAddWithoutValidation() and it wasn't parsed yet. // - 'parsed': The header value was successfully parsed. It was either added using Add() where the value was parsed // immediately, or if added using TryAddWithoutValidation() a user already accessed a property/method triggering the // value to be parsed. // - 'invalid': The header value was parsed, but parsing failed because the value is invalid. Storing invalid values // allows users to still retrieve the value (by calling GetValues()), but it will not be exposed as strongly typed // object. E.g. the client receives a response with the following header: 'Via: 1.1 proxy, invalid' // - HttpHeaders.GetValues() will return "1.1 proxy", "invalid" // - HttpResponseHeaders.Via collection will only contain one ViaHeaderValue object with value "1.1 proxy" [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is not a collection")] public abstract class HttpHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>> { private Dictionary<HeaderDescriptor, HeaderStoreItemInfo> _headerStore; private readonly HttpHeaderType _allowedHeaderTypes; private readonly HttpHeaderType _treatAsCustomHeaderTypes; private enum StoreLocation { Raw, Invalid, Parsed } protected HttpHeaders() : this(HttpHeaderType.All, HttpHeaderType.None) { } internal HttpHeaders(HttpHeaderType allowedHeaderTypes, HttpHeaderType treatAsCustomHeaderTypes) { // Should be no overlap Debug.Assert((allowedHeaderTypes & treatAsCustomHeaderTypes) == 0); _allowedHeaderTypes = allowedHeaderTypes; _treatAsCustomHeaderTypes = treatAsCustomHeaderTypes; } internal Dictionary<HeaderDescriptor, HeaderStoreItemInfo> HeaderStore => _headerStore; public void Add(string name, string value) { Add(GetHeaderDescriptor(name), value); } internal void Add(HeaderDescriptor descriptor, string value) { // We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing // the value then throws, we would have to remove the header from the store again. So just get a // HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header. HeaderStoreItemInfo info; bool addToStore; PrepareHeaderInfoForAdd(descriptor, out info, out addToStore); ParseAndAddValue(descriptor, info, value); // If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add // it to the store if we added at least one value. if (addToStore && (info.ParsedValue != null)) { AddHeaderToStore(descriptor, info); } } public void Add(string name, IEnumerable<string> values) { Add(GetHeaderDescriptor(name), values); } internal void Add(HeaderDescriptor descriptor, IEnumerable<string> values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } HeaderStoreItemInfo info; bool addToStore; PrepareHeaderInfoForAdd(descriptor, out info, out addToStore); try { // Note that if the first couple of values are valid followed by an invalid value, the valid values // will be added to the store before the exception for the invalid value is thrown. foreach (string value in values) { ParseAndAddValue(descriptor, info, value); } } finally { // Even if one of the values was invalid, make sure we add the header for the valid ones. We need to be // consistent here: If values get added to an _existing_ header, then all values until the invalid one // get added. Same here: If multiple values get added to a _new_ header, make sure the header gets added // with the valid values. // However, if all values for a _new_ header were invalid, then don't add the header. if (addToStore && (info.ParsedValue != null)) { AddHeaderToStore(descriptor, info); } } } public bool TryAddWithoutValidation(string name, string value) => TryGetHeaderDescriptor(name, out HeaderDescriptor descriptor) && TryAddWithoutValidation(descriptor, value); internal bool TryAddWithoutValidation(HeaderDescriptor descriptor, string value) { if (value == null) { // We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty // values, we'll just add them to the collection. This will result in delimiter-only values: // E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,". value = string.Empty; } HeaderStoreItemInfo info = GetOrCreateHeaderInfo(descriptor, false); AddValue(info, value, StoreLocation.Raw); return true; } public bool TryAddWithoutValidation(string name, IEnumerable<string> values) => TryGetHeaderDescriptor(name, out HeaderDescriptor descriptor) && TryAddWithoutValidation(descriptor, values); internal bool TryAddWithoutValidation(HeaderDescriptor descriptor, IEnumerable<string> values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } HeaderStoreItemInfo info = GetOrCreateHeaderInfo(descriptor, false); foreach (string value in values) { // We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty // values, we'll just add them to the collection. This will result in delimiter-only values: // E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,". AddValue(info, value ?? string.Empty, StoreLocation.Raw); } return true; } public void Clear() { if (_headerStore != null) { _headerStore.Clear(); } } public bool Remove(string name) { return Remove(GetHeaderDescriptor(name)); } public IEnumerable<string> GetValues(string name) { return GetValues(GetHeaderDescriptor(name)); } internal IEnumerable<string> GetValues(HeaderDescriptor descriptor) { IEnumerable<string> values; if (!TryGetValues(descriptor, out values)) { throw new InvalidOperationException(SR.net_http_headers_not_found); } return values; } public bool TryGetValues(string name, out IEnumerable<string> values) { HeaderDescriptor descriptor; if (!TryGetHeaderDescriptor(name, out descriptor)) { values = null; return false; } return TryGetValues(descriptor, out values); } internal bool TryGetValues(HeaderDescriptor descriptor, out IEnumerable<string> values) { if (_headerStore == null) { values = null; return false; } HeaderStoreItemInfo info = null; if (TryGetAndParseHeaderInfo(descriptor, out info)) { values = GetValuesAsStrings(descriptor, info); return true; } values = null; return false; } public bool Contains(string name) { return Contains(GetHeaderDescriptor(name)); } internal bool Contains(HeaderDescriptor descriptor) { if (_headerStore == null) { return false; } // We can't just call headerStore.ContainsKey() since after parsing the value the header may not exist // anymore (if the value contains invalid newline chars, we remove the header). So try to parse the // header value. HeaderStoreItemInfo info = null; return TryGetAndParseHeaderInfo(descriptor, out info); } public override string ToString() { if (_headerStore == null || _headerStore.Count == 0) { return string.Empty; } // Return all headers as string similar to: // HeaderName1: Value1, Value2 // HeaderName2: Value1 // ... var sb = new StringBuilder(); foreach (KeyValuePair<string, string> header in GetHeaderStrings()) { sb.Append(header.Key).Append(": ").AppendLine(header.Value); } return sb.ToString(); } internal IEnumerable<KeyValuePair<string, string>> GetHeaderStrings() { if (_headerStore == null) { yield break; } foreach (KeyValuePair<HeaderDescriptor, HeaderStoreItemInfo> header in _headerStore) { string stringValue = GetHeaderString(header.Key, header.Value); yield return new KeyValuePair<string, string>(header.Key.Name, stringValue); } } internal string GetHeaderString(string name) { if (!TryGetHeaderDescriptor(name, out HeaderDescriptor descriptor)) { return string.Empty; } return GetHeaderString(descriptor); } internal string GetHeaderString(HeaderDescriptor descriptor, object exclude = null) { HeaderStoreItemInfo info; if (!TryGetHeaderInfo(descriptor, out info)) { return string.Empty; } return GetHeaderString(descriptor, info, exclude); } private string GetHeaderString(HeaderDescriptor descriptor, HeaderStoreItemInfo info, object exclude = null) { string stringValue; string[] values = GetValuesAsStrings(descriptor, info, exclude); if (values.Length == 1) { stringValue = values[0]; } else { // Note that if we get multiple values for a header that doesn't support multiple values, we'll // just separate the values using a comma (default separator). string separator = HttpHeaderParser.DefaultSeparator; if ((descriptor.Parser != null) && (descriptor.Parser.SupportsMultipleValues)) { separator = descriptor.Parser.Separator; } stringValue = string.Join(separator, values); } return stringValue; } #region IEnumerable<KeyValuePair<string, IEnumerable<string>>> Members public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator() { return _headerStore != null && _headerStore.Count > 0 ? GetEnumeratorCore() : ((IEnumerable<KeyValuePair<string, IEnumerable<string>>>)Array.Empty<KeyValuePair<string, IEnumerable<string>>>()).GetEnumerator(); } private IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumeratorCore() { foreach (KeyValuePair<HeaderDescriptor, HeaderStoreItemInfo> header in _headerStore) { HeaderDescriptor descriptor = header.Key; HeaderStoreItemInfo info = header.Value; // Make sure we parse all raw values before returning the result. Note that this has to be // done before we calculate the array length (next line): A raw value may contain a list of // values. if (!ParseRawHeaderValues(descriptor, info, false)) { // We have an invalid header value (contains invalid newline chars). Delete it. _headerStore.Remove(descriptor); } else { string[] values = GetValuesAsStrings(descriptor, info); yield return new KeyValuePair<string, IEnumerable<string>>(descriptor.Name, values); } } } #endregion #region IEnumerable Members Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion internal void AddParsedValue(HeaderDescriptor descriptor, object value) { Debug.Assert(value != null); Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); HeaderStoreItemInfo info = GetOrCreateHeaderInfo(descriptor, true); // If the current header has only one value, we can't add another value. The strongly typed property // must not call AddParsedValue(), but SetParsedValue(). E.g. for headers like 'Date', 'Host'. Debug.Assert(descriptor.Parser.SupportsMultipleValues, $"Header '{descriptor.Name}' doesn't support multiple values"); AddValue(info, value, StoreLocation.Parsed); } internal void SetParsedValue(HeaderDescriptor descriptor, object value) { Debug.Assert(value != null); Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); // This method will first clear all values. This is used e.g. when setting the 'Date' or 'Host' header. // I.e. headers not supporting collections. HeaderStoreItemInfo info = GetOrCreateHeaderInfo(descriptor, true); info.InvalidValue = null; info.ParsedValue = null; info.RawValue = null; AddValue(info, value, StoreLocation.Parsed); } internal void SetOrRemoveParsedValue(HeaderDescriptor descriptor, object value) { if (value == null) { Remove(descriptor); } else { SetParsedValue(descriptor, value); } } internal bool Remove(HeaderDescriptor descriptor) { if (_headerStore == null) { return false; } return _headerStore.Remove(descriptor); } internal bool RemoveParsedValue(HeaderDescriptor descriptor, object value) { Debug.Assert(value != null); if (_headerStore == null) { return false; } // If we have a value for this header, then verify if we have a single value. If so, compare that // value with 'item'. If we have a list of values, then remove 'item' from the list. HeaderStoreItemInfo info = null; if (TryGetAndParseHeaderInfo(descriptor, out info)) { Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); Debug.Assert(descriptor.Parser.SupportsMultipleValues, "This method should not be used for single-value headers. Use Remove(string) instead."); bool result = false; // If there is no entry, just return. if (info.ParsedValue == null) { return false; } IEqualityComparer comparer = descriptor.Parser.Comparer; List<object> parsedValues = info.ParsedValue as List<object>; if (parsedValues == null) { Debug.Assert(info.ParsedValue.GetType() == value.GetType(), "Stored value does not have the same type as 'value'."); if (AreEqual(value, info.ParsedValue, comparer)) { info.ParsedValue = null; result = true; } } else { foreach (object item in parsedValues) { Debug.Assert(item.GetType() == value.GetType(), "One of the stored values does not have the same type as 'value'."); if (AreEqual(value, item, comparer)) { // Remove 'item' rather than 'value', since the 'comparer' may consider two values // equal even though the default obj.Equals() may not (e.g. if 'comparer' does // case-insensitive comparison for strings, but string.Equals() is case-sensitive). result = parsedValues.Remove(item); break; } } // If we removed the last item in a list, remove the list. if (parsedValues.Count == 0) { info.ParsedValue = null; } } // If there is no value for the header left, remove the header. if (info.IsEmpty) { bool headerRemoved = Remove(descriptor); Debug.Assert(headerRemoved, "Existing header '" + descriptor.Name + "' couldn't be removed."); } return result; } return false; } internal bool ContainsParsedValue(HeaderDescriptor descriptor, object value) { Debug.Assert(value != null); if (_headerStore == null) { return false; } // If we have a value for this header, then verify if we have a single value. If so, compare that // value with 'item'. If we have a list of values, then compare each item in the list with 'item'. HeaderStoreItemInfo info = null; if (TryGetAndParseHeaderInfo(descriptor, out info)) { Debug.Assert(descriptor.Parser != null, "Can't add parsed value if there is no parser available."); Debug.Assert(descriptor.Parser.SupportsMultipleValues, "This method should not be used for single-value headers. Use equality comparer instead."); // If there is no entry, just return. if (info.ParsedValue == null) { return false; } List<object> parsedValues = info.ParsedValue as List<object>; IEqualityComparer comparer = descriptor.Parser.Comparer; if (parsedValues == null) { Debug.Assert(info.ParsedValue.GetType() == value.GetType(), "Stored value does not have the same type as 'value'."); return AreEqual(value, info.ParsedValue, comparer); } else { foreach (object item in parsedValues) { Debug.Assert(item.GetType() == value.GetType(), "One of the stored values does not have the same type as 'value'."); if (AreEqual(value, item, comparer)) { return true; } } return false; } } return false; } internal virtual void AddHeaders(HttpHeaders sourceHeaders) { Debug.Assert(sourceHeaders != null); Debug.Assert(GetType() == sourceHeaders.GetType(), "Can only copy headers from an instance of the same type."); if (sourceHeaders._headerStore == null) { return; } foreach (KeyValuePair<HeaderDescriptor, HeaderStoreItemInfo> header in sourceHeaders._headerStore) { // Only add header values if they're not already set on the message. Note that we don't merge // collections: If both the default headers and the message have set some values for a certain // header, then we don't try to merge the values. if ((_headerStore == null) || (!_headerStore.ContainsKey(header.Key))) { HeaderStoreItemInfo sourceInfo = header.Value; // If DefaultRequestHeaders values are copied to multiple messages, it is useful to parse these // default header values only once. This is what we're doing here: By parsing raw headers in // 'sourceHeaders' before copying values to our header store. if (!sourceHeaders.ParseRawHeaderValues(header.Key, sourceInfo, false)) { // If after trying to parse source header values no value is left (i.e. all values contain // invalid newline chars), delete it and skip to the next header. sourceHeaders._headerStore.Remove(header.Key); } else { AddHeaderInfo(header.Key, sourceInfo); } } } } private void AddHeaderInfo(HeaderDescriptor descriptor, HeaderStoreItemInfo sourceInfo) { HeaderStoreItemInfo destinationInfo = CreateAndAddHeaderToStore(descriptor); // We have custom header values. The parsed values are strings. if (descriptor.Parser == null) { Debug.Assert((sourceInfo.RawValue == null) && (sourceInfo.InvalidValue == null), "No raw or invalid values expected for custom headers."); // Custom header values are always stored as string or list of strings. destinationInfo.ParsedValue = CloneStringHeaderInfoValues(sourceInfo.ParsedValue); } else { // We have a parser, so we have to copy invalid values and clone parsed values. // Invalid values are always strings. Strings are immutable. So we only have to clone the // collection (if there is one). destinationInfo.InvalidValue = CloneStringHeaderInfoValues(sourceInfo.InvalidValue); // Now clone and add parsed values (if any). if (sourceInfo.ParsedValue != null) { List<object> sourceValues = sourceInfo.ParsedValue as List<object>; if (sourceValues == null) { CloneAndAddValue(destinationInfo, sourceInfo.ParsedValue); } else { foreach (object item in sourceValues) { CloneAndAddValue(destinationInfo, item); } } } } } private static void CloneAndAddValue(HeaderStoreItemInfo destinationInfo, object source) { // We only have one value. Clone it and assign it to the store. ICloneable cloneableValue = source as ICloneable; if (cloneableValue != null) { AddValue(destinationInfo, cloneableValue.Clone(), StoreLocation.Parsed); } else { // If it doesn't implement ICloneable, it's a value type or an immutable type like String/Uri. AddValue(destinationInfo, source, StoreLocation.Parsed); } } private static object CloneStringHeaderInfoValues(object source) { if (source == null) { return null; } List<object> sourceValues = source as List<object>; if (sourceValues == null) { // If we just have one value, return the reference to the string (strings are immutable so it's OK // to use the reference). return source; } else { // If we have a list of strings, create a new list and copy all strings to the new list. return new List<object>(sourceValues); } } private HeaderStoreItemInfo GetOrCreateHeaderInfo(HeaderDescriptor descriptor, bool parseRawValues) { HeaderStoreItemInfo result = null; bool found = false; if (parseRawValues) { found = TryGetAndParseHeaderInfo(descriptor, out result); } else { found = TryGetHeaderInfo(descriptor, out result); } if (!found) { result = CreateAndAddHeaderToStore(descriptor); } Debug.Assert(result != null); return result; } private HeaderStoreItemInfo CreateAndAddHeaderToStore(HeaderDescriptor descriptor) { // If we don't have the header in the store yet, add it now. HeaderStoreItemInfo result = new HeaderStoreItemInfo(); // If the descriptor header type is in _treatAsCustomHeaderTypes, it must be converted to a custom header before calling this method Debug.Assert((descriptor.HeaderType & _treatAsCustomHeaderTypes) == 0); AddHeaderToStore(descriptor, result); return result; } private void AddHeaderToStore(HeaderDescriptor descriptor, HeaderStoreItemInfo info) { if (_headerStore == null) { _headerStore = new Dictionary<HeaderDescriptor, HeaderStoreItemInfo>(); } _headerStore.Add(descriptor, info); } private bool TryGetHeaderInfo(HeaderDescriptor descriptor, out HeaderStoreItemInfo info) { if (_headerStore == null) { info = null; return false; } return _headerStore.TryGetValue(descriptor, out info); } private bool TryGetAndParseHeaderInfo(HeaderDescriptor key, out HeaderStoreItemInfo info) { if (TryGetHeaderInfo(key, out info)) { return ParseRawHeaderValues(key, info, true); } return false; } private bool ParseRawHeaderValues(HeaderDescriptor descriptor, HeaderStoreItemInfo info, bool removeEmptyHeader) { // Prevent multiple threads from parsing the raw value at the same time, or else we would get // false duplicates or false nulls. lock (info) { // Unlike TryGetHeaderInfo() this method tries to parse all non-validated header values (if any) // before returning to the caller. if (info.RawValue != null) { List<string> rawValues = info.RawValue as List<string>; if (rawValues == null) { ParseSingleRawHeaderValue(descriptor, info); } else { ParseMultipleRawHeaderValues(descriptor, info, rawValues); } // At this point all values are either in info.ParsedValue, info.InvalidValue, or were removed since they // contain invalid newline chars. Reset RawValue. info.RawValue = null; // During parsing, we removed the value since it contains invalid newline chars. Return false to indicate that // this is an empty header. If the caller specified to remove empty headers, we'll remove the header before // returning. if ((info.InvalidValue == null) && (info.ParsedValue == null)) { if (removeEmptyHeader) { // After parsing the raw value, no value is left because all values contain invalid newline // chars. Debug.Assert(_headerStore != null); _headerStore.Remove(descriptor); } return false; } } } return true; } private static void ParseMultipleRawHeaderValues(HeaderDescriptor descriptor, HeaderStoreItemInfo info, List<string> rawValues) { if (descriptor.Parser == null) { foreach (string rawValue in rawValues) { if (!ContainsInvalidNewLine(rawValue, descriptor.Name)) { AddValue(info, rawValue, StoreLocation.Parsed); } } } else { foreach (string rawValue in rawValues) { if (!TryParseAndAddRawHeaderValue(descriptor, info, rawValue, true)) { if (NetEventSource.IsEnabled) NetEventSource.Log.HeadersInvalidValue(descriptor.Name, rawValue); } } } } private static void ParseSingleRawHeaderValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info) { string rawValue = info.RawValue as string; Debug.Assert(rawValue != null, "RawValue must either be List<string> or string."); if (descriptor.Parser == null) { if (!ContainsInvalidNewLine(rawValue, descriptor.Name)) { AddValue(info, rawValue, StoreLocation.Parsed); } } else { if (!TryParseAndAddRawHeaderValue(descriptor, info, rawValue, true)) { if (NetEventSource.IsEnabled) NetEventSource.Log.HeadersInvalidValue(descriptor.Name, rawValue); } } } // See Add(name, string) internal bool TryParseAndAddValue(HeaderDescriptor descriptor, string value) { // We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing // the value then throws, we would have to remove the header from the store again. So just get a // HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header. HeaderStoreItemInfo info; bool addToStore; PrepareHeaderInfoForAdd(descriptor, out info, out addToStore); bool result = TryParseAndAddRawHeaderValue(descriptor, info, value, false); if (result && addToStore && (info.ParsedValue != null)) { // If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add // it to the store if we added at least one value. AddHeaderToStore(descriptor, info); } return result; } // See ParseAndAddValue private static bool TryParseAndAddRawHeaderValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, string value, bool addWhenInvalid) { Debug.Assert(info != null); Debug.Assert(descriptor.Parser != null); // Values are added as 'invalid' if we either can't parse the value OR if we already have a value // and the current header doesn't support multiple values: e.g. trying to add a date/time value // to the 'Date' header if we already have a date/time value will result in the second value being // added to the 'invalid' header values. if (!info.CanAddValue(descriptor.Parser)) { if (addWhenInvalid) { AddValue(info, value ?? string.Empty, StoreLocation.Invalid); } return false; } int index = 0; object parsedValue = null; if (descriptor.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue)) { // The raw string only represented one value (which was successfully parsed). Add the value and return. if ((value == null) || (index == value.Length)) { if (parsedValue != null) { AddValue(info, parsedValue, StoreLocation.Parsed); } return true; } Debug.Assert(index < value.Length, "Parser must return an index value within the string length."); // If we successfully parsed a value, but there are more left to read, store the results in a temp // list. Only when all values are parsed successfully write the list to the store. List<object> parsedValues = new List<object>(); if (parsedValue != null) { parsedValues.Add(parsedValue); } while (index < value.Length) { if (descriptor.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue)) { if (parsedValue != null) { parsedValues.Add(parsedValue); } } else { if (!ContainsInvalidNewLine(value, descriptor.Name) && addWhenInvalid) { AddValue(info, value, StoreLocation.Invalid); } return false; } } // All values were parsed correctly. Copy results to the store. foreach (object item in parsedValues) { AddValue(info, item, StoreLocation.Parsed); } return true; } if (!ContainsInvalidNewLine(value, descriptor.Name) && addWhenInvalid) { AddValue(info, value ?? string.Empty, StoreLocation.Invalid); } return false; } private static void AddValue(HeaderStoreItemInfo info, object value, StoreLocation location) { // Since we have the same pattern for all three store locations (raw, invalid, parsed), we use // this helper method to deal with adding values: // - if 'null' just set the store property to 'value' // - if 'List<T>' append 'value' to the end of the list // - if 'T', i.e. we have already a value stored (but no list), create a list, add the stored value // to the list and append 'value' at the end of the newly created list. object currentStoreValue = null; switch (location) { case StoreLocation.Raw: currentStoreValue = info.RawValue; AddValueToStoreValue<string>(value, ref currentStoreValue); info.RawValue = currentStoreValue; break; case StoreLocation.Invalid: currentStoreValue = info.InvalidValue; AddValueToStoreValue<string>(value, ref currentStoreValue); info.InvalidValue = currentStoreValue; break; case StoreLocation.Parsed: Debug.Assert((value == null) || (!(value is List<object>)), "Header value types must not derive from List<object> since this type is used internally to store " + "lists of values. So we would not be able to distinguish between a single value and a list of values."); currentStoreValue = info.ParsedValue; AddValueToStoreValue<object>(value, ref currentStoreValue); info.ParsedValue = currentStoreValue; break; default: Debug.Fail("Unknown StoreLocation value: " + location.ToString()); break; } } private static void AddValueToStoreValue<T>(object value, ref object currentStoreValue) where T : class { // If there is no value set yet, then add current item as value (we don't create a list // if not required). If 'info.Value' is already assigned then make sure 'info.Value' is a // List<T> and append 'item' to the list. if (currentStoreValue == null) { currentStoreValue = value; } else { List<T> storeValues = currentStoreValue as List<T>; if (storeValues == null) { storeValues = new List<T>(2); Debug.Assert(currentStoreValue is T); storeValues.Add(currentStoreValue as T); currentStoreValue = storeValues; } Debug.Assert(value is T); storeValues.Add(value as T); } } // Since most of the time we just have 1 value, we don't create a List<object> for one value, but we change // the return type to 'object'. The caller has to deal with the return type (object vs. List<object>). This // is to optimize the most common scenario where a header has only one value. internal object GetParsedValues(HeaderDescriptor descriptor) { HeaderStoreItemInfo info = null; if (!TryGetAndParseHeaderInfo(descriptor, out info)) { return null; } return info.ParsedValue; } private void PrepareHeaderInfoForAdd(HeaderDescriptor descriptor, out HeaderStoreItemInfo info, out bool addToStore) { info = null; addToStore = false; if (!TryGetAndParseHeaderInfo(descriptor, out info)) { info = new HeaderStoreItemInfo(); addToStore = true; } } private void ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, string value) { Debug.Assert(info != null); if (descriptor.Parser == null) { // If we don't have a parser for the header, we consider the value valid if it doesn't contains // invalid newline characters. We add the values as "parsed value". Note that we allow empty values. CheckInvalidNewLine(value); AddValue(info, value ?? string.Empty, StoreLocation.Parsed); return; } // If the header only supports 1 value, we can add the current value only if there is no // value already set. if (!info.CanAddValue(descriptor.Parser)) { throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_single_value_header, descriptor.Name)); } int index = 0; object parsedValue = descriptor.Parser.ParseValue(value, info.ParsedValue, ref index); // The raw string only represented one value (which was successfully parsed). Add the value and return. // If value is null we still have to first call ParseValue() to allow the parser to decide whether null is // a valid value. If it is (i.e. no exception thrown), we set the parsed value (if any) and return. if ((value == null) || (index == value.Length)) { // If the returned value is null, then it means the header accepts empty values. I.e. we don't throw // but we don't add 'null' to the store either. if (parsedValue != null) { AddValue(info, parsedValue, StoreLocation.Parsed); } return; } Debug.Assert(index < value.Length, "Parser must return an index value within the string length."); // If we successfully parsed a value, but there are more left to read, store the results in a temp // list. Only when all values are parsed successfully write the list to the store. List<object> parsedValues = new List<object>(); if (parsedValue != null) { parsedValues.Add(parsedValue); } while (index < value.Length) { parsedValue = descriptor.Parser.ParseValue(value, info.ParsedValue, ref index); if (parsedValue != null) { parsedValues.Add(parsedValue); } } // All values were parsed correctly. Copy results to the store. foreach (object item in parsedValues) { AddValue(info, item, StoreLocation.Parsed); } } private HeaderDescriptor GetHeaderDescriptor(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(name)); } if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor)) { throw new FormatException(SR.net_http_headers_invalid_header_name); } if ((descriptor.HeaderType & _allowedHeaderTypes) != 0) { return descriptor; } else if ((descriptor.HeaderType & _treatAsCustomHeaderTypes) != 0) { return descriptor.AsCustomHeader(); } throw new InvalidOperationException(SR.net_http_headers_not_allowed_header_name); } private bool TryGetHeaderDescriptor(string name, out HeaderDescriptor descriptor) { if (string.IsNullOrEmpty(name)) { descriptor = default(HeaderDescriptor); return false; } if (!HeaderDescriptor.TryGet(name, out descriptor)) { return false; } if ((descriptor.HeaderType & _allowedHeaderTypes) != 0) { return true; } else if ((descriptor.HeaderType & _treatAsCustomHeaderTypes) != 0) { descriptor = descriptor.AsCustomHeader(); return true; } return false; } private static void CheckInvalidNewLine(string value) { if (value == null) { return; } if (HttpRuleParser.ContainsInvalidNewLine(value)) { throw new FormatException(SR.net_http_headers_no_newlines); } } private static bool ContainsInvalidNewLine(string value, string name) { if (HttpRuleParser.ContainsInvalidNewLine(value)) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_no_newlines, name, value)); return true; } return false; } private static string[] GetValuesAsStrings(HeaderDescriptor descriptor, HeaderStoreItemInfo info, object exclude = null) { int length = GetValueCount(info); string[] values; if (length > 0) { values = new string[length]; int currentIndex = 0; ReadStoreValues<string>(values, info.RawValue, null, null, ref currentIndex); ReadStoreValues<object>(values, info.ParsedValue, descriptor.Parser, exclude, ref currentIndex); // Set parser parameter to 'null' for invalid values: The invalid values is always a string so we // don't need the parser to "serialize" the value to a string. ReadStoreValues<string>(values, info.InvalidValue, null, null, ref currentIndex); // The values array may not be full because some values were excluded if (currentIndex < length) { values = values.AsSpan(0, currentIndex).ToArray(); } } else { values = Array.Empty<string>(); } Debug.Assert(values != null); return values; } internal static int GetValuesAsStrings(HeaderDescriptor descriptor, HeaderStoreItemInfo info, ref string[] values) { Debug.Assert(values != null); int length = GetValueCount(info); if (length > 0) { if (values.Length < length) { values = new string[length]; } int currentIndex = 0; ReadStoreValues<string>(values, info.RawValue, null, null, ref currentIndex); ReadStoreValues<object>(values, info.ParsedValue, descriptor.Parser, null, ref currentIndex); ReadStoreValues<string>(values, info.InvalidValue, null, null, ref currentIndex); Debug.Assert(currentIndex == length); } return length; } private static int GetValueCount(HeaderStoreItemInfo info) { Debug.Assert(info != null); int valueCount = Count<string>(info.RawValue); valueCount += Count<string>(info.InvalidValue); valueCount += Count<object>(info.ParsedValue); return valueCount; static int Count<T>(object valueStore) => valueStore is null ? 0 : valueStore is List<T> list ? list.Count : 1; } private static void ReadStoreValues<T>(string[] values, object storeValue, HttpHeaderParser parser, T exclude, ref int currentIndex) { Debug.Assert(values != null); if (storeValue != null) { List<T> storeValues = storeValue as List<T>; if (storeValues == null) { if (ShouldAdd<T>(storeValue, parser, exclude)) { values[currentIndex] = parser == null ? storeValue.ToString() : parser.ToString(storeValue); currentIndex++; } } else { foreach (object item in storeValues) { if (ShouldAdd<T>(item, parser, exclude)) { values[currentIndex] = parser == null ? item.ToString() : parser.ToString(item); currentIndex++; } } } } } private static bool ShouldAdd<T>(object storeValue, HttpHeaderParser parser, T exclude) { bool add = true; if (parser != null && exclude != null) { if (parser.Comparer != null) { add = !parser.Comparer.Equals(exclude, storeValue); } else { add = !exclude.Equals(storeValue); } } return add; } private bool AreEqual(object value, object storeValue, IEqualityComparer comparer) { Debug.Assert(value != null); if (comparer != null) { return comparer.Equals(value, storeValue); } // We don't have a comparer, so use the Equals() method. return value.Equals(storeValue); } #region Private Classes internal class HeaderStoreItemInfo { internal HeaderStoreItemInfo() { } internal object RawValue { get; set; } internal object InvalidValue { get; set; } internal object ParsedValue { get; set; } internal bool CanAddValue(HttpHeaderParser parser) { Debug.Assert(parser != null, "There should be no reason to call CanAddValue if there is no parser for the current header."); // If the header only supports one value, and we have already a value set, then we can't add // another value. E.g. the 'Date' header only supports one value. We can't add multiple timestamps // to 'Date'. // So if this is a known header, ask the parser if it supports multiple values and check whether // we already have a (valid or invalid) value. // Note that we ignore the rawValue by purpose: E.g. we are parsing 2 raw values for a header only // supporting 1 value. When the first value gets parsed, CanAddValue returns true and we add the // parsed value to ParsedValue. When the second value is parsed, CanAddValue returns false, because // we have already a parsed value. return parser.SupportsMultipleValues || ((InvalidValue == null) && (ParsedValue == null)); } internal bool IsEmpty => (RawValue == null) && (InvalidValue == null) && (ParsedValue == null); } #endregion } }
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 Aglaia.API.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; } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Text.RegularExpressions; namespace SubSonic.Sugar { /// <summary> /// Summary for the Validation class /// </summary> public static class Validation { /// <summary> /// Determines whether the specified eval string contains only alpha characters. /// </summary> /// <param name="evalString">The eval string.</param> /// <returns> /// <c>true</c> if the specified eval string is alpha; otherwise, <c>false</c>. /// </returns> public static bool IsAlpha(string evalString) { return !Regex.IsMatch(evalString, RegexPattern.ALPHA); } /// <summary> /// Determines whether the specified eval string contains only alphanumeric characters /// </summary> /// <param name="evalString">The eval string.</param> /// <returns> /// <c>true</c> if the string is alphanumeric; otherwise, <c>false</c>. /// </returns> public static bool IsAlphaNumeric(string evalString) { return !Regex.IsMatch(evalString, RegexPattern.ALPHA_NUMERIC); } /// <summary> /// Determines whether the specified eval string contains only alphanumeric characters /// </summary> /// <param name="evalString">The eval string.</param> /// <param name="allowSpaces">if set to <c>true</c> [allow spaces].</param> /// <returns> /// <c>true</c> if the string is alphanumeric; otherwise, <c>false</c>. /// </returns> public static bool IsAlphaNumeric(string evalString, bool allowSpaces) { if(allowSpaces) return !Regex.IsMatch(evalString, RegexPattern.ALPHA_NUMERIC_SPACE); return IsAlphaNumeric(evalString); } /// <summary> /// Determines whether the specified eval string contains only numeric characters /// </summary> /// <param name="evalString">The eval string.</param> /// <returns> /// <c>true</c> if the string is numeric; otherwise, <c>false</c>. /// </returns> public static bool IsNumeric(string evalString) { return !Regex.IsMatch(evalString, RegexPattern.NUMERIC); } /// <summary> /// Determines whether the specified email address string is valid based on regular expression evaluation. /// </summary> /// <param name="emailAddressString">The email address string.</param> /// <returns> /// <c>true</c> if the specified email address is valid; otherwise, <c>false</c>. /// </returns> public static bool IsEmail(string emailAddressString) { return Regex.IsMatch(emailAddressString, RegexPattern.EMAIL); } /// <summary> /// Determines whether the specified string is lower case. /// </summary> /// <param name="inputString">The input string.</param> /// <returns> /// <c>true</c> if the specified string is lower case; otherwise, <c>false</c>. /// </returns> public static bool IsLowerCase(string inputString) { return Regex.IsMatch(inputString, RegexPattern.LOWER_CASE); } /// <summary> /// Determines whether the specified string is upper case. /// </summary> /// <param name="inputString">The input string.</param> /// <returns> /// <c>true</c> if the specified string is upper case; otherwise, <c>false</c>. /// </returns> public static bool IsUpperCase(string inputString) { return Regex.IsMatch(inputString, RegexPattern.UPPER_CASE); } /// <summary> /// Determines whether the specified string is a valid GUID. /// </summary> /// <param name="guid">The GUID.</param> /// <returns> /// <c>true</c> if the specified string is a valid GUID; otherwise, <c>false</c>. /// </returns> public static bool IsGuid(string guid) { return Regex.IsMatch(guid, RegexPattern.GUID); } /// <summary> /// Determines whether the specified string is a valid US Zip Code, using either 5 or 5+4 format. /// </summary> /// <param name="zipCode">The zip code.</param> /// <returns> /// <c>true</c> if it is a valid zip code; otherwise, <c>false</c>. /// </returns> public static bool IsZIPCodeAny(string zipCode) { return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE_PLUS_FOUR_OPTIONAL); } /// <summary> /// Determines whether the specified string is a valid US Zip Code, using the 5 digit format. /// </summary> /// <param name="zipCode">The zip code.</param> /// <returns> /// <c>true</c> if it is a valid zip code; otherwise, <c>false</c>. /// </returns> public static bool IsZIPCodeFive(string zipCode) { return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE); } /// <summary> /// Determines whether the specified string is a valid US Zip Code, using the 5+4 format. /// </summary> /// <param name="zipCode">The zip code.</param> /// <returns> /// <c>true</c> if it is a valid zip code; otherwise, <c>false</c>. /// </returns> public static bool IsZIPCodeFivePlusFour(string zipCode) { return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE_PLUS_FOUR); } /// <summary> /// Determines whether the specified string is a valid Social Security number. Dashes are optional. /// </summary> /// <param name="socialSecurityNumber">The Social Security Number</param> /// <returns> /// <c>true</c> if it is a valid Social Security number; otherwise, <c>false</c>. /// </returns> public static bool IsSocialSecurityNumber(string socialSecurityNumber) { return Regex.IsMatch(socialSecurityNumber, RegexPattern.SOCIAL_SECURITY); } /// <summary> /// Determines whether the specified string is a valid IP address. /// </summary> /// <param name="ipAddress">The ip address.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsIPAddress(string ipAddress) { return Regex.IsMatch(ipAddress, RegexPattern.IP_ADDRESS); } /// <summary> /// Determines whether the specified string is a valid US state either by full name or two letter abbreviation. /// </summary> /// <param name="stateName">The state name.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsUSState(string stateName) { stateName = stateName.ToUpper(); if(stateName.Length > 2) return (!String.IsNullOrEmpty(Strings.USStateNameToAbbrev(stateName))); return (!String.IsNullOrEmpty(Strings.USStateAbbrevToName(stateName))); } /// <summary> /// Determines whether the specified string is a valid US phone number using the referenced regex string. /// </summary> /// <param name="telephoneNumber">The telephone number.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsUSTelephoneNumber(string telephoneNumber) { return Regex.IsMatch(telephoneNumber, RegexPattern.US_TELEPHONE); } /// <summary> /// Determines whether the specified string is a valid currency string using the referenced regex string. /// </summary> /// <param name="currency">The currency string.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsUSCurrency(string currency) { return Regex.IsMatch(currency, RegexPattern.US_CURRENCY); } /// <summary> /// Determines whether the specified string is a valid URL string using the referenced regex string. /// </summary> /// <param name="url">The URL string.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsURL(string url) { return Regex.IsMatch(url, RegexPattern.URL); } /// <summary> /// Determines whether the specified string is consider a strong password based on the supplied string. /// </summary> /// <param name="password">The password.</param> /// <returns> /// <c>true</c> if strong; otherwise, <c>false</c>. /// </returns> public static bool IsStrongPassword(string password) { return Regex.IsMatch(password, RegexPattern.STRONG_PASSWORD); } #region Credit Cards /// <summary> /// Determines whether the specified string is a valid credit, based on matching any one of the eight credit card strings /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardAny(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_AMERICAN_EXPRESS) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_CARTE_BLANCHE) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DINERS_CLUB) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DISCOVER) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_EN_ROUTE) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_JCB) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_MASTER_CARD) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_VISA); } return false; } /// <summary> /// Determines whether the specified string is an American Express, Discover, MasterCard, or Visa /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardBigFour(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_AMERICAN_EXPRESS) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DISCOVER) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_MASTER_CARD) || Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_VISA); } return false; } /// <summary> /// Determines whether the specified string is an American Express card /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardAmericanExpress(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_AMERICAN_EXPRESS); } return false; } /// <summary> /// Determines whether the specified string is an Carte Blanche card /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardCarteBlanche(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_CARTE_BLANCHE); } return false; } /// <summary> /// Determines whether the specified string is an Diner's Club card /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardDinersClub(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DINERS_CLUB); } return false; } /// <summary> /// Determines whether the specified string is a Discover card /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardDiscover(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DISCOVER); } return false; } /// <summary> /// Determines whether the specified string is an En Route card /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardEnRoute(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_EN_ROUTE); } return false; } /// <summary> /// Determines whether the specified string is an JCB card /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardJCB(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_JCB); } return false; } /// <summary> /// Determines whether the specified string is a Master Card credit card /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardMasterCard(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_MASTER_CARD); } return false; } /// <summary> /// Determines whether the specified string is Visa card. /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns> /// <c>true</c> if valid; otherwise, <c>false</c>. /// </returns> public static bool IsCreditCardVisa(string creditCard) { if(CreditPassesFormatCheck(creditCard)) { creditCard = CleanCreditCardNumber(creditCard); return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_VISA); } return false; } /// <summary> /// Cleans the credit card number, returning just the numeric values. /// </summary> /// <param name="creditCard">The credit card.</param> /// <returns></returns> public static string CleanCreditCardNumber(string creditCard) { Regex regex = new Regex(RegexPattern.CREDIT_CARD_STRIP_NON_NUMERIC, RegexOptions.IgnoreCase | RegexOptions.Singleline); return regex.Replace(creditCard, String.Empty); } /// <summary> /// Determines whether the credit card number, once cleaned, passes the Luhn algorith. /// See: http://en.wikipedia.org/wiki/Luhn_algorithm /// </summary> /// <param name="creditCardNumber">The credit card number.</param> /// <returns></returns> private static bool CreditPassesFormatCheck(string creditCardNumber) { creditCardNumber = CleanCreditCardNumber(creditCardNumber); if(Numbers.IsInteger(creditCardNumber)) { int[] numArray = new int[creditCardNumber.Length]; for(int i = 0; i < numArray.Length; i++) numArray[i] = Convert.ToInt16(creditCardNumber[i].ToString()); return IsValidLuhn(numArray); } return false; } /// <summary> /// Determines whether the specified int array passes the Luhn algorith /// </summary> /// <param name="digits">The int array to evaluate</param> /// <returns> /// <c>true</c> if it validates; otherwise, <c>false</c>. /// </returns> public static bool IsValidLuhn(int[] digits) { int sum = 0; bool alt = false; for(int i = digits.Length - 1; i >= 0; i--) { if(alt) { digits[i] *= 2; if(digits[i] > 9) digits[i] -= 9; // equivalent to adding the value of digits } sum += digits[i]; alt = !alt; } return sum % 10 == 0; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace UpgradeYourself.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) 2014 Christian Crowhurst. All rights reserved. // see LICENSE using System; using System.Collections.Generic; using System.Threading; using CcAcca.CacheAbstraction.Statistics; using NUnit.Framework; namespace CcAcca.CacheAbstraction.Test.Statistics { [TestFixture] public class ItemAccessCacheStatisticExamples : CacheStatisticExamplesBase { private IStatisticsCache _cache; #region Setup/Teardown [SetUp] public void TestInitialise() { _cache = CreateCacheWith(new ItemAccessCacheStatistic()); } #endregion [Test] public void AddShouldRecordWriteTime() { //when DateTimeOffset expectedTime = DateTimeOffset.Now; _cache.AddOrUpdate("key1", new object()); Thread.Sleep(60); //then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; AssertAccessTime(itemStats.LastWrite, expectedTime); } [Test] public void AddShouldNotRecordReadTime() { //when _cache.AddOrUpdate("key1", new object()); //then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; Assert.That(itemStats.LastRead, Is.Null); } [Test] public void GetCacheItemShouldRecordReadTime() { // given _cache.AddOrUpdate("key1", new object()); Thread.Sleep(60); // when _cache.GetCacheItem<object>("key1"); DateTimeOffset expectedTime = DateTimeOffset.Now; // then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; AssertAccessTime(itemStats.LastRead, expectedTime); } [Test] public void GetCacheItemShouldIncrementAccessCount() { // given _cache.AddOrUpdate("key1", new object()); // when _cache.GetCacheItem<object>("key1"); _cache.GetCacheItem<object>("key1"); // then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; Assert.That(itemStats.ReadCount, Is.EqualTo(2)); } [Test] public void AddOrUpdateShouldResetAccessCount() { // given _cache.AddOrUpdate("key1", new object()); _cache.GetCacheItem<object>("key1"); _cache.GetCacheItem<object>("key1"); // when _cache.AddOrUpdate("key1", new object()); // then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; Assert.That(itemStats.ReadCount, Is.EqualTo(0)); } [Test] public void AddOrUpdateFactoryShouldResetAccessCount() { // given _cache.AddOrUpdate("key1", new object()); _cache.GetCacheItem<object>("key1"); _cache.GetCacheItem<object>("key1"); // when _cache.AddOrUpdate("key1", new object(), (k, v) => new object()); // then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; Assert.That(itemStats.ReadCount, Is.EqualTo(0)); } [Test] public void AddOrUpdateShouldResetLastRead() { // given _cache.AddOrUpdate("key1", new object()); _cache.GetCacheItem<object>("key1"); // when _cache.AddOrUpdate("key1", new object()); // then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; Assert.That(itemStats.LastRead, Is.Null); } [Test] public void AddOrUpdateFactoryShouldResetLastRead() { // given _cache.AddOrUpdate("key1", new object()); _cache.GetCacheItem<object>("key1"); // when _cache.AddOrUpdate("key1", new object(), (k, v) => new object()); // then CacheItemAccessInfo itemStats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ["key1"]; Assert.That(itemStats.LastRead, Is.Null); } [Test] public void GetCacheItemShouldSkipRecordingStatsForMissingItems() { // when _cache.GetCacheItem<object>("key1"); // then var stats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess); Assert.That(stats, Is.Empty); } [Test] public void RemoveShouldRemoveItemStats() { // given _cache.AddOrUpdate("key1", new object()); Assert.IsNotEmpty( _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess), "checking assumptions"); // when _cache.Remove("key1"); // then var stats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess); Assert.That(stats, Is.Empty); } [Test] public void FlushShouldRemoveAllItemStats() { // given _cache.AddOrUpdate("key1", new object()); _cache.AddOrUpdate("key2", new object()); Assert.IsNotEmpty( _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess), "checking assumptions"); // when _cache.Flush(); // then var stats = _cache.Statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess); Assert.That(stats, Is.Empty); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests that orders are unchangeable from the QCAlgorithm Layer /// Orders should only be modifiable via their ticket and only in permitted ways /// </summary> /// <meta name="tag" content="backtesting brokerage" /> /// <meta name="tag" content="regression test" /> /// <meta name="tag" content="options" /> public class OrderImmutabilityRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA); private OrderTicket _ticket; private Order _originalOrder; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 07); //Set Start Date SetEndDate(2013, 10, 09); //Set End Date SetCash(100000); //Set Strategy Cash AddEquity("SPY", Resolution.Daily); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested) { _ticket = LimitOrder(_spy, 10, 100); Debug("Purchased Stock"); // Here we will show how to correctly change an order, we will then verify at End of Algorithm! // First get the order as it is now, should be a copy, so it wont be updated! _originalOrder = Transactions.GetOrderById(_ticket.OrderId); // Create an UpdateOrderRequest and send it to the ticket var updateFields = new UpdateOrderFields { Quantity = 20, Tag = "Pepe", LimitPrice = data[_spy].Low}; var response = _ticket.Update(updateFields); // Test order time if (_originalOrder.Time != UtcTime) { Error("Order Time should be UtcTime!"); throw new Exception("Order Time should be UtcTime!"); } } } /// <summary> /// All order events get pushed through this function /// This function will test that what we get from Transactions is indeed a clone /// The only authentic way to change the order is to change through the order ticket! /// </summary> /// <param name="orderEvent">OrderEvent object that contains all the information about the event</param> public override void OnOrderEvent(OrderEvent orderEvent) { // Get the order twice, since they are clones they should NOT be the same var orderV1 = Transactions.GetOrderById(orderEvent.OrderId); var orderV2 = Transactions.GetOrderById(orderEvent.OrderId); if (orderV1 == orderV2) { Error("Orders should be clones, hence not equal!"); throw new Exception("Orders should be clones, hence not equal!"); } // Try and manipulate orderV2 using the only external accessor BrokerID, since we // are changing a clone the BrokerIDs should not be the same orderV2.BrokerId.Add("FAKE BROKER ID"); var orderV3 = Transactions.GetOrderById(orderEvent.OrderId); if (orderV2.BrokerId.SequenceEqual(orderV3.BrokerId)) { Error("Broker IDs should not be the same!"); throw new Exception("Broker IDs should not be the same!"); } //Try and manipulate the orderV1 using UpdateOrderRequest //NOTICE: Orders should only be updated through their tickets! var updateFields = new UpdateOrderFields { Quantity = 99, Tag = "Pepe2!" }; var updateRequest = new UpdateOrderRequest(DateTime.Now, orderEvent.OrderId, updateFields); orderV1.ApplyUpdateOrderRequest(updateRequest); var orderV4 = Transactions.GetOrderById(orderEvent.OrderId); if (orderV4.Quantity == orderV1.Quantity) { Error("Order quantity should not be the same!"); throw new Exception("Order quantity should not be the same!"); } if (orderV4.Tag == orderV1.Tag) { Error("Order tag should not be the same!"); throw new Exception("Order tag should not be the same!"); } } /// <summary> /// Will run at End of Algorithm /// We will be using this to check our order was updated! /// </summary> public override void OnEndOfAlgorithm() { //Get an updated copy of the order and compare to our original var updatedOrder = Transactions.GetOrderById(_ticket.OrderId); if (updatedOrder.Quantity == _originalOrder.Quantity) { Error("Quantities should have been updated!"); throw new Exception("Quantities should have been updated!"); } if (updatedOrder.Tag == _originalOrder.Tag) { Error("Tag should have been updated!"); throw new Exception("Tag should have been updated!"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "-3.591%"}, {"Drawdown", "0.000%"}, {"Expectancy", "0"}, {"Net Profit", "-0.030%"}, {"Sharpe Ratio", "-9.982"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "-0.017"}, {"Beta", "0.027"}, {"Annual Standard Deviation", "0.004"}, {"Annual Variance", "0"}, {"Information Ratio", "5.399"}, {"Tracking Error", "0.132"}, {"Treynor Ratio", "-1.359"}, {"Total Fees", "$1.00"}, {"Estimated Strategy Capacity", "$34000000000.00"}, {"Lowest Capacity Asset", "SPY R735QTJ8XC9X"}, {"Fitness Score", "0.004"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "79228162514264337593543950335"}, {"Return Over Maximum Drawdown", "-113.603"}, {"Portfolio Turnover", "0.009"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "8e894e13efd89d8cd8672c76a2e1d92d"} }; } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Diagnostics; using System.Threading; using Cassandra.IntegrationTests.Policies.Util; using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.Tests; using NUnit.Framework; namespace Cassandra.IntegrationTests.Policies.Tests { [TestFixture, Category(TestCategory.Long), Ignore("tests that are not marked with 'short' need to be refactored/deleted")] public class ReconnectionPolicyTests : TestGlobals { private PolicyTestTools _policyTestTools = null; [SetUp] public void SetupTest() { _policyTestTools = new PolicyTestTools(); } /// <summary> /// Test the ExponentialReconnectionPolicy. /// /// @test_category connection:reconnection /// </summary> [Test] public void ExponentialReconnectionPolicyTest() { var builder = ClusterBuilder().WithReconnectionPolicy(new ExponentialReconnectionPolicy(2*1000, 5*60*1000)); // Ensure that ExponentialReconnectionPolicy is what we should be testing if (!(builder.GetConfiguration().Policies.ReconnectionPolicy is ExponentialReconnectionPolicy)) { Assert.Fail("Set policy does not match retrieved policy."); } // Test basic getters ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) builder.GetConfiguration().Policies.ReconnectionPolicy; Assert.True(reconnectionPolicy.BaseDelayMs == 2*1000); Assert.True(reconnectionPolicy.MaxDelayMs == 5*60*1000); // Test erroneous instantiations try { new ExponentialReconnectionPolicy(-1, 1); Assert.Fail(); } catch (ArgumentException){} try { new ExponentialReconnectionPolicy(1, -1); Assert.Fail(); } catch (ArgumentException){} try { new ExponentialReconnectionPolicy(-1, -1); Assert.Fail(); } catch (ArgumentException){} try { new ExponentialReconnectionPolicy(2, 1); Assert.Fail(); } catch (ArgumentException){} // Test nextDelays() var schedule = new ExponentialReconnectionPolicy(2*1000, 5*60*1000).NewSchedule(); Assert.True(schedule.NextDelayMs() == 2000); Assert.True(schedule.NextDelayMs() == 4000); Assert.True(schedule.NextDelayMs() == 8000); Assert.True(schedule.NextDelayMs() == 16000); Assert.True(schedule.NextDelayMs() == 32000); for (int i = 0; i < 64; ++i) schedule.NextDelayMs(); Assert.True(schedule.NextDelayMs() == reconnectionPolicy.MaxDelayMs); //// Run integration test //long restartTime = 2 + 4 + 8 + 2; // 16: 3 full cycles + 2 seconds //long retryTime = 30; // 4th cycle start time //long breakTime = 62; // time until next reconnection attempt //ReconnectionPolicyTest(builder, restartTime, retryTime, breakTime); } /// <summary> /// Test the ConstantReconnectionPolicy. /// /// @test_category connection:reconnection /// </summary> [Test] public void ConstantReconnectionPolicyTest() { Builder builder = ClusterBuilder().WithReconnectionPolicy(new ConstantReconnectionPolicy(25*1000)); // Ensure that ConstantReconnectionPolicy is what we should be testing if (!(builder.GetConfiguration().Policies.ReconnectionPolicy is ConstantReconnectionPolicy)) { Assert.Fail("Set policy does not match retrieved policy."); } // Test basic getters ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) builder.GetConfiguration().Policies.ReconnectionPolicy; Assert.True(reconnectionPolicy.ConstantDelayMs == 25*1000); // Test erroneous instantiations try { new ConstantReconnectionPolicy(-1); Assert.Fail(); } catch (ArgumentException) { } // Test nextDelays() var schedule = new ConstantReconnectionPolicy(10*1000).NewSchedule(); Assert.True(schedule.NextDelayMs() == 10000); Assert.True(schedule.NextDelayMs() == 10000); Assert.True(schedule.NextDelayMs() == 10000); Assert.True(schedule.NextDelayMs() == 10000); Assert.True(schedule.NextDelayMs() == 10000); //// Run integration test //int restartTime = 32; //int retryTime = 50; //int breakTime = 10; // time until next reconnection attempt //reconnectionPolicyTest(builder, restartTime, retryTime, breakTime); } public void ReconnectionPolicyTest(Builder builder, long restartTime, long retryTime, long breakTime) { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(1); _policyTestTools.CreateSchema(testCluster.Session, 1); _policyTestTools.InitPreparedStatement(testCluster, 12); _policyTestTools.Query(testCluster, 12); // Ensure a basic test works _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 12); _policyTestTools.ResetCoordinators(); testCluster.StopForce(1); // Start timing and ensure that the node is down //long startTime = 0; var startTime = Stopwatch.StartNew(); // = 0; try { //startTime = System.nanoTime() / 1000000000; _policyTestTools.Query(testCluster, 12); Assert.Fail("Test race condition where node has not shut off quickly enough."); } catch (NoHostAvailableException){} long elapsedSeconds; bool restarted = false; while (true) { //thisTime = System.nanoTime() / 1000000000; elapsedSeconds = startTime.ElapsedMilliseconds/1000; // Restart node at restartTime if (!restarted && elapsedSeconds > restartTime) { testCluster.Start(1); restarted = true; } // Continue testing queries each second try { _policyTestTools.Query(testCluster, 12); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 12); _policyTestTools.ResetCoordinators(); // Ensure the time when the query completes successfully is what was expected Assert.True(retryTime - 6 < elapsedSeconds && elapsedSeconds < retryTime + 6, string.Format("Waited {0} seconds instead an expected {1} seconds wait", elapsedSeconds, retryTime)); } catch (NoHostAvailableException) { Thread.Sleep(1000); continue; } Thread.Sleep((int) (breakTime*1000)); // The same query once more, just to be sure _policyTestTools.Query(testCluster, 12); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 12); _policyTestTools.ResetCoordinators(); // Ensure the reconnection times reset testCluster.StopForce(1); // Start timing and ensure that the node is down //startTime = 0; startTime.Reset(); try { //startTime = System.nanoTime() / 1000000000; startTime.Start(); _policyTestTools.Query(testCluster, 12); Assert.Fail("Test race condition where node has not shut off quickly enough."); } catch (NoHostAvailableException) { } restarted = false; while (true) { //elapsedSeconds = System.nanoTime() / 1000000000; elapsedSeconds = startTime.ElapsedMilliseconds/1000; // Restart node at restartTime if (!restarted && elapsedSeconds > restartTime) { testCluster.Start(1); restarted = true; } // Continue testing queries each second try { _policyTestTools.Query(testCluster, 12); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 12); _policyTestTools.ResetCoordinators(); // Ensure the time when the query completes successfully is what was expected Assert.True(retryTime - 3 < elapsedSeconds && elapsedSeconds < retryTime + 3, string.Format("Waited {0} seconds instead an expected {1} seconds wait", elapsedSeconds, retryTime)); } catch (NoHostAvailableException) { Thread.Sleep(1000); continue; } break; } break; } } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using Microsoft.Extensions.Logging; using Orleans.Messaging; using Orleans.Serialization; using System.Threading.Tasks; namespace Orleans.Runtime.Messaging { internal class IncomingMessageAcceptor : DedicatedAsynchAgent { private readonly ConcurrentObjectPool<SaeaPoolWrapper> receiveEventArgsPool; private const int SocketBufferSize = 1024 * 128; // 128 kb private const int PreambleMaxSize = 1024 * 4; // 4 kb private readonly IPEndPoint listenAddress; private Action<Message> sniffIncomingMessageHandler; private readonly LingerOption receiveLingerOption = new LingerOption(true, 0); internal Socket AcceptingSocket; protected MessageCenter MessageCenter; protected HashSet<Socket> OpenReceiveSockets; private bool isStopping = false; protected readonly MessageFactory MessageFactory; private static readonly CounterStatistic allocatedSocketEventArgsCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_ALLOCATED_SOCKET_EVENT_ARGS, false); private readonly CounterStatistic checkedOutSocketEventArgsCounter; private readonly CounterStatistic checkedInSocketEventArgsCounter; private readonly SerializationManager serializationManager; public Action<Message> SniffIncomingMessage { set { if (sniffIncomingMessageHandler != null) throw new InvalidOperationException("IncomingMessageAcceptor SniffIncomingMessage already set"); sniffIncomingMessageHandler = value; } } private const int LISTEN_BACKLOG_SIZE = 1024; protected SocketDirection SocketDirection { get; private set; } // Used for holding enough info to handle receive completion internal IncomingMessageAcceptor(MessageCenter msgCtr, IPEndPoint here, SocketDirection socketDirection, MessageFactory messageFactory, SerializationManager serializationManager, ExecutorService executorService, ILoggerFactory loggerFactory) :base(executorService, loggerFactory) { this.loggerFactory = loggerFactory; Log = loggerFactory.CreateLogger<IncomingMessageAcceptor>(); MessageCenter = msgCtr; listenAddress = here; this.MessageFactory = messageFactory; this.receiveEventArgsPool = new ConcurrentObjectPool<SaeaPoolWrapper>(() => this.CreateSocketReceiveAsyncEventArgsPoolWrapper()); this.serializationManager = serializationManager; if (here == null) listenAddress = MessageCenter.MyAddress.Endpoint; AcceptingSocket = MessageCenter.SocketManager.GetAcceptingSocketForEndpoint(listenAddress); Log.Info(ErrorCode.Messaging_IMA_OpenedListeningSocket, "Opened a listening socket at address " + AcceptingSocket.LocalEndPoint); OpenReceiveSockets = new HashSet<Socket>(); OnFault = FaultBehavior.CrashOnFault; SocketDirection = socketDirection; checkedOutSocketEventArgsCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_CHECKED_OUT_SOCKET_EVENT_ARGS, false); checkedInSocketEventArgsCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_CHECKED_IN_SOCKET_EVENT_ARGS, false); IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_IN_USE_SOCKET_EVENT_ARGS, () => checkedOutSocketEventArgsCounter.GetCurrentValue() - checkedInSocketEventArgsCounter.GetCurrentValue()); } protected override void Run() { try { AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE); StartAccept(null); } catch (Exception ex) { Log.Error(ErrorCode.MessagingAcceptAsyncSocketException, "Exception beginning accept on listening socket", ex); throw; } if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Started accepting connections."); } public override void Stop() { base.Stop(); this.isStopping = true; if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Disconnecting the listening socket"); SocketManager.CloseSocket(AcceptingSocket); Socket[] temp; lock (Lockable) { temp = new Socket[OpenReceiveSockets.Count]; OpenReceiveSockets.CopyTo(temp); } foreach (var socket in temp) { SafeCloseSocket(socket); } lock (Lockable) { ClearSockets(); } } protected virtual bool RecordOpenedSocket(Socket sock) { GrainId client; if (!ReceiveSocketPreample(sock, false, out client)) return false; NetworkingStatisticsGroup.OnOpenedReceiveSocket(); return true; } protected bool ReceiveSocketPreample(Socket sock, bool expectProxiedConnection, out GrainId client) { client = null; if (Cts.IsCancellationRequested) return false; if (!ReadConnectionPreamble(sock, out client)) { return false; } if (Log.IsEnabled(LogLevel.Trace)) Log.Trace(ErrorCode.MessageAcceptor_Connection, "Received connection from {0} at source address {1}", client, sock.RemoteEndPoint.ToString()); if (expectProxiedConnection) { // Proxied Gateway Connection - must have sender id if (client.Equals(Constants.SiloDirectConnectionId)) { Log.Error(ErrorCode.MessageAcceptor_NotAProxiedConnection, $"Gateway received unexpected non-proxied connection from {client} at source address {sock.RemoteEndPoint}"); return false; } } else { // Direct connection - should not have sender id if (!client.Equals(Constants.SiloDirectConnectionId)) { Log.Error(ErrorCode.MessageAcceptor_UnexpectedProxiedConnection, $"Silo received unexpected proxied connection from {client} at source address {sock.RemoteEndPoint}"); return false; } } lock (Lockable) { OpenReceiveSockets.Add(sock); } return true; } private bool ReadConnectionPreamble(Socket socket, out GrainId grainId) { grainId = null; byte[] buffer = null; try { buffer = ReadFromSocket(socket, sizeof(int)); // Read the size if (buffer == null) return false; Int32 size = BitConverter.ToInt32(buffer, 0); if (size > 0) { buffer = ReadFromSocket(socket, size); // Receive the client ID if (buffer == null) return false; grainId = GrainIdExtensions.FromByteArray(buffer); } return true; } catch (Exception exc) { Log.Error(ErrorCode.GatewayFailedToParse, $"Failed to convert the data that read from the socket. buffer = {Utils.EnumerableToString(buffer)}, from endpoint {socket.RemoteEndPoint}.", exc); return false; } } private byte[] ReadFromSocket(Socket sock, int expected) { if (expected > PreambleMaxSize) { Log.Warn(ErrorCode.GatewayAcceptor_InvalidSize, "Invalid expected size {0} while receiving connection preamble data from endpoint {1}.", expected, sock.RemoteEndPoint); return null; } var buffer = new byte[expected]; int offset = 0; while (offset < buffer.Length) { try { int bytesRead = sock.Receive(buffer, offset, buffer.Length - offset, SocketFlags.None); if (bytesRead == 0) { Log.Warn(ErrorCode.GatewayAcceptor_SocketClosed, "Remote socket closed while receiving connection preamble data from endpoint {0}.", sock.RemoteEndPoint); return null; } offset += bytesRead; } catch (Exception ex) { Log.Warn(ErrorCode.GatewayAcceptor_ExceptionReceiving, "Exception receiving connection preamble data from endpoint " + sock.RemoteEndPoint, ex); return null; } } return buffer; } protected virtual void RecordClosedSocket(Socket sock) { if (TryRemoveClosedSocket(sock)) NetworkingStatisticsGroup.OnClosedReceivingSocket(); } protected bool TryRemoveClosedSocket(Socket sock) { lock (Lockable) { return OpenReceiveSockets.Remove(sock); } } protected virtual void ClearSockets() { lock (Lockable) { OpenReceiveSockets.Clear(); } } /// <summary> /// Begins an operation to accept a connection request from the client. /// </summary> /// <param name="acceptEventArg">The context object to use when issuing /// the accept operation on the server's listening socket.</param> private void StartAccept(SocketAsyncEventArgs acceptEventArg) { if (acceptEventArg == null) { acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.UserToken = this; acceptEventArg.Completed += OnAcceptCompleted; } else { // We have handed off the connection info from the // accepting socket to the receiving socket. So, now we will clear // the socket info from that object, so it will be // ready for a new socket acceptEventArg.AcceptSocket = null; } // Socket.AcceptAsync begins asynchronous operation to accept the connection. // Note the listening socket will pass info to the SocketAsyncEventArgs // object that has the Socket that does the accept operation. // If you do not create a Socket object and put it in the SAEA object // before calling AcceptAsync and use the AcceptSocket property to get it, // then a new Socket object will be created by .NET. try { // AcceptAsync returns true if the I / O operation is pending.The SocketAsyncEventArgs.Completed event // on the e parameter will be raised upon completion of the operation.Returns false if the I/O operation // completed synchronously. The SocketAsyncEventArgs.Completed event on the e parameter will not be raised // and the e object passed as a parameter may be examined immediately after the method call returns to retrieve // the result of the operation. while (!AcceptingSocket.AcceptAsync(acceptEventArg)) { ProcessAccept(acceptEventArg, true); } } catch (SocketException ex) { Log.Warn(ErrorCode.MessagingAcceptAsyncSocketException, "Socket error on accepting socket during AcceptAsync {0}", ex.SocketErrorCode); RestartAcceptingSocket(); } catch (ObjectDisposedException) { // Socket was closed, but we're not shutting down; we need to open a new socket and start over... // Close the old socket and open a new one Log.Warn(ErrorCode.MessagingAcceptingSocketClosed, "Accepting socket was closed when not shutting down"); RestartAcceptingSocket(); } catch (Exception ex) { // There was a network error. We need to get a new accepting socket and re-issue an accept before we continue. // Close the old socket and open a new one Log.Warn(ErrorCode.MessagingAcceptAsyncSocketException, "Exception on accepting socket during AcceptAsync", ex); RestartAcceptingSocket(); } } private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e) { ((IncomingMessageAcceptor)e.UserToken).ProcessAccept(e, false); } /// <summary> /// Process the accept for the socket listener. /// </summary> /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param> /// <param name="completedSynchronously">Shows whether AcceptAsync completed synchronously, /// if true - the next accept operation woun't be started. Used for avoiding potential stack overflows.</param> private void ProcessAccept(SocketAsyncEventArgs e, bool completedSynchronously) { var ima = e.UserToken as IncomingMessageAcceptor; try { if (ima == null) { Log.Warn(ErrorCode.Messaging_IMA_AcceptCallbackUnexpectedState, "AcceptCallback invoked with an unexpected async state of type {0}", e.UserToken?.GetType().ToString() ?? "null"); return; } if (e.SocketError != SocketError.Success) { RestartAcceptingSocket(); return; } // First check to see if we're shutting down, in which case there's no point in doing anything other // than closing the accepting socket and returning. if (ima.Cts == null || ima.Cts.IsCancellationRequested) { SocketManager.CloseSocket(ima.AcceptingSocket); ima.Log.Info(ErrorCode.Messaging_IMA_ClosingSocket, "Closing accepting socket during shutdown"); return; } Socket sock = e.AcceptSocket; if (sock.Connected) { if (ima.Log.IsEnabled(LogLevel.Debug)) ima.Log.Debug("Received a connection from {0}", sock.RemoteEndPoint); // Finally, process the incoming request: // Prep the socket so it will reset on close sock.LingerState = receiveLingerOption; Task.Factory.StartNew(() => { // Add the socket to the open socket collection if (ima.RecordOpenedSocket(sock)) { // Get the socket for the accepted client connection and put it into the // ReadEventArg object user token. var readEventArgs = GetSocketReceiveAsyncEventArgs(sock); StartReceiveAsync(sock, readEventArgs, ima); } else { ima.SafeCloseSocket(sock); } }).Ignore(); } // The next accept will be started in the caller method if (completedSynchronously) { return; } // Start a new Accept StartAccept(e); } catch (Exception ex) { var logger = ima?.Log ?? this.Log; logger.Error(ErrorCode.Messaging_IMA_ExceptionAccepting, "Unexpected exception in IncomingMessageAccepter.AcceptCallback", ex); RestartAcceptingSocket(); } } private void StartReceiveAsync(Socket sock, SocketAsyncEventArgs readEventArgs, IncomingMessageAcceptor ima) { try { // Set up the async receive if (!sock.ReceiveAsync(readEventArgs)) { ProcessReceive(readEventArgs); } } catch (Exception exception) { var socketException = exception as SocketException; var context = readEventArgs.UserToken as ReceiveCallbackContext; ima.Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException, $"Exception on new socket during ReceiveAsync with RemoteEndPoint " + $"{socketException?.SocketErrorCode}: {context?.RemoteEndPoint}", exception); ima.SafeCloseSocket(sock); FreeSocketAsyncEventArgs(readEventArgs); } } private SocketAsyncEventArgs GetSocketReceiveAsyncEventArgs(Socket sock) { var saea = receiveEventArgsPool.Allocate(); var token = ((ReceiveCallbackContext) saea.SocketAsyncEventArgs.UserToken); token.IMA = this; token.Socket = sock; checkedOutSocketEventArgsCounter.Increment(); return saea.SocketAsyncEventArgs; } private SaeaPoolWrapper CreateSocketReceiveAsyncEventArgsPoolWrapper() { SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); readEventArgs.Completed += OnReceiveCompleted; var buffer = new byte[SocketBufferSize]; // SocketAsyncEventArgs and ReceiveCallbackContext's buffer shares the same buffer list with pinned arrays. readEventArgs.SetBuffer(buffer, 0, buffer.Length); var poolWrapper = new SaeaPoolWrapper(readEventArgs); // Creates with incomplete state: IMA should be set before using readEventArgs.UserToken = new ReceiveCallbackContext(poolWrapper, this.MessageFactory, this.serializationManager, this.loggerFactory); allocatedSocketEventArgsCounter.Increment(); return poolWrapper; } private void FreeSocketAsyncEventArgs(SocketAsyncEventArgs args) { var receiveToken = (ReceiveCallbackContext) args.UserToken; receiveToken.Reset(); args.AcceptSocket = null; checkedInSocketEventArgsCounter.Increment(); receiveEventArgsPool.Free(receiveToken.SaeaPoolWrapper); } private static void OnReceiveCompleted(object sender, SocketAsyncEventArgs e) { if (e.LastOperation != SocketAsyncOperation.Receive) { throw new ArgumentException("The last operation completed on the socket was not a receive"); } var rcc = e.UserToken as ReceiveCallbackContext; if (rcc.IMA.Log.IsEnabled(LogLevel.Trace)) rcc.IMA.Log.Trace("Socket receive completed from remote " + e.RemoteEndPoint); rcc.IMA.ProcessReceive(e); } /// <summary> /// This method is invoked when an asynchronous receive operation completes. /// If the remote host closed the connection, then the socket is closed. /// </summary> /// <param name="e">SocketAsyncEventArg associated with the completed receive operation.</param> private void ProcessReceive(SocketAsyncEventArgs e) { var rcc = e.UserToken as ReceiveCallbackContext; // If no data was received, close the connection. This is a normal // situation that shows when the remote host has finished sending data. if (e.BytesTransferred <= 0) { if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Closing recieving socket: " + e.RemoteEndPoint); rcc.IMA.SafeCloseSocket(rcc.Socket); FreeSocketAsyncEventArgs(e); return; } if (e.SocketError != SocketError.Success) { Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException, $"Socket error on new socket during ReceiveAsync with RemoteEndPoint: {e.SocketError}"); rcc.IMA.SafeCloseSocket(rcc.Socket); FreeSocketAsyncEventArgs(e); return; } Socket sock = rcc.Socket; try { rcc.ProcessReceived(e); } catch (Exception ex) { rcc.IMA.Log.Error(ErrorCode.Messaging_IMA_BadBufferReceived, $"ProcessReceivedBuffer exception with RemoteEndPoint {rcc.RemoteEndPoint}: ", ex); // There was a problem with the buffer, presumably data corruption, so give up rcc.IMA.SafeCloseSocket(rcc.Socket); FreeSocketAsyncEventArgs(e); // And we're done return; } StartReceiveAsync(sock, e, rcc.IMA); } protected virtual void HandleMessage(Message msg, Socket receivedOnSocket) { // See it's a Ping message, and if so, short-circuit it object pingObj; var requestContext = msg.RequestContextData; if (requestContext != null && requestContext.TryGetValue(RequestContext.PING_APPLICATION_HEADER, out pingObj) && pingObj is bool && (bool)pingObj) { MessagingStatisticsGroup.OnPingReceive(msg.SendingSilo); if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Responding to Ping from {0}", msg.SendingSilo); if (!msg.TargetSilo.Equals(MessageCenter.MyAddress)) // got ping that is not destined to me. For example, got a ping to my older incarnation. { MessagingStatisticsGroup.OnRejectedMessage(msg); Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, $"The target silo is no longer active: target was {msg.TargetSilo.ToLongString()}, but this silo is {MessageCenter.MyAddress.ToLongString()}. " + $"The rejected ping message is {msg}."); MessageCenter.OutboundQueue.SendMessage(rejection); } else { var response = this.MessageFactory.CreateResponseMessage(msg); response.BodyObject = Response.Done; MessageCenter.SendMessage(response); } return; } // sniff message headers for directory cache management sniffIncomingMessageHandler?.Invoke(msg); // Don't process messages that have already timed out if (msg.IsExpired) { msg.DropExpiredMessage(MessagingStatisticsGroup.Phase.Receive); return; } // If we've stopped application message processing, then filter those out now // Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here. if (MessageCenter.IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && !Constants.SystemMembershipTableId.Equals(msg.SendingGrain)) { // We reject new requests, and drop all other messages if (msg.Direction != Message.Directions.Request) return; MessagingStatisticsGroup.OnRejectedMessage(msg); var reject = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, "Silo stopping"); MessageCenter.SendMessage(reject); return; } // Make sure the message is for us. Note that some control messages may have no target // information, so a null target silo is OK. if ((msg.TargetSilo == null) || msg.TargetSilo.Matches(MessageCenter.MyAddress)) { // See if it's a message for a client we're proxying. if (MessageCenter.IsProxying && MessageCenter.TryDeliverToProxy(msg)) return; // Nope, it's for us MessageCenter.InboundQueue.PostMessage(msg); return; } if (!msg.TargetSilo.Endpoint.Equals(MessageCenter.MyAddress.Endpoint)) { // If the message is for some other silo altogether, then we need to forward it. if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Forwarding message {0} from {1} to silo {2}", msg.Id, msg.SendingSilo, msg.TargetSilo); MessageCenter.OutboundQueue.SendMessage(msg); return; } // If the message was for this endpoint but an older epoch, then reject the message // (if it was a request), or drop it on the floor if it was a response or one-way. if (msg.Direction == Message.Directions.Request) { MessagingStatisticsGroup.OnRejectedMessage(msg); Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Transient, string.Format("The target silo is no longer active: target was {0}, but this silo is {1}. The rejected message is {2}.", msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg)); MessageCenter.OutboundQueue.SendMessage(rejection); if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Rejecting an obsolete request; target was {0}, but this silo is {1}. The rejected message is {2}.", msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg); } } private void RestartAcceptingSocket() { try { if (this.isStopping) { if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("System is stopping, I will not restart the accepting socket"); return; } if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Restarting of the accepting socket"); SocketManager.CloseSocket(AcceptingSocket); AcceptingSocket = MessageCenter.SocketManager.GetAcceptingSocketForEndpoint(listenAddress); AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE); StartAccept(null); } catch (Exception ex) { Log.Error(ErrorCode.Runtime_Error_100016, "Unable to create a new accepting socket", ex); throw; } } private void SafeCloseSocket(Socket sock) { RecordClosedSocket(sock); SocketManager.CloseSocket(sock); } private class ReceiveCallbackContext { private readonly MessageFactory messageFactory; private readonly IncomingMessageBuffer _buffer; private Socket socket; public Socket Socket { get { return socket; } internal set { socket = value; RemoteEndPoint = socket.RemoteEndPoint; } } public EndPoint RemoteEndPoint { get; private set; } public IncomingMessageAcceptor IMA { get; internal set; } public SaeaPoolWrapper SaeaPoolWrapper { get; } public ReceiveCallbackContext(SaeaPoolWrapper poolWrapper, MessageFactory messageFactory, SerializationManager serializationManager, ILoggerFactory loggerFactory) { this.messageFactory = messageFactory; SaeaPoolWrapper = poolWrapper; _buffer = new IncomingMessageBuffer(loggerFactory, serializationManager); } public void ProcessReceived(SocketAsyncEventArgs e) { #if TRACK_DETAILED_STATS ThreadTrackingStatistic tracker = null; if (StatisticsCollector.CollectThreadTimeTrackingStats) { int id = System.Threading.Thread.CurrentThread.ManagedThreadId; if (!trackers.TryGetValue(id, out tracker)) { tracker = new ThreadTrackingStatistic("ThreadPoolThread." + System.Threading.Thread.CurrentThread.ManagedThreadId); bool added = trackers.TryAdd(id, tracker); if (added) { tracker.OnStartExecution(); } } tracker.OnStartProcessing(); } #endif try { _buffer.UpdateReceivedData(e.Buffer, e.BytesTransferred); while (true) { Message msg = null; try { if (!this._buffer.TryDecodeMessage(out msg)) break; this.IMA.HandleMessage(msg, this.Socket); } catch (Exception exception) { // If deserialization completely failed or the message was one-way, rethrow the exception // so that it can be handled at another level. if (msg?.Headers == null || msg.Direction != Message.Directions.Request) { throw; } // The message body was not successfully decoded, but the headers were. // Send a fast fail to the caller. MessagingStatisticsGroup.OnRejectedMessage(msg); var response = this.messageFactory.CreateResponseMessage(msg); response.Result = Message.ResponseTypes.Error; response.BodyObject = Response.ExceptionResponse(exception); // Send the error response and continue processing the next message. this.IMA.MessageCenter.SendMessage(response); } } } catch (Exception exc) { try { // Log details of receive state machine IMA.Log.Error(ErrorCode.MessagingProcessReceiveBufferException, $"Exception trying to process {e.BytesTransferred} bytes from endpoint {RemoteEndPoint}", exc); } catch (Exception) { } _buffer.Reset(); // Reset back to a hopefully good base state throw; } #if TRACK_DETAILED_STATS finally { if (StatisticsCollector.CollectThreadTimeTrackingStats) { tracker.IncrementNumberOfProcessed(); tracker.OnStopProcessing(); } } #endif } public void Reset() { _buffer.Reset(); } } private class SaeaPoolWrapper : PooledResource<SaeaPoolWrapper> { public SocketAsyncEventArgs SocketAsyncEventArgs { get; } public SaeaPoolWrapper(SocketAsyncEventArgs socketAsyncEventArgs) { SocketAsyncEventArgs = socketAsyncEventArgs; } } } }
// StrategyCam v1.0 // 2014-03-04 (YYYY-MM-DD) // by Fabian Hager using UnityEngine; using System.Collections; [AddComponentMenu("Camera-Control/Strategy Camera")] public class StrategyCam : MonoBehaviour { // scroll, zoom, rotate and incline speeds public float scrollSpeed = 2.5f; public float zoomSpeed = 4f; public float rotateSpeed = 1f; public float inclineSpeed = 2.5f; // speed factors for key-controlled zoom, rotate and incline public float keyZoomSpeedFactor = 2f; public float keyRotateSpeedFactor = 1.5f; public float keyInclineSpeedFactor = 0.5f; // scroll, zoom, rotate and incline smoothnesses (higher values make the camera take more time to reach its intended position) public float scrollAndZoomSmooth = 0.08f; public float rotateAndInclineSmooth = 0.03f; // initital values for lookAt, zoom, rotation and inclination public float initialRotation = 0f; // 1 is one revolution public float initialInclination = 0.3f; // 0 is top-down, 1 is parallel to the x-z-plane public float initialZoom = 10f; // distance between camera position and the point on the x-z-plane the camera looks at public Vector3 initialLookAt = new Vector3(0f, 0f, 0f); // zoom to or from cursor modes public bool zoomOutFromCursor = false; public bool zoomInToCursor = true; // snapping rotation or inclination back to initial values after rotation or inclination keys have been released public bool snapBackRotation = false; public bool snapBackInclination = false; // Edge Scrolling public bool MouseEdgeScrolling = false; // snapping speed (for rotation and inclination) public float snapBackSpeed = 6f; // zooming in increases the inclination (from minInclination to maxInclination) public bool inclinationByZoom = false; // scroll, zoom, and inclination boundaries public float minX = -10f; public float maxX = 10f; public float minZ = -10f; public float maxZ = 10f; public float minZoom = 0.4f; public float maxZoom = 40f; public float minInclination = 0f; public float maxInclination = 0.9f; public float minRotation = -1f; public float maxRotation = 1f; // x-wrap and z-wrap (when reaching the boundaries the cam will jump to the other side, good for continuous maps) public bool xWrap = false; public bool zWrap = false; // keys for different controls public KeyCode keyScrollForward = KeyCode.W; public KeyCode keyScrollLeft = KeyCode.A; public KeyCode keyScrollBack = KeyCode.S; public KeyCode keyScrollRight = KeyCode.D; public KeyCode keyRotateAndIncline = KeyCode.LeftAlt; public KeyCode keyZoomIn = KeyCode.None; public KeyCode keyZoomOut = KeyCode.None; public KeyCode keyRotateLeft = KeyCode.None; public KeyCode keyRotateRight = KeyCode.None; public KeyCode keyInclineUp = KeyCode.None; public KeyCode keyInclineDown = KeyCode.None; // width of the scroll sensitive area at the screen boundaries in px private int scrollBoundaries = 2; // target camera values (approached asymptotically for smoothing) private Vector3 targetLookAt = new Vector3(0f, 0f, 0f); private float targetZoom = 10f; private float targetRotation = 0f; private float targetInclination = 0f; // current camera values private Vector3 currentLookAt = new Vector3(0f, 0f, 0f); private float currentZoom = 10f; private float currentRotation = 0f; private float currentInclination = 0.3f; // snapping takes constant time (regardless of snapping distance), these values store where the snapping began (when the rotate and incline button was released) private float snapRotation = 0f; private float snapInclination = 0f; // for calculations private Vector3 viewDirection = new Vector3(0f, 0f, 0f); private float zoomRequest = 0f; private float rotateRequest = 0f; private float inclineRequest = 0f; private float targetSnap = 0f; private Vector3 xDirection = new Vector3(0f, 0f, 0f); private Vector3 yDirection = new Vector3(0f, 0f, 0f); private float oldTargetZoom = 0f; private float zoomPart = 0f; private Vector3 cursorPosition = new Vector3(0f, 0f, 0f); private Vector3 cursorDifference = new Vector3(0f, 0f, 0f); // for calculations (making camera behaviour framerate-independent) private float time = 0f; // to determine if camera is currently being rotated by the user private bool rotating = false; private Vector3 lastMousePosition = new Vector3(0f, 0f); // for trigonometry private static float TAU = Mathf.PI*2; private float LastFrameLookat = 0; // access methods for camera values for "jumps" private float desiredZoom = 0f; private bool changeZoom = false; public void SetZoom(float zoom) { if (zoom < minZoom) zoom = minZoom; if (zoom > maxZoom) zoom = maxZoom; desiredZoom = zoom; changeZoom = true; } private float desiredRotation = 0f; private bool changeRotation = false; public void SetRotation(float rotation) { if (rotation < minRotation) rotation = minRotation; if (rotation > maxRotation) rotation = maxRotation; desiredRotation = rotation; changeRotation = true; } private float desiredInclination = 0f; private bool changeInclination = false; public void SetInclination(float inclination) { if (inclination < minInclination) inclination = minInclination; if (inclination > maxInclination) inclination = maxInclination; desiredInclination = inclination; changeInclination = true; } private Vector3 desiredLookAt = new Vector3(0f, 0f, 0f); private bool changeLookAt = false; public void setLookAt(Vector3 lookAt) { if (lookAt.x < minX) lookAt.x = minX; if (lookAt.x > maxX) lookAt.x = maxX; if (lookAt.z < minZ) lookAt.z = minZ; if (lookAt.z > maxZ) lookAt.z = maxZ; lookAt.y = 0f; desiredLookAt = lookAt; changeLookAt = true; } void Update () { // handle the "jumps" if (changeZoom) { targetZoom = desiredZoom; changeZoom = false; } if (changeRotation) { targetRotation = desiredRotation; changeRotation = false; } if (changeLookAt) { targetLookAt = desiredLookAt; changeLookAt = false; } if (changeInclination) { targetInclination = desiredInclination; changeInclination = false; } time = Time.deltaTime; // determine directions the camera should move in when scrolling yDirection.x = transform.up.x; yDirection.y = 0; yDirection.z = transform.up.z; yDirection = yDirection.normalized; xDirection.x = transform.right.x; xDirection.y = 0; xDirection.z = transform.right.z; xDirection = xDirection.normalized; // scrolling when the cursor touches the screen boundaries or when WASD keys are used if((Input.mousePosition.x >= Screen.width - scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollRight)) { targetLookAt.x = targetLookAt.x + xDirection.x*scrollSpeed*time*targetZoom; targetLookAt.z = targetLookAt.z + xDirection.z*scrollSpeed*time*targetZoom; } if((Input.mousePosition.x <= scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollLeft)) { targetLookAt.x = targetLookAt.x - xDirection.x*scrollSpeed*time*targetZoom; targetLookAt.z = targetLookAt.z - xDirection.z*scrollSpeed*time*targetZoom; } if((Input.mousePosition.y >= Screen.height - scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollForward)) { targetLookAt.x = targetLookAt.x + yDirection.x*scrollSpeed*time*targetZoom; targetLookAt.z = targetLookAt.z + yDirection.z*scrollSpeed*time*targetZoom; } if((Input.mousePosition.y <= scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollBack)) { targetLookAt.x = targetLookAt.x - yDirection.x*scrollSpeed*time*targetZoom; targetLookAt.z = targetLookAt.z - yDirection.z*scrollSpeed*time*targetZoom; } //if (Input.GetMouseButton(0)) //{ // if left button pressed... // cursorDifference = Input.mousePosition - lastMousePosition; // targetLookAt += cursorDifference; // Debug.Log("thing " + cursorDifference.x); // lastMousePosition = Input.mousePosition; //} if (Input.GetMouseButton(0)) // MMB { // Hold button and drag camera around targetLookAt -= new Vector3(Input.GetAxis("Mouse X") * 2 * currentZoom * Time.deltaTime, 0, Input.GetAxis("Mouse Y") * 2 * currentZoom * Time.deltaTime); } // zooming when the mousewheel or the zoom keys are used zoomRequest = Input.GetAxis("Mouse ScrollWheel"); if (Input.GetKey(keyZoomIn)) zoomRequest += keyZoomSpeedFactor*time; if (Input.GetKey(keyZoomOut)) zoomRequest -= keyZoomSpeedFactor*time; if (zoomRequest != 0) { // needed for zoom to cursor behaviour oldTargetZoom = targetZoom; // zoom targetZoom = targetZoom - zoomSpeed*targetZoom*zoomRequest; // enforce zoom boundaries if (targetZoom > maxZoom) targetZoom = maxZoom; if (targetZoom < minZoom) targetZoom = minZoom; // zoom-dependent inclination behaviour if (inclinationByZoom) { // determine where the current targetZoom is in the range of the zoomBoundaries zoomPart = 1f-((targetZoom-minZoom)/maxZoom); // make sure the inclination increase mostly happens at the lowest zoom levels (when the camera is closest to the x-z-plane) zoomPart = zoomPart*zoomPart*zoomPart*zoomPart*zoomPart*zoomPart*zoomPart*zoomPart; // apply the inclination targetInclination = minInclination + zoomPart*(maxInclination-minInclination); } // zoom to and from cursor behaviour if ((zoomRequest > 0 && zoomInToCursor) || (zoomRequest < 0 && zoomOutFromCursor)) { // determine the point on the x-z-plane the cursor hovers over cursorPosition = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition).direction; cursorPosition = transform.position + cursorPosition*(transform.position.y/-cursorPosition.y); // move closer to that point (in the same proportion the zoom has just changed) targetLookAt = targetLookAt - ((oldTargetZoom-targetZoom)/(oldTargetZoom))*(targetLookAt - cursorPosition); } } // rotating and inclining when the middle mouse button or Left ALT is pressed rotateRequest = 0f; inclineRequest = 0f; if (Input.GetMouseButton(2) || Input.GetKey(keyRotateAndIncline)) { if (rotating) { // how far the cursor has travelled on screen cursorDifference = Input.mousePosition-lastMousePosition; // determine the rotation rotateRequest += rotateSpeed*0.001f*cursorDifference.x; // determine the inclination inclineRequest -= inclineSpeed*0.001f*cursorDifference.y; } else { // rotation has just started rotating = true; } // store cursor position lastMousePosition = Input.mousePosition; } else { rotating = false; } // key controlled rotation and inclination if (Input.GetKey(keyRotateLeft)) rotateRequest += keyRotateSpeedFactor*rotateSpeed*time; if (Input.GetKey(keyRotateRight)) rotateRequest -= keyRotateSpeedFactor*rotateSpeed*time; if (Input.GetKey(keyInclineUp)) inclineRequest += keyInclineSpeedFactor*inclineSpeed*time; if (Input.GetKey(keyInclineDown)) inclineRequest -= keyInclineSpeedFactor*inclineSpeed*time; if (rotateRequest != 0f) { // apply rotation targetRotation += rotateRequest; // enforce boundaries if (targetRotation > maxRotation) targetRotation = maxRotation; if (targetRotation < minRotation) targetRotation = minRotation; // make sure rotation stays in the interval between -0.5 and 0.5; if (targetRotation > 0.5f) { targetRotation -= 1f; currentRotation -= 1f; } else if (targetRotation < -0.5f) { targetRotation += 1f; currentRotation += 1f; } // in case inclination stops afterwards store the last inclination (for snapping) snapRotation = targetRotation; rotateRequest = 0f; } else if (!rotating) { // snap back if (snapBackRotation) { // determine the next rotation value assuming constant snap speed targetSnap = targetRotation + time*snapBackSpeed*(initialRotation - snapRotation); // finish the snap when it would diverge again (this means it has reached or overshot the initial rotation) if (Mathf.Abs(targetSnap-initialRotation) > Mathf.Abs(targetRotation-initialRotation)) targetSnap = initialRotation; // apply the snap targetRotation = targetSnap; } } if (!inclinationByZoom && inclineRequest != 0f) { // apply inclination targetInclination += inclineRequest; // enforce boundaries if (targetInclination > maxInclination) targetInclination = maxInclination; if (targetInclination < minInclination) targetInclination = minInclination; // in case inclination stops afterwards store the last inclination (for snapping) snapInclination = targetInclination; inclineRequest = 0f; } else if (!rotating) { // snap back if (snapBackInclination && !inclinationByZoom) { // determine the next inclination value assuming constant snap speed targetSnap = targetInclination + time*snapBackSpeed*(initialInclination - snapInclination); // finish the snap when it would diverge again (this means it has reached or overshot the initial inclination) if (Mathf.Abs(targetSnap-initialInclination) > Mathf.Abs(targetInclination-initialInclination)) targetSnap = initialInclination; // apply the snap targetInclination = targetSnap; } } // enforce scroll boundaries if (xWrap) { if (targetLookAt.x > maxX) { targetLookAt.x -= maxX-minX; currentLookAt.x -= maxX-minX; } if (targetLookAt.x < minX) { targetLookAt.x += maxX-minX; currentLookAt.x += maxX-minX; } } else { if (targetLookAt.x > maxX) targetLookAt.x = maxX; if (targetLookAt.x < minX) targetLookAt.x = minX; } if (zWrap) { if (targetLookAt.z > maxZ) { targetLookAt.z -= maxZ-minZ; currentLookAt.z -= maxZ-minZ; } if (targetLookAt.z < minZ) { targetLookAt.z += maxZ-minZ; currentLookAt.z += maxZ-minZ; } } else { if (targetLookAt.z > maxZ) targetLookAt.z = maxZ; if (targetLookAt.z < minZ) targetLookAt.z = minZ; } // calculate the current values (let them approach target values asymptotically - this is the actual smoothing) currentLookAt = currentLookAt - (time*(currentLookAt - targetLookAt))/scrollAndZoomSmooth; currentZoom = currentZoom - (time*(currentZoom - targetZoom))/scrollAndZoomSmooth; currentRotation = currentRotation - (time*(currentRotation - targetRotation))/rotateAndInclineSmooth; if (inclinationByZoom) { // zoom-dependent inclination means the smoothing must be the smoothing when zooming currentInclination = currentInclination - (time*(currentInclination - targetInclination))/scrollAndZoomSmooth; } else { currentInclination = currentInclination - (time*(currentInclination - targetInclination))/rotateAndInclineSmooth; } // calculate the viewDirection of the camera from inclination and rotation viewDirection = (Vector3.down*(1.0f-currentInclination) + new Vector3(Mathf.Sin(currentRotation*TAU), 0, Mathf.Cos(currentRotation*TAU))*(currentInclination)).normalized; // apply the current camera values to move and rotate the camera transform.position = currentLookAt + currentZoom*(-viewDirection); transform.LookAt(currentLookAt); } void Start () { // enforce sanity values (preventing weird effects or NaN results due to division by 0 if (scrollAndZoomSmooth < 0.01f) scrollAndZoomSmooth = 0.01f; if (rotateAndInclineSmooth < 0.01f) rotateAndInclineSmooth = 0.01f; if (minInclination < 0.001f) minInclination = 0.001f; // enforce that initial values are within boundaries if (initialInclination < minInclination) initialInclination = minInclination; if (initialInclination > maxInclination) initialInclination = maxInclination; if (initialRotation < minRotation) initialRotation = minRotation; if (initialRotation > maxRotation) initialRotation = maxRotation; if (initialZoom < minZoom) initialZoom = minZoom; if (initialZoom > maxZoom) initialZoom = maxZoom; //initialLookAt.y = 0f; if (initialLookAt.x > maxX) initialLookAt.x = maxX; if (initialLookAt.x < minX) initialLookAt.x = minX; if (initialLookAt.z > maxZ) initialLookAt.z = maxZ; if (initialLookAt.z < minZ) initialLookAt.z = minZ; // initialise current camera values currentZoom = initialZoom; currentInclination = initialInclination; currentRotation = initialRotation; currentLookAt = initialLookAt; // initialise target camera values (to current camera values) targetLookAt = currentLookAt; targetInclination = currentInclination; targetZoom = currentZoom; targetRotation = currentRotation; } }
/* * UUnit system from UnityCommunity * Heavily modified * 0.4 release by pboechat * http://wiki.unity3d.com/index.php?title=UUnit * http://creativecommons.org/licenses/by-sa/3.0/ */ using System; using System.Text; using System.Collections.Generic; using System.Reflection; namespace PlayFab.UUnit { [AttributeUsage(AttributeTargets.Method)] public class UUnitTestAttribute : Attribute { } public class UUnitTestSuite { private const int TIME_ALIGNMENT_WIDTH = 10; private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(15); private static readonly StringBuilder sb = new StringBuilder(); private readonly List<UUnitTestContext> _testContexts = new List<UUnitTestContext>(); private int _activeIndex = 0; private readonly UUnitTestReport _testReport = new UUnitTestReport(PlayFabSettings.BuildIdentifier); private UUnitActiveState _suiteState = UUnitActiveState.PENDING; private UUnitTestCase activeTestInstance = null; public string GenerateTestSummary() { sb.Length = 0; DateTime now = DateTime.UtcNow, eachStartTime, eachEndTime; int finished = 0, passed = 0, failed = 0, skipped = 0; foreach (var eachContext in _testContexts) { // Count tests if (eachContext.ActiveState == UUnitActiveState.COMPLETE) { finished++; eachStartTime = eachContext.StartTime; eachEndTime = eachContext.EndTime; if (eachContext.FinishState == UUnitFinishState.PASSED) passed++; else if (eachContext.FinishState == UUnitFinishState.SKIPPED) skipped++; else failed++; } else { eachStartTime = eachContext.ActiveState == UUnitActiveState.PENDING ? now : eachContext.StartTime; eachEndTime = now; } // line for each test report if (sb.Length != 0) sb.Append("\n"); var ms = (eachEndTime - eachStartTime).TotalMilliseconds.ToString("0"); for (var i = ms.Length; i < TIME_ALIGNMENT_WIDTH; i++) sb.Append(' '); sb.Append(ms).Append(" ms - ").Append(eachContext.FinishState); sb.Append(" - ").Append(eachContext.Name); if (!string.IsNullOrEmpty(eachContext.TestResultMsg)) { sb.Append(" - ").Append(eachContext.TestResultMsg); // TODO: stacktrace } } sb.AppendFormat("\nTesting complete: {0}/{1} test run, {2} tests passed, {3} tests failed, {4} tests skipped.", finished, _testContexts.Count, passed, failed, skipped); return sb.ToString(); } public TestSuiteReport GetInternalReport() { return _testReport.InternalReport; } public void FindAndAddAllTestCases(Type parent, string filter = null) { if (_suiteState != UUnitActiveState.PENDING) throw new Exception("Must add all tests before executing tests."); #if NETFX_CORE var eachAssembly = typeof(UUnitTestCase).GetTypeInfo().Assembly; // We can only load assemblies known in advance on WSA #else var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var eachAssembly in assemblies) #endif FindAndAddAllTestCases(eachAssembly, parent, filter); } public void FindAndAddAllTestCases(Assembly assembly, Type parent, string filter = null) { if (_suiteState != UUnitActiveState.PENDING) throw new Exception("Must add all tests before executing tests."); var types = assembly.GetTypes(); foreach (var t in types) if (!t.GetTypeInfo().IsAbstract && t.GetTypeInfo().IsSubclassOf(parent)) AddTestsForType(t.AsType(), filter); } private void AddTestsForType(Type testCaseType, string filter = null) { if (_suiteState != UUnitActiveState.PENDING) throw new Exception("Must add all tests before executing tests."); var filterSet = AssembleFilter(filter); UUnitTestCase newTestCase = null; foreach (var constructorInfo in testCaseType.GetTypeInfo().GetConstructors()) { try { newTestCase = (UUnitTestCase)constructorInfo.Invoke(null); } catch (Exception) { } // Ignore it and try the next one } if (newTestCase == null) throw new Exception(testCaseType.Name + " must have a parameter-less constructor."); var methods = testCaseType.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); List<object> attributesList = new List<object>(); foreach (var methodInfo in methods) { attributesList.Clear(); attributesList.AddRange(methodInfo.GetCustomAttributes(typeof(UUnitTestAttribute), false)); if (attributesList.Count == 0 || !MatchesFilters(methodInfo.Name, filterSet)) // There can only be 1, and we only care about attribute existence (no data on attribute), and it has to match the filter continue; Action<UUnitTestContext> eachTestDelegate = CreateDelegate<UUnitTestContext>(testCaseType.Name, newTestCase, methodInfo); if (eachTestDelegate != null) _testContexts.Add(new UUnitTestContext(newTestCase, eachTestDelegate, methodInfo.Name)); } } private static Action<T> CreateDelegate<T>(string typeName, object instance, MethodInfo methodInfo) { Action<T> eachTestDelegate; try { eachTestDelegate = methodInfo.CreateDelegate(typeof(Action<T>), instance) as Action<T>; } catch (Exception e) { var sb2 = new StringBuilder(); sb2.Append(typeName).Append(".").Append(methodInfo.Name).Append(" must match the test delegate signature: Action<T>"); sb2.Append("\n").Append(e); sb2.Append("\nExpected Params: ["); var actionInfo = typeof(Action<T>).GetMethod("Invoke"); foreach (var param in actionInfo.GetParameters()) sb2.Append(param.Name).Append(","); sb2.Append("]"); sb2.Append("\nActual Params: ["); foreach (var param in methodInfo.GetParameters()) sb2.Append(param.Name).Append(","); sb2.Append("]"); throw new Exception(sb2.ToString()); } return eachTestDelegate; } private HashSet<string> AssembleFilter(string filter) { if (string.IsNullOrEmpty(filter)) return null; var filterWords = filter.ToLower().Split(new char[] { '\n', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (filterWords.Length > 0) return new HashSet<string>(filterWords); return null; } private bool MatchesFilters(string name, HashSet<string> filterSet) { if (filterSet == null) return true; var nameLc = name.ToLower(); foreach (var eachFilter in filterSet) if (nameLc.Contains(eachFilter)) return true; return false; } /// <summary> /// Return that tests were run, and all of them reported success /// </summary> public bool AllTestsPassed() { return _testReport.AllTestsPassed(); } /// <summary> /// Tick the test suite. /// This should be called once per Update until it returns true. /// Once it returns true, testing is complete /// </summary> public bool TickTestSuite() { if (_suiteState == UUnitActiveState.COMPLETE) return true; if (_suiteState == UUnitActiveState.PENDING) _suiteState = UUnitActiveState.ACTIVE; // Check if we should cycle to the next test var nextTest = _activeIndex < _testContexts.Count ? _testContexts[_activeIndex] : null; if (nextTest != null && nextTest.ActiveState == UUnitActiveState.COMPLETE) { if (nextTest.FinishState == UUnitFinishState.FAILED && nextTest.retryCount < nextTest.TestInstance.maxRetry) { // Reset the test and try again nextTest.AttemptRetry(); } else { // Record this test result TrackTestResult(nextTest); // Retrys are expired, move to the next test _activeIndex++; nextTest = (_activeIndex >= _testContexts.Count) ? null : _testContexts[_activeIndex]; } } if (nextTest != null && nextTest.ActiveState == UUnitActiveState.PENDING) StartTest(nextTest); else if (nextTest != null) TickTest(nextTest); var testsDone = _activeIndex >= _testContexts.Count; if (testsDone && _suiteState == UUnitActiveState.ACTIVE) { _suiteState = UUnitActiveState.READY; ManageInstance(null, activeTestInstance); // Ensure that the final test is cleaned up } return _suiteState == UUnitActiveState.READY; } private void TrackTestResult(UUnitTestContext testContext) { _testReport.TestComplete(testContext.TestDelegate.Target.GetType().Name + "." + testContext.Name, testContext.FinishState, (int)(testContext.EndTime - testContext.StartTime).TotalMilliseconds, testContext.TestResultMsg, null); } /// <summary> /// Start a test, track which test is active, and manage timers /// </summary> private void StartTest(UUnitTestContext testContext) { ManageInstance(testContext.TestInstance, activeTestInstance); testContext.StartTime = DateTime.UtcNow; testContext.ActiveState = UUnitActiveState.ACTIVE; _testReport.TestStarted(); if (testContext.ActiveState == UUnitActiveState.ACTIVE) Wrap(testContext, testContext.TestInstance.SetUp); if (testContext.ActiveState == UUnitActiveState.ACTIVE) Wrap(testContext, testContext.TestDelegate); // Async tests can't resolve this tick, so just return } /// <summary> /// Ensure that exceptions in any test-functions are relayed to the testContext as failures /// </summary> private void Wrap(UUnitTestContext testContext, Action<UUnitTestContext> testFunc) { try { testFunc(testContext); } catch (UUnitSkipException uu) { // Silence the assert and ensure the test is marked as complete - The exception is just to halt the test process testContext.EndTest(UUnitFinishState.SKIPPED, uu.Message); } catch (UUnitException uu) { // Silence the assert and ensure the test is marked as complete - The exception is just to halt the test process testContext.EndTest(UUnitFinishState.FAILED, uu.Message + "\n" + uu.StackTrace); } catch (Exception e) { // Report this exception as an unhandled failure in the test testContext.EndTest(UUnitFinishState.FAILED, e.ToString()); } } /// <summary> /// Manage the ClassSetUp and ClassTearDown functions for each UUnitTestCase /// </summary> private void ManageInstance(UUnitTestCase newtestInstance, UUnitTestCase oldTestInstance) { if (ReferenceEquals(newtestInstance, oldTestInstance)) return; if (oldTestInstance != null) oldTestInstance.ClassTearDown(); if (newtestInstance != null) newtestInstance.ClassSetUp(); activeTestInstance = newtestInstance; } private void TickTest(UUnitTestContext testContext) { var now = DateTime.UtcNow; var timedOut = (now - testContext.StartTime) > TestTimeout; if (testContext.ActiveState != UUnitActiveState.READY && !timedOut) // Not finished & not timed out { Wrap(testContext, testContext.TestInstance.Tick); return; } else if (testContext.ActiveState == UUnitActiveState.ACTIVE && timedOut) { testContext.EndTest(UUnitFinishState.TIMEDOUT, "Test duration exceeded maxumum"); } testContext.EndTime = now; Wrap(testContext, testContext.TestInstance.TearDown); testContext.ActiveState = UUnitActiveState.COMPLETE; } } }
using System; #if !SILVERLIGHT using System.Collections.Concurrent; #else using TvdP.Collections; #endif using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace AutoMapper { public class TypeMapFactory : ITypeMapFactory { private static readonly ConcurrentDictionary<Type, TypeInfo> _typeInfos = new ConcurrentDictionary<Type, TypeInfo>(); public TypeMap CreateTypeMap(Type sourceType, Type destinationType, IMappingOptions options) { var sourceTypeInfo = GetTypeInfo(sourceType); var destTypeInfo = GetTypeInfo(destinationType); var typeMap = new TypeMap(sourceTypeInfo, destTypeInfo); foreach (var destProperty in destTypeInfo.GetPublicWriteAccessors()) { var members = new LinkedList<MemberInfo>(); if (MapDestinationPropertyToSource(members, sourceTypeInfo, destProperty.Name, options)) { var resolvers = members.Select(mi => mi.ToMemberGetter()); var destPropertyAccessor = destProperty.ToMemberAccessor(); #if !SILVERLIGHT typeMap.AddPropertyMap(destPropertyAccessor, resolvers); #else typeMap.AddPropertyMap(destPropertyAccessor, resolvers.Cast<IValueResolver>()); #endif } } if (!destinationType.IsAbstract && destinationType.IsClass) { foreach (var destCtor in destTypeInfo.GetConstructors().OrderByDescending(ci => ci.GetParameters().Length)) { if (MapDestinationCtorToSource(typeMap, destCtor, sourceTypeInfo, options)) { break; } } } return typeMap; } private bool MapDestinationCtorToSource(TypeMap typeMap, ConstructorInfo destCtor, TypeInfo sourceTypeInfo, IMappingOptions options) { var parameters = new List<ConstructorParameterMap>(); foreach (var parameter in destCtor.GetParameters()) { var members = new LinkedList<MemberInfo>(); if (!MapDestinationPropertyToSource(members, sourceTypeInfo, parameter.Name, options)) return false; var resolvers = members.Select(mi => mi.ToMemberGetter()); var param = new ConstructorParameterMap(parameter, resolvers.ToArray()); parameters.Add(param); } typeMap.AddConstructorMap(destCtor, parameters); return true; } private static TypeInfo GetTypeInfo(Type type) { TypeInfo typeInfo = _typeInfos.GetOrAdd(type, t => new TypeInfo(type)); return typeInfo; } private bool MapDestinationPropertyToSource(LinkedList<MemberInfo> resolvers, TypeInfo sourceType, string nameToSearch, IMappingOptions mappingOptions) { if (string.IsNullOrEmpty(nameToSearch)) return true; var sourceProperties = sourceType.GetPublicReadAccessors(); var sourceNoArgMethods = sourceType.GetPublicNoArgMethods(); MemberInfo resolver = FindTypeMember(sourceProperties, sourceNoArgMethods, nameToSearch, mappingOptions); bool foundMatch = resolver != null; if (foundMatch) { resolvers.AddLast(resolver); } else { string[] matches = mappingOptions.DestinationMemberNamingConvention.SplittingExpression .Matches(nameToSearch) .Cast<Match>() .Select(m => m.Value) .ToArray(); for (int i = 1; (i <= matches.Length) && (!foundMatch); i++) { NameSnippet snippet = CreateNameSnippet(matches, i, mappingOptions); var valueResolver = FindTypeMember(sourceProperties, sourceNoArgMethods, snippet.First, mappingOptions); if (valueResolver != null) { resolvers.AddLast(valueResolver); foundMatch = MapDestinationPropertyToSource(resolvers, GetTypeInfo(valueResolver.GetMemberType()), snippet.Second, mappingOptions); if (!foundMatch) { resolvers.RemoveLast(); } } } } return foundMatch; } private static MemberInfo FindTypeMember(IEnumerable<MemberInfo> modelProperties, IEnumerable<MethodInfo> getMethods, string nameToSearch, IMappingOptions mappingOptions) { MemberInfo pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, nameToSearch)); if (pi != null) return pi; MethodInfo mi = getMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch)); if (mi != null) return mi; pi = modelProperties.FirstOrDefault( prop => NameMatches(mappingOptions.SourceMemberNameTransformer(prop.Name), nameToSearch)); if (pi != null) return pi; mi = getMethods.FirstOrDefault( m => NameMatches(mappingOptions.SourceMemberNameTransformer(m.Name), nameToSearch)); if (mi != null) return mi; pi = modelProperties.FirstOrDefault( prop => NameMatches(prop.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch))); if (pi != null) return pi; pi = getMethods.FirstOrDefault( m => NameMatches(m.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch))); if (pi != null) return pi; return null; } private static bool NameMatches(string memberName, string nameToMatch) { return String.Compare(memberName, nameToMatch, StringComparison.OrdinalIgnoreCase) == 0; } private NameSnippet CreateNameSnippet(IEnumerable<string> matches, int i, IMappingOptions mappingOptions) { return new NameSnippet { First = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Take(i).ToArray()), Second = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Skip(i).ToArray()) }; } private class NameSnippet { public string First { get; set; } public string Second { get; set; } } } }
using System; using NUnit.Framework; using SharpVectors.Dom.Svg; namespace SharpVectors.UnitTests.Svg.BasicTypesAndInterfaces { // The resulting test values were generated using MuPad Light // NOTE: The original implementation of SvgMatrix returned doubles when accessing properties. To stay consistent with the SVG specification, these were switched to floats. The original double values used in the assertions have been left "just in case". They are being converted to floats using the trailing "f". [TestFixture] public class SvgMatrixTests { [Test] public void TestConstructor() { ISvgMatrix m = new SvgMatrix(); Assert.AreEqual(1, m.A); Assert.AreEqual(0, m.B); Assert.AreEqual(0, m.C); Assert.AreEqual(1, m.D); Assert.AreEqual(0, m.E); Assert.AreEqual(0, m.F); } [Test] public void TestConstructor2() { ISvgMatrix m = new SvgMatrix(1, 2, 3, 4, 5, 6); Assert.AreEqual(1, m.A); Assert.AreEqual(2, m.B); Assert.AreEqual(3, m.C); Assert.AreEqual(4, m.D); Assert.AreEqual(5, m.E); Assert.AreEqual(6, m.F); } [Test] public void TestMultiply() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = new SvgMatrix(7, 8, 9, 10, 11, 12); ISvgMatrix m3 = m1.Multiply(m2); Assert.AreEqual(31, m3.A); Assert.AreEqual(46, m3.B); Assert.AreEqual(39, m3.C); Assert.AreEqual(58, m3.D); Assert.AreEqual(52, m3.E); Assert.AreEqual(76, m3.F); } [Test] public void TestInverse() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.Inverse(); Assert.AreEqual(-2, m2.A); Assert.AreEqual(1, m2.B); Assert.AreEqual(1.5, m2.C); Assert.AreEqual(-0.5, m2.D); Assert.AreEqual(1, m2.E); Assert.AreEqual(-2, m2.F); } [Test] [ExpectedException(typeof(SvgException))] public void TestNoInverse() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 6, 0, 0); ISvgMatrix m2 = m1.Inverse(); } [Test] public void TestTranslate() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.Translate(10,20); Assert.AreEqual(1, m2.A); Assert.AreEqual(2, m2.B); Assert.AreEqual(3, m2.C); Assert.AreEqual(4, m2.D); Assert.AreEqual(75, m2.E); Assert.AreEqual(106, m2.F); } [Test] public void TestScale() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.Scale(10); Assert.AreEqual(10, m2.A); Assert.AreEqual(20, m2.B); Assert.AreEqual(30, m2.C); Assert.AreEqual(40, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] public void TestScaleNonUniform() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.ScaleNonUniform(10,20); Assert.AreEqual(10, m2.A); Assert.AreEqual(20, m2.B); Assert.AreEqual(60, m2.C); Assert.AreEqual(80, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] public void TestRotate() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.Rotate(30); Assert.AreEqual(2.36602540378444f, m2.A); Assert.AreEqual(3.73205080756888f, m2.B); Assert.AreEqual(2.09807621135332f, m2.C); Assert.AreEqual(2.46410161513775f, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] public void TestRotateFromVector() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.RotateFromVector(1.73205080756888f, 1); Assert.AreEqual(2.36602540378444f, m2.A); Assert.AreEqual(3.73205080756888f, m2.B); Assert.AreEqual(2.09807621135332f, m2.C); //D property incorrect when using doubles, probably due to rounding //Assert.AreEqual(2.46410161513775, m2.D); Assert.AreEqual(2.46410161513776f, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] [ExpectedException(typeof(SvgException))] public void TestRotateFromVectorZeroX() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 6, 0, 0); ISvgMatrix m2 = m1.RotateFromVector(0, 1); } [Test] [ExpectedException(typeof(SvgException))] public void TestRotateFromVectorZeroY() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 6, 0, 0); ISvgMatrix m2 = m1.RotateFromVector(1, 0); } [Test] public void TestFlipX() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.FlipX(); Assert.AreEqual(-1, m2.A); Assert.AreEqual(-2, m2.B); Assert.AreEqual(3, m2.C); Assert.AreEqual(4, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] public void TestFlipY() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.FlipY(); Assert.AreEqual(1, m2.A); Assert.AreEqual(2, m2.B); Assert.AreEqual(-3, m2.C); Assert.AreEqual(-4, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] public void TestSkewX() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.SkewX(30); Assert.AreEqual(1, m2.A); Assert.AreEqual(2, m2.B); Assert.AreEqual(3.57735026918963f, m2.C); Assert.AreEqual(5.15470053837925f, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] public void TestSkewY() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = m1.SkewY(30); Assert.AreEqual(2.73205080756888f, m2.A); Assert.AreEqual(4.3094010767585f, m2.B); Assert.AreEqual(3, m2.C); Assert.AreEqual(4, m2.D); Assert.AreEqual(5, m2.E); Assert.AreEqual(6, m2.F); } [Test] public void TestMultiply2() { ISvgMatrix m1 = new SvgMatrix(1, 2, 3, 4, 5, 6); ISvgMatrix m2 = new SvgMatrix(7, 8, 9, 10, 11, 12); SvgMatrix m3 = (SvgMatrix) m1 * (SvgMatrix) m2; Assert.AreEqual(31, m3.A); Assert.AreEqual(46, m3.B); Assert.AreEqual(39, m3.C); Assert.AreEqual(58, m3.D); Assert.AreEqual(52, m3.E); Assert.AreEqual(76, m3.F); } } }
#region Header // // Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Autodesk.Revit.DB; namespace RevitLookup.Snoop.Forms { /// <summary> /// Summary description for Object form. /// </summary> public class Parameters : System.Windows.Forms.Form { protected System.Windows.Forms.Button m_bnOK; protected System.Windows.Forms.TreeView m_tvObjs; protected System.Windows.Forms.ContextMenu m_cntxMenuObjId; protected System.Windows.Forms.MenuItem m_mnuItemBrowseReflection; protected System.Windows.Forms.ListView m_lvData; protected System.Windows.Forms.ColumnHeader m_lvCol_label; protected System.Windows.Forms.ColumnHeader m_lvCol_value; private Button m_bnParamEnums; private Button m_bnParamEnumsMap; protected Snoop.Collectors.CollectorObj m_snoopCollector = new Snoop.Collectors.CollectorObj(); protected System.Object m_curObj; Element m_elem; private ContextMenuStrip listViewContextMenuStrip; private System.Windows.Forms.MenuItem m_mnuItemCopy; private ToolStripMenuItem copyToolStripMenuItem; private ToolStrip toolStrip1; private ToolStripButton toolStripButton1; private ToolStripButton toolStripButton2; private PrintDialog m_printDialog; private System.Drawing.Printing.PrintDocument m_printDocument; private PrintPreviewDialog m_printPreviewDialog; private IContainer components; private Int32[] m_maxWidths; private ToolStripButton toolStripButton3; private Int32 m_currentPrintItem = 0; public Parameters(Element elem, ParameterSet paramSet) { m_elem = elem; // this constructor is for derived classes to call InitializeComponent(); m_tvObjs.BeginUpdate(); AddParametersToTree(paramSet); m_tvObjs.ExpandAll(); m_tvObjs.EndUpdate(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> protected void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Parameters)); this.m_tvObjs = new System.Windows.Forms.TreeView(); this.m_cntxMenuObjId = new System.Windows.Forms.ContextMenu(); this.m_mnuItemCopy = new System.Windows.Forms.MenuItem(); this.m_mnuItemBrowseReflection = new System.Windows.Forms.MenuItem(); this.m_bnOK = new System.Windows.Forms.Button(); this.m_lvData = new System.Windows.Forms.ListView(); this.m_lvCol_label = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.m_lvCol_value = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.listViewContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.m_bnParamEnums = new System.Windows.Forms.Button(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.m_printDialog = new System.Windows.Forms.PrintDialog(); this.m_printDocument = new System.Drawing.Printing.PrintDocument(); this.m_printPreviewDialog = new System.Windows.Forms.PrintPreviewDialog(); this.m_bnParamEnumsMap = new System.Windows.Forms.Button(); this.listViewContextMenuStrip.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // m_tvObjs // this.m_tvObjs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.m_tvObjs.ContextMenu = this.m_cntxMenuObjId; this.m_tvObjs.HideSelection = false; this.m_tvObjs.Location = new System.Drawing.Point(11, 38); this.m_tvObjs.Name = "m_tvObjs"; this.m_tvObjs.Size = new System.Drawing.Size(248, 415); this.m_tvObjs.TabIndex = 0; this.m_tvObjs.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreeNodeSelected); this.m_tvObjs.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.TreeNodeSelected); // // m_cntxMenuObjId // this.m_cntxMenuObjId.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.m_mnuItemCopy, this.m_mnuItemBrowseReflection}); // // m_mnuItemCopy // this.m_mnuItemCopy.Index = 0; this.m_mnuItemCopy.Text = "Copy"; this.m_mnuItemCopy.Click += new System.EventHandler(this.ContextMenuClick_Copy); // // m_mnuItemBrowseReflection // this.m_mnuItemBrowseReflection.Index = 1; this.m_mnuItemBrowseReflection.Text = "Browse Using Reflection..."; this.m_mnuItemBrowseReflection.Click += new System.EventHandler(this.ContextMenuClick_BrowseReflection); // // m_bnOK // this.m_bnOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.m_bnOK.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.m_bnOK.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnOK.Location = new System.Drawing.Point(476, 459); this.m_bnOK.Name = "m_bnOK"; this.m_bnOK.Size = new System.Drawing.Size(75, 23); this.m_bnOK.TabIndex = 2; this.m_bnOK.Text = "OK"; // // m_lvData // this.m_lvData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_lvData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.m_lvCol_label, this.m_lvCol_value}); this.m_lvData.ContextMenuStrip = this.listViewContextMenuStrip; this.m_lvData.FullRowSelect = true; this.m_lvData.GridLines = true; this.m_lvData.Location = new System.Drawing.Point(275, 38); this.m_lvData.Name = "m_lvData"; this.m_lvData.Size = new System.Drawing.Size(504, 415); this.m_lvData.TabIndex = 3; this.m_lvData.UseCompatibleStateImageBehavior = false; this.m_lvData.View = System.Windows.Forms.View.Details; this.m_lvData.Click += new System.EventHandler(this.DataItemSelected); this.m_lvData.DoubleClick += new System.EventHandler(this.DataItemSelected); // // m_lvCol_label // this.m_lvCol_label.Text = "Field"; this.m_lvCol_label.Width = 200; // // m_lvCol_value // this.m_lvCol_value.Text = "Value"; this.m_lvCol_value.Width = 300; // // listViewContextMenuStrip // this.listViewContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.copyToolStripMenuItem}); this.listViewContextMenuStrip.Name = "listViewContextMenuStrip"; this.listViewContextMenuStrip.Size = new System.Drawing.Size(103, 26); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = global::RevitLookup.Properties.Resources.Copy; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size(102, 22); this.copyToolStripMenuItem.Text = "Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.CopyToolStripMenuItem_Click); // // m_bnParamEnums // this.m_bnParamEnums.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.m_bnParamEnums.Location = new System.Drawing.Point(11, 459); this.m_bnParamEnums.Name = "m_bnParamEnums"; this.m_bnParamEnums.Size = new System.Drawing.Size(130, 23); this.m_bnParamEnums.TabIndex = 4; this.m_bnParamEnums.Text = "Built-in Enums Snoop..."; this.m_bnParamEnums.UseVisualStyleBackColor = true; this.m_bnParamEnums.Click += new System.EventHandler(this.OnBnEnumSnoop); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton1, this.toolStripButton2, this.toolStripButton3}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(800, 25); this.toolStrip1.TabIndex = 5; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = global::RevitLookup.Properties.Resources.Print; this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.Text = "Print"; this.toolStripButton1.Click += new System.EventHandler(this.PrintMenuItem_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = global::RevitLookup.Properties.Resources.Preview; this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 22); this.toolStripButton2.Text = "Print Preview"; this.toolStripButton2.Click += new System.EventHandler(this.PrintPreviewMenuItem_Click); // // toolStripButton3 // this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton3.Image = global::RevitLookup.Properties.Resources.Copy; this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton3.Name = "toolStripButton3"; this.toolStripButton3.Size = new System.Drawing.Size(23, 22); this.toolStripButton3.Text = "Copy To Clipboard"; this.toolStripButton3.Click += new System.EventHandler(this.ContextMenuClick_Copy); // // m_printDialog // this.m_printDialog.Document = this.m_printDocument; this.m_printDialog.UseEXDialog = true; // // m_printDocument // this.m_printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.PrintDocument_PrintPage); // // m_printPreviewDialog // this.m_printPreviewDialog.AutoScrollMargin = new System.Drawing.Size(0, 0); this.m_printPreviewDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0); this.m_printPreviewDialog.ClientSize = new System.Drawing.Size(400, 300); this.m_printPreviewDialog.Document = this.m_printDocument; this.m_printPreviewDialog.Enabled = true; this.m_printPreviewDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("m_printPreviewDialog.Icon"))); this.m_printPreviewDialog.Name = "m_printPreviewDialog"; this.m_printPreviewDialog.Visible = false; // // m_bnParamEnumsMap // this.m_bnParamEnumsMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.m_bnParamEnumsMap.Location = new System.Drawing.Point(153, 459); this.m_bnParamEnumsMap.Name = "m_bnParamEnumsMap"; this.m_bnParamEnumsMap.Size = new System.Drawing.Size(130, 23); this.m_bnParamEnumsMap.TabIndex = 6; this.m_bnParamEnumsMap.Text = "Built-in Enums Map..."; this.m_bnParamEnumsMap.UseVisualStyleBackColor = true; this.m_bnParamEnumsMap.Click += new System.EventHandler(this.OnBnEnumMap); // // Parameters // this.AcceptButton = this.m_bnOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.m_bnOK; this.ClientSize = new System.Drawing.Size(800, 489); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.m_bnParamEnumsMap); this.Controls.Add(this.m_bnParamEnums); this.Controls.Add(this.m_lvData); this.Controls.Add(this.m_bnOK); this.Controls.Add(this.m_tvObjs); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(650, 200); this.Name = "Parameters"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Snoop Parameters"; this.listViewContextMenuStrip.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion protected void AddParametersToTree(ParameterSet paramSet) { m_tvObjs.Sorted = true; // initialize the tree control foreach (Parameter tmpObj in paramSet) { TreeNode tmpNode = new TreeNode(Utils.GetParameterObjectLabel(tmpObj)) { Tag = tmpObj }; m_tvObjs.Nodes.Add(tmpNode); } } #region Events /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void TreeNodeSelected(object sender, System.Windows.Forms.TreeViewEventArgs e) { m_curObj = e.Node.Tag; // collect the data about this object m_snoopCollector.Collect(m_curObj); // display it Snoop.Utils.Display(m_lvData, m_snoopCollector); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void TreeNodeSelected (object sender, System.Windows.Forms.TreeNodeMouseClickEventArgs e) { m_curObj = e.Node.Tag; // collect the data about this object m_snoopCollector.Collect(m_curObj); // display it Snoop.Utils.Display(m_lvData, m_snoopCollector); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void DataItemSelected(object sender, System.EventArgs e) { Snoop.Utils.DataItemSelected(m_lvData); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ContextMenuClick_Copy (object sender, System.EventArgs e) { if (m_tvObjs.SelectedNode != null) { Utils.CopyToClipboard(m_lvData); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ContextMenuClick_BrowseReflection(object sender, System.EventArgs e) { Snoop.Utils.BrowseReflection(m_curObj); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnBnEnumSnoop(object sender, EventArgs e) { Hashtable enumMap = new Hashtable(); // TBD: iterating over the Parameters using basic reflection gives us lots // of duplicates (not sure why). Instead, use Enum.GetNames() which will return // only unique Enum names. Then go backward to get the actual BuiltinParam Enum. // See TestElements.ParameterEnums() and TestElements.ParameterEnumsNoDup() for an // explanation of what is going on. (jma - 07/24/06) string [] strs = System.Enum.GetNames(typeof(BuiltInParameter)); foreach (string str in strs) { // look up the actual enum from its name BuiltInParameter paramEnum = (BuiltInParameter)System.Enum.Parse(typeof(BuiltInParameter), str); // see if this Element supports that parameter Parameter tmpParam = m_elem.get_Parameter(paramEnum); if (tmpParam != null) { enumMap.Add(str, tmpParam); } } RevitLookup.Snoop.Forms.ParamEnumSnoop dbox = new RevitLookup.Snoop.Forms.ParamEnumSnoop(enumMap); dbox.ShowDialog(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnBnEnumMap(object sender, EventArgs e) { ArrayList labelStrs = new ArrayList(); ArrayList valueStrs = new ArrayList(); // TBD: iterating over the Parameters using basic reflection gives us lots // of duplicates (not sure why). Instead, use Enum.GetNames() which will return // only unique Enum names. Then go backward to get the actual BuiltinParam Enum. // See TestElements.ParameterEnums() and TestElements.ParameterEnumsNoDup() for an // explanation of what is going on. (jma - 07/24/06) string [] strs = System.Enum.GetNames(typeof(BuiltInParameter)); foreach (string str in strs) { // look up the actual enum from its name BuiltInParameter paramEnum = (BuiltInParameter)System.Enum.Parse(typeof(BuiltInParameter), str); // see if this Element supports that parameter Parameter tmpParam = m_elem.get_Parameter(paramEnum); if (tmpParam != null) { labelStrs.Add(str); valueStrs.Add(Utils.GetParameterObjectLabel(tmpParam)); } } RevitLookup.Snoop.Forms.ParamEnum dbox = new RevitLookup.Snoop.Forms.ParamEnum(labelStrs, valueStrs); dbox.ShowDialog(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CopyToolStripMenuItem_Click (object sender, EventArgs e) { if (m_lvData.SelectedItems.Count > 0) { Utils.CopyToClipboard(m_lvData.SelectedItems[0], false); } else { Clipboard.Clear(); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrintMenuItem_Click (object sender, EventArgs e) { Utils.UpdatePrintSettings(m_printDocument, m_tvObjs, m_lvData, ref m_maxWidths); Utils.PrintMenuItemClick(m_printDialog, m_tvObjs); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrintPreviewMenuItem_Click (object sender, EventArgs e) { Utils.UpdatePrintSettings(m_printDocument, m_tvObjs, m_lvData, ref m_maxWidths); Utils.PrintPreviewMenuItemClick(m_printPreviewDialog, m_tvObjs); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrintDocument_PrintPage (object sender, System.Drawing.Printing.PrintPageEventArgs e) { m_currentPrintItem = Utils.Print(m_tvObjs.SelectedNode.Text, m_lvData, e, m_maxWidths[0], m_maxWidths[1], m_currentPrintItem); } #endregion } }
namespace AngleSharp.Css { using System; /// <summary> /// Contains a list of known CSS functions. /// </summary> public static class FunctionNames { /// <summary> /// The url function. /// </summary> public static readonly String Url = "url"; /// <summary> /// The url-prefix function. /// </summary> public static readonly String UrlPrefix = "url-prefix"; /// <summary> /// The domain function. /// </summary> public static readonly String Domain = "domain"; /// <summary> /// The regexp function. /// </summary> public static readonly String Regexp = "regexp"; /// <summary> /// The rgba function. /// </summary> public static readonly String Rgba = "rgba"; /// <summary> /// The rgb function. /// </summary> public static readonly String Rgb = "rgb"; /// <summary> /// The hsl function. /// </summary> public static readonly String Hsl = "hsl"; /// <summary> /// The hsla function. /// </summary> public static readonly String Hsla = "hsla"; /// <summary> /// The rect function. /// </summary> public static readonly String Rect = "rect"; /// <summary> /// The attr function. /// </summary> public static readonly String Attr = "attr"; /// <summary> /// The fit-content function. /// </summary> public static readonly String FitContent = "fit-content"; /// <summary> /// The repeat function. /// </summary> public static readonly String Repeat = "repeat"; /// <summary> /// The minmax function. /// </summary> public static readonly String Minmax = "minmax"; /// <summary> /// The var function. /// </summary> public static readonly String Var = "var"; /// <summary> /// The linear-gradient function. /// </summary> public static readonly String LinearGradient = "linear-gradient"; /// <summary> /// The radial-gradient function. /// </summary> public static readonly String RadialGradient = "radial-gradient"; /// <summary> /// The repeating-linear-gradient function. /// </summary> public static readonly String RepeatingLinearGradient = "repeating-linear-gradient"; /// <summary> /// The repeating-radial-gradient function. /// </summary> public static readonly String RepeatingRadialGradient = "repeating-radial-gradient"; /// <summary> /// The image function. /// </summary> public static readonly String Image = "image"; /// <summary> /// The counter function. /// </summary> public static readonly String Counter = "counter"; /// <summary> /// The counters function. /// </summary> public static readonly String Counters = "counters"; /// <summary> /// The calc function. /// </summary> public static readonly String Calc = "calc"; /// <summary> /// The toggle function. /// </summary> public static readonly String Toggle = "toggle"; /// <summary> /// The translate function. /// </summary> public static readonly String Translate = "translate"; /// <summary> /// The translatex function. /// </summary> public static readonly String TranslateX = "translateX"; /// <summary> /// The translatey function. /// </summary> public static readonly String TranslateY = "translateY"; /// <summary> /// The translatez function. /// </summary> public static readonly String TranslateZ = "translateZ"; /// <summary> /// The translate3d function. /// </summary> public static readonly String Translate3d = "translate3d"; /// <summary> /// The matrix function. /// </summary> public static readonly String Matrix = "matrix"; /// <summary> /// The matrix3d function. /// </summary> public static readonly String Matrix3d = "matrix3d"; /// <summary> /// The rotate function. /// </summary> public static readonly String Rotate = "rotate"; /// <summary> /// The rotate3d function. /// </summary> public static readonly String Rotate3d = "rotate3d"; /// <summary> /// The rotatex function. /// </summary> public static readonly String RotateX = "rotateX"; /// <summary> /// The rotatey function. /// </summary> public static readonly String RotateY = "rotateY"; /// <summary> /// The rotatez function. /// </summary> public static readonly String RotateZ = "rotateZ"; /// <summary> /// The skew function. /// </summary> public static readonly String Skew = "skew"; /// <summary> /// The skewx function. /// </summary> public static readonly String SkewX = "skewX"; /// <summary> /// The skewy function. /// </summary> public static readonly String SkewY = "skewY"; /// <summary> /// The scale function. /// </summary> public static readonly String Scale = "scale"; /// <summary> /// The scale3d function. /// </summary> public static readonly String Scale3d = "scale3d"; /// <summary> /// The scalez function. /// </summary> public static readonly String ScaleX = "scaleX"; /// <summary> /// The scaley function. /// </summary> public static readonly String ScaleY = "scaleY"; /// <summary> /// The scalex function. /// </summary> public static readonly String ScaleZ = "scaleZ"; /// <summary> /// The steps function. /// </summary> public static readonly String Steps = "steps"; /// <summary> /// The cubic-bezier function. /// </summary> public static readonly String CubicBezier = "cubic-bezier"; /// <summary> /// The perspective function. /// </summary> public static readonly String Perspective = "perspective"; /// <summary> /// The gray function. /// </summary> public static readonly String Gray = "gray"; /// <summary> /// The hwb function. /// </summary> public static readonly String Hwb = "hwb"; /// <summary> /// The hwba function. /// </summary> public static readonly String Hwba = "hwba"; /// <summary> /// The content function. /// </summary> public static readonly String Content = "content"; /// <summary> /// The running function. /// </summary> public static readonly String Running = "running"; } }
namespace BelkaCloudDownloader.Gui { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Properties; using Utils; using TaskStatus = Utils.TaskStatus; /// <summary> /// Small GUI meant for testing of BelkaCloudDownloader library. /// </summary> public sealed partial class MainForm : Form { /// <summary> /// A list of available cloud plugins. /// </summary> private readonly IList<CloudPlugin> plugins = new List<CloudPlugin> { new GoogleCloudPlugin(), new DropboxPlugin() }; /// <summary> /// Holds and serializes on disk currently selected downloading settings. /// </summary> private SettingsWrapper settings = new SettingsWrapper(); /// <summary> /// Maps a downloader task to its last estimation. Used to quickly lookup estimation when progress of /// a task changed. /// </summary> private Dictionary<AbstractTask, int> subtaskEstimations = new Dictionary<AbstractTask, int>(); /// <summary> /// Cancellation token source used to cancel downloading operation. /// </summary> private CancellationTokenSource cancellationTokenSource; /// <summary> /// State of a form. /// </summary> private State state = State.Ready; /// <summary> /// Last known status of a downloader. Used in progress reporting. /// </summary> private Status lastStatus; /// <summary> /// Last known information about current task. Used in progress reporting. /// </summary> private string lastInfo = string.Empty; /// <summary> /// Initializes a new instance of the <see cref="MainForm"/> class. /// </summary> public MainForm() { this.InitializeComponent(); if (string.IsNullOrEmpty(this.directorySelector.Directory)) { this.downloadOrCancelButton.Enabled = false; } this.directorySelector.DirectoryChanged += this.OnTargetDirectoryChanged; foreach (var plugin in this.plugins) { foreach (var protocol in plugin.Protocols) { protocol.Settings = this.settings; } var pluginRadioButton = new RadioButton { Text = plugin.CloudName }; pluginRadioButton.CheckedChanged += this.OnPluginRadioButtonCheckedChanged; pluginRadioButton.Tag = plugin; this.selectCloudLayout.Controls.Add(pluginRadioButton); if (plugin.CloudName == this.settings.CloudName) { pluginRadioButton.Checked = true; } } if ((this.settings.CloudName == null) && (this.selectCloudLayout.Controls.Count > 0)) { (this.selectCloudLayout.Controls[0] as RadioButton).Checked = true; } } /// <summary> /// State of a form. /// </summary> private enum State { /// <summary> /// Form is waiting for user input. /// </summary> Ready, /// <summary> /// Application is downloading and can cancel downloading process. /// </summary> Downloading } /// <summary> /// Helper method that produces human-readable message from status report. /// </summary> /// <param name="status">Information about status change.</param> /// <returns>Human-readable status message.</returns> private static string StatusToString(Status status) { switch (status) { case Status.Initialized: return "Ready."; case Status.Authenticating: return "Authenticating..."; case Status.Done: return "Done."; case Status.DownloadingFiles: return "Downloading files..."; case Status.ListingFiles: return "Listing files..."; case Status.DownloadingMetaInformation: return "Downloading meta information..."; case Status.Error: return "Error!"; case Status.DownloadingAccountInfo: return "Downloading account info..."; case Status.DownloadingCalendar: return "Downloading calendar..."; case Status.DownloadingGeolocationData: return "Downloading geolocation data..."; default: throw new ArgumentOutOfRangeException(nameof(status)); } } /// <summary> /// Registers GUI handlers for events in downloader. /// </summary> /// <param name="downloader">Downloader object that needs its events to be connected and reported /// by GUI.</param> private void ConnectDownloader(AbstractDownloader downloader) { downloader.EstimationChanged += (s, args) => { if (this.state != State.Ready) { this.overallProgressBar.Maximum = this.Estimate(); } }; downloader.ProgressChanged += (s, args) => { if (this.state != State.Ready) { this.overallProgressBar.Value = args.Progress; this.statusLabel.Text = this.StatusText(this.lastStatus, this.lastInfo); } }; downloader.CurrentOperationEstimationChanged += (s, args) => { this.subtaskEstimations[args.Task] = args.Estimation; this.currentOperationProgressBar.Maximum = args.Estimation; }; downloader.CurrentOperationProgressChanged += (s, args) => { if (!this.subtaskEstimations.ContainsKey(args.Task)) { throw new InternalErrorException( $"Have no estimation for task {args.Task.Info}, but it is reporting progress."); } this.currentOperationProgressBar.Maximum = this.subtaskEstimations[args.Task]; this.currentOperationProgressBar.Value = args.Progress; if ((this.state == State.Ready) || (args.Info.Length == 0)) { return; } this.lastInfo = args.Info; this.statusLabel.Text = this.StatusText(this.lastStatus, args.Info); }; // TODO: Display preliminary results. ////protocol.PreliminaryResultsReady += (s, args) => { }; downloader.StatusChanged += (s, args) => { if (this.state == State.Ready) { return; } this.lastStatus = args.Status; this.lastInfo = string.Empty; this.statusLabel.Text = this.StatusText(args.Status); }; } /// <summary> /// Returns text for status bar based on current status and additional info. /// </summary> /// <param name="status">Downloader status.</param> /// <param name="currentOperationInfo">Additional information about current operation.</param> /// <returns>Human-readable string with current status and progress info.</returns> private string StatusText(Status status, string currentOperationInfo = "") => $"({this.overallProgressBar.Value}/{this.overallProgressBar.Maximum}) {MainForm.StatusToString(status)}" + (currentOperationInfo.Length == 0 ? string.Empty : $" | ({this.currentOperationProgressBar.Value}/{this.currentOperationProgressBar.Maximum}) " + $"{currentOperationInfo}"); /// <summary> /// Handler for CheckedChanged event of plugin selection radio buttons. /// </summary> /// <param name="sender">Object that raised an event.</param> /// <param name="e">Event arguments.</param> private void OnPluginRadioButtonCheckedChanged(object sender, EventArgs e) { foreach (var radioButton in this.selectCloudLayout.Controls .Cast<object>().Select(control => control as RadioButton)) { Debug.Assert(radioButton != null, "selectCloudLayout must contain only radio buttons"); if (!radioButton.Checked) { continue; } this.authenticationMethodLayout.Controls.Clear(); this.capabilitiesLayout.Controls.Clear(); var cloud = radioButton.Tag as CloudPlugin; Debug.Assert(cloud != null, "Radio buttons in selectCloudLayout must have a tag of type CloudPlugin."); this.settings.CloudName = cloud.CloudName; var authenticationMethodsSet = new HashSet<string>(); foreach (var authenticationMethod in cloud.Protocols.SelectMany( protocol => protocol.AuthenticationMethods)) { authenticationMethodsSet.Add(authenticationMethod); } foreach (var authenticationMethod in authenticationMethodsSet) { var authenticationRadioButton = new RadioButton { Text = authenticationMethod }; authenticationRadioButton.CheckedChanged += this.OnAuthenticationRadioButtonCheckedChanged; authenticationRadioButton.Tag = cloud; authenticationRadioButton.Width = 180; this.authenticationMethodLayout.Controls.Add(authenticationRadioButton); if (authenticationMethod == this.settings.GetAuthenticationMethod()) { authenticationRadioButton.Checked = true; } } if ((this.settings.GetAuthenticationMethod() == null) && (this.authenticationMethodLayout.Controls.Count > 0)) { ((RadioButton)this.authenticationMethodLayout.Controls[0]).Checked = true; } return; } } /// <summary> /// Handler for CheckedChanged event of authentication methods radio buttons. /// </summary> /// <param name="sender">Object that raised an event.</param> /// <param name="e">Event arguments.</param> private void OnAuthenticationRadioButtonCheckedChanged(object sender, EventArgs e) { foreach (var radioButton in this.authenticationMethodLayout.Controls .Cast<object>().Select(control => control as RadioButton)) { Debug.Assert(radioButton != null, "authenticationMethodLayout must contain only radio buttons"); if (!radioButton.Checked) { continue; } var authenticationMethod = radioButton.Text; this.settings.SetAuthenticationMethod(authenticationMethod); var cloud = radioButton.Tag as CloudPlugin; Debug.Assert( cloud != null, "Radio buttons in authenticationMethodLayout must have a tag of type CloudPlugin."); this.capabilitiesLayout.Controls.Clear(); this.authenticationInfoPanel.Controls.Clear(); var storedCapabilities = this.settings.GetCapabilities(authenticationMethod); foreach (var protocol in cloud.Protocols) { if (!protocol.AuthenticationMethods.Contains(authenticationMethod)) { continue; } foreach (var capability in protocol.Capabilities) { var capabilityCheckBox = new CheckBox { Text = capability, Checked = true, Width = 200, Tag = authenticationMethod }; capabilityCheckBox.CheckedChanged += this.CapabilityCheckBoxOnCheckedChanged; this.capabilitiesLayout.Controls.Add(capabilityCheckBox); capabilityCheckBox.Checked = storedCapabilities.Contains(capability); } } var authenticationControl = cloud.Protocols .First(p => p.AuthenticationMethods.Contains(authenticationMethod)) .AuthenticationControl(authenticationMethod); authenticationControl.Dock = DockStyle.Fill; this.authenticationInfoPanel.Controls.Add(authenticationControl); } } /// <summary> /// Handler for changing of check state of one of the capabilities checkbox. /// </summary> /// <param name="sender">Checkbox that sent an event.</param> /// <param name="eventArgs">Event arguments.</param> private void CapabilityCheckBoxOnCheckedChanged(object sender, EventArgs eventArgs) { var checkBox = sender as CheckBox; Debug.Assert( checkBox != null, "Capability CheckBox shal be a sender for CapabilityCheckBoxOnCheckedChanged."); var authenticationMethod = (string)checkBox.Tag; this.settings.SetCapability(authenticationMethod, checkBox.Text, checkBox.Checked); } /// <summary> /// Handler for "Download" button, which also works as "Cancel" when the program is downloading. /// </summary> /// <param name="sender">Button that sends the signal.</param> /// <param name="args">Event arguments.</param> private async void OnDownloadOrCancelButtonClick(object sender, EventArgs args) { if (this.state == State.Ready) { this.resultsViewer.Clear(); this.currentOperationProgressBar.Value = 0; this.overallProgressBar.Value = 0; this.state = State.Downloading; this.downloadOrCancelButton.Text = Resources.MainFormOnDownloadOrCancelButtonClickCancel; this.cancellationTokenSource = new CancellationTokenSource(); var currentExecutedProtocols = new Downloader(this.cancellationTokenSource.Token); this.SelectedProtocols().ToList().ForEach(p => currentExecutedProtocols.AddSubDownloader(p)); currentExecutedProtocols.Log = DownloaderGlobalLog.Log; this.ConnectDownloader(currentExecutedProtocols); var tasks = new List<Task<object>>(); var results = new List<object>(); this.overallProgressBar.Maximum = this.Estimate(); this.currentOperationProgressBar.Maximum = 0; try { tasks.AddRange( this.SelectedProtocols() .Select( protocol => protocol.Execute( this.directorySelector.Directory, this.authenticationInfoPanel.Controls[0], this.SelectedCapabilities().ToList(), this.cancellationTokenSource.Token, this.currentOperationProgressBar))); this.resultsViewer.DisplayResults(results); } catch (TaskCanceledException) { this.statusLabel.Text = Resources.MainFormOnDownloadOrCancelButtonClickTaskCancelled; this.overallProgressBar.Value = 0; this.currentOperationProgressBar.Value = 0; } catch (Exception e) { DownloaderGlobalLog.Log.LogError("Exception was unhandled by downloader, aborting download.", e); this.cancellationTokenSource.Cancel(); this.statusLabel.Text = this.StatusText(Status.Error, "Unhandled exception, see log for details."); } this.state = State.Ready; if (this.overallProgressBar.Value != 0) { this.overallProgressBar.Value = this.overallProgressBar.Maximum; } if (!this.cancellationTokenSource.Token.IsCancellationRequested) { this.ReportTaskStatus(currentExecutedProtocols); } this.SelectedProtocols().ToList().ForEach(p => p.Clear()); currentExecutedProtocols.Clear(); this.downloadOrCancelButton.Text = Resources.MainFormOnDownloadOrCancelButtonClickDownload; this.downloadOrCancelButton.Enabled = true; } else { this.cancellationTokenSource.Cancel(); this.downloadOrCancelButton.Enabled = false; } } /// <summary> /// Prints status of a downloader in status bar. /// </summary> /// <param name="downloader">Downloader whose status shall be reported.</param> private void ReportTaskStatus(AbstractDownloader downloader) { this.statusLabel.Text = this.StatusText(downloader.Status); switch (downloader.TaskStatus) { case TaskStatus.Failure: this.statusLabel.Text += Resources.MainFormDownloadingFailed; break; case TaskStatus.Errors: this.statusLabel.Text += Resources.MainFormDownloadingComletedWithErrors; break; case TaskStatus.Success: this.statusLabel.Text += Resources.MainFormDownloadingCompletedSuccessfully; break; } } /// <summary> /// Gets an estimation of time required by currently selected protocols in abstract work units. /// </summary> /// <returns>Estimation of time required by currently selected protocols (in abstract work units).</returns> private int Estimate() => this.SelectedProtocols().Aggregate(0, (current, protocol) => current + protocol.Estimation); /// <summary> /// Returns a collection of currently selected protocols. /// </summary> /// <returns>A collection of protocols selected by user.</returns> private IEnumerable<Protocol> SelectedProtocols() { var authenticationMethodRadioButton = this.authenticationMethodLayout.Controls .Cast<RadioButton>().FirstOrDefault(rb => rb.Checked); var authenticationMethod = authenticationMethodRadioButton?.Text; var cloud = authenticationMethodRadioButton?.Tag as CloudPlugin; if (cloud == null) { yield break; } foreach (var protocol in cloud.Protocols.Where( protocol => protocol.AuthenticationMethods.Contains(authenticationMethod) && protocol.Capabilities.Intersect(this.SelectedCapabilities()).Any())) { yield return protocol; } } /// <summary> /// Returns a list of selected pieces of information to download. /// </summary> /// <returns>A list of selected capability names taken from protocols.</returns> private IEnumerable<string> SelectedCapabilities() => this.capabilitiesLayout.Controls.Cast<CheckBox>().Where(cb => cb.Checked).Select(cb => cb.Text); /// <summary> /// Handler for changes in a field where folder with downloaded files shall be entered. /// </summary> /// <param name="sender">Control that sent a signal.</param> /// <param name="e">Event arguments.</param> private void OnTargetDirectoryChanged(object sender, EventArgs e) => this.downloadOrCancelButton.Enabled = !string.IsNullOrEmpty(this.directorySelector.Directory); } }
using Azure; using Azure.Core; using Azure.Messaging.EventHubs; using Orleans.Runtime; using Orleans.Streams; using System; namespace Orleans.Configuration { /// <summary> /// EventHub settings for a specific hub /// </summary> public class EventHubOptions { /// <summary> /// Gets the delegate used to create connections to Azure Event Hub. /// </summary> internal CreateConnectionDelegate CreateConnection { get; private set; } /// <summary> /// Event Hub consumer group. /// </summary> internal string ConsumerGroup { get; private set; } /// <summary> /// Event Hub name. /// </summary> internal string EventHubName { get; private set; } /// <summary> /// Connection options used when creating a connection to an Azure Event Hub. /// </summary> public EventHubConnectionOptions ConnectionOptions { get; set; } = new EventHubConnectionOptions { TransportType = EventHubsTransportType.AmqpTcp }; /// <summary> /// Creates an Azure Event Hub connection. /// </summary> /// <param name="connectionOptions">The connection options.</param> /// <returns>An Azure Event Hub connection.</returns> public delegate EventHubConnection CreateConnectionDelegate(EventHubConnectionOptions connectionOptions); /// <summary> /// Configures the Azure Event Hub connection using the provided connection string. /// </summary> public void ConfigureEventHubConnection(string connectionString, string eventHubName, string consumerGroup) { EventHubName = eventHubName; ConsumerGroup = consumerGroup; if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(connectionString)); } ValidateValues(eventHubName, consumerGroup); CreateConnection = connectionOptions => new EventHubConnection(connectionString, EventHubName, connectionOptions); } /// <summary> /// Configures the Azure Event Hub connection using the provided fully-qualified namespace string and credential. /// </summary> public void ConfigureEventHubConnection(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, AzureNamedKeyCredential credential) { EventHubName = eventHubName; ConsumerGroup = consumerGroup; if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace)) { throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(fullyQualifiedNamespace)); } ValidateValues(eventHubName, consumerGroup); if (credential is null) { throw new ArgumentNullException(nameof(credential)); } CreateConnection = connectionOptions => new EventHubConnection(fullyQualifiedNamespace, EventHubName, credential, connectionOptions); } /// <summary> /// Configures the Azure Event Hub connection using the provided fully-qualified namespace string and credential. /// </summary> public void ConfigureEventHubConnection(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, AzureSasCredential credential) { EventHubName = eventHubName; ConsumerGroup = consumerGroup; if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace)) { throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(fullyQualifiedNamespace)); } ValidateValues(eventHubName, consumerGroup); if (credential is null) { throw new ArgumentNullException(nameof(credential)); } CreateConnection = connectionOptions => new EventHubConnection(fullyQualifiedNamespace, EventHubName, credential, connectionOptions); } /// <summary> /// Configures the Azure Event Hub connection using the provided fully-qualified namespace string and credential. /// </summary> public void ConfigureEventHubConnection(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, TokenCredential credential) { EventHubName = eventHubName; ConsumerGroup = consumerGroup; if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace)) { throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(fullyQualifiedNamespace)); } ValidateValues(eventHubName, consumerGroup); if (credential is null) { throw new ArgumentNullException(nameof(credential)); } CreateConnection = connectionOptions => new EventHubConnection(fullyQualifiedNamespace, EventHubName, credential, connectionOptions); } /// <summary> /// Configures the Azure Event Hub connection using the provided connection instance. /// </summary> public void ConfigureEventHubConnection(EventHubConnection connection, string consumerGroup) { EventHubName = connection.EventHubName; ConsumerGroup = consumerGroup; ValidateValues(connection.EventHubName, consumerGroup); if (connection is null) throw new ArgumentNullException(nameof(connection)); CreateConnection = _ => connection; } /// <summary> /// Configures the Azure Event Hub connection using the provided delegate. /// </summary> public void ConfigureEventHubConnection(CreateConnectionDelegate createConnection, string eventHubName, string consumerGroup) { EventHubName = eventHubName; ConsumerGroup = consumerGroup; ValidateValues(eventHubName, consumerGroup); CreateConnection = createConnection ?? throw new ArgumentNullException(nameof(createConnection)); } private void ValidateValues(string eventHubName, string consumerGroup) { if (string.IsNullOrWhiteSpace(eventHubName)) { throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(eventHubName)); } if (string.IsNullOrWhiteSpace(consumerGroup)) { throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(consumerGroup)); } } } public class EventHubOptionsValidator : IConfigurationValidator { private readonly EventHubOptions options; private readonly string name; public EventHubOptionsValidator(EventHubOptions options, string name) { this.options = options; this.name = name; } public void ValidateConfiguration() { if (options.CreateConnection is null) { throw new OrleansConfigurationException($"Azure Event Hub connection not configured for stream provider options {nameof(EventHubOptions)} with name \"{name}\". Use the {options.GetType().Name}.{nameof(EventHubOptions.ConfigureEventHubConnection)} method to configure the connection."); } if (string.IsNullOrEmpty(options.ConsumerGroup)) { throw new OrleansConfigurationException($"{nameof(EventHubOptions)} on stream provider {this.name} is invalid. {nameof(EventHubOptions.ConsumerGroup)} is invalid"); } if (string.IsNullOrEmpty(options.EventHubName)) { throw new OrleansConfigurationException($"{nameof(EventHubOptions)} on stream provider {this.name} is invalid. {nameof(EventHubOptions.EventHubName)} is invalid"); } } } public class StreamCheckpointerConfigurationValidator : IConfigurationValidator { private readonly IServiceProvider services; private string name; public StreamCheckpointerConfigurationValidator(IServiceProvider services, string name) { this.services = services; this.name = name; } public void ValidateConfiguration() { var checkpointerFactory = services.GetServiceByName<IStreamQueueCheckpointerFactory>(this.name); if (checkpointerFactory == null) throw new OrleansConfigurationException($"No IStreamQueueCheckpointer is configured with PersistentStreamProvider {this.name}. Please configure one."); } } public class EventHubReceiverOptions { /// <summary> /// Optional parameter that configures the receiver prefetch count. /// </summary> public int? PrefetchCount { get; set; } /// <summary> /// In cases where no checkpoint is found, this indicates if service should read from the most recent data, or from the beginning of a partition. /// </summary> public bool StartFromNow { get; set; } = DEFAULT_START_FROM_NOW; public const bool DEFAULT_START_FROM_NOW = true; } public class EventHubStreamCachePressureOptions { /// <summary> /// SlowConsumingPressureMonitorConfig /// </summary> public double? SlowConsumingMonitorFlowControlThreshold { get; set; } /// <summary> /// SlowConsumingMonitorPressureWindowSize /// </summary> public TimeSpan? SlowConsumingMonitorPressureWindowSize { get; set; } /// <summary> /// AveragingCachePressureMonitorFlowControlThreshold, AveragingCachePressureMonitor is turn on by default. /// User can turn it off by setting this value to null /// </summary> public double? AveragingCachePressureMonitorFlowControlThreshold { get; set; } = DEFAULT_AVERAGING_CACHE_PRESSURE_MONITORING_THRESHOLD; public const double AVERAGING_CACHE_PRESSURE_MONITORING_OFF = 1.0; public const double DEFAULT_AVERAGING_CACHE_PRESSURE_MONITORING_THRESHOLD = 1.0 / 3.0; } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleETrade.SampleETradePublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleETrade { using System; using System.ComponentModel; using System.IO; using System.Reflection; using System.Windows; using Ecng.Common; using Ecng.Xaml; using StockSharp.Messages; using StockSharp.BusinessEntities; using StockSharp.ETrade; using StockSharp.ETrade.Native; using StockSharp.Logging; using StockSharp.Xaml; using StockSharp.Localization; public partial class MainWindow { public static MainWindow Instance { get; private set; } public static readonly DependencyProperty IsConnectedProperty = DependencyProperty.Register("IsConnected", typeof(bool), typeof(MainWindow), new PropertyMetadata(default(bool))); public bool IsConnected { get { return (bool)GetValue(IsConnectedProperty); } set { SetValue(IsConnectedProperty, value); } } public ETradeTrader Trader { get; private set; } private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); //private Security[] _securities; private static string ConsumerKey => Properties.Settings.Default.ConsumerKey; private static bool IsSandbox => Properties.Settings.Default.Sandbox; private readonly LogManager _logManager = new LogManager(); public MainWindow() { Instance = this; InitializeComponent(); Title = Title.Put("E*TRADE"); Closing += OnClosing; _ordersWindow.MakeHideable(); _securitiesWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); _myTradesWindow.MakeHideable(); var guilistener = new GuiLogListener(_logControl); guilistener.Filters.Add(msg => msg.Level > LogLevels.Debug); _logManager.Listeners.Add(guilistener); var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var path = Path.Combine(location ?? "", "ETrade", "restdump_{0:yyyyMMdd-HHmmss}.log".Put(DateTime.Now)); _logManager.Listeners.Add(new FileLogListener(path)); Application.Current.MainWindow = this; } private void OnClosing(object sender, CancelEventArgs cancelEventArgs) { Properties.Settings.Default.Save(); _ordersWindow.DeleteHideable(); _securitiesWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _myTradesWindow.DeleteHideable(); _securitiesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); _myTradesWindow.Close(); if (Trader != null) Trader.Dispose(); } private void ConnectClick(object sender, RoutedEventArgs e) { var secret = PwdBox.Password; if (!IsConnected) { if (ConsumerKey.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3689); return; } if (secret.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3690); return; } if (Trader == null) { // create connector Trader = new ETradeTrader(); try { Trader.AccessToken = null; var token = OAuthToken.Deserialize(Properties.Settings.Default.AccessToken); if (token != null && token.ConsumerKey.ToLowerInvariant() == ConsumerKey.ToLowerInvariant()) Trader.AccessToken = token; } catch (Exception ex) { MessageBox.Show(this, LocalizedStrings.Str3691Params.Put(ex)); } Trader.LogLevel = LogLevels.Debug; _logManager.Sources.Add(Trader); // subscribe on connection successfully event Trader.Connected += () => this.GuiAsync(() => { Properties.Settings.Default.AccessToken = Trader.AccessToken.Serialize(); OnConnectionChanged(true); }); // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false)); // subscribe on error event Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, msg, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security))); Trader.NewSecurity += security => _securitiesWindow.SecurityPicker.Securities.Add(security); Trader.NewMyTrade += trade => _myTradesWindow.TradeGrid.Trades.Add(trade); Trader.NewOrder += order => _ordersWindow.OrderGrid.Orders.Add(order); Trader.NewStopOrder += order => _stopOrdersWindow.OrderGrid.Orders.Add(order); Trader.NewPortfolio += portfolio => { _portfoliosWindow.PortfolioGrid.Portfolios.Add(portfolio); // subscribe on portfolio updates Trader.RegisterPortfolio(portfolio); }; Trader.NewPosition += position => _portfoliosWindow.PortfolioGrid.Positions.Add(position); // subscribe on error of order registration event Trader.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail; // subscribe on error of order cancelling event Trader.OrderCancelFailed += OrderFailed; // subscribe on error of stop-order registration event Trader.StopOrderRegisterFailed += _stopOrdersWindow.OrderGrid.AddRegistrationFail; // subscribe on error of stop-order cancelling event Trader.StopOrderCancelFailed += OrderFailed; Trader.MassOrderCancelFailed += (transId, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716)); // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; } Trader.Sandbox = IsSandbox; //Trader.SandboxSecurities = IsSandbox ? GetSandboxSecurities() : null; Trader.ConsumerKey = ConsumerKey; Trader.ConsumerSecret = secret; Trader.Connect(); } else { Trader.Disconnect(); } } private void OnConnectionChanged(bool isConnected) { IsConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void OrderFailed(OrderFail fail) { this.GuiAsync(() => { MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153); }); } private void ShowMyTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_myTradesWindow); } private void ShowSecuritiesClick(object sender, RoutedEventArgs e) { ShowOrHide(_securitiesWindow); } private void ShowPortfoliosClick(object sender, RoutedEventArgs e) { ShowOrHide(_portfoliosWindow); } private void ShowOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_ordersWindow); } private void ShowStopOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_stopOrdersWindow); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException(nameof(window)); if (window.Visibility == Visibility.Visible) window.Hide(); else window.Show(); } //private Security[] GetSandboxSecurities() //{ // return _securities ?? (_securities = new[] // { // new Security // { // Id = "CSCO@EQ", Code = "CSCO", Name = "CISCO SYS INC", ExchangeBoard = ExchangeBoard.Test, // Decimals = 2, VolumeStep = 1, StepPrice = 0.01m, PriceStep = 0.01m // }, // new Security // { // Id = "IBM@EQ", Code = "IBM", Name = "INTERNATIONAL BUSINESS MACHS COM", ExchangeBoard = ExchangeBoard.Test, // Decimals = 2, VolumeStep = 1, StepPrice = 0.01m, PriceStep = 0.01m // }, // new Security // { // Id = "MSFT@EQ", Code = "MSFT", Name = "MICROSOFT CORP COM", ExchangeBoard = ExchangeBoard.Test, // Decimals = 2, VolumeStep = 1, StepPrice = 0.01m, PriceStep = 0.01m // } // }); //} } }
using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Text.RegularExpressions; namespace NQuery.Runtime { internal static class BuiltInOperators { #region Null Placeholders // NOTE: Don't remove these methods! // They are used in the Binder. The reflected MethodInfo objects of theses // methods is returned to unary and binary operators where one operand is null. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "a")] public static DBNull Placeholder(DBNull a) { throw ExceptionBuilder.InternalError("Placeholder(DBNull) should never get called."); } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "a")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "b")] public static DBNull Placeholder(DBNull a, DBNull b) { throw ExceptionBuilder.InternalError("Placeholder(DBNull,DBNull) should never get called."); } #endregion #region General Equality Checks public static bool op_Equality(object a, object b) { return Equals(a, b); } public static bool op_Inequality(object a, object b) { return !Equals(a, b); } #endregion #region Enum Equality public static bool op_Equality(Enum a, string b) { string enumAsString = a.ToString(); return enumAsString == b; } public static bool op_Equality(string a, Enum b) { string enumAsString = b.ToString(); return a == enumAsString; } public static bool op_Equality(Enum a, Int32 b) { return Convert.ToInt32(a, CultureInfo.InvariantCulture) == b; } public static bool op_Equality(Int32 a, Enum b) { return a == Convert.ToInt32(b, CultureInfo.InvariantCulture); } public static bool op_Equality(Enum a, Int64 b) { return Convert.ToInt64(a, CultureInfo.InvariantCulture) == b; } public static bool op_Equality(Int64 a, Enum b) { return a == Convert.ToInt64(b, CultureInfo.InvariantCulture); } public static bool op_Inequality(Enum a, string b) { string enumAsString = a.ToString(); return enumAsString != b; } public static bool op_Inequality(string a, Enum b) { string enumAsString = b.ToString(); return a != enumAsString; } public static bool op_Inequality(Enum a, Int32 b) { return Convert.ToInt32(a, CultureInfo.InvariantCulture) != b; } public static bool op_Inequality(Int32 a, Enum b) { return a != Convert.ToInt32(b, CultureInfo.InvariantCulture); } public static bool op_Inequality(Enum a, Int64 b) { return Convert.ToInt64(a, CultureInfo.InvariantCulture) != b; } public static bool op_Inequality(Int64 a, Enum b) { return a != Convert.ToInt64(b, CultureInfo.InvariantCulture); } #endregion #region Enum Bitwise Operators public static Enum op_BitwiseOr(Enum a, Enum b) { return (Enum)Enum.ToObject(a.GetType(), Convert.ToInt64(a, CultureInfo.InvariantCulture) | Convert.ToInt64(b, CultureInfo.InvariantCulture)); } public static Enum op_BitwiseAnd(Enum a, Enum b) { return (Enum)Enum.ToObject(a.GetType(), Convert.ToInt64(a, CultureInfo.InvariantCulture) & Convert.ToInt64(b, CultureInfo.InvariantCulture)); } #endregion #region Boolean public static bool op_Logicalnot(bool a) { return !a; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "a")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "b")] public static bool op_LogicalOr(bool a, bool b) { throw ExceptionBuilder.InternalError("op_LogicalOr(bool, bool) should never get called."); } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "a")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "b")] public static bool op_LogicalAnd(bool a, bool b) { throw ExceptionBuilder.InternalError("op_LogicalAnd(bool, bool) should never get called."); } public static bool op_ExclusiveOr(bool a, bool b) { return a ^ b; } public static bool op_Equality(bool a, bool b) { return a == b; } public static bool op_Inequality(bool a, bool b) { return a != b; } #endregion #region String public static bool op_Equality(string a, string b) { return a == b; } public static bool op_Inequality(string a, string b) { return a != b; } public static bool op_LessThan(string a, string b) { return String.Compare(a, b, StringComparison.CurrentCulture) < 0; } public static bool op_LessThanOrEqual(string a, string b) { return String.Compare(a, b, StringComparison.CurrentCulture) <= 0; } public static bool op_GreaterThan(string a, string b) { return String.Compare(a, b, StringComparison.CurrentCulture) > 0; } public static bool op_GreaterThanOrEqual(string a, string b) { return String.Compare(a, b, StringComparison.CurrentCulture) >= 0; } public static string op_Addition(string a, string b) { return String.Concat(a, b); } public static bool op_SimilarTo(string str, string regex) { Regex r = new Regex(regex, RegexOptions.Multiline); return r.IsMatch(str); } public static bool op_Like(string str, string expr) { str = str.ToUpper(CultureInfo.CurrentCulture); StringBuilder sb = new StringBuilder(); sb.Append('^'); for (int i = 0; i < expr.Length; i++) { switch (expr[i]) { case '%': sb.Append(".*"); break; case '_': sb.Append('.'); break; default: sb.Append(Char.ToUpper(expr[i], CultureInfo.CurrentCulture)); break; } } sb.Append('$'); Regex r = new Regex(sb.ToString(), RegexOptions.Singleline); return r.IsMatch(str); } public static bool op_SoundsLike(string left, string right) { if (left == null || right == null) return false; return Soundex.GetCode(left) == Soundex.GetCode(right); } #endregion #region Int32 public static int op_UnaryPlus(int a) { return a; } public static int op_UnaryNegation(int a) { return -a; } public static int op_OnesComplement(int a) { return ~a; } public static bool op_Equality(int a, int b) { return a == b; } public static bool op_Inequality(int a, int b) { return a != b; } public static bool op_LessThan(int a, int b) { return a < b; } public static bool op_LessThanOrEqual(int a, int b) { return a <= b; } public static bool op_GreaterThan(int a, int b) { return a > b; } public static bool op_GreaterThanOrEqual(int a, int b) { return a >= b; } public static int op_LeftShift(int a, int b) { return a << b; } public static int op_RightShift(int a, int b) { return a >> b; } public static int op_BitwiseOr(int a, int b) { return a | b; } public static int op_BitwiseAnd(int a, int b) { return a & b; } public static int op_ExclusiveOr(int a, int b) { return a ^ b; } public static int op_Addition(int a, int b) { return a + b; } public static int op_Subtraction(int a, int b) { return a - b; } public static int op_Multiply(int a, int b) { return a * b; } public static int op_Division(int a, int b) { return a / b; } public static int op_Modulus(int a, int b) { return a % b; } public static int op_Power(int a, int b) { return (int) Math.Pow(a, b); } #endregion #region UInt32 public static uint op_UnaryPlus(uint a) { return a; } public static uint op_OnesComplement(uint a) { return ~a; } public static bool op_Equality(uint a, uint b) { return a == b; } public static bool op_Inequality(uint a, uint b) { return a != b; } public static bool op_LessThan(uint a, uint b) { return a < b; } public static bool op_LessThanOrEqual(uint a, uint b) { return a <= b; } public static bool op_GreaterThan(uint a, uint b) { return a > b; } public static bool op_GreaterThanOrEqual(uint a, uint b) { return a >= b; } public static uint op_LeftShift(uint a, int b) { return a << b; } public static uint op_RightShift(uint a, int b) { return a >> b; } public static uint op_BitwiseOr(uint a, uint b) { return a | b; } public static uint op_BitwiseAnd(uint a, uint b) { return a & b; } public static uint op_ExclusiveOr(uint a, uint b) { return a ^ b; } public static uint op_Addition(uint a, uint b) { return a + b; } public static uint op_Subtraction(uint a, uint b) { return a - b; } public static uint op_Multiply(uint a, uint b) { return a * b; } public static uint op_Division(uint a, uint b) { return a / b; } public static uint op_Modulus(uint a, uint b) { return a % b; } public static uint op_Power(uint a, uint b) { return (uint) Math.Pow(a, b); } #endregion #region Int64 public static long op_UnaryPlus(long a) { return a; } public static long op_UnaryNegation(long a) { return -a; } public static long op_OnesComplement(long a) { return ~a; } public static bool op_Equality(long a, long b) { return a == b; } public static bool op_Inequality(long a, long b) { return a != b; } public static bool op_LessThan(long a, long b) { return a < b; } public static bool op_LessThanOrEqual(long a, long b) { return a <= b; } public static bool op_GreaterThan(long a, long b) { return a > b; } public static bool op_GreaterThanOrEqual(long a, long b) { return a >= b; } public static long op_LeftShift(long a, int b) { return a << b; } public static long op_RightShift(long a, int b) { return a >> b; } public static long op_BitwiseOr(long a, long b) { return a | b; } public static long op_BitwiseAnd(long a, long b) { return a & b; } public static long op_ExclusiveOr(long a, long b) { return a ^ b; } public static long op_Addition(long a, long b) { return a + b; } public static long op_Subtraction(long a, long b) { return a - b; } public static long op_Multiply(long a, long b) { return a * b; } public static long op_Division(long a, long b) { return a / b; } public static long op_Modulus(long a, long b) { return a % b; } public static long op_Power(long a, long b) { return (long) Math.Pow(a, b); } #endregion #region UInt64 public static ulong op_UnaryPlus(ulong a) { return a; } public static ulong op_OnesComplement(ulong a) { return ~a; } public static bool op_Equality(ulong a, ulong b) { return a == b; } public static bool op_Inequality(ulong a, ulong b) { return a != b; } public static bool op_LessThan(ulong a, ulong b) { return a < b; } public static bool op_LessThanOrEqual(ulong a, ulong b) { return a <= b; } public static bool op_GreaterThan(ulong a, ulong b) { return a > b; } public static bool op_GreaterThanOrEqual(ulong a, ulong b) { return a >= b; } public static ulong op_LeftShift(ulong a, int b) { return a << b; } public static ulong op_RightShift(ulong a, int b) { return a >> b; } public static ulong op_BitwiseOr(ulong a, ulong b) { return a | b; } public static ulong op_BitwiseAnd(ulong a, ulong b) { return a & b; } public static ulong op_ExclusiveOr(ulong a, ulong b) { return a ^ b; } public static ulong op_Addition(ulong a, ulong b) { return a + b; } public static ulong op_Subtraction(ulong a, ulong b) { return a - b; } public static ulong op_Multiply(ulong a, ulong b) { return a * b; } public static ulong op_Division(ulong a, ulong b) { return a / b; } public static ulong op_Modulus(ulong a, ulong b) { return a % b; } public static ulong op_Power(ulong a, ulong b) { return (ulong) Math.Pow(a, b); } #endregion #region Single public static float op_UnaryPlus(float a) { return a; } public static float op_UnaryNegation(float a) { return -a; } public static bool op_Equality(float a, float b) { return a == b; } public static bool op_Inequality(float a, float b) { return a != b; } public static bool op_LessThan(float a, float b) { return a < b; } public static bool op_LessThanOrEqual(float a, float b) { return a <= b; } public static bool op_GreaterThan(float a, float b) { return a > b; } public static bool op_GreaterThanOrEqual(float a, float b) { return a >= b; } public static float op_Addition(float a, float b) { return a + b; } public static float op_Subtraction(float a, float b) { return a - b; } public static float op_Multiply(float a, float b) { return a * b; } public static float op_Division(float a, float b) { return a / b; } public static float op_Modulus(float a, float b) { return a % b; } public static float op_Power(float a, float b) { return (float) Math.Pow(a, b); } #endregion #region Double public static double op_UnaryPlus(double a) { return a; } public static double op_UnaryNegation(double a) { return -a; } public static bool op_Equality(double a, double b) { return a == b; } public static bool op_Inequality(double a, double b) { return a != b; } public static bool op_LessThan(double a, double b) { return a < b; } public static bool op_LessThanOrEqual(double a, double b) { return a <= b; } public static bool op_GreaterThan(double a, double b) { return a > b; } public static bool op_GreaterThanOrEqual(double a, double b) { return a >= b; } public static double op_Addition(double a, double b) { return a + b; } public static double op_Subtraction(double a, double b) { return a - b; } public static double op_Multiply(double a, double b) { return a * b; } public static double op_Division(double a, double b) { return a / b; } public static double op_Modulus(double a, double b) { return a % b; } public static double op_Power(double a, double b) { return Math.Pow(a, b); } #endregion #region DateTime and TimeSpan public static TimeSpan op_Division(TimeSpan a, int b) { return new TimeSpan(a.Ticks / b); } public static DateTime op_Addition(DateTime a, double b) { return a.AddDays(b); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Text; using System.Timers; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Mono.Addins; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")] public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}"; private Scene m_scene = null; private int m_savetime = 5; // seconds to wait before saving changed appearance private int m_sendtime = 2; // seconds to wait before sending changed appearance private bool m_reusetextures = false; private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates private System.Timers.Timer m_updateTimer = new System.Timers.Timer(); private Dictionary<UUID,long> m_savequeue = new Dictionary<UUID,long>(); private Dictionary<UUID,long> m_sendqueue = new Dictionary<UUID,long>(); private object m_setAppearanceLock = new object(); #region Region Module interface public void Initialise(IConfigSource config) { IConfig appearanceConfig = config.Configs["Appearance"]; if (appearanceConfig != null) { m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime))); m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime))); m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures",m_reusetextures); // m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime); } } public void AddRegion(Scene scene) { if (m_scene == null) m_scene = scene; scene.RegisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient += SubscribeToClientEvents; } public void RemoveRegion(Scene scene) { if (scene == m_scene) { scene.UnregisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient -= SubscribeToClientEvents; } m_scene = null; } public void RegionLoaded(Scene scene) { m_updateTimer.Enabled = false; m_updateTimer.AutoReset = true; m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer); } public void Close() { } public string Name { get { return "Default Avatar Factory"; } } public bool IsSharedModule { get { return false; } } public Type ReplaceableInterface { get { return null; } } private void SubscribeToClientEvents(IClientAPI client) { client.OnRequestWearables += Client_OnRequestWearables; client.OnSetAppearance += Client_OnSetAppearance; client.OnAvatarNowWearing += Client_OnAvatarNowWearing; client.OnCachedTextureRequest += Client_OnCachedTextureRequest; } #endregion #region IAvatarFactoryModule /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems) { SetAppearance(sp, appearance.Texture, appearance.VisualParams, cacheItems); } public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { float oldoff = sp.Appearance.AvatarFeetOffset; Vector3 oldbox = sp.Appearance.AvatarBoxSize; SetAppearance(sp, textureEntry, visualParams, cacheItems); sp.Appearance.SetSize(avSize); float off = sp.Appearance.AvatarFeetOffset; Vector3 box = sp.Appearance.AvatarBoxSize; if (oldoff != off || oldbox != box) ((ScenePresence)sp).SetSize(box, off); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems) { // m_log.DebugFormat( // "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}", // sp.Name, textureEntry, visualParams); // TODO: This is probably not necessary any longer, just assume the // textureEntry set implies that the appearance transaction is complete bool changed = false; // Process the texture entry transactionally, this doesn't guarantee that Appearance is // going to be handled correctly but it does serialize the updates to the appearance lock (m_setAppearanceLock) { // Process the visual params, this may change height as well if (visualParams != null) { changed = sp.Appearance.SetVisualParams(visualParams); } // Process the baked texture array if (textureEntry != null) { m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID); // WriteBakedTexturesReport(sp, m_log.DebugFormat); changed = sp.Appearance.SetTextureEntries(textureEntry) || changed; // WriteBakedTexturesReport(sp, m_log.DebugFormat); UpdateBakedTextureCache(sp, cacheItems); // This appears to be set only in the final stage of the appearance // update transaction. In theory, we should be able to do an immediate // appearance send and save here. } // NPC should send to clients immediately and skip saving appearance if (((ScenePresence)sp).PresenceType == PresenceType.Npc) { SendAppearance((ScenePresence)sp); return; } // save only if there were changes, send no matter what (doesn't hurt to send twice) if (changed) QueueAppearanceSave(sp.ControllingClient.AgentId); QueueAppearanceSend(sp.ControllingClient.AgentId); } // m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString()); } private void SendAppearance(ScenePresence sp) { // Send the appearance to everyone in the scene sp.SendAppearanceToAllOtherAgents(); // Send animations back to the avatar as well sp.Animator.SendAnimPack(); } public bool SendAppearance(UUID agentId) { // m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId); ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) { // This is expected if the user has gone away. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId); return false; } SendAppearance(sp); return true; } public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); return GetBakedTextureFaces(sp); } public WearableCacheItem[] GetCachedItems(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); WearableCacheItem[] items = sp.Appearance.WearableCacheItems; //foreach (WearableCacheItem item in items) //{ //} return items; } public bool SaveBakedTextures(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return false; m_log.DebugFormat( "[AV FACTORY]: Permanently saving baked textures for {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp); if (bakedTextures.Count == 0) return false; foreach (BakeType bakeType in bakedTextures.Keys) { Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType]; if (bakedTextureFace == null) { // This can happen legitimately, since some baked textures might not exist //m_log.WarnFormat( // "[AV FACTORY]: No texture ID set for {0} for {1} in {2} not found when trying to save permanently", // bakeType, sp.Name, m_scene.RegionInfo.RegionName); continue; } AssetBase asset = m_scene.AssetService.Get(bakedTextureFace.TextureID.ToString()); if (asset != null) { // Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars asset.ID = asset.FullID.ToString(); asset.Temporary = false; asset.Local = false; m_scene.AssetService.Store(asset); } else { m_log.WarnFormat( "[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently", bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName); } } return true; } /// <summary> /// Queue up a request to send appearance. /// </summary> /// <remarks> /// Makes it possible to accumulate changes without sending out each one separately. /// </remarks> /// <param name="agentId"></param> public void QueueAppearanceSend(UUID agentid) { // m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000); lock (m_sendqueue) { m_sendqueue[agentid] = timestamp; m_updateTimer.Start(); } } public void QueueAppearanceSave(UUID agentid) { // m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000); lock (m_savequeue) { m_savequeue[agentid] = timestamp; m_updateTimer.Start(); } } // called on textures update public bool UpdateBakedTextureCache(IScenePresence sp, WearableCacheItem[] cacheItems) { if(cacheItems == null) return false; // npcs dont have baked cache if (((ScenePresence)sp).isNPC) return true; // uploaded baked textures will be in assets local cache IAssetService cache = m_scene.AssetService; IBakedTextureModule m_BakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); int validDirtyBakes = 0; int hits = 0; // our main cacheIDs mapper is p.Appearance.WearableCacheItems WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems; if (wearableCache == null) { wearableCache = WearableCacheItem.GetDefaultCacheItem(); } List<UUID> missing = new List<UUID>(); // Process received baked textures for (int i = 0; i < cacheItems.Length; i++) { int idx = (int)cacheItems[i].TextureIndex; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // No face if (face == null) { // for some reason viewer is cleaning this sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint) idx); sp.Appearance.Texture.FaceTextures[idx].TextureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE; wearableCache[idx].CacheId = UUID.Zero; wearableCache[idx].TextureID = UUID.Zero; wearableCache[idx].TextureAsset = null; continue; } else { if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) { wearableCache[idx].CacheId = UUID.Zero; wearableCache[idx].TextureID = UUID.Zero; wearableCache[idx].TextureAsset = null; continue; } /* if (face.TextureID == wearableCache[idx].TextureID && m_BakedTextureModule != null) { if (wearableCache[idx].CacheId != cacheItems[i].CacheId) { wearableCache[idx].CacheId = cacheItems[i].CacheId; validDirtyBakes++; //assuming this can only happen if asset is in cache } hits++; continue; } */ wearableCache[idx].TextureAsset = null; if (cache != null) wearableCache[idx].TextureAsset = cache.GetCached(face.TextureID.ToString()); if (wearableCache[idx].TextureAsset != null) { if ( wearableCache[idx].TextureID != face.TextureID || wearableCache[idx].CacheId != cacheItems[i].CacheId) validDirtyBakes++; wearableCache[idx].TextureID = face.TextureID; wearableCache[idx].CacheId = cacheItems[i].CacheId; hits++; } else { wearableCache[idx].CacheId = UUID.Zero; wearableCache[idx].TextureID = UUID.Zero; wearableCache[idx].TextureAsset = null; missing.Add(face.TextureID); continue; } } } sp.Appearance.WearableCacheItems = wearableCache; if (missing.Count > 0) { foreach (UUID id in missing) sp.ControllingClient.SendRebakeAvatarTextures(id); } if (validDirtyBakes > 0 && hits == cacheItems.Length) { // if we got a full set of baked textures save all in BakedTextureModule if (m_BakedTextureModule != null) { m_log.Debug("[UpdateBakedCache] uploading to bakedModule cache"); m_BakedTextureModule.Store(sp.UUID, wearableCache); } } // debug m_log.Debug("[UpdateBakedCache] cache hits: " + hits.ToString() + " changed entries: " + validDirtyBakes.ToString() + " rebakes " + missing.Count); /* for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++) { int j = AvatarAppearance.BAKE_INDICES[iter]; m_log.Debug("[UpdateBCache] {" + iter + "/" + sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" + sp.Appearance.WearableCacheItems[j].CacheId + ", t-" + sp.Appearance.WearableCacheItems[j].TextureID); } */ return (hits == cacheItems.Length); } // called when we get a new root avatar public bool ValidateBakedTextureCache(IScenePresence sp) { int hits = 0; if (((ScenePresence)sp).isNPC) return true; lock (m_setAppearanceLock) { IAssetService cache = m_scene.AssetService; IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); WearableCacheItem[] bakedModuleCache = null; if (cache == null) return false; WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems; // big debug m_log.DebugFormat("[AVFACTORY]: ValidateBakedTextureCache start for {0} {1}", sp.Name, sp.UUID); /* for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++) { int j = AvatarAppearance.BAKE_INDICES[iter]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[j]; if (wearableCache == null) { if (face != null) m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- " + face.TextureID); else m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- No texture"); } else { if (face != null) m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " ft- " + face.TextureID + "}: cc-" + wearableCache[j].CacheId + ", ct-" + wearableCache[j].TextureID ); else m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t - No texture" + "}: cc-" + wearableCache[j].CacheId + ", ct-" + wearableCache[j].TextureID ); } } */ bool wearableCacheValid = false; if (wearableCache == null) { wearableCache = WearableCacheItem.GetDefaultCacheItem(); } else { // we may have received a full cache // check same coerence and store wearableCacheValid = true; for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; if (face != null) { if (face.TextureID == wearableCache[idx].TextureID && face.TextureID != UUID.Zero) { if (wearableCache[idx].TextureAsset != null) { hits++; wearableCache[idx].TextureAsset.Temporary = true; wearableCache[idx].TextureAsset.Local = true; cache.Store(wearableCache[idx].TextureAsset); continue; } if (cache.GetCached((wearableCache[idx].TextureID).ToString()) != null) { hits++; continue; } } wearableCacheValid = false; } } wearableCacheValid = (wearableCacheValid && (hits >= AvatarAppearance.BAKE_INDICES.Length - 1)); if (wearableCacheValid) m_log.Debug("[ValidateBakedCache] have valid local cache"); } bool checkExternal = false; if (!wearableCacheValid) { // only use external bake module on login condition check // ScenePresence ssp = null; // if (sp is ScenePresence) { // ssp = (ScenePresence)sp; // checkExternal = (((uint)ssp.TeleportFlags & (uint)TeleportFlags.ViaLogin) != 0) && // bakedModule != null; // or do it anytime we dont have the cache checkExternal = bakedModule != null; } } if (checkExternal) { hits = 0; bool gotbacked = false; m_log.Debug("[ValidateBakedCache] local cache invalid, checking bakedModule"); try { bakedModuleCache = bakedModule.Get(sp.UUID); } catch (Exception e) { m_log.ErrorFormat(e.ToString()); bakedModuleCache = null; } if (bakedModuleCache != null) { m_log.Debug("[ValidateBakedCache] got bakedModule " + bakedModuleCache.Length + " cached textures"); for (int i = 0; i < bakedModuleCache.Length; i++) { int j = (int)bakedModuleCache[i].TextureIndex; if (bakedModuleCache[i].TextureAsset != null) { wearableCache[j].TextureID = bakedModuleCache[i].TextureID; wearableCache[j].CacheId = bakedModuleCache[i].CacheId; wearableCache[j].TextureAsset = bakedModuleCache[i].TextureAsset; bakedModuleCache[i].TextureAsset.Temporary = true; bakedModuleCache[i].TextureAsset.Local = true; cache.Store(bakedModuleCache[i].TextureAsset); } } gotbacked = true; } if (gotbacked) { // force the ones we got for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; if (sp.Appearance.Texture.FaceTextures[idx] == null) sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint)idx); sp.Appearance.Texture.FaceTextures[idx].TextureID = wearableCache[idx].TextureID; face = sp.Appearance.Texture.FaceTextures[idx]; // this should be removed if (face.TextureID != UUID.Zero && face.TextureID != AppearanceManager.DEFAULT_AVATAR_TEXTURE) hits++; continue; } } } sp.Appearance.WearableCacheItems = wearableCache; } // debug m_log.DebugFormat("[ValidateBakedCache]: Completed texture check for {0} {1} with {2} hits", sp.Name, sp.UUID, hits); /* for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++) { int j = AvatarAppearance.BAKE_INDICES[iter]; m_log.Debug("[ValidateBakedCache] {" + iter + "/" + sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" + sp.Appearance.WearableCacheItems[j].CacheId + ", t-" + sp.Appearance.WearableCacheItems[j].TextureID); } */ return (hits >= AvatarAppearance.BAKE_INDICES.Length - 1); // skirt is optional } public int RequestRebake(IScenePresence sp, bool missingTexturesOnly) { if (((ScenePresence)sp).isNPC) return 0; int texturesRebaked = 0; // IImprovedAssetCache cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // if there is no texture entry, skip it if (face == null) continue; if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue; if (missingTexturesOnly) { if (m_scene.AssetService.Get(face.TextureID.ToString()) != null) { continue; } else { // On inter-simulator teleports, this occurs if baked textures are not being stored by the // grid asset service (which means that they are not available to the new region and so have // to be re-requested from the client). // // The only available core OpenSimulator behaviour right now // is not to store these textures, temporarily or otherwise. m_log.DebugFormat( "[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.", face.TextureID, idx, sp.Name); } } else { m_log.DebugFormat( "[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.", face.TextureID, idx, sp.Name); } texturesRebaked++; sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID); } return texturesRebaked; } #endregion #region AvatarFactoryModule private methods private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp) { if (sp.IsChildAgent) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = new Dictionary<BakeType, Primitive.TextureEntryFace>(); AvatarAppearance appearance = sp.Appearance; Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures; foreach (int i in Enum.GetValues(typeof(BakeType))) { BakeType bakeType = (BakeType)i; if (bakeType == BakeType.Unknown) continue; // m_log.DebugFormat( // "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}", // acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]); int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType); Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture bakedTextures[bakeType] = texture; } return bakedTextures; } private void HandleAppearanceUpdateTimer(object sender, EventArgs ea) { long now = DateTime.Now.Ticks; lock (m_sendqueue) { Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue); foreach (KeyValuePair<UUID, long> kvp in sends) { // We have to load the key and value into local parameters to avoid a race condition if we loop // around and load kvp with a different value before FireAndForget has launched its thread. UUID avatarID = kvp.Key; long sendTime = kvp.Value; // m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now); if (sendTime < now) { Util.FireAndForget(o => SendAppearance(avatarID), null, "AvatarFactoryModule.SendAppearance"); m_sendqueue.Remove(avatarID); } } } lock (m_savequeue) { Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue); foreach (KeyValuePair<UUID, long> kvp in saves) { // We have to load the key and value into local parameters to avoid a race condition if we loop // around and load kvp with a different value before FireAndForget has launched its thread. UUID avatarID = kvp.Key; long sendTime = kvp.Value; if (sendTime < now) { Util.FireAndForget(o => SaveAppearance(avatarID), null, "AvatarFactoryModule.SaveAppearance"); m_savequeue.Remove(avatarID); } } // We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on // another thread inbetween the first count calls and m_updateTimer.Stop() on this thread. lock (m_sendqueue) if (m_savequeue.Count == 0 && m_sendqueue.Count == 0) m_updateTimer.Stop(); } } private void SaveAppearance(UUID agentid) { // We must set appearance parameters in the en_US culture in order to avoid issues where values are saved // in a culture where decimal points are commas and then reloaded in a culture which just treats them as // number seperators. Culture.SetCurrentCulture(); ScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) { // This is expected if the user has gone away. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid); return; } // m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid); // This could take awhile since it needs to pull inventory // We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape // assets and item asset id changes to complete. // I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids // multiple save requests. SetAppearanceAssets(sp.UUID, sp.Appearance); // List<AvatarAttachment> attachments = sp.Appearance.GetAttachments(); // foreach (AvatarAttachment att in attachments) // { // m_log.DebugFormat( // "[AVFACTORY]: For {0} saving attachment {1} at point {2}", // sp.Name, att.ItemID, att.AttachPoint); // } m_scene.AvatarService.SetAppearance(agentid, sp.Appearance); // Trigger this here because it's the final step in the set/queue/save process for appearance setting. // Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes). m_scene.EventManager.TriggerAvatarAppearanceChanged(sp); } /// <summary> /// For a given set of appearance items, check whether the items are valid and add their asset IDs to /// appearance data. /// </summary> /// <param name='userID'></param> /// <param name='appearance'></param> private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance) { IInventoryService invService = m_scene.InventoryService; if (invService.GetRootFolder(userID) != null) { for (int i = 0; i < appearance.Wearables.Length; i++) { for (int j = 0; j < appearance.Wearables[i].Count; j++) { if (appearance.Wearables[i][j].ItemID == UUID.Zero) { m_log.WarnFormat( "[AVFACTORY]: Wearable item {0}:{1} for user {2} unexpectedly UUID.Zero. Ignoring.", i, j, userID); continue; } // Ignore ruth's assets if (i < AvatarWearable.DefaultWearables.Length) { if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) continue; } InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); baseItem = invService.GetItem(baseItem); if (baseItem != null) { appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); } else { m_log.WarnFormat( "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", appearance.Wearables[i][j].ItemID, (WearableType)i); appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID); } } } } else { m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); } // IInventoryService invService = m_scene.InventoryService; // bool resetwearable = false; // if (invService.GetRootFolder(userID) != null) // { // for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) // { // for (int j = 0; j < appearance.Wearables[i].Count; j++) // { // // Check if the default wearables are not set // if (appearance.Wearables[i][j].ItemID == UUID.Zero) // { // switch ((WearableType) i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // m_log.Warn("[AVFACTORY]: UUID.Zero Wearables, passing fake values."); // resetwearable = true; // break; // // } // continue; // } // // // Ignore ruth's assets except for the body parts! missing body parts fail avatar appearance on V1 // if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) // { // switch ((WearableType)i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // // m_log.WarnFormat("[AVFACTORY]: {0} Default Wearables, passing existing values.", (WearableType)i); // resetwearable = true; // break; // // } // continue; // } // // InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); // baseItem = invService.GetItem(baseItem); // // if (baseItem != null) // { // appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); // int unmodifiedWearableIndexForClosure = i; // m_scene.AssetService.Get(baseItem.AssetID.ToString(), this, // delegate(string x, object y, AssetBase z) // { // if (z == null) // { // TryAndRepairBrokenWearable( // (WearableType)unmodifiedWearableIndexForClosure, invService, // userID, appearance); // } // }); // } // else // { // m_log.ErrorFormat( // "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", // appearance.Wearables[i][j].ItemID, (WearableType)i); // // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // // } // } // } // // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int) WearableType.Eyes] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Eyes are Null, passing existing values.", (WearableType.Eyes)); // // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int) WearableType.Eyes][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Eyes are UUID.Zero are broken, {0} {1}", // appearance.Wearables[(int) WearableType.Eyes][0].ItemID, // appearance.Wearables[(int) WearableType.Eyes][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Shape] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} shape is Null, passing existing values.", (WearableType.Shape)); // // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Shape][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Shape is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Shape][0].ItemID, // appearance.Wearables[(int)WearableType.Shape][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Hair] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Hair is Null, passing existing values.", (WearableType.Hair)); // // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Hair][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Hair is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Hair][0].ItemID, // appearance.Wearables[(int)WearableType.Hair][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Skin] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Skin is Null, passing existing values.", (WearableType.Skin)); // // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Skin][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Skin is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Skin][0].ItemID, // appearance.Wearables[(int)WearableType.Skin][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // // } // // } // if (resetwearable) // { // ScenePresence presence = null; // if (m_scene.TryGetScenePresence(userID, out presence)) // { // presence.ControllingClient.SendWearables(presence.Appearance.Wearables, // presence.Appearance.Serial++); // } // } // // } // else // { // m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); // } } private void TryAndRepairBrokenWearable(WearableType type, IInventoryService invService, UUID userID,AvatarAppearance appearance) { UUID defaultwearable = GetDefaultItem(type); if (defaultwearable != UUID.Zero) { UUID newInvItem = UUID.Random(); InventoryItemBase itembase = new InventoryItemBase(newInvItem, userID) { AssetID = defaultwearable, AssetType = (int)FolderType.BodyPart, CreatorId = userID.ToString(), //InvType = (int)InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService.GetFolderForType(userID, FolderType.BodyPart).ID, Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type), BasePermissions = (uint) PermissionMask.Copy, CurrentPermissions = (uint) PermissionMask.Copy, EveryOnePermissions = (uint) PermissionMask.Copy, GroupPermissions = (uint) PermissionMask.Copy, NextPermissions = (uint) PermissionMask.Copy }; invService.AddItem(itembase); UUID LinkInvItem = UUID.Random(); itembase = new InventoryItemBase(LinkInvItem, userID) { AssetID = newInvItem, AssetType = (int)AssetType.Link, CreatorId = userID.ToString(), InvType = (int) InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService.GetFolderForType(userID, FolderType.CurrentOutfit).ID, Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type), BasePermissions = (uint) PermissionMask.Copy, CurrentPermissions = (uint) PermissionMask.Copy, EveryOnePermissions = (uint) PermissionMask.Copy, GroupPermissions = (uint) PermissionMask.Copy, NextPermissions = (uint) PermissionMask.Copy }; invService.AddItem(itembase); appearance.Wearables[(int)type] = new AvatarWearable(newInvItem, GetDefaultItem(type)); ScenePresence presence = null; if (m_scene.TryGetScenePresence(userID, out presence)) { m_scene.SendInventoryUpdate(presence.ControllingClient, invService.GetFolderForType(userID, FolderType.CurrentOutfit), false, true); } } } private UUID GetDefaultItem(WearableType wearable) { // These are ruth UUID ret = UUID.Zero; switch (wearable) { case WearableType.Eyes: ret = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7"); break; case WearableType.Hair: ret = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66"); break; case WearableType.Pants: ret = new UUID("00000000-38f9-1111-024e-222222111120"); break; case WearableType.Shape: ret = new UUID("66c41e39-38f9-f75a-024e-585989bfab73"); break; case WearableType.Shirt: ret = new UUID("00000000-38f9-1111-024e-222222111110"); break; case WearableType.Skin: ret = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb"); break; case WearableType.Undershirt: ret = new UUID("16499ebb-3208-ec27-2def-481881728f47"); break; case WearableType.Underpants: ret = new UUID("4ac2e9c7-3671-d229-316a-67717730841d"); break; } return ret; } #endregion #region Client Event Handlers /// <summary> /// Tell the client for this scene presence what items it should be wearing now /// </summary> /// <param name="client"></param> private void Client_OnRequestWearables(IClientAPI client) { Util.FireAndForget(delegate(object x) { Thread.Sleep(4000); // m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++); else m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId); }, null, "AvatarFactoryModule.OnClientRequestWearables"); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) received from a client /// </summary> /// <param name="client"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { // m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) SetAppearance(sp, textureEntry, visualParams,avSize, cacheItems); else m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId); } /// <summary> /// Update what the avatar is wearing using an item from their inventory. /// </summary> /// <param name="client"></param> /// <param name="e"></param> private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e) { // m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null) { m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId); return; } // we need to clean out the existing textures sp.Appearance.ResetAppearance(); // operate on a copy of the appearance so we don't have to lock anything yet AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false); foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) { // If the wearable type is larger than the current array, expand it if (avatAppearance.Wearables.Length <= wear.Type) { int currentLength = avatAppearance.Wearables.Length; AvatarWearable[] wears = avatAppearance.Wearables; Array.Resize(ref wears, wear.Type + 1); for (int i = currentLength ; i <= wear.Type ; i++) wears[i] = new AvatarWearable(); avatAppearance.Wearables = wears; } avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero); } avatAppearance.GetAssetsFrom(sp.Appearance); lock (m_setAppearanceLock) { // Update only those fields that we have changed. This is important because the viewer // often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing // shouldn't overwrite the changes made in SetAppearance. sp.Appearance.Wearables = avatAppearance.Wearables; sp.Appearance.Texture = avatAppearance.Texture; // We don't need to send the appearance here since the "iswearing" will trigger a new set // of visual param and baked texture changes. When those complete, the new appearance will be sent QueueAppearanceSave(client.AgentId); } } /// <summary> /// Respond to the cached textures request from the client /// </summary> /// <param name="client"></param> /// <param name="serial"></param> /// <param name="cachedTextureRequest"></param> private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest) { // m_log.WarnFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>(); foreach (CachedTextureRequestArg request in cachedTextureRequest) { UUID texture = UUID.Zero; int index = request.BakedTextureIndex; if (m_reusetextures) { // this is the most insanely dumb way to do this... however it seems to // actually work. if the appearance has been reset because wearables have // changed then the texture entries are zero'd out until the bakes are // uploaded. on login, if the textures exist in the cache (eg if you logged // into the simulator recently, then the appearance will pull those and send // them back in the packet and you won't have to rebake. if the textures aren't // in the cache then the intial makeroot() call in scenepresence will zero // them out. // // a better solution (though how much better is an open question) is to // store the hashes in the appearance and compare them. Thats's coming. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index]; if (face != null) texture = face.TextureID; // m_log.WarnFormat("[AVFACTORY]: reuse texture {0} for index {1}",texture,index); } CachedTextureResponseArg response = new CachedTextureResponseArg(); response.BakedTextureIndex = index; response.BakedTextureID = texture; response.HostName = null; cachedTextureResponse.Add(response); } // m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial); // The serial number appears to be used to match requests and responses // in the texture transaction. We just send back the serial number // that was provided in the request. The viewer bumps this for us. client.SendCachedTextureResponse(sp, serial, cachedTextureResponse); } #endregion public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction) { outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID"); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID); foreach (BakeType bt in bakedTextures.Keys) { string rawTextureID; if (bakedTextures[bt] == null) { rawTextureID = "not set"; } else { rawTextureID = bakedTextures[bt].TextureID.ToString(); if (m_scene.AssetService.Get(rawTextureID) == null) rawTextureID += " (not found)"; else rawTextureID += " (uploaded)"; } outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID); } bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp); outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete"); } } }
// <copyright file="ContinuousUniformTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous { using Random = System.Random; /// <summary> /// Continuous uniform tests. /// </summary> [TestFixture, Category("Distributions")] public class ContinuousUniformTests { /// <summary> /// Can create continuous uniform. /// </summary> [Test] public void CanCreateContinuousUniform() { var n = new ContinuousUniform(); Assert.AreEqual(0.0, n.LowerBound); Assert.AreEqual(1.0, n.UpperBound); } /// <summary> /// Can create continuous uniform. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(0.0, 0.0)] [TestCase(0.0, 0.1)] [TestCase(0.0, 1.0)] [TestCase(10.0, 10.0)] [TestCase(-5.0, 11.0)] [TestCase(-5.0, 100.0)] [TestCase(Double.NegativeInfinity, Double.PositiveInfinity)] public void CanCreateContinuousUniform(double lower, double upper) { var n = new ContinuousUniform(lower, upper); Assert.AreEqual(lower, n.LowerBound); Assert.AreEqual(upper, n.UpperBound); } /// <summary> /// Continuous uniform create fails with bad parameters. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(Double.NaN, 1.0)] [TestCase(1.0, Double.NaN)] [TestCase(Double.NaN, Double.NaN)] [TestCase(1.0, 0.0)] public void ContinuousUniformCreateFailsWithBadParameters(double lower, double upper) { Assert.That(() => new ContinuousUniform(lower, upper), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var n = new ContinuousUniform(1.0, 2.0); Assert.AreEqual("ContinuousUniform(Lower = 1, Upper = 2)", n.ToString()); } /// <summary> /// Validate entropy. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(-0.0, 2.0)] [TestCase(0.0, 2.0)] [TestCase(0.1, 4.0)] [TestCase(1.0, 10.0)] [TestCase(10.0, 11.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateEntropy(double lower, double upper) { var n = new ContinuousUniform(lower, upper); Assert.AreEqual(Math.Log(upper - lower), n.Entropy); } /// <summary> /// Validate skewness. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(-0.0, 2.0)] [TestCase(0.0, 2.0)] [TestCase(0.1, 4.0)] [TestCase(1.0, 10.0)] [TestCase(10.0, 11.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateSkewness(double lower, double upper) { var n = new ContinuousUniform(lower, upper); Assert.AreEqual(0.0, n.Skewness); } /// <summary> /// Validate mode. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(-0.0, 2.0)] [TestCase(0.0, 2.0)] [TestCase(0.1, 4.0)] [TestCase(1.0, 10.0)] [TestCase(10.0, 11.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateMode(double lower, double upper) { var n = new ContinuousUniform(lower, upper); Assert.AreEqual((lower + upper) / 2.0, n.Mode); } /// <summary> /// Validate median. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(-0.0, 2.0)] [TestCase(0.0, 2.0)] [TestCase(0.1, 4.0)] [TestCase(1.0, 10.0)] [TestCase(10.0, 11.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateMedian(double lower, double upper) { var n = new ContinuousUniform(lower, upper); Assert.AreEqual((lower + upper) / 2.0, n.Median); } /// <summary> /// Validate minimum. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(-0.0, 2.0)] [TestCase(0.0, 2.0)] [TestCase(0.1, 4.0)] [TestCase(1.0, 10.0)] [TestCase(10.0, 11.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateMinimum(double lower, double upper) { var n = new ContinuousUniform(lower, upper); Assert.AreEqual(lower, n.Minimum); } /// <summary> /// Validate maximum. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(-0.0, 2.0)] [TestCase(0.0, 2.0)] [TestCase(0.1, 4.0)] [TestCase(1.0, 10.0)] [TestCase(10.0, 11.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateMaximum(double lower, double upper) { var n = new ContinuousUniform(lower, upper); Assert.AreEqual(upper, n.Maximum); } /// <summary> /// Validate density. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(0.0, 0.0)] [TestCase(0.0, 0.1)] [TestCase(0.0, 1.0)] [TestCase(0.0, 10.0)] [TestCase(-5.0, 100.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateDensity(double lower, double upper) { var n = new ContinuousUniform(lower, upper); for (var i = 0; i < 11; i++) { var x = i - 5.0; if (x >= lower && x <= upper) { Assert.AreEqual(1.0/(upper - lower), n.Density(x)); Assert.AreEqual(1.0/(upper - lower), ContinuousUniform.PDF(lower, upper, x)); } else { Assert.AreEqual(0.0, n.Density(x)); Assert.AreEqual(0.0, ContinuousUniform.PDF(lower, upper, x)); } } } /// <summary> /// Validate density log. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(0.0, 0.0)] [TestCase(0.0, 0.1)] [TestCase(0.0, 1.0)] [TestCase(0.0, 10.0)] [TestCase(-5.0, 100.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateDensityLn(double lower, double upper) { var n = new ContinuousUniform(lower, upper); for (var i = 0; i < 11; i++) { var x = i - 5.0; if (x >= lower && x <= upper) { Assert.AreEqual(-Math.Log(upper - lower), n.DensityLn(x)); Assert.AreEqual(-Math.Log(upper - lower), ContinuousUniform.PDFLn(lower, upper, x)); } else { Assert.AreEqual(double.NegativeInfinity, n.DensityLn(x)); Assert.AreEqual(double.NegativeInfinity, ContinuousUniform.PDFLn(lower, upper, x)); } } } /// <summary> /// Can sample static. /// </summary> [Test] public void CanSampleStatic() { ContinuousUniform.Sample(new Random(0), 0.0, 1.0); } /// <summary> /// Can sample sequence static. /// </summary> [Test] public void CanSampleSequenceStatic() { var ied = ContinuousUniform.Samples(new Random(0), 0.0, 1.0); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Fail sample static with bad parameters. /// </summary> [Test] public void FailSampleStatic() { Assert.That(() => ContinuousUniform.Sample(new Random(0), 0.0, -1.0), Throws.ArgumentException); } /// <summary> /// Fail sample sequence static with bad parameters. /// </summary> [Test] public void FailSampleSequenceStatic() { Assert.That(() => ContinuousUniform.Samples(new Random(0), 0.0, -1.0).First(), Throws.ArgumentException); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new ContinuousUniform(); n.Sample(); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var n = new ContinuousUniform(); var ied = n.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Validate cumulative distribution. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(0.0, 0.0)] [TestCase(0.0, 0.1)] [TestCase(0.0, 1.0)] [TestCase(0.0, 10.0)] [TestCase(-5.0, 100.0)] [TestCase(0.0, Double.PositiveInfinity)] public void ValidateCumulativeDistribution(double lower, double upper) { var n = new ContinuousUniform(lower, upper); for (var i = 0; i < 11; i++) { var x = i - 5.0; if (x <= lower) { Assert.AreEqual(0.0, n.CumulativeDistribution(x)); Assert.AreEqual(0.0, ContinuousUniform.CDF(lower, upper, x)); } else if (x >= upper) { Assert.AreEqual(1.0, n.CumulativeDistribution(x)); Assert.AreEqual(1.0, ContinuousUniform.CDF(lower, upper, x)); } else { Assert.AreEqual((x - lower)/(upper - lower), n.CumulativeDistribution(x)); Assert.AreEqual((x - lower)/(upper - lower), ContinuousUniform.CDF(lower, upper, x)); } } } /// <summary> /// Validate inverse cumulative distribution. /// </summary> /// <param name="lower">Lower bound.</param> /// <param name="upper">Upper bound.</param> [TestCase(0.0, 0.0)] [TestCase(0.0, 0.1)] [TestCase(0.0, 1.0)] [TestCase(0.0, 10.0)] [TestCase(-5.0, 100.0)] public void ValidateInverseCumulativeDistribution(double lower, double upper) { var n = new ContinuousUniform(lower, upper); for (var i = 0; i < 11; i++) { var x = i - 5.0; if (x <= lower) { Assert.AreEqual(lower, n.InverseCumulativeDistribution(0.0), 1e-12); Assert.AreEqual(lower, ContinuousUniform.InvCDF(lower, upper, 0.0), 1e-12); } else if (x >= upper) { Assert.AreEqual(upper, n.InverseCumulativeDistribution(1.0), 1e-12); Assert.AreEqual(upper, ContinuousUniform.InvCDF(lower, upper, 1.0), 1e-12); } else { Assert.AreEqual(x, n.InverseCumulativeDistribution((x - lower)/(upper - lower)), 1e-12); Assert.AreEqual(x, ContinuousUniform.InvCDF(lower, upper, (x - lower)/(upper - lower)), 1e-12); } } } } }
using UnityEngine; using System; using System.Collections; using System.Runtime.InteropServices; namespace ChartboostSDK { public class CBExternal { private static bool initialized = false; private static string _logTag = "ChartboostSDK"; public static void Log (string message) { if(CBSettings.isLogging() && Debug.isDebugBuild) Debug.Log(_logTag + "/" + message); } private static bool checkInitialized() { if (initialized) { return true; } else { Debug.LogError("The Chartboost SDK needs to be initialized before we can show any ads"); return false; } } #if UNITY_EDITOR || (!UNITY_ANDROID && !UNITY_IPHONE) /// Initializes the Chartboost plugin. /// This must be called before using any other Chartboost features. public static void init() { Log("Unity : init with version " + Application.unityVersion); // Will verify all the id and signatures against example ones. CBSettings.getIOSAppId (); CBSettings.getIOSAppSecret (); CBSettings.getAndroidAppId (); CBSettings.getAndroidAppSecret (); CBSettings.getAmazonAppId (); CBSettings.getAmazonAppSecret (); } /// Caches an interstitial. public static void cacheInterstitial(CBLocation location) { Log("Unity : cacheInterstitial at location = " + location.ToString()); } /// Checks for a cached an interstitial. public static bool hasInterstitial(CBLocation location) { Log("Unity : hasInterstitial at location = " + location.ToString()); return false; } /// Loads an interstitial. public static void showInterstitial(CBLocation location) { Log("Unity : showInterstitial at location = " + location.ToString()); } /// Caches the more apps screen. public static void cacheMoreApps(CBLocation location) { Log("Unity : cacheMoreApps at location = " + location.ToString()); } /// Checks to see if the more apps screen is cached. public static bool hasMoreApps(CBLocation location) { Log("Unity : hasMoreApps at location = " + location.ToString()); return false; } /// Shows the more apps screen. public static void showMoreApps(CBLocation location) { Log("Unity : showMoreApps at location = " + location.ToString()); } public static void cacheInPlay(CBLocation location) { Log("Unity : cacheInPlay at location = " + location.ToString()); } public static bool hasInPlay(CBLocation location) { Log("Unity : hasInPlay at location = " + location.ToString()); return false; } public static CBInPlay getInPlay(CBLocation location) { Log("Unity : getInPlay at location = " + location.ToString()); return null; } /// Caches a rewarded video. public static void cacheRewardedVideo(CBLocation location) { Log("Unity : cacheRewardedVideo at location = " + location.ToString()); } /// Checks for a cached a rewarded video. public static bool hasRewardedVideo(CBLocation location) { Log("Unity : hasRewardedVideo at location = " + location.ToString()); return false; } /// Loads a rewarded video. public static void showRewardedVideo(CBLocation location) { Log("Unity : showRewardedVideo at location = " + location.ToString()); } // Sends back the reponse by the delegate call for ShouldDisplayInterstitial public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) { Log("Unity : chartBoostShouldDisplayInterstitialCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) { Log("Unity : chartBoostShouldDisplayRewardedVideoCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayMoreApps public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) { Log("Unity : chartBoostShouldDisplayMoreAppsCallbackResult"); } /// Sets the name of the game object to be used by the Chartboost iOS SDK public static void setGameObjectName(string name) { Log("Unity : Set Game object name for callbacks to = " + name); } /// Set the custom id used for rewarded video call public static void setCustomId(string id) { Log("Unity : setCustomId to = " + id); } /// Get the custom id used for rewarded video call public static string getCustomId() { Log("Unity : getCustomId"); return ""; } /// Confirm if an age gate passed or failed. When specified /// Chartboost will wait for this call before showing the ios app store public static void didPassAgeGate(bool pass) { Log("Unity : didPassAgeGate with value = " + pass); } /// Open a URL using a Chartboost Custom Scheme public static void handleOpenURL(string url, string sourceApp) { Log("Unity : handleOpenURL at url = " + url + " for app = " + sourceApp); } /// Set to true if you would like to implement confirmation for ad clicks, such as an age gate. /// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial. public static void setShouldPauseClickForConfirmation(bool pause) { Log("Unity : setShouldPauseClickForConfirmation with value = " + pause); } /// Set to false if you want interstitials to be disabled in the first user session public static void setShouldRequestInterstitialsInFirstSession(bool request) { Log("Unity : setShouldRequestInterstitialsInFirstSession with value = " + request); } public static bool getAutoCacheAds() { Log("Unity : getAutoCacheAds"); return false; } public static void setAutoCacheAds(bool autoCacheAds) { Log("Unity : setAutoCacheAds with value = " + autoCacheAds); } public static void setStatusBarBehavior(CBStatusBarBehavior statusBarBehavior) { Log("Unity : setStatusBarBehavior with value = " + statusBarBehavior); } public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) { Log("Unity : setShouldDisplayLoadingViewForMoreApps with value = " + shouldDisplay); } public static void setShouldPrefetchVideoContent(bool shouldPrefetch) { Log("Unity : setShouldPrefetchVideoContent with value = " + shouldPrefetch); } public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) { int levelType = (int)type; Log(String.Format("Unity : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description)); } public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) { int levelType = (int)type; Log(String.Format("Unity : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description)); } public static void pause(bool paused) { Log("Unity : pause"); } /// Shuts down the Chartboost plugin public static void destroy() { Log("Unity : destroy"); } /// Used to notify Chartboost that the Android back button has been pressed /// Returns true to indicate that Chartboost has handled the event and it should not be further processed public static bool onBackPressed() { Log("Unity : onBackPressed"); return true; } public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) { Log("Unity: trackInAppGooglePlayPurchaseEvent"); } public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) { Log("Unity: trackInAppAmazonStorePurchaseEvent"); } public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) { Log("Unity : trackInAppAppleStorePurchaseEvent"); } public static bool isAnyViewVisible() { Log("Unity : isAnyViewVisible"); return false; } #elif UNITY_IPHONE [DllImport("__Internal")] private static extern void _chartBoostInit(string appId, string appSignature, string unityVersion); [DllImport("__Internal")] private static extern bool _chartBoostIsAnyViewVisible(); [DllImport("__Internal")] private static extern void _chartBoostCacheInterstitial(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasInterstitial(string location); [DllImport("__Internal")] private static extern void _chartBoostShowInterstitial(string location); [DllImport("__Internal")] private static extern void _chartBoostCacheRewardedVideo(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasRewardedVideo(string location); [DllImport("__Internal")] private static extern void _chartBoostShowRewardedVideo(string location); [DllImport("__Internal")] private static extern void _chartBoostCacheMoreApps(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasMoreApps(string location); [DllImport("__Internal")] private static extern void _chartBoostShowMoreApps(string location); [DllImport("__Internal")] private static extern void _chartBoostCacheInPlay(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasInPlay(string location); [DllImport("__Internal")] private static extern IntPtr _chartBoostGetInPlay(string location); [DllImport("__Internal")] private static extern void _chartBoostSetCustomId(string id); [DllImport("__Internal")] private static extern void _chartBoostDidPassAgeGate(bool pass); [DllImport("__Internal")] private static extern string _chartBoostGetCustomId(); [DllImport("__Internal")] private static extern void _chartBoostHandleOpenURL(string url, string sourceApp); [DllImport("__Internal")] private static extern void _chartBoostSetShouldPauseClickForConfirmation(bool pause); [DllImport("__Internal")] private static extern void _chartBoostSetShouldRequestInterstitialsInFirstSession(bool request); [DllImport("__Internal")] private static extern void _chartBoostShouldDisplayInterstitialCallbackResult(bool result); [DllImport("__Internal")] private static extern void _chartBoostShouldDisplayRewardedVideoCallbackResult(bool result); [DllImport("__Internal")] private static extern void _chartBoostShouldDisplayMoreAppsCallbackResult(bool result); [DllImport("__Internal")] private static extern bool _chartBoostGetAutoCacheAds(); [DllImport("__Internal")] private static extern void _chartBoostSetAutoCacheAds(bool autoCacheAds); [DllImport("__Internal")] private static extern void _chartBoostSetShouldDisplayLoadingViewForMoreApps(bool shouldDisplay); [DllImport("__Internal")] private static extern void _chartBoostSetShouldPrefetchVideoContent(bool shouldDisplay); [DllImport("__Internal")] private static extern void _chartBoostTrackInAppPurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier); [DllImport("__Internal")] private static extern void _chartBoostSetGameObjectName(string name); [DllImport("__Internal")] private static extern void _chartBoostSetStatusBarBehavior(CBStatusBarBehavior statusBarBehavior); [DllImport("__Internal")] private static extern void _chartBoostTrackLevelInfo(String eventLabel, int levelType, int mainLevel, int subLevel, String description); /// Initializes the Chartboost plugin. /// This must be called before using any other Chartboost features. public static void init() { // get the AppID and AppSecret from CBSettings string appID = CBSettings.getIOSAppId (); string appSecret = CBSettings.getIOSAppSecret (); if (Application.platform == RuntimePlatform.IPhonePlayer) _chartBoostInit(appID, appSecret, Application.unityVersion); initialized = true; } /// Shuts down the Chartboost plugin public static void destroy() { Log("Unity : destroy"); } /// Check to see if any chartboost ad or view is visible public static bool isAnyViewVisible() { bool handled = false; if (!checkInitialized()) return handled; handled = _chartBoostIsAnyViewVisible(); Log("iOS : isAnyViewVisible = " + handled ); return handled; } /// Caches an interstitial. public static void cacheInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheInterstitial(location.ToString()); Log("iOS : cacheInterstitial at location = " + location.ToString()); } /// Checks for a cached an interstitial. public static bool hasInterstitial(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasInterstitial at location = " + location.ToString()); return _chartBoostHasInterstitial(location.ToString()); } /// Loads an interstitial. public static void showInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostShowInterstitial(location.ToString()); Log("iOS : showInterstitial at location = " + location.ToString()); } /// Caches the more apps screen. public static void cacheMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheMoreApps(location.ToString()); Log("iOS : cacheMoreApps at location = " + location.ToString()); } /// Checks to see if the more apps screen is cached. public static bool hasMoreApps(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasMoreApps at location = " + location.ToString()); return _chartBoostHasMoreApps(location.ToString()); } /// Shows the more apps screen. public static void showMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostShowMoreApps(location.ToString()); Log("iOS : showMoreApps at location = " + location.ToString()); } public static void cacheInPlay(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheInPlay(location.ToString()); Log("iOS : cacheInPlay at location = " + location.ToString()); } public static bool hasInPlay(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasInPlay at location = " + location.ToString()); return _chartBoostHasInPlay(location.ToString()); } public static CBInPlay getInPlay(CBLocation location) { if (!checkInitialized()) return null; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return null; } IntPtr inPlayId = _chartBoostGetInPlay(location.ToString()); // No Inplay was available right now if(inPlayId == IntPtr.Zero) { return null; } CBInPlay inPlayAd = new CBInPlay(inPlayId); Log("iOS : getInPlay at location = " + location.ToString()); return inPlayAd; } /// Caches a rewarded video. public static void cacheRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheRewardedVideo(location.ToString()); Log("iOS : cacheRewardedVideo at location = " + location.ToString()); } /// Checks for a cached a rewarded video. public static bool hasRewardedVideo(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasRewardedVideo at location = " + location.ToString()); return _chartBoostHasRewardedVideo(location.ToString()); } /// Loads a rewarded video. public static void showRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostShowRewardedVideo(location.ToString()); Log("iOS : showRewardedVideo at location = " + location.ToString()); } // Sends back the reponse by the delegate call for ShouldDisplayInterstitial public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) { if (!checkInitialized()) return; _chartBoostShouldDisplayInterstitialCallbackResult(result); Log("iOS : chartBoostShouldDisplayInterstitialCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) { if (!checkInitialized()) return; _chartBoostShouldDisplayRewardedVideoCallbackResult(result); Log("iOS : chartBoostShouldDisplayRewardedVideoCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayMoreApps public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) { if (!checkInitialized()) return; _chartBoostShouldDisplayMoreAppsCallbackResult(result); Log("iOS : chartBoostShouldDisplayMoreAppsCallbackResult"); } /// Set the custom id used for rewarded video call public static void setCustomId(string id) { if (!checkInitialized()) return; _chartBoostSetCustomId(id); Log("iOS : setCustomId to = " + id); } /// Get the custom id used for rewarded video call public static string getCustomId() { if (!checkInitialized()) return null; Log("iOS : getCustomId"); return _chartBoostGetCustomId(); } /// Confirm if an age gate passed or failed. When specified /// Chartboost will wait for this call before showing the ios app store public static void didPassAgeGate(bool pass) { if (!checkInitialized()) return; _chartBoostDidPassAgeGate(pass); Log("iOS : didPassAgeGate with value = " + pass); } /// Open a URL using a Chartboost Custom Scheme public static void handleOpenURL(string url, string sourceApp) { if (!checkInitialized()) return; _chartBoostHandleOpenURL(url, sourceApp); Log("iOS : handleOpenURL at url = " + url + " for app = " + sourceApp); } /// Set to true if you would like to implement confirmation for ad clicks, such as an age gate. /// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial. public static void setShouldPauseClickForConfirmation(bool pause) { if (!checkInitialized()) return; _chartBoostSetShouldPauseClickForConfirmation(pause); Log("iOS : setShouldPauseClickForConfirmation with value = " + pause); } /// Set to false if you want interstitials to be disabled in the first user session public static void setShouldRequestInterstitialsInFirstSession(bool request) { if (!checkInitialized()) return; _chartBoostSetShouldRequestInterstitialsInFirstSession(request); Log("iOS : setShouldRequestInterstitialsInFirstSession with value = " + request); } /// Sets the name of the game object to be used by the Chartboost iOS SDK public static void setGameObjectName(string name) { _chartBoostSetGameObjectName(name); Log("iOS : Set Game object name for callbacks to = " + name); } /// Check if we are autocaching ads after every show call public static bool getAutoCacheAds() { Log("iOS : getAutoCacheAds"); return _chartBoostGetAutoCacheAds(); } /// Sets whether to autocache after every show call public static void setAutoCacheAds(bool autoCacheAds) { _chartBoostSetAutoCacheAds(autoCacheAds); Log("iOS : Set AutoCacheAds to = " + autoCacheAds); } /// Sets whether to autocache after every show call public static void setStatusBarBehavior(CBStatusBarBehavior statusBarBehavior) { _chartBoostSetStatusBarBehavior(statusBarBehavior); Log("iOS : Set StatusBarBehavior to = " + statusBarBehavior); } /// Sets whether to display loading view for moreapps public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) { _chartBoostSetShouldDisplayLoadingViewForMoreApps(shouldDisplay); Log("iOS : Set Should Display Loading View for More Apps to = " + shouldDisplay); } /// Sets whether to prefetch videos or not public static void setShouldPrefetchVideoContent(bool shouldPrefetch) { _chartBoostSetShouldPrefetchVideoContent(shouldPrefetch); Log("iOS : Set setShouldPrefetchVideoContent to = " + shouldPrefetch); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) { int levelType = (int)type; _chartBoostTrackLevelInfo(eventLabel, levelType, mainLevel, subLevel, description); Log(String.Format("iOS : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description)); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) { int levelType = (int)type; _chartBoostTrackLevelInfo(eventLabel, levelType, mainLevel, 0, description); Log(String.Format("iOS : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description)); } /// IAP Tracking call public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) { _chartBoostTrackInAppPurchaseEvent(receipt, productTitle, productDescription, productPrice, productCurrency, productIdentifier); Log("iOS : trackInAppAppleStorePurchaseEvent"); } #elif UNITY_ANDROID private static AndroidJavaObject _plugin; /// Initialize the android sdk public static void init() { // get the AppID and AppSecret from CBSettings string appID = CBSettings.getSelectAndroidAppId (); string appSecret = CBSettings.getSelectAndroidAppSecret (); string unityVersion = Application.unityVersion; // find the plugin instance using (var pluginClass = new AndroidJavaClass("com.chartboost.sdk.unity.CBPlugin")) _plugin = pluginClass.CallStatic<AndroidJavaObject>("instance"); _plugin.Call("init", appID, appSecret, unityVersion); initialized = true; } /// Check to see if any chartboost ad or view is visible public static bool isAnyViewVisible() { bool handled = false; if (!checkInitialized()) return handled; handled = _plugin.Call<bool>("isAnyViewVisible"); Log("Android : isAnyViewVisible = " + handled ); return handled; } /// Caches an interstitial. public static void cacheInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("cacheInterstitial", location.ToString()); Log("Android : cacheInterstitial at location = " + location.ToString()); } /// Checks for a cached an interstitial. public static bool hasInterstitial(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasInterstitial at location = " + location.ToString()); return _plugin.Call<bool>("hasInterstitial", location.ToString()); } /// Loads an interstitial. public static void showInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("showInterstitial", location.ToString()); Log("Android : showInterstitial at location = " + location.ToString()); } /// Caches the more apps screen. public static void cacheMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; }; _plugin.Call("cacheMoreApps", location.ToString()); Log("Android : cacheMoreApps at location = " + location.ToString()); } /// Checks to see if the more apps screen is cached. public static bool hasMoreApps(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasMoreApps at location = " + location.ToString()); return _plugin.Call<bool>("hasMoreApps", location.ToString()); } /// Shows the more apps screen. public static void showMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("showMoreApps", location.ToString()); Log("Android : showMoreApps at location = " + location.ToString()); } public static void cacheInPlay(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("cacheInPlay", location.ToString()); Log("Android : cacheInPlay at location = " + location.ToString()); } public static bool hasInPlay(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasInPlay at location = " + location.ToString()); return _plugin.Call<bool>("hasCachedInPlay", location.ToString()); } public static CBInPlay getInPlay(CBLocation location) { Log("Android : getInPlay at location = " + location.ToString()); if (!checkInitialized()) return null; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return null; } try { AndroidJavaObject androidInPlayAd = _plugin.Call<AndroidJavaObject>("getInPlay", location.ToString()); CBInPlay inPlayAd = new CBInPlay(androidInPlayAd, _plugin); return inPlayAd; } catch { return null; } } /// Caches a rewarded video. public static void cacheRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("cacheRewardedVideo", location.ToString()); Log("Android : cacheRewardedVideo at location = " + location.ToString()); } /// Checks for a cached a rewarded video. public static bool hasRewardedVideo(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasRewardedVideo at location = " + location.ToString()); return _plugin.Call<bool>("hasRewardedVideo", location.ToString()); } /// Loads a rewarded video. public static void showRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("showRewardedVideo", location.ToString()); Log("Android : showRewardedVideo at location = " + location.ToString()); } // Sends back the reponse by the delegate call for ShouldDisplayInterstitial public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) { if (!checkInitialized()) return; _plugin.Call("chartBoostShouldDisplayInterstitialCallbackResult", result); Log("Android : chartBoostShouldDisplayInterstitialCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) { if (!checkInitialized()) return; _plugin.Call("chartBoostShouldDisplayRewardedVideoCallbackResult", result); Log("Android : chartBoostShouldDisplayRewardedVideoCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayMoreApps public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) { if (!checkInitialized()) return; _plugin.Call("chartBoostShouldDisplayMoreAppsCallbackResult", result); Log("Android : chartBoostShouldDisplayMoreAppsCallbackResult"); } public static void didPassAgeGate(bool pass) { _plugin.Call ("didPassAgeGate",pass); } public static void setShouldPauseClickForConfirmation(bool shouldPause) { _plugin.Call ("setShouldPauseClickForConfirmation",shouldPause); } public static String getCustomId() { return _plugin.Call<String>("getCustomId"); } public static void setCustomId(String customId) { _plugin.Call("setCustomId", customId); } public static bool getAutoCacheAds() { return _plugin.Call<bool>("getAutoCacheAds"); } public static void setAutoCacheAds(bool autoCacheAds) { _plugin.Call ("setAutoCacheAds", autoCacheAds); } public static void setShouldRequestInterstitialsInFirstSession(bool shouldRequest) { _plugin.Call ("setShouldRequestInterstitialsInFirstSession", shouldRequest); } public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) { _plugin.Call ("setShouldDisplayLoadingViewForMoreApps", shouldDisplay); } public static void setShouldPrefetchVideoContent(bool shouldPrefetch) { _plugin.Call ("setShouldPrefetchVideoContent", shouldPrefetch); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) {; int levelType = (int)type; _plugin.Call ("trackLevelInfo", eventLabel, levelType, mainLevel, subLevel, description); Log(String.Format("Android : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description)); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) {; int levelType = (int)type; _plugin.Call ("trackLevelInfo", eventLabel, levelType, mainLevel, description); Log(String.Format("Android : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description)); } /// Sets the name of the game object to be used by the Chartboost Android SDK public static void setGameObjectName(string name) { _plugin.Call("setGameObjectName", name); } /// Informs the Chartboost SDK about the lifecycle of your app public static void pause(bool paused) { if (!checkInitialized()) return; _plugin.Call("pause", paused); Log("Android : pause"); } /// Shuts down the Chartboost plugin public static void destroy() { if (!checkInitialized()) return; _plugin.Call("destroy"); initialized = false; Log("Android : destroy"); } /// Used to notify Chartboost that the Android back button has been pressed /// Returns true to indicate that Chartboost has handled the event and it should not be further processed public static bool onBackPressed() { bool handled = false; if (!checkInitialized()) return false; handled = _plugin.Call<bool>("onBackPressed"); Log("Android : onBackPressed"); return handled; } public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) { Log("Android: trackInAppGooglePlayPurchaseEvent"); _plugin.Call("trackInAppGooglePlayPurchaseEvent", title,description,price,currency,productID,purchaseData,purchaseSignature); } public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) { Log("Android: trackInAppAmazonStorePurchaseEvent"); _plugin.Call("trackInAppAmazonStorePurchaseEvent", title,description,price,currency,productID,userID,purchaseToken); } #endif } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace SslSecuredWebApplicationSample.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/*============================================================================= * * (C) Copyright 2007, Michael Carlisle (mike.carlisle@thecodeking.co.uk) * * http://www.TheCodeKing.co.uk * * All rights reserved. * The code and information is provided "as-is" without waranty of any kind, * either expressed or implied. * *============================================================================= */ using System; using System.Windows.Forms; using TheCodeKing.Net.Messaging.Concrete.IOStream; using TheCodeKing.Net.Messaging.Concrete.WindowsMessaging; using System.Diagnostics; using TheCodeKing.Net.Messaging.Concrete.MultiBroadcast; using TheCodeKing.Net.Messaging.Concrete; namespace TheCodeKing.Net.Messaging { /// <summary> /// An implementation of IXDListener used to send and recieve messages interprocess, using the Windows /// Messaging XDTransportMode. Applications may leverage this instance to register listeners on pseudo 'channels', and /// receive messages broadcast using a concrete IXDBroadcast implementation on the same machine. Non-form based /// application are not supported by this implementation. /// </summary> public sealed class XDListener : NativeWindow, IXDListener { // Flag as to whether dispose has been called private bool disposed = false; private NetworkRelayListener networkRelay; /// <summary> /// Creates a concrete IXDListener which uses the XDTransportMode.WindowsMessaging implementaion. This method /// is now deprecated and XDListener.CreateInstance(XDTransportMode.WindowsMessaging) should be used instead. /// </summary> [Obsolete("Use the static CreateListener method to create a particular implementation of IXDListener.")] public XDListener() :this(true) { } /// <summary> /// The non-obsolete constructor used internally for creating new instances of XDListener. /// </summary> /// <param name="nonObsolete"></param> internal XDListener(bool nonObsolete) { // create a top-level native window CreateParams p = new CreateParams(); p.Width = 0; p.Height = 0; p.X = 0; p.Y = 0; p.Caption = string.Concat("TheCodeKing.Net.XDServices.",Guid.NewGuid().ToString()); p.Parent = IntPtr.Zero; base.CreateHandle(p); this.networkRelay = new NetworkRelayListener(XDBroadcast.CreateBroadcast(XDTransportMode.WindowsMessaging), XDListener.CreateListener(XDTransportMode.MailSlot)); } /// <summary> /// The delegate used for handling cross AppDomain communications. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args containing the DataGram data.</param> public delegate void XDMessageHandler(object sender, XDMessageEventArgs e); /// <summary> /// The event fired when messages are received. /// </summary> public event XDMessageHandler MessageReceived; /// <summary> /// Creates an concrete implementation of IXDListener to listen for messages using /// either a specific XDTransportMode. /// </summary> /// <param name="transport"></param> /// <returns></returns> public static IXDListener CreateListener(XDTransportMode transport) { switch (transport) { case XDTransportMode.IOStream: return new XDIOStreamListener(); case XDTransportMode.MailSlot: return new TheCodeKing.Net.Messaging.Concrete.MailSlot.XDMailSlotListener(); default: return new XDListener(true); } } /// <summary> /// Registers the instance to recieve messages from a named channel. /// </summary> /// <param name="channelName">The channel name to listen on.</param> public void RegisterChannel(string channelName) { if (string.IsNullOrEmpty(channelName)) { throw new ArgumentNullException(channelName, "The channel name cannot be null or empty."); } if (disposed) { throw new ObjectDisposedException("IXDListener", "This instance has been disposed."); } Native.SetProp(this.Handle, GetChannelKey(channelName), (int)this.Handle); } /// <summary> /// Unregisters the channel name with the instance, so that messages from this /// channel will no longer be received. /// </summary> /// <param name="channelName">The channel name to stop listening for.</param> public void UnRegisterChannel(string channelName) { if (string.IsNullOrEmpty(channelName)) { throw new ArgumentNullException(channelName, "The channel name cannot be null or empty."); } if (disposed) { throw new ObjectDisposedException("IXDListener", "This instance has been disposed."); } Native.RemoveProp(this.Handle, GetChannelKey(channelName)); } /// <summary> /// The native window message filter used to catch our custom WM_COPYDATA /// messages containing cross AppDomain messages. All other messages are ignored. /// </summary> /// <param name="msg">A representation of the native Windows Message.</param> protected override void WndProc(ref Message msg) { base.WndProc(ref msg); if (msg.Msg == Native.WM_COPYDATA) { // we can free any unmanaged resources immediately in the dispose, managed channel and message // data will still be retained in the object passed to the event using (DataGram dataGram = DataGram.FromPointer(msg.LParam)) { if (MessageReceived != null && dataGram.IsValid) { MessageReceived.Invoke(this, new XDMessageEventArgs(dataGram)); } } } } /// <summary> /// Gets a channel key string associated with the channel name. This is used as the /// property name attached to listening windows in order to identify them as /// listeners. Using the key instead of user defined channel name avoids protential /// property name clashes. /// </summary> /// <param name="channelName">The channel name for which a channel key is required.</param> /// <returns>The string channel key.</returns> internal static string GetChannelKey(string channelName) { return string.Format("TheCodeKing.Net.XDServices.{0}", channelName); } /// <summary> /// Deconstructor, cleans unmanaged resources only /// </summary> ~XDListener() { Dispose(false); } /// <summary> /// Dispose implementation, which ensures the native window is destroyed /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose implementation which ensures the native window is destroyed, and /// managed resources detached. /// </summary> private void Dispose(bool disposeManaged) { if (!disposed) { disposed = true; if (disposeManaged) { if (networkRelay != null) { networkRelay.Dispose(); networkRelay = null; } if (MessageReceived != null) { // remove all handlers Delegate[] del = MessageReceived.GetInvocationList(); foreach (XDMessageHandler msg in del) { MessageReceived -= msg; } } if (this.Handle != IntPtr.Zero) { this.DestroyHandle(); this.Dispose(); } } } } } }
using GeckoUBL.Ubl21.Udt; namespace GeckoUBL.Ubl21.Cac { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] [System.Xml.Serialization.XmlRootAttribute("MainCarriageShipmentStage", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)] public class ShipmentStageType { /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType ID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType TransportModeCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType TransportMeansTypeCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType TransitDirectionCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType PreCarriageIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType OnCarriageIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public DateType EstimatedDeliveryDate { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TimeType EstimatedDeliveryTime { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public DateType RequiredDeliveryDate { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TimeType RequiredDeliveryTime { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType LoadingSequenceID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType SuccessiveSequenceID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Instructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType[] Instructions { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("DemurrageInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType[] DemurrageInstructions { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public QuantityType CrewQuantity { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public QuantityType PassengerQuantity { get; set; } /// <remarks/> public PeriodType TransitPeriod { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("CarrierParty")] public PartyType[] CarrierParty { get; set; } /// <remarks/> public TransportMeansType TransportMeans { get; set; } /// <remarks/> public LocationType1 LoadingPortLocation { get; set; } /// <remarks/> public LocationType1 UnloadingPortLocation { get; set; } /// <remarks/> public LocationType1 TransshipPortLocation { get; set; } /// <remarks/> public TransportEventType LoadingTransportEvent { get; set; } /// <remarks/> public TransportEventType ExaminationTransportEvent { get; set; } /// <remarks/> public TransportEventType AvailabilityTransportEvent { get; set; } /// <remarks/> public TransportEventType ExportationTransportEvent { get; set; } /// <remarks/> public TransportEventType DischargeTransportEvent { get; set; } /// <remarks/> public TransportEventType WarehousingTransportEvent { get; set; } /// <remarks/> public TransportEventType TakeoverTransportEvent { get; set; } /// <remarks/> public TransportEventType OptionalTakeoverTransportEvent { get; set; } /// <remarks/> public TransportEventType DropoffTransportEvent { get; set; } /// <remarks/> public TransportEventType ActualPickupTransportEvent { get; set; } /// <remarks/> public TransportEventType DeliveryTransportEvent { get; set; } /// <remarks/> public TransportEventType ReceiptTransportEvent { get; set; } /// <remarks/> public TransportEventType StorageTransportEvent { get; set; } /// <remarks/> public TransportEventType AcceptanceTransportEvent { get; set; } /// <remarks/> public PartyType TerminalOperatorParty { get; set; } /// <remarks/> public PartyType CustomsAgentParty { get; set; } /// <remarks/> public PeriodType EstimatedTransitPeriod { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("FreightAllowanceCharge")] public AllowanceChargeType[] FreightAllowanceCharge { get; set; } /// <remarks/> public LocationType1 FreightChargeLocation { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("DetentionTransportEvent")] public TransportEventType[] DetentionTransportEvent { get; set; } /// <remarks/> public TransportEventType RequestedDepartureTransportEvent { get; set; } /// <remarks/> public TransportEventType RequestedArrivalTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("RequestedWaypointTransportEvent")] public TransportEventType[] RequestedWaypointTransportEvent { get; set; } /// <remarks/> public TransportEventType PlannedDepartureTransportEvent { get; set; } /// <remarks/> public TransportEventType PlannedArrivalTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("PlannedWaypointTransportEvent")] public TransportEventType[] PlannedWaypointTransportEvent { get; set; } /// <remarks/> public TransportEventType ActualDepartureTransportEvent { get; set; } /// <remarks/> public TransportEventType ActualWaypointTransportEvent { get; set; } /// <remarks/> public TransportEventType ActualArrivalTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("TransportEvent")] public TransportEventType[] TransportEvent { get; set; } /// <remarks/> public TransportEventType EstimatedDepartureTransportEvent { get; set; } /// <remarks/> public TransportEventType EstimatedArrivalTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("PassengerPerson")] public PersonType[] PassengerPerson { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("DriverPerson")] public PersonType[] DriverPerson { get; set; } /// <remarks/> public PersonType ReportingPerson { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("CrewMemberPerson")] public PersonType[] CrewMemberPerson { get; set; } /// <remarks/> public PersonType SecurityOfficerPerson { get; set; } /// <remarks/> public PersonType MasterPerson { get; set; } /// <remarks/> public PersonType ShipsSurgeonPerson { get; set; } } }
// // MessageDialog.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using Xwt.Backends; namespace Xwt { public static class MessageDialog { public static WindowFrame RootWindow { get; set; } #region ShowError public static void ShowError (string primaryText) { ShowError (RootWindow, primaryText); } public static void ShowError (WindowFrame parent, string primaryText) { ShowError (parent, primaryText, null); } public static void ShowError (string primaryText, string secondaryText) { ShowError (RootWindow, primaryText, secondaryText); } public static void ShowError (WindowFrame parent, string primaryText, string secondaryText) { GenericAlert (parent, Toolkit.CurrentEngine.Defaults.MessageDialog.ErrorIcon, primaryText, secondaryText, Command.Ok); } #endregion #region ShowWarning public static void ShowWarning (string primaryText) { ShowWarning (RootWindow, primaryText); } public static void ShowWarning (WindowFrame parent, string primaryText) { ShowWarning (parent, primaryText, null); } public static void ShowWarning (string primaryText, string secondaryText) { ShowWarning (RootWindow, primaryText, secondaryText); } public static void ShowWarning (WindowFrame parent, string primaryText, string secondaryText) { GenericAlert (parent, Toolkit.CurrentEngine.Defaults.MessageDialog.WarningIcon, primaryText, secondaryText, Command.Ok); } #endregion #region ShowMessage public static void ShowMessage (string primaryText) { ShowMessage (RootWindow, primaryText); } public static void ShowMessage (WindowFrame parent, string primaryText) { ShowMessage (parent, primaryText, null); } public static void ShowMessage (string primaryText, string secondaryText) { ShowMessage (RootWindow, primaryText, secondaryText); } public static void ShowMessage (string primaryText, string secondaryText, Drawing.Image icon) { ShowMessage (RootWindow, primaryText, secondaryText, icon); } public static void ShowMessage (WindowFrame parent, string primaryText, string secondaryText) { GenericAlert (parent, Toolkit.CurrentEngine.Defaults.MessageDialog.InformationIcon, primaryText, secondaryText, Command.Ok); } public static void ShowMessage (WindowFrame parent, string primaryText, string secondaryText, Drawing.Image icon) { GenericAlert (parent, icon, primaryText, secondaryText, Command.Ok); } #endregion #region Confirm public static bool Confirm (string primaryText, Command button) { return Confirm (primaryText, null, button); } public static bool Confirm (string primaryText, string secondaryText, Command button) { return Confirm (RootWindow, primaryText, secondaryText, button); } public static bool Confirm (string primaryText, string secondaryText, Drawing.Image icon, Command button) { return Confirm (RootWindow, primaryText, secondaryText, icon, button); } public static bool Confirm (WindowFrame window, string primaryText, string secondaryText, Command button) { return GenericAlert (window, Toolkit.CurrentEngine.Defaults.MessageDialog.QuestionIcon, primaryText, secondaryText, Command.Cancel, button) == button; } public static bool Confirm (WindowFrame window, string primaryText, string secondaryText, Drawing.Image icon, Command button) { return GenericAlert (window, icon, primaryText, secondaryText, Command.Cancel, button) == button; } public static bool Confirm (string primaryText, Command button, bool confirmIsDefault) { return Confirm (primaryText, null, button, confirmIsDefault); } public static bool Confirm (string primaryText, string secondaryText, Command button, bool confirmIsDefault) { return GenericAlert (RootWindow, Toolkit.CurrentEngine.Defaults.MessageDialog.QuestionIcon, primaryText, secondaryText, confirmIsDefault ? 0 : 1, Command.Cancel, button) == button; } public static bool Confirm (string primaryText, string secondaryText, Drawing.Image icon, Command button, bool confirmIsDefault) { return GenericAlert (RootWindow, icon, primaryText, secondaryText, confirmIsDefault ? 0 : 1, Command.Cancel, button) == button; } public static bool Confirm (ConfirmationMessage message) { return GenericAlert (RootWindow, message) == message.ConfirmButton; } #endregion #region AskQuestion public static Command AskQuestion (string primaryText, params Command[] buttons) { return AskQuestion (primaryText, null, buttons); } public static Command AskQuestion (string primaryText, string secondaryText, params Command[] buttons) { return GenericAlert (RootWindow, Toolkit.CurrentEngine.Defaults.MessageDialog.QuestionIcon, primaryText, secondaryText, buttons); } public static Command AskQuestion (string primaryText, string secondaryText, Drawing.Image icon, params Command [] buttons) { return GenericAlert (RootWindow, icon, primaryText, secondaryText, buttons); } public static Command AskQuestion (string primaryText, int defaultButton, params Command[] buttons) { return AskQuestion (primaryText, null, defaultButton, buttons); } public static Command AskQuestion (string primaryText, string secondaryText, int defaultButton, params Command[] buttons) { return GenericAlert (RootWindow, Toolkit.CurrentEngine.Defaults.MessageDialog.QuestionIcon, primaryText, secondaryText, defaultButton, buttons); } public static Command AskQuestion (string primaryText, string secondaryText, Drawing.Image icon, int defaultButton, params Command [] buttons) { return GenericAlert (RootWindow, icon, primaryText, secondaryText, defaultButton, buttons); } public static Command AskQuestion (QuestionMessage message) { return GenericAlert (RootWindow, message); } #endregion static Command GenericAlert (WindowFrame parent, Xwt.Drawing.Image icon, string primaryText, string secondaryText, params Command[] buttons) { return GenericAlert (parent, icon, primaryText, secondaryText, buttons.Length - 1, buttons); } static Command GenericAlert (WindowFrame parent, Xwt.Drawing.Image icon, string primaryText, string secondaryText, int defaultButton, params Command[] buttons) { GenericMessage message = new GenericMessage () { Icon = icon, Text = primaryText, SecondaryText = secondaryText, DefaultButton = defaultButton }; foreach (Command but in buttons) message.Buttons.Add (but); return GenericAlert (parent, message); } static Command GenericAlert (WindowFrame parent, MessageDescription message) { if (message.ApplyToAllButton != null) return message.ApplyToAllButton; IAlertDialogBackend backend = Toolkit.CurrentEngine.Backend.CreateBackend<IAlertDialogBackend> (); backend.Initialize (Toolkit.CurrentEngine.Context); if (message.Icon != null) message.Icon.InitForToolkit (Toolkit.CurrentEngine); using (backend) { var res = backend.Run (parent ?? RootWindow, message); if (backend.ApplyToAll) message.ApplyToAllButton = res; return res; } } } public class MessageDescription { internal MessageDescription () { DefaultButton = -1; Buttons = new List<Command> (); Options = new List<AlertOption> (); } public IList<Command> Buttons { get; private set; } public IList<AlertOption> Options { get; private set; } internal Command ApplyToAllButton { get; set; } public Xwt.Drawing.Image Icon { get; set; } public string Text { get; set; } public string SecondaryText { get; set; } public bool AllowApplyToAll { get; set; } public int DefaultButton { get; set; } public void AddOption (string id, string text, bool setByDefault) { Options.Add (new AlertOption (id, text) { Value = setByDefault }); } public bool GetOptionValue (string id) { foreach (var op in Options) if (op.Id == id) return op.Value; throw new ArgumentException ("Invalid option id"); } public void SetOptionValue (string id, bool value) { foreach (var op in Options) { if (op.Id == id) { op.Value = value; return; } } throw new ArgumentException ("Invalid option id"); } } public class AlertOption { internal AlertOption (string id, string text) { this.Id = id; this.Text = text; } public string Id { get; private set; } public string Text { get; private set; } public bool Value { get; set; } } public sealed class GenericMessage: MessageDescription { public GenericMessage () { } public GenericMessage (string text) { Text = text; } public GenericMessage (string text, string secondaryText): this (text) { SecondaryText = secondaryText; } public new IList<Command> Buttons { get { return base.Buttons; } } } public sealed class QuestionMessage: MessageDescription { public QuestionMessage () { Icon = Toolkit.CurrentEngine.Defaults.MessageDialog.QuestionIcon; } public QuestionMessage (string text): this () { Text = text; } public QuestionMessage (string text, string secondaryText): this (text) { SecondaryText = secondaryText; } public new IList<Command> Buttons { get { return base.Buttons; } } } public sealed class ConfirmationMessage: MessageDescription { Command confirmButton; public ConfirmationMessage () { Icon = Toolkit.CurrentEngine.Defaults.MessageDialog.QuestionIcon; Buttons.Add (Command.Cancel); } public ConfirmationMessage (Command button): this () { ConfirmButton = button; } public ConfirmationMessage (string primaryText, Command button): this (button) { Text = primaryText; } public ConfirmationMessage (string primaryText, string secondaryText, Command button): this (primaryText, button) { SecondaryText = secondaryText; } public Command ConfirmButton { get { return confirmButton; } set { if (Buttons.Count == 2) Buttons.RemoveAt (1); Buttons.Add (value); confirmButton = value; } } public bool ConfirmIsDefault { get { return DefaultButton == 1; } set { if (value) DefaultButton = 1; else DefaultButton = 0; } } } public sealed class MessageDialogDefaults { Drawing.Image informationIcon; Drawing.Image warningIcon; Drawing.Image errorIcon; Drawing.Image confirmationIcon; Drawing.Image questionIcon; /// <summary> /// Gets or sets the icon shown in Information dialogs. /// </summary> /// <value>The information icon.</value> public Drawing.Image InformationIcon { get { if (informationIcon != null) return informationIcon; return StockIcons.Information; } set { informationIcon = value; } } /// <summary> /// Gets or sets the icon shown in Warning dialogs. /// </summary> /// <value>The warning icon.</value> public Drawing.Image WarningIcon { get { if (warningIcon != null) return warningIcon; return StockIcons.Warning; } set { warningIcon = value; } } /// <summary> /// Gets or sets the icon shown in Error dialogs. /// </summary> /// <value>The error icon.</value> public Drawing.Image ErrorIcon { get { if (errorIcon != null) return errorIcon; return StockIcons.Error; } set { errorIcon = value; } } /// <summary> /// Gets or sets the icon shown in Confirmation dialogs. /// </summary> /// <value>The confirmation icon.</value> public Drawing.Image ConfirmationIcon { get { if (confirmationIcon != null) return confirmationIcon; return StockIcons.Question; } set { confirmationIcon = value; } } /// <summary> /// Gets or sets the icon shown in Question dialogs. /// </summary> /// <value>The question icon.</value> public Drawing.Image QuestionIcon { get { if (questionIcon != null) return questionIcon; return StockIcons.Question; } set { questionIcon = value; } } } }
using System.Configuration; using Rhino.Etl.Core.Infrastructure; namespace Rhino.Etl.Core.Operations { using System; using System.Collections.Generic; using System.Data.SqlClient; using DataReaders; using System.Data; /// <summary> /// Allows to execute an operation that perform a bulk insert into a sql server database /// </summary> public abstract class SqlBulkInsertOperation : AbstractDatabaseOperation { private string preCommand; private string postCommand; /// <summary> /// The schema of the destination table /// </summary> private IDictionary<string, Type> _schema = new Dictionary<string, Type>(); /// <summary> /// The mapping of columns from the row to the database schema. /// Important: The column name in the database is case sensitive! /// </summary> public IDictionary<string, string> Mappings = new Dictionary<string, string>(); private readonly IDictionary<string, Type> _inputSchema = new Dictionary<string, Type>(); private SqlBulkCopy sqlBulkCopy; private string targetTable; private int timeout; private int batchSize; private int notifyBatchSize; private SqlBulkCopyOptions bulkCopyOptions = SqlBulkCopyOptions.Default; /// <summary> /// A command to run after the row commands /// </summary> protected string PostCommand { get { return postCommand; } set { postCommand = value; } } /// <summary> /// A command to run prior to the row commands /// </summary> protected string PreCommand { get { return preCommand; } set { preCommand = value; } } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="targetTable">The target table.</param> protected SqlBulkInsertOperation(string connectionStringName, string targetTable) : this(ConfigurationManager.ConnectionStrings[connectionStringName], targetTable) { } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringSettings">Connection string settings to use.</param> /// <param name="targetTable">The target table.</param> protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable) : this(connectionStringSettings, targetTable, 600) { } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="targetTable">The target table.</param> /// <param name="timeout">The timeout.</param> protected SqlBulkInsertOperation(string connectionStringName, string targetTable, int timeout) : this(ConfigurationManager.ConnectionStrings[connectionStringName], targetTable, timeout) { Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory"); this.targetTable = targetTable; this.timeout = timeout; } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringSettings">Connection string settings to use.</param> /// <param name="targetTable">The target table.</param> /// <param name="timeout">The timeout.</param> protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable, int timeout) : base(connectionStringSettings) { Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory"); this.targetTable = targetTable; this.timeout = timeout; } /// <summary>The timeout value of the bulk insert operation</summary> public virtual int Timeout { get { return timeout; } set { timeout = value; } } /// <summary>The batch size value of the bulk insert operation</summary> public virtual int BatchSize { get { return batchSize; } set { batchSize = value; } } /// <summary>The batch size value of the bulk insert operation</summary> public virtual int NotifyBatchSize { get { return notifyBatchSize > 0 ? notifyBatchSize : batchSize; } set { notifyBatchSize = value; } } /// <summary>The table or view to bulk load the data into.</summary> public string TargetTable { get { return targetTable; } set { targetTable = value; } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.TableLock"/> option on, otherwise <c>false</c>.</summary> public virtual bool LockTable { get { return IsOptionOn(SqlBulkCopyOptions.TableLock); } set { ToggleOption(SqlBulkCopyOptions.TableLock, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.KeepIdentity"/> option on, otherwise <c>false</c>.</summary> public virtual bool KeepIdentity { get { return IsOptionOn(SqlBulkCopyOptions.KeepIdentity); } set { ToggleOption(SqlBulkCopyOptions.KeepIdentity, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.KeepNulls"/> option on, otherwise <c>false</c>.</summary> public virtual bool KeepNulls { get { return IsOptionOn(SqlBulkCopyOptions.KeepNulls); } set { ToggleOption(SqlBulkCopyOptions.KeepNulls, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.CheckConstraints"/> option on, otherwise <c>false</c>.</summary> public virtual bool CheckConstraints { get { return IsOptionOn(SqlBulkCopyOptions.CheckConstraints); } set { ToggleOption(SqlBulkCopyOptions.CheckConstraints, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.FireTriggers"/> option on, otherwise <c>false</c>.</summary> public virtual bool FireTriggers { get { return IsOptionOn(SqlBulkCopyOptions.FireTriggers); } set { ToggleOption(SqlBulkCopyOptions.FireTriggers, value); } } /// <summary>Turns a <see cref="bulkCopyOptions"/> on or off depending on the value of <paramref name="on"/></summary> /// <param name="option">The <see cref="SqlBulkCopyOptions"/> to turn on or off.</param> /// <param name="on"><c>true</c> to set the <see cref="SqlBulkCopyOptions"/> <paramref name="option"/> on otherwise <c>false</c> to turn the <paramref name="option"/> off.</param> protected void ToggleOption(SqlBulkCopyOptions option, bool on) { if (on) { TurnOptionOn(option); } else { TurnOptionOff(option); } } /// <summary>Returns <c>true</c> if the <paramref name="option"/> is turned on, otherwise <c>false</c></summary> /// <param name="option">The <see cref="SqlBulkCopyOptions"/> option to test for.</param> /// <returns></returns> protected bool IsOptionOn(SqlBulkCopyOptions option) { return (bulkCopyOptions & option) == option; } /// <summary>Turns the <paramref name="option"/> on.</summary> /// <param name="option"></param> protected void TurnOptionOn(SqlBulkCopyOptions option) { bulkCopyOptions |= option; } /// <summary>Turns the <paramref name="option"/> off.</summary> /// <param name="option"></param> protected void TurnOptionOff(SqlBulkCopyOptions option) { if (IsOptionOn(option)) bulkCopyOptions ^= option; } /// <summary>The table or view's schema information.</summary> public IDictionary<string, Type> Schema { get { return _schema; } set { _schema = value; } } /// <summary> /// Prepares the mapping for use, by default, it uses the schema mapping. /// This is the preferred appraoch /// </summary> public virtual void PrepareMapping() { foreach (KeyValuePair<string, Type> pair in _schema) { Mappings[pair.Key] = pair.Key; } } /// <summary>Use the destination Schema and Mappings to create the /// operations input schema so it can build the adapter for sending /// to the WriteToServer method.</summary> public virtual void CreateInputSchema() { foreach (KeyValuePair<string, string> pair in Mappings) { _inputSchema.Add(pair.Key, _schema[pair.Value]); } } /// <summary> /// Executes this operation /// </summary> public override IEnumerable<Row> Execute(IEnumerable<Row> rows) { Guard.Against<ArgumentException>(rows == null, "SqlBulkInsertOperation cannot accept a null enumerator"); PrepareSchema(); PrepareMapping(); CreateInputSchema(); using (SqlConnection connection = (SqlConnection)Use.Connection(ConnectionStringSettings)) using (SqlTransaction transaction = (SqlTransaction)BeginTransaction(connection)) { if (!string.IsNullOrEmpty(PreCommand)) { Debug("Executing PreCommand '{0}'", PreCommand); using (IDbCommand preCmd = connection.CreateCommand()) { preCmd.CommandTimeout = Timeout; preCmd.CommandText = PreCommand; preCmd.Transaction = transaction; preCmd.ExecuteNonQuery(); } } sqlBulkCopy = CreateSqlBulkCopy(connection, transaction); DictionaryEnumeratorDataReader adapter = new DictionaryEnumeratorDataReader(_inputSchema, rows); sqlBulkCopy.WriteToServer(adapter); if (!string.IsNullOrEmpty(PostCommand)) { using (IDbCommand postCmd = connection.CreateCommand()) { postCmd.CommandTimeout = Timeout; postCmd.CommandText = PostCommand; postCmd.Transaction = transaction; postCmd.ExecuteNonQuery(); } } if (PipelineExecuter.HasErrors) { Warn("Rolling back transaction in {0}", Name); if (transaction != null) transaction.Rollback(); Warn("Rolled back transaction in {0}", Name); } else { Debug("Committing {0}", Name); if (transaction != null) transaction.Commit(); Debug("Committed {0}", Name); } } yield break; } /// <summary> /// Handle sql notifications /// </summary> protected virtual void onSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) { Debug("{0} rows copied to database", e.RowsCopied); } /// <summary> /// Prepares the schema of the target table /// </summary> protected abstract void PrepareSchema(); /// <summary> /// Creates the SQL bulk copy instance /// </summary> private SqlBulkCopy CreateSqlBulkCopy(SqlConnection connection, SqlTransaction transaction) { SqlBulkCopy copy = new SqlBulkCopy(connection, bulkCopyOptions, transaction); copy.BatchSize = batchSize; foreach (KeyValuePair<string, string> pair in Mappings) { copy.ColumnMappings.Add(pair.Key, pair.Value); } copy.NotifyAfter = NotifyBatchSize; copy.SqlRowsCopied += onSqlRowsCopied; copy.DestinationTableName = TargetTable; copy.BulkCopyTimeout = Timeout; return copy; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows.Automation; using EnvDTE; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Python; using TestUtilities.UI; namespace PythonToolsUITests { [TestClass] public class ObjectBrowserTest { private class NodeInfo { public NodeInfo(string name, string description, string[] members = null) { Name = name; Description = description; Members = (members != null) ? new Collection<string>(members) : new Collection<string>(); } public string Name { get; private set; } public string Description { get; private set; } public Collection<string> Members { get; private set; } } private static void AssertNodes(ObjectBrowser objectBrowser, params NodeInfo[] expectedNodes) { AssertNodes(objectBrowser, true, expectedNodes); } private static void AssertNodes(ObjectBrowser objectBrowser, bool expand, params NodeInfo[] expectedNodes) { for (int i = 0; i < expectedNodes.Length; ++i) { // Check node name for (int j = 0; j < 100; j++) { if (i < objectBrowser.TypeBrowserPane.Nodes.Count) { break; } System.Threading.Thread.Sleep(250); } string str = objectBrowser.TypeBrowserPane.Nodes[i].Value.Trim(); Console.WriteLine("Found node: {0}", str); Assert.AreEqual(expectedNodes[i].Name, str, ""); objectBrowser.TypeBrowserPane.Nodes[i].Select(); if (expand) { try { objectBrowser.TypeBrowserPane.Nodes[i].ExpandCollapse(); } catch (InvalidOperationException) { } } System.Threading.Thread.Sleep(1000); // Check detailed node description. str = objectBrowser.DetailPane.Value.Trim(); if(expectedNodes[i].Description != str) { for (int j = 0; j < str.Length; j++) { Console.WriteLine("{0} {1}", (int)str[j], (int)expectedNodes[i].Description[j]); } } Assert.AreEqual(expectedNodes[i].Description, str, ""); // Check dependent nodes in member pane int nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; var expectedMembers = expectedNodes[i].Members; if (expectedMembers == null) { Assert.AreEqual(0, nodeCount, "Node Count: " + nodeCount.ToString()); } else { Assert.AreEqual(expectedMembers.Count, nodeCount, "Node Count: " + nodeCount.ToString()); for (int j = 0; j < expectedMembers.Count; ++j) { str = objectBrowser.TypeNavigatorPane.Nodes[j].Value.Trim(); Assert.AreEqual(expectedMembers[j], str, ""); } } } } [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserBasicTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Outlining.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); AssertNodes(objectBrowser, new NodeInfo("Outlining", "Outlining"), new NodeInfo("BadForStatement.py", "BadForStatement.py"), new NodeInfo("NestedFuncDef.py", "NestedFuncDef.py", new[] { "def f()" }), new NodeInfo("Program.py", "Program.py", new[] { "def f()", "i" })); app.Dte.Solution.Close(false); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserSearchTextTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\ObjectBrowser.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); // Initially, we should have only the top-level collapsed node for the project int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); // Sanity-check the starting view with all nodes expanded. var expectedNodesBeforeSearch = new[] { new NodeInfo("ObjectBrowser", "ObjectBrowser"), new NodeInfo("Program.py", "Program.py", new[] { "def frob()" }), new NodeInfo("class Fob", "class Fob"), new NodeInfo("class FobOarBaz", "class FobOarBaz", new[] { "def frob(self)" }), new NodeInfo("class Oar", "class Oar", new[] { "def oar(self)" }), }; AssertNodes(objectBrowser, expectedNodesBeforeSearch); // Do the search and check results objectBrowser.SearchText.SetValue("oar"); System.Threading.Thread.Sleep(1000); objectBrowser.SearchButton.Click(); System.Threading.Thread.Sleep(1000); var expectedNodesAfterSearch = new[] { new NodeInfo("oar", "def oar(self)\rdeclared in Oar"), new NodeInfo("Oar", "class Oar", new[] { "def oar(self)" }), new NodeInfo("FobOarBaz", "class FobOarBaz", new[] { "def frob(self)" }), }; AssertNodes(objectBrowser, expectedNodesAfterSearch); // Clear the search and check that we get back to the starting view. objectBrowser.ClearSearchButton.Click(); System.Threading.Thread.Sleep(1000); AssertNodes(objectBrowser, false, expectedNodesBeforeSearch); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserExpandTypeBrowserTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Inheritance.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[0].Value; Assert.AreEqual("Inheritance", str, ""); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString()); str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserCommentsTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Inheritance.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].Select(); nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; Assert.AreEqual(4, nodeCount, "Node Count: " + nodeCount.ToString()); str = objectBrowser.TypeNavigatorPane.Nodes[0].Value; Assert.AreEqual("member", str.Trim(), ""); str = objectBrowser.TypeNavigatorPane.Nodes[1].Value; Assert.AreEqual("members", str.Trim(), ""); str = objectBrowser.TypeNavigatorPane.Nodes[2].Value; Assert.AreEqual("s", str.Trim(), ""); str = objectBrowser.TypeNavigatorPane.Nodes[3].Value; Assert.AreEqual("t", str.Trim(), ""); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[2].Select(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node Count: " + nodeCount.ToString()); str = objectBrowser.TypeNavigatorPane.Nodes[0].Value; Assert.IsTrue(str.Trim().StartsWith("def __init__(self"), str); str = objectBrowser.TypeNavigatorPane.Nodes[1].Value; Assert.AreEqual("def tell(self)", str.Trim(), ""); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("SchoolMember"), str); Assert.IsTrue(str.Trim().Contains("Represents any school member."), str); objectBrowser.TypeNavigatorPane.Nodes[1].Select(); System.Threading.Thread.Sleep(1000); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("def tell(self)"), str); Assert.IsTrue(str.Trim().Contains("Tell my detail."), str); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserInheritanceRelationshipTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Inheritance.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].Select(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node Count: " + nodeCount.ToString()); str = objectBrowser.TypeNavigatorPane.Nodes[0].Value; Assert.IsTrue(str.Trim().StartsWith("def __init__(self"), str); str = objectBrowser.TypeNavigatorPane.Nodes[1].Value; Assert.AreEqual("def tell(self)", str.Trim(), ""); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("Student(SchoolMember)"), str); Assert.IsTrue(str.Trim().Contains("Represents a student."), str); objectBrowser.TypeNavigatorPane.Nodes[1].Select(); System.Threading.Thread.Sleep(1000); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("def tell(self)"), str); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserNavigationTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[4].Select(); System.Threading.Thread.Sleep(1000); app.ExecuteCommand("Edit.GoToDefinition"); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveDocument.Name; Assert.AreEqual("Program.py", str, ""); int lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(14, lineNo, "Line number: " + lineNo.ToString()); app.OpenObjectBrowser(); objectBrowser.TypeBrowserPane.Nodes[2].Select(); System.Threading.Thread.Sleep(1000); app.ExecuteCommand("Edit.GoToDefinition"); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveDocument.Name; Assert.AreEqual("MyModule.py", str, ""); lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(1, lineNo, "Line number: " + lineNo.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserContextMenuBasicTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); Assert.AreEqual("Copy", menu.Items[0].Value.Trim(), ""); Assert.AreEqual("View Namespaces", menu.Items[1].Value.Trim(), ""); Assert.AreEqual("View Containers", menu.Items[2].Value.Trim(), ""); Assert.AreEqual("Sort Alphabetically", menu.Items[3].Value.Trim(), ""); Assert.AreEqual("Sort By Object Type", menu.Items[4].Value.Trim(), ""); Assert.AreEqual("Sort By Object Access", menu.Items[5].Value.Trim(), ""); Assert.AreEqual("Group By Object Type", menu.Items[6].Value.Trim(), ""); Keyboard.PressAndRelease(System.Windows.Input.Key.Escape); objectBrowser.TypeBrowserPane.Nodes[2].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); itemCount = menu.Items.Count; Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString()); Assert.AreEqual("Go To Definition", menu.Items[0].Value.Trim(), ""); Assert.AreEqual("Go To Declaration", menu.Items[1].Value.Trim(), ""); Assert.AreEqual("Go To Reference", menu.Items[2].Value.Trim(), ""); Assert.AreEqual("Browse Definition", menu.Items[3].Value.Trim(), ""); Assert.AreEqual("Find All References", menu.Items[4].Value.Trim(), ""); Assert.AreEqual("Filter To Type", menu.Items[5].Value.Trim(), ""); Assert.AreEqual("Copy", menu.Items[6].Value.Trim(), ""); Assert.AreEqual("View Namespaces", menu.Items[7].Value.Trim(), ""); Assert.AreEqual("View Containers", menu.Items[8].Value.Trim(), ""); Assert.AreEqual("Sort Alphabetically", menu.Items[9].Value.Trim(), ""); Assert.AreEqual("Sort By Object Type", menu.Items[10].Value.Trim(), ""); Assert.AreEqual("Sort By Object Access", menu.Items[11].Value.Trim(), ""); Assert.AreEqual("Group By Object Type", menu.Items[12].Value.Trim(), ""); Keyboard.PressAndRelease(System.Windows.Input.Key.Escape); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserTypeBrowserViewTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); menu.Items[1].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); Assert.IsTrue(menu.Items[1].ToggleStatus); menu.Items[2].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserTypeBrowserSortTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); menu.Items[6].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(4, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); Assert.AreEqual("Namespaces", objectBrowser.TypeBrowserPane.Nodes[3].Value, ""); Assert.AreEqual("Namespaces", objectBrowser.TypeBrowserPane.Nodes[1].Value, ""); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[0].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); Assert.IsTrue(menu.Items[6].ToggleStatus); menu.Items[3].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(4, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("class SchoolMember\n", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[3].Value; Assert.AreEqual("Program.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[4].Value; Assert.AreEqual("class Student(MyModule.SchoolMember)\n", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[5].Value; Assert.AreEqual("class Teacher(MyModule.SchoolMember)\n", str, ""); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserNavigateVarContextMenuTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[4].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString()); menu.Items[0].Check(); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveDocument.Name; Assert.AreEqual("Program.py", str, ""); int lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(14, lineNo, "Line number: " + lineNo.ToString()); app.OpenObjectBrowser(); objectBrowser.TypeBrowserPane.Nodes[5].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); menu.Items[0].Check(); System.Threading.Thread.Sleep(1000); lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(3, lineNo, "Line number: " + lineNo.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserFindAllReferencesTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[4].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString()); menu.Items[4].Check(); System.Threading.Thread.Sleep(1000); //this needs to be updated for bug #4840 str = app.Dte.ActiveWindow.Caption; Assert.IsTrue(str.Contains("2 matches found"), str); objectBrowser.TypeBrowserPane.Nodes[2].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); menu.Items[4].Check(); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveWindow.Caption; Assert.IsTrue(str.Contains("2 matches found"), str); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void NavigateTo() { using (var app = new VisualStudioApp()) { app.OpenProject(@"TestData\Navigation.sln"); using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "Class"; Assert.AreEqual(4, dialog.WaitForNumberOfResults(4)); } using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "cls"; Assert.AreEqual(4, dialog.WaitForNumberOfResults(4)); } using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "func"; Assert.AreEqual(8, dialog.WaitForNumberOfResults(8)); } using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "fn"; Assert.AreEqual(8, dialog.WaitForNumberOfResults(8)); } } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ResourceViewIsDisabledTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Outlining.sln"); System.Threading.Thread.Sleep(1000); app.OpenResourceView(); var resourceView = app.ResourceView; Assert.IsNotNull(resourceView); System.Threading.Thread.Sleep(1000); Assert.IsNull(resourceView.TypeBrowserPane); } } } }
/* * Copyright (C) 2005-2016 Christoph Rupp (chris@crupp.de). * All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * See the file COPYING for License information. */ namespace Upscaledb { /// <summary> /// Upscaledb constants - error codes and flags /// </summary> public sealed class UpsConst { private UpsConst() { } /// <summary>Operation completed successfully</summary> public const int UPS_SUCCESS = 0; /// <summary>Invalid record size</summary> public const int UPS_INV_RECORD_SIZE = -2; /// <summary>Invalid key size</summary> public const int UPS_INV_KEY_SIZE = -3; /// <summary>Invalid key size</summary> public const int UPS_INV_KEYSIZE = -3; /// <summary>Invalid page size (must be 1024 or a multiple of 2048)</summary> public const int UPS_INV_PAGESIZE = -4; /// <summary>Memory allocation failed - out of memory</summary> public const int UPS_OUT_OF_MEMORY = -6; /// <summary>Invalid function parameter</summary> public const int UPS_INV_PARAMETER = -8; /// <summary>Invalid file header</summary> public const int UPS_INV_FILE_HEADER = -9; /// <summary>Invalid file version</summary> public const int UPS_INV_FILE_VERSION = -10; /// <summary>Key was not found</summary> public const int UPS_KEY_NOT_FOUND = -11; /// <summary>Tried to insert a key which already exists</summary> public const int UPS_DUPLICATE_KEY = -12; /// <summary>Internal Database integrity violated</summary> public const int UPS_INTEGRITY_VIOLATED = -13; /// <summary>Internal upscaledb error</summary> public const int UPS_INTERNAL_ERROR = -14; /// <summary>Tried to modify the Database, but the file was opened as read-only</summary> public const int UPS_WRITE_PROTECTED = -15; /// <summary>Database record not found</summary> public const int UPS_BLOB_NOT_FOUND = -16; /// <summary>Prefix comparison function needs more data</summary> public const int UPS_PREFIX_REQUEST_FULLKEY = -17; /// <summary>Generic file I/O error</summary> public const int UPS_IO_ERROR = -18; /// <summary>Function is not yet implemented</summary> public const int UPS_NOT_IMPLEMENTED = -20; /// <summary>File not found</summary> public const int UPS_FILE_NOT_FOUND = -21; /// <summary>Operation would block</summary> public const int UPS_WOULD_BLOCK = -22; /// <summary>Object was not initialized correctly</summary> public const int UPS_NOT_READY = -23; /// <summary>Database limits reached</summary> public const int UPS_LIMITS_REACHED = -24; /// <summary>Object was already initialized</summary> public const int UPS_ALREADY_INITIALIZED = -27; /// <summary>Database needs recovery</summary> public const int UPS_NEED_RECOVERY = -28; /// <summary>Cursor must be closed prior to Transaction abort/commit</summary> public const int UPS_CURSOR_STILL_OPEN = -29; /// <summary>Operation conflicts with another Transaction</summary> public const int UPS_TXN_CONFLICT = -31; /// <summary>Database cannot be closed because it is modified in a Transaction</summary> public const int UPS_TXN_STIL_OPEN = -33; /// <summary>Cursor does not point to a valid item</summary> public const int UPS_CURSOR_IS_NIL = -100; /// <summary>Database not found</summary> public const int UPS_DATABASE_NOT_FOUND = -200; /// <summary>Database name already exists</summary> public const int UPS_DATABASE_ALREADY_EXISTS = -201; /// <summary>Database already open, or: Database handle is already initialized</summary> public const int UPS_DATABASE_ALREADY_OPEN = -202; /// <summary>Environment already open, or: Environment handle is already initialized</summary> public const int UPS_ENVIRONMENT_ALREADY_OPEN = -203; /// <summary>Invalid log file header</summary> public const int UPS_LOG_INV_FILE_HEADER = -300; // Error handling levels /// <summary>A debug message</summary> public const int UPS_DEBUG_LEVEL_DEBUG = 0; /// <summary>A normal error message</summary> public const int UPS_DEBUG_LEVEL_NORMAL = 1; /// <summary>A fatal error message</summary> public const int UPS_DEBUG_LEVEL_FATAL = 3; // Transaction constants /// <summary>Flag for Transaction.Begin</summary> public const int UPS_TXN_READ_ONLY = 1; /// <summary>Flag for Transaction.Commit</summary> public const int UPS_TXN_FORCE_WRITE = 1; // Create/Open flags /// <summary>Flag for Database.Open, Database.Create</summary> public const int UPS_ENABLE_FSYNC = 0x001; /// <summary>Flag for Database.Open</summary> public const int UPS_READ_ONLY = 0x004; /// <summary>Flag for Database.Create</summary> public const int UPS_IN_MEMORY = 0x00080; /// <summary>Flag for Database.Open, Database.Create</summary> public const int UPS_DISABLE_MMAP = 0x00200; /// <summary>Flag for Database.Open, Database.Create</summary> public const int UPS_DISABLE_FREELIST_FLUSH = 0x00800; /// <summary>Flag for Database.Create</summary> public const int UPS_RECORD_NUMBER32 = 0x01000; /// <summary>Flag for Database.Create</summary> public const int UPS_RECORD_NUMBER64 = 0x02000; /// <summary>Flag for Database.Create (deprecated)</summary> public const int UPS_RECORD_NUMBER = UPS_RECORD_NUMBER64; /// <summary>Flag for Database.Create</summary> public const int UPS_ENABLE_DUPLICATE_KEYS = 0x04000; /// <summary>Flag for Database.Create</summary> public const int UPS_ENABLE_RECOVERY = UPS_ENABLE_TRANSACTIONS; /// <summary>Flag for Database.Open</summary> public const int UPS_AUTO_RECOVERY = 0x10000; /// <summary>Flag for Database.Create, Database.Open</summary> public const int UPS_ENABLE_TRANSACTIONS = 0x20000; /// <summary>Flag for Database.Create, Database.Open</summary> public const int UPS_CACHE_UNLIMITED = 0x40000; /// <summary>Flag for Environment.Create, Environment.Open</summary> public const int UPS_FLUSH_WHEN_COMMITTED = 0x01000000; /// <summary>Flag for Environment.Create, Environment.Open</summary> public const int UPS_ENABLE_CRC32 = 0x02000000; // Extended parameters /// <summary>Parameter name for Environment.Open, /// Environment.Create</summary> public const int UPS_PARAM_CACHE_SIZE = 0x00100; /// <summary>Parameter name for Environment.Open, /// Environment.Create (deprecated)</summary> public const int UPS_PARAM_CACHESIZE = 0x00100; /// <summary>Parameter name for Environment.Create</summary> public const int UPS_PARAM_PAGE_SIZE = 0x00101; /// <summary>Parameter name for Environment.Create (deprecated)</summary> public const int UPS_PARAM_PAGESIZE = 0x00101; /// <summary>Parameter name for Database.Create</summary> public const int UPS_PARAM_KEY_SIZE = 0x00102; /// <summary>Parameter name for Database.Create (deprecated)</summary> public const int UPS_PARAM_KEYSIZE = 0x00102; /// <summary>Parameter name for GetParameters</summary> public const int UPS_PARAM_MAX_DATABASES = 0x00103; /// <summary>Parameter name for Database.Create</summary> public const int UPS_PARAM_KEY_TYPE = 0x00104; /// <summary>Parameter name for Environment.Open, Environment.Create</summary> public const int UPS_PARAM_NETWORK_TIMEOUT_SEC = 0x00000107; /// <summary>Parameter name for Database.Create</summary> public const int UPS_PARAM_RECORD_SIZE = 0x00108; /// <summary>Parameter name for Environment.Create, /// Environment.Open</summary> public const int UPS_PARAM_FILE_SIZE_LIMIT = 0x00109; /// <summary>Parameter name for Database.Create</summary> public const int UPS_PARAM_CUSTOM_COMPARE_NAME = 0x00111; // Database operations /// <summary>Parameter for GetParameters</summary> public const int UPS_PARAM_FLAGS = 0x00000200; /// <summary>Parameter for GetParameters</summary> public const int UPS_PARAM_FILEMODE = 0x00000201; /// <summary>Parameter for GetParameters</summary> public const int UPS_PARAM_FILENAME = 0x00000202; /// <summary>Parameter for GetParameters</summary> public const int UPS_PARAM_DATABASE_NAME = 0x00000203; /// <summary>Parameter for GetParameters</summary> public const int UPS_PARAM_MAX_KEYS_PER_PAGE = 0x00000204; /// <summary>Value for UPS_PARAM_KEY_SIZE</summary> public const int UPS_KEY_SIZE_UNLIMITED = 0xffff; /// <summary>Value for UPS_PARAM_RECORD_SIZE</summary> public const long UPS_RECORD_SIZE_UNLIMITED = 0xffffffff; /// <summary>Value for Environment.Create, /// Environment.Open</summary> public const int UPS_PARAM_JOURNAL_COMPRESSION = 0x1000; /// <summary>Value for Database.Create, /// Database.Open</summary> public const int UPS_PARAM_RECORD_COMPRESSION = 0x1001; /// <summary>Value for Database.Create, /// Database.Open</summary> public const int UPS_PARAM_KEY_COMPRESSION = 0x1002; /// <summary>"null" compression</summary> public const int UPS_COMPRESSION_NONE = 0; /// <summary>zlib compression</summary> public const int UPS_COMPRESSION_ZLIB = 1; /// <summary>snappy compression</summary> public const int UPS_COMPRESSION_SNAPPY = 2; /// <summary>lzf compression</summary> public const int UPS_COMPRESSION_LZF = 3; /// <summary>lzop compression</summary> public const int UPS_COMPRESSION_LZOP = 4; // Database operations /// <summary>Flag for Database.Insert, Cursor.Insert</summary> public const int UPS_OVERWRITE = 0x0001; /// <summary>Flag for Database.Insert, Cursor.Insert</summary> public const int UPS_DUPLICATE = 0x0002; /// <summary>Flag for Cursor.Insert</summary> public const int UPS_DUPLICATE_INSERT_BEFORE = 0x0004; /// <summary>Flag for Cursor.Insert</summary> public const int UPS_DUPLICATE_INSERT_AFTER = 0x0008; /// <summary>Flag for Cursor.Insert</summary> public const int UPS_DUPLICATE_INSERT_FIRST = 0x0010; /// <summary>Flag for Cursor.Insert</summary> public const int UPS_DUPLICATE_INSERT_LAST = 0x0020; /// <summary>Flag for Database.Find</summary> public const int UPS_DIRECT_ACCESS = 0x0040; /// <summary>Flag for Database.Insert</summary> public const int UPS_HINT_APPEND = 0x0080000; /// <summary>Flag for Database.Insert</summary> public const int UPS_HINT_PREPEND = 0x0100000; /// <summary>Flag for Database.Close</summary> public const int UPS_AUTO_CLEANUP = 1; /// <summary>Private flag for testing</summary> public const int UPS_DONT_CLEAR_LOG = 2; /// <summary>Flag for Database.Close</summary> public const int UPS_TXN_AUTO_ABORT = 4; /// <summary>Flag for Database.Close</summary> public const int UPS_TXN_AUTO_COMMIT = 8; // Cursor operations /// <summary>Flag for Cursor.Move</summary> public const int UPS_CURSOR_FIRST = 1; /// <summary>Flag for Cursor.Move</summary> public const int UPS_CURSOR_LAST = 2; /// <summary>Flag for Cursor.Move</summary> public const int UPS_CURSOR_NEXT = 4; /// <summary>Flag for Cursor.Move</summary> public const int UPS_CURSOR_PREVIOUS = 8; /// <summary>Flag for Cursor.Move</summary> public const int UPS_SKIP_DUPLICATES = 16; /// <summary>Flag for Cursor.Move</summary> public const int UPS_ONLY_DUPLICATES = 32; // Cursor find flags /// <summary>Flag for Cursor.Find</summary> public const int UPS_FIND_EQ_MATCH = 0x4000; /// <summary>Flag for Cursor.Find</summary> public const int UPS_FIND_LT_MATCH = 0x1000; /// <summary>Flag for Cursor.Find</summary> public const int UPS_FIND_GT_MATCH = 0x2000; /// <summary>Flag for Cursor.Find</summary> public const int UPS_FIND_LEQ_MATCH = (UPS_FIND_LT_MATCH | UPS_FIND_EQ_MATCH); /// <summary>Flag for Cursor.Find</summary> public const int UPS_FIND_GEQ_MATCH = (UPS_FIND_GT_MATCH | UPS_FIND_EQ_MATCH); /// <summary>A binary blob without type; sorted by memcmp</summary> public const int UPS_TYPE_BINARY = 0; /// <summary>A binary blob without type; sorted by callback function</summary> public const int UPS_TYPE_CUSTOM = 1; /// <summary>An unsigned 8-bit integer</summary> public const int UPS_TYPE_UINT8 = 3; /// <summary>An unsigned 16-bit integer</summary> public const int UPS_TYPE_UINT16 = 5; /// <summary>An unsigned 32-bit integer</summary> public const int UPS_TYPE_UINT32 = 7; /// <summary>An unsigned 64-bit integer</summary> public const int UPS_TYPE_UINT64 = 9; /// <summary>An 32-bit float</summary> public const int UPS_TYPE_REAL32 = 11; /// <summary>An 64-bit double</summary> public const int UPS_TYPE_REAL64 = 12; /// <summary>Insert operation</summary> public const int UPS_OP_INSERT = 1; /// <summary>Erase operation</summary> public const int UPS_OP_ERASE = 2; /// <summary>Find operation</summary> public const int UPS_OP_FIND = 3; } }
// This file has been generated by the GUI designer. Do not modify. namespace Valle.GesTpv { public partial class VenPrecios { private global::Gtk.VBox vbox1; private global::Gtk.HBox hbox1; private global::Gtk.VBox vbox2; private global::Gtk.Label label1; private global::Valle.GtkUtilidades.ArbolDeVista arbolSeciones; private global::Gtk.VBox vbox3; private global::Gtk.Notebook notebook1; private global::Gtk.VBox vbox4; private global::Gtk.Label label3; private global::Gtk.SpinButton txtEuros; private global::Gtk.HButtonBox hbuttonbox1; private global::Gtk.Button btnRevertirEuros; private global::Gtk.Button btnActualizarEuro; private global::Gtk.Label label2; private global::Gtk.VBox vbox5; private global::Gtk.Label label24; private global::Gtk.SpinButton txtPorcentaje; private global::Gtk.HButtonBox hbuttonbox2; private global::Gtk.Button btnRevertirPorc; private global::Gtk.Button btnActualizarPorc; private global::Gtk.Label label4; private global::Valle.GtkUtilidades.ArbolDeVista arbolArticulos; private global::Gtk.HButtonBox hbuttonbox3; private global::Gtk.Button btnAplicarCmb; private global::Gtk.Label lblInfomacion; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget Valle.GesTpv.VenPrecios this.Name = "Valle.GesTpv.VenPrecios"; this.Title = global::Mono.Unix.Catalog.GetString ("Cambio de precios"); this.Icon = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./Iconos/exec.gif")); this.WindowPosition = ((global::Gtk.WindowPosition)(3)); this.Modal = true; this.BorderWidth = ((uint)(6)); // Container child Valle.GesTpv.VenPrecios.Gtk.Container+ContainerChild this.vbox1 = new global::Gtk.VBox (); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; // Container child vbox1.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; this.hbox1.BorderWidth = ((uint)(6)); // Container child hbox1.Gtk.Box+BoxChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 6; // Container child vbox2.Gtk.Box+BoxChild this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Mostrar familias"); this.vbox2.Add (this.label1); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.label1])); w1.Position = 0; // Container child vbox2.Gtk.Box+BoxChild this.arbolSeciones = new global::Valle.GtkUtilidades.ArbolDeVista (); this.arbolSeciones.WidthRequest = 310; this.arbolSeciones.HeightRequest = 210; this.arbolSeciones.Events = ((global::Gdk.EventMask)(256)); this.arbolSeciones.Name = "arbolSeciones"; this.vbox2.Add (this.arbolSeciones); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.arbolSeciones])); w2.Position = 1; this.hbox1.Add (this.vbox2); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox2])); w3.Position = 0; w3.Expand = false; w3.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.notebook1 = new global::Gtk.Notebook (); this.notebook1.CanFocus = true; this.notebook1.Name = "notebook1"; this.notebook1.CurrentPage = 1; this.notebook1.BorderWidth = ((uint)(12)); // Container child notebook1.Gtk.Notebook+NotebookChild this.vbox4 = new global::Gtk.VBox (); this.vbox4.Name = "vbox4"; this.vbox4.Spacing = 6; this.vbox4.BorderWidth = ((uint)(45)); // Container child vbox4.Gtk.Box+BoxChild this.label3 = new global::Gtk.Label (); this.label3.Name = "label3"; this.label3.Xalign = 0F; this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("Euros a incrementar"); this.vbox4.Add (this.label3); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.label3])); w4.Position = 0; w4.Expand = false; w4.Fill = false; // Container child vbox4.Gtk.Box+BoxChild this.txtEuros = new global::Gtk.SpinButton (0, 100, 1); this.txtEuros.CanFocus = true; this.txtEuros.Name = "txtEuros"; this.txtEuros.Adjustment.PageIncrement = 10; this.txtEuros.ClimbRate = 1; this.txtEuros.Digits = ((uint)(2)); this.txtEuros.Numeric = true; this.vbox4.Add (this.txtEuros); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.txtEuros])); w5.Position = 1; w5.Expand = false; w5.Fill = false; // Container child vbox4.Gtk.Box+BoxChild this.hbuttonbox1 = new global::Gtk.HButtonBox (); this.hbuttonbox1.Name = "hbuttonbox1"; this.hbuttonbox1.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btnRevertirEuros = new global::Gtk.Button (); this.btnRevertirEuros.Sensitive = false; this.btnRevertirEuros.CanFocus = true; this.btnRevertirEuros.Name = "btnRevertirEuros"; this.btnRevertirEuros.UseStock = true; this.btnRevertirEuros.UseUnderline = true; this.btnRevertirEuros.Label = "gtk-undo"; this.hbuttonbox1.Add (this.btnRevertirEuros); global::Gtk.ButtonBox.ButtonBoxChild w6 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.btnRevertirEuros])); w6.Expand = false; w6.Fill = false; // Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btnActualizarEuro = new global::Gtk.Button (); this.btnActualizarEuro.CanFocus = true; this.btnActualizarEuro.Name = "btnActualizarEuro"; this.btnActualizarEuro.UseStock = true; this.btnActualizarEuro.UseUnderline = true; this.btnActualizarEuro.Label = "gtk-execute"; this.hbuttonbox1.Add (this.btnActualizarEuro); global::Gtk.ButtonBox.ButtonBoxChild w7 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.btnActualizarEuro])); w7.Position = 1; w7.Expand = false; w7.Fill = false; this.vbox4.Add (this.hbuttonbox1); global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.hbuttonbox1])); w8.Position = 2; w8.Expand = false; w8.Fill = false; this.notebook1.Add (this.vbox4); // Notebook tab this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Incremento en euros"); this.notebook1.SetTabLabel (this.vbox4, this.label2); this.label2.ShowAll (); // Container child notebook1.Gtk.Notebook+NotebookChild this.vbox5 = new global::Gtk.VBox (); this.vbox5.Name = "vbox5"; this.vbox5.Spacing = 6; this.vbox5.BorderWidth = ((uint)(48)); // Container child vbox5.Gtk.Box+BoxChild this.label24 = new global::Gtk.Label (); this.label24.Name = "label24"; this.label24.Xalign = 0F; this.label24.LabelProp = global::Mono.Unix.Catalog.GetString ("Porcentaje"); this.vbox5.Add (this.label24); global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.label24])); w10.Position = 0; w10.Expand = false; w10.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.txtPorcentaje = new global::Gtk.SpinButton (0, 100, 1); this.txtPorcentaje.CanFocus = true; this.txtPorcentaje.Name = "txtPorcentaje"; this.txtPorcentaje.Adjustment.PageIncrement = 10; this.txtPorcentaje.ClimbRate = 1; this.txtPorcentaje.Numeric = true; this.vbox5.Add (this.txtPorcentaje); global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.txtPorcentaje])); w11.Position = 1; w11.Expand = false; w11.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.hbuttonbox2 = new global::Gtk.HButtonBox (); this.hbuttonbox2.Name = "hbuttonbox2"; this.hbuttonbox2.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btnRevertirPorc = new global::Gtk.Button (); this.btnRevertirPorc.Sensitive = false; this.btnRevertirPorc.CanFocus = true; this.btnRevertirPorc.Name = "btnRevertirPorc"; this.btnRevertirPorc.UseStock = true; this.btnRevertirPorc.UseUnderline = true; this.btnRevertirPorc.Label = "gtk-undo"; this.hbuttonbox2.Add (this.btnRevertirPorc); global::Gtk.ButtonBox.ButtonBoxChild w12 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2 [this.btnRevertirPorc])); w12.Expand = false; w12.Fill = false; // Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btnActualizarPorc = new global::Gtk.Button (); this.btnActualizarPorc.CanFocus = true; this.btnActualizarPorc.Name = "btnActualizarPorc"; this.btnActualizarPorc.UseStock = true; this.btnActualizarPorc.UseUnderline = true; this.btnActualizarPorc.Label = "gtk-execute"; this.hbuttonbox2.Add (this.btnActualizarPorc); global::Gtk.ButtonBox.ButtonBoxChild w13 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2 [this.btnActualizarPorc])); w13.Position = 1; w13.Expand = false; w13.Fill = false; this.vbox5.Add (this.hbuttonbox2); global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hbuttonbox2])); w14.Position = 2; w14.Expand = false; w14.Fill = false; this.notebook1.Add (this.vbox5); global::Gtk.Notebook.NotebookChild w15 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.vbox5])); w15.Position = 1; // Notebook tab this.label4 = new global::Gtk.Label (); this.label4.Name = "label4"; this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("Porcentaje"); this.notebook1.SetTabLabel (this.vbox5, this.label4); this.label4.ShowAll (); this.vbox3.Add (this.notebook1); global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.notebook1])); w16.Position = 0; this.hbox1.Add (this.vbox3); global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox3])); w17.Position = 1; this.vbox1.Add (this.hbox1); global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbox1])); w18.Position = 0; w18.Expand = false; w18.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.arbolArticulos = new global::Valle.GtkUtilidades.ArbolDeVista (); this.arbolArticulos.Events = ((global::Gdk.EventMask)(256)); this.arbolArticulos.Name = "arbolArticulos"; this.vbox1.Add (this.arbolArticulos); global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.arbolArticulos])); w19.Position = 1; // Container child vbox1.Gtk.Box+BoxChild this.hbuttonbox3 = new global::Gtk.HButtonBox (); this.hbuttonbox3.Name = "hbuttonbox3"; this.hbuttonbox3.BorderWidth = ((uint)(3)); this.hbuttonbox3.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child hbuttonbox3.Gtk.ButtonBox+ButtonBoxChild this.btnAplicarCmb = new global::Gtk.Button (); this.btnAplicarCmb.CanFocus = true; this.btnAplicarCmb.Name = "btnAplicarCmb"; this.btnAplicarCmb.UseStock = true; this.btnAplicarCmb.UseUnderline = true; this.btnAplicarCmb.Label = "gtk-apply"; this.hbuttonbox3.Add (this.btnAplicarCmb); global::Gtk.ButtonBox.ButtonBoxChild w20 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox3 [this.btnAplicarCmb])); w20.Expand = false; w20.Fill = false; this.vbox1.Add (this.hbuttonbox3); global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbuttonbox3])); w21.Position = 2; w21.Expand = false; w21.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.lblInfomacion = new global::Gtk.Label (); this.lblInfomacion.Name = "lblInfomacion"; this.lblInfomacion.Xalign = 0F; this.lblInfomacion.LabelProp = global::Mono.Unix.Catalog.GetString ("label2"); this.vbox1.Add (this.lblInfomacion); global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.lblInfomacion])); w22.Position = 3; w22.Expand = false; w22.Fill = false; this.Add (this.vbox1); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 727; this.DefaultHeight = 571; this.Show (); this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent); this.arbolSeciones.FilaActivada += new global::Gtk.RowActivatedHandler (this.OnArbolSecionesFilaActivada); this.btnRevertirEuros.Clicked += new global::System.EventHandler (this.OnBtnRevertirEurosClicked); this.btnActualizarEuro.Clicked += new global::System.EventHandler (this.OnBtnActualizarEuroClicked); this.btnRevertirPorc.Clicked += new global::System.EventHandler (this.OnBtnRevertirPorcClicked); this.btnActualizarPorc.Clicked += new global::System.EventHandler (this.OnBtnActualizarPorcClicked); this.btnAplicarCmb.Clicked += new global::System.EventHandler (this.OnBtnAplicarCmbClicked); } } }
//--------------------------------------------------------------------- // <copyright file="TypeRestriction.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Data.Common.CommandTrees; using System.Data.Common.CommandTrees.ExpressionBuilder; using System.Data.Common.Utils; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Data.Mapping.ViewGeneration.CqlGeneration; using System.Data.Metadata.Edm; using System.Linq; namespace System.Data.Mapping.ViewGeneration.Structures { using DomainBoolExpr = System.Data.Common.Utils.Boolean.BoolExpr<System.Data.Common.Utils.Boolean.DomainConstraint<BoolLiteral, Constant>>; /// <summary> /// A class that denotes the boolean expression: "varType in values". /// See the comments in <see cref="MemberRestriction"/> for complete and incomplete restriction objects. /// </summary> internal class TypeRestriction : MemberRestriction { #region Constructors /// <summary> /// Creates an incomplete type restriction of the form "<paramref name="member"/> in <paramref name="values"/>". /// </summary> internal TypeRestriction(MemberPath member, IEnumerable<EdmType> values) : base(new MemberProjectedSlot(member), CreateTypeConstants(values)) { } /// <summary> /// Creates an incomplete type restriction of the form "<paramref name="member"/> = <paramref name="value"/>". /// </summary> internal TypeRestriction(MemberPath member, Constant value) : base(new MemberProjectedSlot(member), value) { Debug.Assert(value is TypeConstant || value.IsNull(), "Type or NULL expected."); } /// <summary> /// Creates a complete type restriction of the form "<paramref name="slot"/> in <paramref name="domain"/>". /// </summary> internal TypeRestriction(MemberProjectedSlot slot, Domain domain) : base(slot, domain) { } #endregion #region Methods /// <summary> /// Requires: <see cref="MemberRestriction.IsComplete"/> is true. /// </summary> internal override DomainBoolExpr FixRange(Set<Constant> range, MemberDomainMap memberDomainMap) { Debug.Assert(IsComplete, "Ranges are fixed only for complete type restrictions."); IEnumerable<Constant> possibleValues = memberDomainMap.GetDomain(RestrictedMemberSlot.MemberPath); BoolLiteral newLiteral = new TypeRestriction(RestrictedMemberSlot, new Domain(range, possibleValues)); return newLiteral.GetDomainBoolExpression(memberDomainMap); } internal override BoolLiteral RemapBool(Dictionary<MemberPath, MemberPath> remap) { MemberProjectedSlot newVar = (MemberProjectedSlot)this.RestrictedMemberSlot.RemapSlot(remap); return new TypeRestriction(newVar, this.Domain); } internal override MemberRestriction CreateCompleteMemberRestriction(IEnumerable<Constant> possibleValues) { Debug.Assert(!this.IsComplete, "CreateCompleteMemberRestriction must be called only for incomplete restrictions."); return new TypeRestriction(this.RestrictedMemberSlot, new Domain(this.Domain.Values, possibleValues)); } internal override StringBuilder AsEsql(StringBuilder builder, string blockAlias, bool skipIsNotNull) { // Add Cql of the form "(T.A IS OF (ONLY Person) OR .....)" // Important to enclose all the OR statements in parens. if (this.Domain.Count > 1) { builder.Append('('); } bool isFirst = true; foreach (Constant constant in this.Domain.Values) { TypeConstant typeConstant = constant as TypeConstant; Debug.Assert(typeConstant != null || constant.IsNull(), "Constants for type checks must be type constants or NULLs"); if (isFirst == false) { builder.Append(" OR "); } isFirst = false; if (Helper.IsRefType(this.RestrictedMemberSlot.MemberPath.EdmType)) { builder.Append("Deref("); this.RestrictedMemberSlot.MemberPath.AsEsql(builder, blockAlias); builder.Append(')'); } else { // non-reference type this.RestrictedMemberSlot.MemberPath.AsEsql(builder, blockAlias); } if (constant.IsNull()) { builder.Append(" IS NULL"); } else { // type constant builder.Append(" IS OF (ONLY "); CqlWriter.AppendEscapedTypeName(builder, typeConstant.EdmType); builder.Append(')'); } } if (Domain.Count > 1) { builder.Append(')'); } return builder; } internal override DbExpression AsCqt(DbExpression row, bool skipIsNotNull) { DbExpression cqt = this.RestrictedMemberSlot.MemberPath.AsCqt(row); if (Helper.IsRefType(this.RestrictedMemberSlot.MemberPath.EdmType)) { cqt = cqt.Deref(); } if (this.Domain.Count == 1) { // Single value cqt = cqt.IsOfOnly(TypeUsage.Create(((TypeConstant)this.Domain.Values.Single()).EdmType)); } else { // Multiple values: build list of var IsOnOnly(t1), var = IsOnOnly(t1), ..., then OR them all. List<DbExpression> operands = this.Domain.Values.Select(t => (DbExpression)cqt.IsOfOnly(TypeUsage.Create(((TypeConstant)t).EdmType))).ToList(); cqt = Helpers.BuildBalancedTreeInPlace(operands, (prev, next) => prev.Or(next)); } return cqt; } internal override StringBuilder AsUserString(StringBuilder builder, string blockAlias, bool skipIsNotNull) { // Add user readable string of the form "T.A IS a (Person OR .....)" if (Helper.IsRefType(RestrictedMemberSlot.MemberPath.EdmType)) { builder.Append("Deref("); RestrictedMemberSlot.MemberPath.AsEsql(builder, blockAlias); builder.Append(')'); } else { // non-reference type RestrictedMemberSlot.MemberPath.AsEsql(builder, blockAlias); } if (Domain.Count > 1) { builder.Append(" is a ("); } else { builder.Append(" is type "); } bool isFirst = true; foreach (Constant constant in Domain.Values) { TypeConstant typeConstant = constant as TypeConstant; Debug.Assert(typeConstant != null || constant.IsNull(), "Constants for type checks must be type constants or NULLs"); if (isFirst == false) { builder.Append(" OR "); } if (constant.IsNull()) { builder.Append(" NULL"); } else { CqlWriter.AppendEscapedTypeName(builder, typeConstant.EdmType); } isFirst = false; } if (Domain.Count > 1) { builder.Append(')'); } return builder; } /// <summary> /// Given a list of <paramref name="types"/> (which can contain nulls), returns a corresponding list of <see cref="TypeConstant"/>s for those types. /// </summary> private static IEnumerable<Constant> CreateTypeConstants(IEnumerable<EdmType> types) { foreach (EdmType type in types) { if (type == null) { yield return Constant.Null; } else { yield return new TypeConstant(type); } } } #endregion #region String methods internal override void ToCompactString(StringBuilder builder) { builder.Append("type("); RestrictedMemberSlot.ToCompactString(builder); builder.Append(") IN ("); StringUtil.ToCommaSeparatedStringSorted(builder, Domain.Values); builder.Append(")"); } #endregion } }
namespace BaristaLabs.BaristaCore.JavaScript { using Internal; using System; using System.Runtime.InteropServices; [System.Diagnostics.DebuggerNonUserCode] public abstract class ChakraEngineBase : IJavaScriptEngine { public JavaScriptValueSafeHandle JsCreateEnhancedFunction(JavaScriptEnhancedNativeFunction nativeFunction, JavaScriptValueSafeHandle metadata, IntPtr callbackState) { Errors.ThrowIfError(LibChakraCore.JsCreateEnhancedFunction(nativeFunction, metadata, callbackState, out JavaScriptValueSafeHandle function)); function.NativeFunctionSource = nameof(LibChakraCore.JsCreateEnhancedFunction); if (function != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(function, out uint valueRefCount)); } return function; } public JavaScriptModuleRecord JsInitializeModuleRecord(JavaScriptModuleRecord referencingModule, JavaScriptValueSafeHandle normalizedSpecifier) { Errors.ThrowIfError(LibChakraCore.JsInitializeModuleRecord(referencingModule, normalizedSpecifier, out JavaScriptModuleRecord moduleRecord)); moduleRecord.NativeFunctionSource = nameof(LibChakraCore.JsInitializeModuleRecord); if (moduleRecord != JavaScriptModuleRecord.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(moduleRecord, out uint valueRefCount)); } return moduleRecord; } public JavaScriptValueSafeHandle JsParseModuleSource(JavaScriptModuleRecord requestModule, JavaScriptSourceContext sourceContext, byte[] script, uint scriptLength, JavaScriptParseModuleSourceFlags sourceFlag) { Errors.ThrowIfError(LibChakraCore.JsParseModuleSource(requestModule, sourceContext, script, scriptLength, sourceFlag, out JavaScriptValueSafeHandle exceptionValueRef)); exceptionValueRef.NativeFunctionSource = nameof(LibChakraCore.JsParseModuleSource); if (exceptionValueRef != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(exceptionValueRef, out uint valueRefCount)); } return exceptionValueRef; } public JavaScriptValueSafeHandle JsModuleEvaluation(JavaScriptModuleRecord requestModule) { Errors.ThrowIfError(LibChakraCore.JsModuleEvaluation(requestModule, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsModuleEvaluation); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public void JsSetModuleHostInfo(JavaScriptModuleRecord requestModule, JavaScriptModuleHostInfoKind moduleHostInfo, IntPtr hostInfo) { Errors.ThrowIfError(LibChakraCore.JsSetModuleHostInfo(requestModule, moduleHostInfo, hostInfo)); } public IntPtr JsGetModuleHostInfo(JavaScriptModuleRecord requestModule, JavaScriptModuleHostInfoKind moduleHostInfo) { Errors.ThrowIfError(LibChakraCore.JsGetModuleHostInfo(requestModule, moduleHostInfo, out IntPtr hostInfo)); return hostInfo; } public JavaScriptValueSafeHandle JsGetAndClearExceptionWithMetadata() { Errors.ThrowIfError(LibChakraCore.JsGetAndClearExceptionWithMetadata(out JavaScriptValueSafeHandle metadata)); metadata.NativeFunctionSource = nameof(LibChakraCore.JsGetAndClearExceptionWithMetadata); if (metadata != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(metadata, out uint valueRefCount)); } return metadata; } public JavaScriptValueSafeHandle JsCreateString(string content, ulong length) { Errors.ThrowIfError(LibChakraCore.JsCreateString(content, length, out JavaScriptValueSafeHandle value)); value.NativeFunctionSource = nameof(LibChakraCore.JsCreateString); if (value != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(value, out uint valueRefCount)); } return value; } public JavaScriptValueSafeHandle JsCreateStringUtf16(string content, ulong length) { Errors.ThrowIfError(LibChakraCore.JsCreateStringUtf16(content, length, out JavaScriptValueSafeHandle value)); value.NativeFunctionSource = nameof(LibChakraCore.JsCreateStringUtf16); if (value != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(value, out uint valueRefCount)); } return value; } public ulong JsCopyString(JavaScriptValueSafeHandle value, byte[] buffer, ulong bufferSize) { Errors.ThrowIfError(LibChakraCore.JsCopyString(value, buffer, bufferSize, out ulong length)); return length; } public ulong JsCopyStringUtf16(JavaScriptValueSafeHandle value, int start, int length, byte[] buffer) { Errors.ThrowIfError(LibChakraCore.JsCopyStringUtf16(value, start, length, buffer, out ulong written)); return written; } public JavaScriptValueSafeHandle JsParse(JavaScriptValueSafeHandle script, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl, JavaScriptParseScriptAttributes parseAttributes) { Errors.ThrowIfError(LibChakraCore.JsParse(script, sourceContext, sourceUrl, parseAttributes, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsParse); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsRun(JavaScriptValueSafeHandle script, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl, JavaScriptParseScriptAttributes parseAttributes) { Errors.ThrowIfError(LibChakraCore.JsRun(script, sourceContext, sourceUrl, parseAttributes, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsRun); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptPropertyIdSafeHandle JsCreatePropertyId(string name, ulong length) { Errors.ThrowIfError(LibChakraCore.JsCreatePropertyId(name, length, out JavaScriptPropertyIdSafeHandle propertyId)); propertyId.NativeFunctionSource = nameof(LibChakraCore.JsCreatePropertyId); if (propertyId != JavaScriptPropertyIdSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(propertyId, out uint valueRefCount)); } return propertyId; } public ulong JsCopyPropertyId(JavaScriptPropertyIdSafeHandle propertyId, byte[] buffer, ulong bufferSize) { Errors.ThrowIfError(LibChakraCore.JsCopyPropertyId(propertyId, buffer, bufferSize, out ulong length)); return length; } public JavaScriptValueSafeHandle JsSerialize(JavaScriptValueSafeHandle script, JavaScriptParseScriptAttributes parseAttributes) { Errors.ThrowIfError(LibChakraCore.JsSerialize(script, out JavaScriptValueSafeHandle buffer, parseAttributes)); buffer.NativeFunctionSource = nameof(LibChakraCore.JsSerialize); if (buffer != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(buffer, out uint valueRefCount)); } return buffer; } public JavaScriptValueSafeHandle JsParseSerialized(JavaScriptValueSafeHandle buffer, JavaScriptSerializedLoadScriptCallback scriptLoadCallback, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl) { Errors.ThrowIfError(LibChakraCore.JsParseSerialized(buffer, scriptLoadCallback, sourceContext, sourceUrl, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsParseSerialized); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsRunSerialized(JavaScriptValueSafeHandle buffer, JavaScriptSerializedLoadScriptCallback scriptLoadCallback, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl) { Errors.ThrowIfError(LibChakraCore.JsRunSerialized(buffer, scriptLoadCallback, sourceContext, sourceUrl, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsRunSerialized); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptPromiseState JsGetPromiseState(JavaScriptValueSafeHandle promise) { Errors.ThrowIfError(LibChakraCore.JsGetPromiseState(promise, out JavaScriptPromiseState state)); return state; } public JavaScriptValueSafeHandle JsGetPromiseResult(JavaScriptValueSafeHandle promise) { Errors.ThrowIfError(LibChakraCore.JsGetPromiseResult(promise, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsGetPromiseResult); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsCreatePromise(out JavaScriptValueSafeHandle resolveFunction, out JavaScriptValueSafeHandle rejectFunction) { Errors.ThrowIfError(LibChakraCore.JsCreatePromise(out JavaScriptValueSafeHandle promise, out resolveFunction, out rejectFunction)); promise.NativeFunctionSource = nameof(LibChakraCore.JsCreatePromise); if (promise != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(promise, out uint valueRefCount)); } resolveFunction.NativeFunctionSource = nameof(LibChakraCore.JsCreatePromise); if (resolveFunction != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(resolveFunction, out uint valueRefCount)); } rejectFunction.NativeFunctionSource = nameof(LibChakraCore.JsCreatePromise); if (rejectFunction != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(rejectFunction, out uint valueRefCount)); } return promise; } public JavaScriptWeakReferenceSafeHandle JsCreateWeakReference(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsCreateWeakReference(value, out JavaScriptWeakReferenceSafeHandle weakRef)); return weakRef; } public JavaScriptValueSafeHandle JsGetWeakReferenceValue(JavaScriptWeakReferenceSafeHandle weakRef) { Errors.ThrowIfError(LibChakraCore.JsGetWeakReferenceValue(weakRef, out JavaScriptValueSafeHandle value)); value.NativeFunctionSource = nameof(LibChakraCore.JsGetWeakReferenceValue); if (value != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(value, out uint valueRefCount)); } return value; } public JavaScriptValueSafeHandle JsCreateSharedArrayBufferWithSharedContent(IntPtr sharedContents) { Errors.ThrowIfError(LibChakraCore.JsCreateSharedArrayBufferWithSharedContent(sharedContents, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCreateSharedArrayBufferWithSharedContent); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public IntPtr JsGetSharedArrayBufferContent(JavaScriptValueSafeHandle sharedArrayBuffer) { Errors.ThrowIfError(LibChakraCore.JsGetSharedArrayBufferContent(sharedArrayBuffer, out IntPtr sharedContents)); return sharedContents; } public void JsReleaseSharedArrayBufferContentHandle(IntPtr sharedContents) { Errors.ThrowIfError(LibChakraCore.JsReleaseSharedArrayBufferContentHandle(sharedContents)); } public bool JsHasOwnProperty(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId) { Errors.ThrowIfError(LibChakraCore.JsHasOwnProperty(@object, propertyId, out bool hasOwnProperty)); return hasOwnProperty; } public ulong JsCopyStringOneByte(JavaScriptValueSafeHandle value, int start, int length, byte[] buffer) { Errors.ThrowIfError(LibChakraCore.JsCopyStringOneByte(value, start, length, buffer, out ulong written)); return written; } public JavaScriptValueSafeHandle JsGetDataViewInfo(JavaScriptValueSafeHandle dataView, out uint byteOffset, out uint byteLength) { Errors.ThrowIfError(LibChakraCore.JsGetDataViewInfo(dataView, out JavaScriptValueSafeHandle arrayBuffer, out byteOffset, out byteLength)); arrayBuffer.NativeFunctionSource = nameof(LibChakraCore.JsGetDataViewInfo); if (arrayBuffer != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(arrayBuffer, out uint valueRefCount)); } return arrayBuffer; } public bool JsLessThan(JavaScriptValueSafeHandle object1, JavaScriptValueSafeHandle object2) { Errors.ThrowIfError(LibChakraCore.JsLessThan(object1, object2, out bool result)); return result; } public bool JsLessThanOrEqual(JavaScriptValueSafeHandle object1, JavaScriptValueSafeHandle object2) { Errors.ThrowIfError(LibChakraCore.JsLessThanOrEqual(object1, object2, out bool result)); return result; } public JavaScriptValueSafeHandle JsCreateExternalObjectWithPrototype(IntPtr data, JavaScriptObjectFinalizeCallback finalizeCallback, JavaScriptValueSafeHandle prototype) { Errors.ThrowIfError(LibChakraCore.JsCreateExternalObjectWithPrototype(data, finalizeCallback, prototype, out JavaScriptValueSafeHandle @object)); @object.NativeFunctionSource = nameof(LibChakraCore.JsCreateExternalObjectWithPrototype); if (@object != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(@object, out uint valueRefCount)); } return @object; } public JavaScriptValueSafeHandle JsObjectGetProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key) { Errors.ThrowIfError(LibChakraCore.JsObjectGetProperty(@object, key, out JavaScriptValueSafeHandle value)); value.NativeFunctionSource = nameof(LibChakraCore.JsObjectGetProperty); if (value != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(value, out uint valueRefCount)); } return value; } public void JsObjectSetProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key, JavaScriptValueSafeHandle value, bool useStrictRules) { Errors.ThrowIfError(LibChakraCore.JsObjectSetProperty(@object, key, value, useStrictRules)); } public bool JsObjectHasProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key) { Errors.ThrowIfError(LibChakraCore.JsObjectHasProperty(@object, key, out bool hasProperty)); return hasProperty; } public bool JsObjectDefineProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key, JavaScriptValueSafeHandle propertyDescriptor) { Errors.ThrowIfError(LibChakraCore.JsObjectDefineProperty(@object, key, propertyDescriptor, out bool result)); return result; } public JavaScriptValueSafeHandle JsObjectDeleteProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key, bool useStrictRules) { Errors.ThrowIfError(LibChakraCore.JsObjectDeleteProperty(@object, key, useStrictRules, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsObjectDeleteProperty); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsObjectGetOwnPropertyDescriptor(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key) { Errors.ThrowIfError(LibChakraCore.JsObjectGetOwnPropertyDescriptor(@object, key, out JavaScriptValueSafeHandle propertyDescriptor)); propertyDescriptor.NativeFunctionSource = nameof(LibChakraCore.JsObjectGetOwnPropertyDescriptor); if (propertyDescriptor != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(propertyDescriptor, out uint valueRefCount)); } return propertyDescriptor; } public bool JsObjectHasOwnProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key) { Errors.ThrowIfError(LibChakraCore.JsObjectHasOwnProperty(@object, key, out bool hasOwnProperty)); return hasOwnProperty; } public void JsSetHostPromiseRejectionTracker(JavaScriptPromiseRejectionTrackerCallback promiseRejectionTrackerCallback, IntPtr callbackState) { Errors.ThrowIfError(LibChakraCore.JsSetHostPromiseRejectionTracker(promiseRejectionTrackerCallback, callbackState)); } public JavaScriptValueSafeHandle JsGetModuleNamespace(JavaScriptModuleRecord requestModule) { Errors.ThrowIfError(LibChakraCore.JsGetModuleNamespace(requestModule, out JavaScriptValueSafeHandle moduleNamespace)); moduleNamespace.NativeFunctionSource = nameof(LibChakraCore.JsGetModuleNamespace); if (moduleNamespace != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(moduleNamespace, out uint valueRefCount)); } return moduleNamespace; } public bool JsGetProxyProperties(JavaScriptValueSafeHandle @object, out JavaScriptValueSafeHandle target, out JavaScriptValueSafeHandle handler) { Errors.ThrowIfError(LibChakraCore.JsGetProxyProperties(@object, out bool isProxy, out target, out handler)); target.NativeFunctionSource = nameof(LibChakraCore.JsGetProxyProperties); if (target != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(target, out uint valueRefCount)); } handler.NativeFunctionSource = nameof(LibChakraCore.JsGetProxyProperties); if (handler != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(handler, out uint valueRefCount)); } return isProxy; } public JavaScriptValueSafeHandle JsSerializeParserState(JavaScriptValueSafeHandle scriptVal, JavaScriptParseScriptAttributes parseAttributes) { Errors.ThrowIfError(LibChakraCore.JsSerializeParserState(scriptVal, out JavaScriptValueSafeHandle bufferVal, parseAttributes)); bufferVal.NativeFunctionSource = nameof(LibChakraCore.JsSerializeParserState); if (bufferVal != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(bufferVal, out uint valueRefCount)); } return bufferVal; } public JavaScriptValueSafeHandle JsRunScriptWithParserState(JavaScriptValueSafeHandle script, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl, JavaScriptParseScriptAttributes parseAttributes, JavaScriptValueSafeHandle parserState) { Errors.ThrowIfError(LibChakraCore.JsRunScriptWithParserState(script, sourceContext, sourceUrl, parseAttributes, parserState, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsRunScriptWithParserState); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptRuntimeSafeHandle JsCreateRuntime(JavaScriptRuntimeAttributes attributes, JavaScriptThreadServiceCallback threadService) { Errors.ThrowIfError(LibChakraCore.JsCreateRuntime(attributes, threadService, out JavaScriptRuntimeSafeHandle runtime)); runtime.NativeFunctionSource = nameof(LibChakraCore.JsCreateRuntime); return runtime; } public void JsCollectGarbage(JavaScriptRuntimeSafeHandle runtime) { Errors.ThrowIfError(LibChakraCore.JsCollectGarbage(runtime)); } public void JsDisposeRuntime(IntPtr runtime) { Errors.ThrowIfError(LibChakraCore.JsDisposeRuntime(runtime)); } public ulong JsGetRuntimeMemoryUsage(JavaScriptRuntimeSafeHandle runtime) { Errors.ThrowIfError(LibChakraCore.JsGetRuntimeMemoryUsage(runtime, out ulong memoryUsage)); return memoryUsage; } public ulong JsGetRuntimeMemoryLimit(JavaScriptRuntimeSafeHandle runtime) { Errors.ThrowIfError(LibChakraCore.JsGetRuntimeMemoryLimit(runtime, out ulong memoryLimit)); return memoryLimit; } public void JsSetRuntimeMemoryLimit(JavaScriptRuntimeSafeHandle runtime, ulong memoryLimit) { Errors.ThrowIfError(LibChakraCore.JsSetRuntimeMemoryLimit(runtime, memoryLimit)); } public void JsSetRuntimeMemoryAllocationCallback(JavaScriptRuntimeSafeHandle runtime, IntPtr callbackState, JavaScriptMemoryAllocationCallback allocationCallback) { Errors.ThrowIfError(LibChakraCore.JsSetRuntimeMemoryAllocationCallback(runtime, callbackState, allocationCallback)); } public void JsSetRuntimeBeforeCollectCallback(JavaScriptRuntimeSafeHandle runtime, IntPtr callbackState, JavaScriptBeforeCollectCallback beforeCollectCallback) { Errors.ThrowIfError(LibChakraCore.JsSetRuntimeBeforeCollectCallback(runtime, callbackState, beforeCollectCallback)); } public uint JsAddRef(SafeHandle @ref) { Errors.ThrowIfError(LibChakraCore.JsAddRef(@ref, out uint count)); return count; } public uint JsRelease(SafeHandle @ref) { Errors.ThrowIfError(LibChakraCore.JsRelease(@ref, out uint count)); return count; } public void JsSetObjectBeforeCollectCallback(SafeHandle @ref, IntPtr callbackState, JavaScriptObjectBeforeCollectCallback objectBeforeCollectCallback) { Errors.ThrowIfError(LibChakraCore.JsSetObjectBeforeCollectCallback(@ref, callbackState, objectBeforeCollectCallback)); } public JavaScriptContextSafeHandle JsCreateContext(JavaScriptRuntimeSafeHandle runtime) { Errors.ThrowIfError(LibChakraCore.JsCreateContext(runtime, out JavaScriptContextSafeHandle newContext)); newContext.NativeFunctionSource = nameof(LibChakraCore.JsCreateContext); if (newContext != JavaScriptContextSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(newContext, out uint valueRefCount)); } return newContext; } public JavaScriptContextSafeHandle JsGetCurrentContext() { Errors.ThrowIfError(LibChakraCore.JsGetCurrentContext(out JavaScriptContextSafeHandle currentContext)); currentContext.NativeFunctionSource = nameof(LibChakraCore.JsGetCurrentContext); if (currentContext != JavaScriptContextSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(currentContext, out uint valueRefCount)); } return currentContext; } public void JsSetCurrentContext(JavaScriptContextSafeHandle context) { Errors.ThrowIfError(LibChakraCore.JsSetCurrentContext(context)); } public JavaScriptContextSafeHandle JsGetContextOfObject(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsGetContextOfObject(@object, out JavaScriptContextSafeHandle context)); context.NativeFunctionSource = nameof(LibChakraCore.JsGetContextOfObject); if (context != JavaScriptContextSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(context, out uint valueRefCount)); } return context; } public IntPtr JsGetContextData(JavaScriptContextSafeHandle context) { Errors.ThrowIfError(LibChakraCore.JsGetContextData(context, out IntPtr data)); return data; } public void JsSetContextData(JavaScriptContextSafeHandle context, IntPtr data) { Errors.ThrowIfError(LibChakraCore.JsSetContextData(context, data)); } public JavaScriptRuntimeSafeHandle JsGetRuntime(JavaScriptContextSafeHandle context) { Errors.ThrowIfError(LibChakraCore.JsGetRuntime(context, out JavaScriptRuntimeSafeHandle runtime)); runtime.NativeFunctionSource = nameof(LibChakraCore.JsGetRuntime); return runtime; } public uint JsIdle() { Errors.ThrowIfError(LibChakraCore.JsIdle(out uint nextIdleTick)); return nextIdleTick; } public JavaScriptValueSafeHandle JsGetSymbolFromPropertyId(JavaScriptPropertyIdSafeHandle propertyId) { Errors.ThrowIfError(LibChakraCore.JsGetSymbolFromPropertyId(propertyId, out JavaScriptValueSafeHandle symbol)); symbol.NativeFunctionSource = nameof(LibChakraCore.JsGetSymbolFromPropertyId); if (symbol != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(symbol, out uint valueRefCount)); } return symbol; } public JavaScriptPropertyIdType JsGetPropertyIdType(JavaScriptPropertyIdSafeHandle propertyId) { Errors.ThrowIfError(LibChakraCore.JsGetPropertyIdType(propertyId, out JavaScriptPropertyIdType propertyIdType)); return propertyIdType; } public JavaScriptPropertyIdSafeHandle JsGetPropertyIdFromSymbol(JavaScriptValueSafeHandle symbol) { Errors.ThrowIfError(LibChakraCore.JsGetPropertyIdFromSymbol(symbol, out JavaScriptPropertyIdSafeHandle propertyId)); propertyId.NativeFunctionSource = nameof(LibChakraCore.JsGetPropertyIdFromSymbol); if (propertyId != JavaScriptPropertyIdSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(propertyId, out uint valueRefCount)); } return propertyId; } public JavaScriptValueSafeHandle JsCreateSymbol(JavaScriptValueSafeHandle description) { Errors.ThrowIfError(LibChakraCore.JsCreateSymbol(description, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCreateSymbol); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsGetOwnPropertySymbols(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsGetOwnPropertySymbols(@object, out JavaScriptValueSafeHandle propertySymbols)); propertySymbols.NativeFunctionSource = nameof(LibChakraCore.JsGetOwnPropertySymbols); if (propertySymbols != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(propertySymbols, out uint valueRefCount)); } return propertySymbols; } public JavaScriptValueSafeHandle JsGetUndefinedValue() { Errors.ThrowIfError(LibChakraCore.JsGetUndefinedValue(out JavaScriptValueSafeHandle undefinedValue)); undefinedValue.NativeFunctionSource = nameof(LibChakraCore.JsGetUndefinedValue); if (undefinedValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(undefinedValue, out uint valueRefCount)); } return undefinedValue; } public JavaScriptValueSafeHandle JsGetNullValue() { Errors.ThrowIfError(LibChakraCore.JsGetNullValue(out JavaScriptValueSafeHandle nullValue)); nullValue.NativeFunctionSource = nameof(LibChakraCore.JsGetNullValue); if (nullValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(nullValue, out uint valueRefCount)); } return nullValue; } public JavaScriptValueSafeHandle JsGetTrueValue() { Errors.ThrowIfError(LibChakraCore.JsGetTrueValue(out JavaScriptValueSafeHandle trueValue)); trueValue.NativeFunctionSource = nameof(LibChakraCore.JsGetTrueValue); if (trueValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(trueValue, out uint valueRefCount)); } return trueValue; } public JavaScriptValueSafeHandle JsGetFalseValue() { Errors.ThrowIfError(LibChakraCore.JsGetFalseValue(out JavaScriptValueSafeHandle falseValue)); falseValue.NativeFunctionSource = nameof(LibChakraCore.JsGetFalseValue); if (falseValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(falseValue, out uint valueRefCount)); } return falseValue; } public JavaScriptValueSafeHandle JsBoolToBoolean(bool value) { Errors.ThrowIfError(LibChakraCore.JsBoolToBoolean(value, out JavaScriptValueSafeHandle booleanValue)); booleanValue.NativeFunctionSource = nameof(LibChakraCore.JsBoolToBoolean); if (booleanValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(booleanValue, out uint valueRefCount)); } return booleanValue; } public bool JsBooleanToBool(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsBooleanToBool(value, out bool boolValue)); return boolValue; } public JavaScriptValueSafeHandle JsConvertValueToBoolean(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsConvertValueToBoolean(value, out JavaScriptValueSafeHandle booleanValue)); booleanValue.NativeFunctionSource = nameof(LibChakraCore.JsConvertValueToBoolean); if (booleanValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(booleanValue, out uint valueRefCount)); } return booleanValue; } public JsValueType JsGetValueType(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsGetValueType(value, out JsValueType type)); return type; } public JavaScriptValueSafeHandle JsDoubleToNumber(double doubleValue) { Errors.ThrowIfError(LibChakraCore.JsDoubleToNumber(doubleValue, out JavaScriptValueSafeHandle value)); value.NativeFunctionSource = nameof(LibChakraCore.JsDoubleToNumber); if (value != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(value, out uint valueRefCount)); } return value; } public JavaScriptValueSafeHandle JsIntToNumber(int intValue) { Errors.ThrowIfError(LibChakraCore.JsIntToNumber(intValue, out JavaScriptValueSafeHandle value)); value.NativeFunctionSource = nameof(LibChakraCore.JsIntToNumber); if (value != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(value, out uint valueRefCount)); } return value; } public double JsNumberToDouble(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsNumberToDouble(value, out double doubleValue)); return doubleValue; } public int JsNumberToInt(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsNumberToInt(value, out int intValue)); return intValue; } public JavaScriptValueSafeHandle JsConvertValueToNumber(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsConvertValueToNumber(value, out JavaScriptValueSafeHandle numberValue)); numberValue.NativeFunctionSource = nameof(LibChakraCore.JsConvertValueToNumber); if (numberValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(numberValue, out uint valueRefCount)); } return numberValue; } public int JsGetStringLength(JavaScriptValueSafeHandle stringValue) { Errors.ThrowIfError(LibChakraCore.JsGetStringLength(stringValue, out int length)); return length; } public JavaScriptValueSafeHandle JsConvertValueToString(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsConvertValueToString(value, out JavaScriptValueSafeHandle stringValue)); stringValue.NativeFunctionSource = nameof(LibChakraCore.JsConvertValueToString); if (stringValue != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(stringValue, out uint valueRefCount)); } return stringValue; } public JavaScriptValueSafeHandle JsGetGlobalObject() { Errors.ThrowIfError(LibChakraCore.JsGetGlobalObject(out JavaScriptValueSafeHandle globalObject)); globalObject.NativeFunctionSource = nameof(LibChakraCore.JsGetGlobalObject); if (globalObject != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(globalObject, out uint valueRefCount)); } return globalObject; } public JavaScriptValueSafeHandle JsCreateObject() { Errors.ThrowIfError(LibChakraCore.JsCreateObject(out JavaScriptValueSafeHandle @object)); @object.NativeFunctionSource = nameof(LibChakraCore.JsCreateObject); if (@object != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(@object, out uint valueRefCount)); } return @object; } public JavaScriptValueSafeHandle JsCreateExternalObject(IntPtr data, JavaScriptObjectFinalizeCallback finalizeCallback) { Errors.ThrowIfError(LibChakraCore.JsCreateExternalObject(data, finalizeCallback, out JavaScriptValueSafeHandle @object)); @object.NativeFunctionSource = nameof(LibChakraCore.JsCreateExternalObject); if (@object != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(@object, out uint valueRefCount)); } return @object; } public JavaScriptValueSafeHandle JsConvertValueToObject(JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsConvertValueToObject(value, out JavaScriptValueSafeHandle @object)); @object.NativeFunctionSource = nameof(LibChakraCore.JsConvertValueToObject); if (@object != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(@object, out uint valueRefCount)); } return @object; } public JavaScriptValueSafeHandle JsGetPrototype(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsGetPrototype(@object, out JavaScriptValueSafeHandle prototypeObject)); prototypeObject.NativeFunctionSource = nameof(LibChakraCore.JsGetPrototype); if (prototypeObject != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(prototypeObject, out uint valueRefCount)); } return prototypeObject; } public void JsSetPrototype(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle prototypeObject) { Errors.ThrowIfError(LibChakraCore.JsSetPrototype(@object, prototypeObject)); } public bool JsInstanceOf(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle constructor) { Errors.ThrowIfError(LibChakraCore.JsInstanceOf(@object, constructor, out bool result)); return result; } public bool JsGetExtensionAllowed(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsGetExtensionAllowed(@object, out bool value)); return value; } public void JsPreventExtension(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsPreventExtension(@object)); } public JavaScriptValueSafeHandle JsGetProperty(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId) { Errors.ThrowIfError(LibChakraCore.JsGetProperty(@object, propertyId, out JavaScriptValueSafeHandle value)); value.NativeFunctionSource = nameof(LibChakraCore.JsGetProperty); if (value != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(value, out uint valueRefCount)); } return value; } public JavaScriptValueSafeHandle JsGetOwnPropertyDescriptor(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId) { Errors.ThrowIfError(LibChakraCore.JsGetOwnPropertyDescriptor(@object, propertyId, out JavaScriptValueSafeHandle propertyDescriptor)); propertyDescriptor.NativeFunctionSource = nameof(LibChakraCore.JsGetOwnPropertyDescriptor); if (propertyDescriptor != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(propertyDescriptor, out uint valueRefCount)); } return propertyDescriptor; } public JavaScriptValueSafeHandle JsGetOwnPropertyNames(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsGetOwnPropertyNames(@object, out JavaScriptValueSafeHandle propertyNames)); propertyNames.NativeFunctionSource = nameof(LibChakraCore.JsGetOwnPropertyNames); if (propertyNames != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(propertyNames, out uint valueRefCount)); } return propertyNames; } public void JsSetProperty(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId, JavaScriptValueSafeHandle value, bool useStrictRules) { Errors.ThrowIfError(LibChakraCore.JsSetProperty(@object, propertyId, value, useStrictRules)); } public bool JsHasProperty(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId) { Errors.ThrowIfError(LibChakraCore.JsHasProperty(@object, propertyId, out bool hasProperty)); return hasProperty; } public JavaScriptValueSafeHandle JsDeleteProperty(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId, bool useStrictRules) { Errors.ThrowIfError(LibChakraCore.JsDeleteProperty(@object, propertyId, useStrictRules, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsDeleteProperty); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public bool JsDefineProperty(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId, JavaScriptValueSafeHandle propertyDescriptor) { Errors.ThrowIfError(LibChakraCore.JsDefineProperty(@object, propertyId, propertyDescriptor, out bool result)); return result; } public bool JsHasIndexedProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle index) { Errors.ThrowIfError(LibChakraCore.JsHasIndexedProperty(@object, index, out bool result)); return result; } public JavaScriptValueSafeHandle JsGetIndexedProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle index) { Errors.ThrowIfError(LibChakraCore.JsGetIndexedProperty(@object, index, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsGetIndexedProperty); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public void JsSetIndexedProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle index, JavaScriptValueSafeHandle value) { Errors.ThrowIfError(LibChakraCore.JsSetIndexedProperty(@object, index, value)); } public void JsDeleteIndexedProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle index) { Errors.ThrowIfError(LibChakraCore.JsDeleteIndexedProperty(@object, index)); } public bool JsHasIndexedPropertiesExternalData(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsHasIndexedPropertiesExternalData(@object, out bool value)); return value; } public IntPtr JsGetIndexedPropertiesExternalData(JavaScriptValueSafeHandle @object, out JsTypedArrayType arrayType, out uint elementLength) { Errors.ThrowIfError(LibChakraCore.JsGetIndexedPropertiesExternalData(@object, out IntPtr data, out arrayType, out elementLength)); return data; } public void JsSetIndexedPropertiesToExternalData(JavaScriptValueSafeHandle @object, IntPtr data, JsTypedArrayType arrayType, uint elementLength) { Errors.ThrowIfError(LibChakraCore.JsSetIndexedPropertiesToExternalData(@object, data, arrayType, elementLength)); } public bool JsEquals(JavaScriptValueSafeHandle object1, JavaScriptValueSafeHandle object2) { Errors.ThrowIfError(LibChakraCore.JsEquals(object1, object2, out bool result)); return result; } public bool JsStrictEquals(JavaScriptValueSafeHandle object1, JavaScriptValueSafeHandle object2) { Errors.ThrowIfError(LibChakraCore.JsStrictEquals(object1, object2, out bool result)); return result; } public bool JsHasExternalData(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsHasExternalData(@object, out bool value)); return value; } public IntPtr JsGetExternalData(JavaScriptValueSafeHandle @object) { Errors.ThrowIfError(LibChakraCore.JsGetExternalData(@object, out IntPtr externalData)); return externalData; } public void JsSetExternalData(JavaScriptValueSafeHandle @object, IntPtr externalData) { Errors.ThrowIfError(LibChakraCore.JsSetExternalData(@object, externalData)); } public JavaScriptValueSafeHandle JsCreateArray(uint length) { Errors.ThrowIfError(LibChakraCore.JsCreateArray(length, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCreateArray); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsCreateArrayBuffer(uint byteLength) { Errors.ThrowIfError(LibChakraCore.JsCreateArrayBuffer(byteLength, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCreateArrayBuffer); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsCreateExternalArrayBuffer(IntPtr data, uint byteLength, JavaScriptObjectFinalizeCallback finalizeCallback, IntPtr callbackState) { Errors.ThrowIfError(LibChakraCore.JsCreateExternalArrayBuffer(data, byteLength, finalizeCallback, callbackState, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCreateExternalArrayBuffer); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsCreateTypedArray(JsTypedArrayType arrayType, JavaScriptValueSafeHandle baseArray, uint byteOffset, uint elementLength) { Errors.ThrowIfError(LibChakraCore.JsCreateTypedArray(arrayType, baseArray, byteOffset, elementLength, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCreateTypedArray); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsCreateDataView(JavaScriptValueSafeHandle arrayBuffer, uint byteOffset, uint byteLength) { Errors.ThrowIfError(LibChakraCore.JsCreateDataView(arrayBuffer, byteOffset, byteLength, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCreateDataView); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JsTypedArrayType JsGetTypedArrayInfo(JavaScriptValueSafeHandle typedArray, out JavaScriptValueSafeHandle arrayBuffer, out uint byteOffset, out uint byteLength) { Errors.ThrowIfError(LibChakraCore.JsGetTypedArrayInfo(typedArray, out JsTypedArrayType arrayType, out arrayBuffer, out byteOffset, out byteLength)); arrayBuffer.NativeFunctionSource = nameof(LibChakraCore.JsGetTypedArrayInfo); if (arrayBuffer != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(arrayBuffer, out uint valueRefCount)); } return arrayType; } public IntPtr JsGetArrayBufferStorage(JavaScriptValueSafeHandle arrayBuffer, out uint bufferLength) { Errors.ThrowIfError(LibChakraCore.JsGetArrayBufferStorage(arrayBuffer, out IntPtr buffer, out bufferLength)); return buffer; } public IntPtr JsGetTypedArrayStorage(JavaScriptValueSafeHandle typedArray, out uint bufferLength, out JsTypedArrayType arrayType, out int elementSize) { Errors.ThrowIfError(LibChakraCore.JsGetTypedArrayStorage(typedArray, out IntPtr buffer, out bufferLength, out arrayType, out elementSize)); return buffer; } public IntPtr JsGetDataViewStorage(JavaScriptValueSafeHandle dataView, out uint bufferLength) { Errors.ThrowIfError(LibChakraCore.JsGetDataViewStorage(dataView, out IntPtr buffer, out bufferLength)); return buffer; } public JavaScriptValueSafeHandle JsCallFunction(JavaScriptValueSafeHandle function, IntPtr[] arguments, ushort argumentCount) { Errors.ThrowIfError(LibChakraCore.JsCallFunction(function, arguments, argumentCount, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsCallFunction); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsConstructObject(JavaScriptValueSafeHandle function, IntPtr[] arguments, ushort argumentCount) { Errors.ThrowIfError(LibChakraCore.JsConstructObject(function, arguments, argumentCount, out JavaScriptValueSafeHandle result)); result.NativeFunctionSource = nameof(LibChakraCore.JsConstructObject); if (result != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(result, out uint valueRefCount)); } return result; } public JavaScriptValueSafeHandle JsCreateFunction(JavaScriptNativeFunction nativeFunction, IntPtr callbackState) { Errors.ThrowIfError(LibChakraCore.JsCreateFunction(nativeFunction, callbackState, out JavaScriptValueSafeHandle function)); function.NativeFunctionSource = nameof(LibChakraCore.JsCreateFunction); if (function != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(function, out uint valueRefCount)); } return function; } public JavaScriptValueSafeHandle JsCreateNamedFunction(JavaScriptValueSafeHandle name, JavaScriptNativeFunction nativeFunction, IntPtr callbackState) { Errors.ThrowIfError(LibChakraCore.JsCreateNamedFunction(name, nativeFunction, callbackState, out JavaScriptValueSafeHandle function)); function.NativeFunctionSource = nameof(LibChakraCore.JsCreateNamedFunction); if (function != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(function, out uint valueRefCount)); } return function; } public JavaScriptValueSafeHandle JsCreateError(JavaScriptValueSafeHandle message) { Errors.ThrowIfError(LibChakraCore.JsCreateError(message, out JavaScriptValueSafeHandle error)); error.NativeFunctionSource = nameof(LibChakraCore.JsCreateError); if (error != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(error, out uint valueRefCount)); } return error; } public JavaScriptValueSafeHandle JsCreateRangeError(JavaScriptValueSafeHandle message) { Errors.ThrowIfError(LibChakraCore.JsCreateRangeError(message, out JavaScriptValueSafeHandle error)); error.NativeFunctionSource = nameof(LibChakraCore.JsCreateRangeError); if (error != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(error, out uint valueRefCount)); } return error; } public JavaScriptValueSafeHandle JsCreateReferenceError(JavaScriptValueSafeHandle message) { Errors.ThrowIfError(LibChakraCore.JsCreateReferenceError(message, out JavaScriptValueSafeHandle error)); error.NativeFunctionSource = nameof(LibChakraCore.JsCreateReferenceError); if (error != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(error, out uint valueRefCount)); } return error; } public JavaScriptValueSafeHandle JsCreateSyntaxError(JavaScriptValueSafeHandle message) { Errors.ThrowIfError(LibChakraCore.JsCreateSyntaxError(message, out JavaScriptValueSafeHandle error)); error.NativeFunctionSource = nameof(LibChakraCore.JsCreateSyntaxError); if (error != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(error, out uint valueRefCount)); } return error; } public JavaScriptValueSafeHandle JsCreateTypeError(JavaScriptValueSafeHandle message) { Errors.ThrowIfError(LibChakraCore.JsCreateTypeError(message, out JavaScriptValueSafeHandle error)); error.NativeFunctionSource = nameof(LibChakraCore.JsCreateTypeError); if (error != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(error, out uint valueRefCount)); } return error; } public JavaScriptValueSafeHandle JsCreateURIError(JavaScriptValueSafeHandle message) { Errors.ThrowIfError(LibChakraCore.JsCreateURIError(message, out JavaScriptValueSafeHandle error)); error.NativeFunctionSource = nameof(LibChakraCore.JsCreateURIError); if (error != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(error, out uint valueRefCount)); } return error; } public bool JsHasException() { Errors.ThrowIfError(LibChakraCore.JsHasException(out bool hasException)); return hasException; } public JavaScriptValueSafeHandle JsGetAndClearException() { Errors.ThrowIfError(LibChakraCore.JsGetAndClearException(out JavaScriptValueSafeHandle exception)); exception.NativeFunctionSource = nameof(LibChakraCore.JsGetAndClearException); if (exception != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(exception, out uint valueRefCount)); } return exception; } public void JsSetException(JavaScriptValueSafeHandle exception) { Errors.ThrowIfError(LibChakraCore.JsSetException(exception)); } public void JsDisableRuntimeExecution(JavaScriptRuntimeSafeHandle runtime) { Errors.ThrowIfError(LibChakraCore.JsDisableRuntimeExecution(runtime)); } public void JsEnableRuntimeExecution(JavaScriptRuntimeSafeHandle runtime) { Errors.ThrowIfError(LibChakraCore.JsEnableRuntimeExecution(runtime)); } public bool JsIsRuntimeExecutionDisabled(JavaScriptRuntimeSafeHandle runtime) { Errors.ThrowIfError(LibChakraCore.JsIsRuntimeExecutionDisabled(runtime, out bool isDisabled)); return isDisabled; } public void JsSetPromiseContinuationCallback(JavaScriptPromiseContinuationCallback promiseContinuationCallback, IntPtr callbackState) { Errors.ThrowIfError(LibChakraCore.JsSetPromiseContinuationCallback(promiseContinuationCallback, callbackState)); } public void JsDiagStartDebugging(JavaScriptRuntimeSafeHandle runtimeHandle, JavaScriptDiagDebugEventCallback debugEventCallback, IntPtr callbackState) { Errors.ThrowIfError(LibChakraCore.JsDiagStartDebugging(runtimeHandle, debugEventCallback, callbackState)); } public IntPtr JsDiagStopDebugging(JavaScriptRuntimeSafeHandle runtimeHandle) { Errors.ThrowIfError(LibChakraCore.JsDiagStopDebugging(runtimeHandle, out IntPtr callbackState)); return callbackState; } public void JsDiagRequestAsyncBreak(JavaScriptRuntimeSafeHandle runtimeHandle) { Errors.ThrowIfError(LibChakraCore.JsDiagRequestAsyncBreak(runtimeHandle)); } public JavaScriptValueSafeHandle JsDiagGetBreakpoints() { Errors.ThrowIfError(LibChakraCore.JsDiagGetBreakpoints(out JavaScriptValueSafeHandle breakpoints)); breakpoints.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetBreakpoints); if (breakpoints != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(breakpoints, out uint valueRefCount)); } return breakpoints; } public JavaScriptValueSafeHandle JsDiagSetBreakpoint(uint scriptId, uint lineNumber, uint columnNumber) { Errors.ThrowIfError(LibChakraCore.JsDiagSetBreakpoint(scriptId, lineNumber, columnNumber, out JavaScriptValueSafeHandle breakpoint)); breakpoint.NativeFunctionSource = nameof(LibChakraCore.JsDiagSetBreakpoint); if (breakpoint != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(breakpoint, out uint valueRefCount)); } return breakpoint; } public void JsDiagRemoveBreakpoint(uint breakpointId) { Errors.ThrowIfError(LibChakraCore.JsDiagRemoveBreakpoint(breakpointId)); } public void JsDiagSetBreakOnException(JavaScriptRuntimeSafeHandle runtimeHandle, JavaScriptDiagBreakOnExceptionAttributes exceptionAttributes) { Errors.ThrowIfError(LibChakraCore.JsDiagSetBreakOnException(runtimeHandle, exceptionAttributes)); } public JavaScriptDiagBreakOnExceptionAttributes JsDiagGetBreakOnException(JavaScriptRuntimeSafeHandle runtimeHandle) { Errors.ThrowIfError(LibChakraCore.JsDiagGetBreakOnException(runtimeHandle, out JavaScriptDiagBreakOnExceptionAttributes exceptionAttributes)); return exceptionAttributes; } public void JsDiagSetStepType(JavaScriptDiagStepType stepType) { Errors.ThrowIfError(LibChakraCore.JsDiagSetStepType(stepType)); } public JavaScriptValueSafeHandle JsDiagGetScripts() { Errors.ThrowIfError(LibChakraCore.JsDiagGetScripts(out JavaScriptValueSafeHandle scriptsArray)); scriptsArray.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetScripts); if (scriptsArray != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(scriptsArray, out uint valueRefCount)); } return scriptsArray; } public JavaScriptValueSafeHandle JsDiagGetSource(uint scriptId) { Errors.ThrowIfError(LibChakraCore.JsDiagGetSource(scriptId, out JavaScriptValueSafeHandle source)); source.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetSource); if (source != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(source, out uint valueRefCount)); } return source; } public JavaScriptValueSafeHandle JsDiagGetFunctionPosition(JavaScriptValueSafeHandle function) { Errors.ThrowIfError(LibChakraCore.JsDiagGetFunctionPosition(function, out JavaScriptValueSafeHandle functionPosition)); functionPosition.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetFunctionPosition); if (functionPosition != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(functionPosition, out uint valueRefCount)); } return functionPosition; } public JavaScriptValueSafeHandle JsDiagGetStackTrace() { Errors.ThrowIfError(LibChakraCore.JsDiagGetStackTrace(out JavaScriptValueSafeHandle stackTrace)); stackTrace.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetStackTrace); if (stackTrace != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(stackTrace, out uint valueRefCount)); } return stackTrace; } public JavaScriptValueSafeHandle JsDiagGetStackProperties(uint stackFrameIndex) { Errors.ThrowIfError(LibChakraCore.JsDiagGetStackProperties(stackFrameIndex, out JavaScriptValueSafeHandle properties)); properties.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetStackProperties); if (properties != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(properties, out uint valueRefCount)); } return properties; } public JavaScriptValueSafeHandle JsDiagGetProperties(uint objectHandle, uint fromCount, uint totalCount) { Errors.ThrowIfError(LibChakraCore.JsDiagGetProperties(objectHandle, fromCount, totalCount, out JavaScriptValueSafeHandle propertiesObject)); propertiesObject.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetProperties); if (propertiesObject != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(propertiesObject, out uint valueRefCount)); } return propertiesObject; } public JavaScriptValueSafeHandle JsDiagGetObjectFromHandle(uint objectHandle) { Errors.ThrowIfError(LibChakraCore.JsDiagGetObjectFromHandle(objectHandle, out JavaScriptValueSafeHandle handleObject)); handleObject.NativeFunctionSource = nameof(LibChakraCore.JsDiagGetObjectFromHandle); if (handleObject != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(handleObject, out uint valueRefCount)); } return handleObject; } public JavaScriptValueSafeHandle JsDiagEvaluate(JavaScriptValueSafeHandle expression, uint stackFrameIndex, JavaScriptParseScriptAttributes parseAttributes, bool forceSetValueProp) { Errors.ThrowIfError(LibChakraCore.JsDiagEvaluate(expression, stackFrameIndex, parseAttributes, forceSetValueProp, out JavaScriptValueSafeHandle evalResult)); evalResult.NativeFunctionSource = nameof(LibChakraCore.JsDiagEvaluate); if (evalResult != JavaScriptValueSafeHandle.Invalid) { Errors.ThrowIfError(LibChakraCore.JsAddRef(evalResult, out uint valueRefCount)); } return evalResult; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) Punit Todi // // Copyright (C) 2004 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 Xunit; namespace System.Data.Tests { public class DataRelationCollectionTest : IDisposable { private DataSet _dataset; private DataTable _tblparent, _tblchild; private DataRelation _relation; public DataRelationCollectionTest() { _dataset = new DataSet(); _tblparent = new DataTable("Customer"); _tblchild = new DataTable("Order"); _dataset.Tables.Add(_tblchild); _dataset.Tables.Add(_tblparent); _dataset.Tables.Add("Item"); _dataset.Tables["Customer"].Columns.Add("custid"); _dataset.Tables["Customer"].Columns.Add("custname"); _dataset.Tables["Order"].Columns.Add("oid"); _dataset.Tables["Order"].Columns.Add("custid"); _dataset.Tables["Order"].Columns.Add("itemid"); _dataset.Tables["Order"].Columns.Add("desc"); _dataset.Tables["Item"].Columns.Add("itemid"); _dataset.Tables["Item"].Columns.Add("desc"); } public void Dispose() { _dataset.Relations.Clear(); } [Fact] public void Add() { DataRelationCollection drcol = _dataset.Relations; DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"]; DataColumn childCol = _dataset.Tables["Order"].Columns["custid"]; DataRelation dr = new DataRelation("CustOrder", parentCol, childCol); drcol.Add(dr); Assert.Equal("CustOrder", drcol[0].RelationName); drcol.Clear(); drcol.Add(parentCol, childCol); Assert.Equal(1, drcol.Count); drcol.Clear(); drcol.Add("NewRelation", parentCol, childCol); Assert.Equal("NewRelation", drcol[0].RelationName); drcol.Clear(); drcol.Add("NewRelation", parentCol, childCol, false); Assert.Equal(1, drcol.Count); drcol.Clear(); drcol.Add("NewRelation", parentCol, childCol, true); Assert.Equal(1, drcol.Count); drcol.Clear(); } [Fact] public void AddException2() { AssertExtensions.Throws<ArgumentException>(null, () => { DataRelationCollection drcol = _dataset.Relations; DataRelation dr1 = new DataRelation("CustOrder" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.Add(dr1); drcol.Add(dr1); }); } [Fact] public void AddException3() { Assert.Throws<DuplicateNameException>(() => { DataRelationCollection drcol = _dataset.Relations; DataRelation dr1 = new DataRelation("DuplicateName" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); DataRelation dr2 = new DataRelation("DuplicateName" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.Add(dr1); drcol.Add(dr2); }); } [Fact] public void AddRange() { DataRelationCollection drcol = _dataset.Relations; DataRelation dr1 = new DataRelation("CustOrder" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); DataRelation dr2 = new DataRelation("ItemOrder" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.AddRange(new DataRelation[] { dr1, dr2 }); Assert.Equal("CustOrder", drcol[0].RelationName); Assert.Equal("ItemOrder", drcol[1].RelationName); } [Fact] public void CanRemove() { DataRelationCollection drcol = _dataset.Relations; DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"]; DataColumn childCol = _dataset.Tables["Order"].Columns["custid"]; DataRelation dr = new DataRelation("CustOrder", parentCol, childCol); drcol.Add(dr); Assert.True(drcol.CanRemove(dr)); Assert.False(drcol.CanRemove(null)); DataRelation dr2 = new DataRelation("ItemOrder" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); Assert.False(drcol.CanRemove(dr2)); } [Fact] public void Clear() { DataRelationCollection drcol = _dataset.Relations; DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"]; DataColumn childCol = _dataset.Tables["Order"].Columns["custid"]; drcol.Add(new DataRelation("CustOrder", parentCol, childCol)); drcol.Add("ItemOrder", _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["itemid"]); drcol.Clear(); Assert.Equal(0, drcol.Count); } [Fact] public void Contains() { DataRelationCollection drcol = _dataset.Relations; DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"]; DataColumn childCol = _dataset.Tables["Order"].Columns["custid"]; DataRelation dr = new DataRelation("CustOrder", parentCol, childCol); drcol.Add(dr); Assert.True(drcol.Contains(dr.RelationName)); string drnull = ""; Assert.False(drcol.Contains(drnull)); dr = new DataRelation("newRelation", childCol, parentCol); Assert.False(drcol.Contains("NoSuchRelation")); } [Fact] public void CopyTo() { DataRelationCollection drcol = _dataset.Relations; drcol.Add("CustOrder" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.Add("ItemOrder" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); DataRelation[] array = new DataRelation[2]; drcol.CopyTo(array, 0); Assert.Equal(2, array.Length); Assert.Equal("CustOrder", array[0].RelationName); Assert.Equal("ItemOrder", array[1].RelationName); DataRelation[] array1 = new DataRelation[4]; drcol.CopyTo(array1, 2); Assert.Null(array1[0]); Assert.Null(array1[1]); Assert.Equal("CustOrder", array1[2].RelationName); Assert.Equal("ItemOrder", array1[3].RelationName); } [Fact] public void Equals() { DataRelationCollection drcol = _dataset.Relations; drcol.Add("CustOrder" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.Add("ItemOrder" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); DataSet newds = new DataSet(); DataRelationCollection drcol1 = newds.Relations; DataRelationCollection drcol2 = _dataset.Relations; Assert.True(drcol.Equals(drcol)); Assert.True(drcol.Equals(drcol2)); Assert.False(drcol1.Equals(drcol)); Assert.False(drcol.Equals(drcol1)); Assert.True(object.Equals(drcol, drcol2)); Assert.False(object.Equals(drcol, drcol1)); } [Fact] public void IndexOf() { DataRelationCollection drcol = _dataset.Relations; DataRelation dr1 = new DataRelation("CustOrder" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); DataRelation dr2 = new DataRelation("ItemOrder" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.Add(dr1); drcol.Add(dr2); Assert.Equal(0, drcol.IndexOf(dr1)); Assert.Equal(1, drcol.IndexOf(dr2)); Assert.Equal(0, drcol.IndexOf("CustOrder")); Assert.Equal(1, drcol.IndexOf("ItemOrder")); Assert.Equal(0, drcol.IndexOf(drcol[0])); Assert.Equal(1, drcol.IndexOf(drcol[1])); Assert.Equal(-1, drcol.IndexOf("_noRelation_")); DataRelation newdr = new DataRelation("newdr" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); Assert.Equal(-1, drcol.IndexOf(newdr)); } [Fact] public void Remove() { DataRelationCollection drcol = _dataset.Relations; DataRelation dr1 = new DataRelation("CustOrder" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); DataRelation dr2 = new DataRelation("ItemOrder" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.Add(dr1); drcol.Add(dr2); drcol.Remove(dr1); Assert.False(drcol.Contains(dr1.RelationName)); drcol.Add(dr1); drcol.Remove("CustOrder"); Assert.False(drcol.Contains("CustOrder")); drcol.Add(dr1); DataRelation drnull = null; drcol.Remove(drnull); DataRelation newdr = new DataRelation("newdr" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); AssertExtensions.Throws<ArgumentException>(null, () => drcol.Remove(newdr)); } [Fact] public void RemoveAt() { DataRelationCollection drcol = _dataset.Relations; DataRelation dr1 = new DataRelation("CustOrder" , _dataset.Tables["Customer"].Columns["custid"] , _dataset.Tables["Order"].Columns["custid"]); DataRelation dr2 = new DataRelation("ItemOrder" , _dataset.Tables["Item"].Columns["itemid"] , _dataset.Tables["Order"].Columns["custid"]); drcol.Add(dr1); drcol.Add(dr2); try { drcol.RemoveAt(-1); Assert.False(true); } catch (IndexOutOfRangeException e) { } try { drcol.RemoveAt(101); Assert.False(true); } catch (IndexOutOfRangeException e) { } drcol.RemoveAt(1); Assert.False(drcol.Contains(dr2.RelationName)); drcol.RemoveAt(0); Assert.False(drcol.Contains(dr1.RelationName)); } } }
#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.Text; using System.IO; using System.Xml; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public class JsonTextReader : JsonReader, IJsonLineInfo { private enum ReadType { Read, ReadAsBytes, ReadAsDecimal, #if !NET20 ReadAsDateTimeOffset #endif } private readonly TextReader _reader; private readonly StringBuffer _buffer; private char? _lastChar; private int _currentLinePosition; private int _currentLineNumber; private bool _end; private ReadType _readType; /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param> public JsonTextReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; _buffer = new StringBuffer(4096); _currentLineNumber = 1; } private void ParseString(char quote) { ReadStringIntoBuffer(quote); if (_readType == ReadType.ReadAsBytes) { byte[] data; if (_buffer.Position == 0) { data = new byte[0]; } else { data = Convert.FromBase64CharArray(_buffer.GetInternalBuffer(), 0, _buffer.Position); _buffer.Position = 0; } SetToken(JsonToken.Bytes, data); } else { string text = _buffer.ToString(); _buffer.Position = 0; if (text.StartsWith("/Date(", StringComparison.Ordinal) && text.EndsWith(")/", StringComparison.Ordinal)) { ParseDate(text); } else { SetToken(JsonToken.String, text); QuoteChar = quote; } } } private void ReadStringIntoBuffer(char quote) { while (true) { char currentChar = MoveNext(); switch (currentChar) { case '\0': if (_end) throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition); _buffer.Append('\0'); break; case '\\': if ((currentChar = MoveNext()) != '\0' || !_end) { switch (currentChar) { case 'b': _buffer.Append('\b'); break; case 't': _buffer.Append('\t'); break; case 'n': _buffer.Append('\n'); break; case 'f': _buffer.Append('\f'); break; case 'r': _buffer.Append('\r'); break; case '\\': _buffer.Append('\\'); break; case '"': case '\'': case '/': _buffer.Append(currentChar); break; case 'u': char[] hexValues = new char[4]; for (int i = 0; i < hexValues.Length; i++) { if ((currentChar = MoveNext()) != '\0' || !_end) hexValues[i] = currentChar; else throw CreateJsonReaderException("Unexpected end while parsing unicode character. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } char hexChar = Convert.ToChar(int.Parse(new string(hexValues), NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo)); _buffer.Append(hexChar); break; default: throw CreateJsonReaderException("Bad JSON escape sequence: {0}. Line {1}, position {2}.", @"\" + currentChar, _currentLineNumber, _currentLinePosition); } } else { throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition); } break; case '"': case '\'': if (currentChar == quote) { return; } else { _buffer.Append(currentChar); } break; default: _buffer.Append(currentChar); break; } } } private JsonReaderException CreateJsonReaderException(string format, params object[] args) { string message = format.FormatWith(CultureInfo.InvariantCulture, args); return new JsonReaderException(message, null, _currentLineNumber, _currentLinePosition); } private TimeSpan ReadOffset(string offsetText) { bool negative = (offsetText[0] == '-'); int hours = int.Parse(offsetText.Substring(1, 2), NumberStyles.Integer, CultureInfo.InvariantCulture); int minutes = 0; if (offsetText.Length >= 5) minutes = int.Parse(offsetText.Substring(3, 2), NumberStyles.Integer, CultureInfo.InvariantCulture); TimeSpan offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes); if (negative) offset = offset.Negate(); return offset; } private void ParseDate(string text) { string value = text.Substring(6, text.Length - 8); DateTimeKind kind = DateTimeKind.Utc; int index = value.IndexOf('+', 1); if (index == -1) index = value.IndexOf('-', 1); TimeSpan offset = TimeSpan.Zero; if (index != -1) { kind = DateTimeKind.Local; offset = ReadOffset(value.Substring(index)); value = value.Substring(0, index); } long javaScriptTicks = long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture); DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks); #if !NET20 if (_readType == ReadType.ReadAsDateTimeOffset) { SetToken(JsonToken.Date, new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset)); } else #endif { DateTime dateTime; switch (kind) { case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified); break; case DateTimeKind.Local: dateTime = utcDateTime.ToLocalTime(); break; default: dateTime = utcDateTime; break; } SetToken(JsonToken.Date, dateTime); } } private const int LineFeedValue = StringUtils.LineFeed; private const int CarriageReturnValue = StringUtils.CarriageReturn; private char MoveNext() { int value = _reader.Read(); switch (value) { case -1: _end = true; return '\0'; case CarriageReturnValue: if (_reader.Peek() == LineFeedValue) _reader.Read(); _currentLineNumber++; _currentLinePosition = 0; break; case LineFeedValue: _currentLineNumber++; _currentLinePosition = 0; break; default: _currentLinePosition++; break; } return (char)value; } private bool HasNext() { return (_reader.Peek() != -1); } private int PeekNext() { return _reader.Peek(); } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> public override bool Read() { _readType = ReadType.Read; return ReadInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns> /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. /// </returns> public override byte[] ReadAsBytes() { _readType = ReadType.ReadAsBytes; if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Bytes) return (byte[]) Value; throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>.</returns> public override decimal? ReadAsDecimal() { _readType = ReadType.ReadAsDecimal; if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading decimal: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Float) return (decimal?)Value; throw CreateJsonReaderException("Unexpected token when reading decimal: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="DateTimeOffset"/>.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { _readType = ReadType.ReadAsDateTimeOffset; if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading date: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Date) return (DateTimeOffset)Value; throw CreateJsonReaderException("Unexpected token when reading date: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } #endif private bool ReadInternal() { while (true) { char currentChar; if (_lastChar != null) { currentChar = _lastChar.Value; _lastChar = null; } else { currentChar = MoveNext(); } if (currentChar == '\0' && _end) return false; switch (CurrentState) { case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: return ParseValue(currentChar); case State.Complete: break; case State.Object: case State.ObjectStart: return ParseObject(currentChar); case State.PostValue: // returns true if it hits // end of object or array if (ParsePostValue(currentChar)) return true; break; case State.Closed: break; case State.Error: break; default: throw CreateJsonReaderException("Unexpected state: {0}. Line {1}, position {2}.", CurrentState, _currentLineNumber, _currentLinePosition); } } } private bool ParsePostValue(char currentChar) { do { switch (currentChar) { case '}': SetToken(JsonToken.EndObject); return true; case ']': SetToken(JsonToken.EndArray); return true; case ')': SetToken(JsonToken.EndConstructor); return true; case '/': ParseComment(); return true; case ',': // finished parsing SetStateBasedOnCurrent(); return false; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else { throw CreateJsonReaderException("After parsing a value an unexpected character was encountered: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool ParseObject(char currentChar) { do { switch (currentChar) { case '}': SetToken(JsonToken.EndObject); return true; case '/': ParseComment(); return true; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else { return ParseProperty(currentChar); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool ParseProperty(char firstChar) { char currentChar = firstChar; char quoteChar; if (ValidIdentifierChar(currentChar)) { quoteChar = '\0'; currentChar = ParseUnquotedProperty(currentChar); } else if (currentChar == '"' || currentChar == '\'') { quoteChar = currentChar; ReadStringIntoBuffer(quoteChar); currentChar = MoveNext(); } else { throw CreateJsonReaderException("Invalid property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } if (currentChar != ':') { currentChar = MoveNext(); // finished property. skip any whitespace and move to colon EatWhitespace(currentChar, false, out currentChar); if (currentChar != ':') throw CreateJsonReaderException("Invalid character after parsing property name. Expected ':' but got: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } SetToken(JsonToken.PropertyName, _buffer.ToString()); QuoteChar = quoteChar; _buffer.Position = 0; return true; } private bool ValidIdentifierChar(char value) { return (char.IsLetterOrDigit(value) || value == '_' || value == '$'); } private char ParseUnquotedProperty(char firstChar) { // parse unquoted property name until whitespace or colon _buffer.Append(firstChar); char currentChar; while ((currentChar = MoveNext()) != '\0' || !_end) { if (char.IsWhiteSpace(currentChar) || currentChar == ':') { return currentChar; } else if (ValidIdentifierChar(currentChar)) { _buffer.Append(currentChar); } else { throw CreateJsonReaderException("Invalid JavaScript property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } } throw CreateJsonReaderException("Unexpected end when parsing unquoted property name. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } private bool ParseValue(char currentChar) { do { switch (currentChar) { case '"': case '\'': ParseString(currentChar); return true; case 't': ParseTrue(); return true; case 'f': ParseFalse(); return true; case 'n': if (HasNext()) { char next = (char)PeekNext(); if (next == 'u') ParseNull(); else if (next == 'e') ParseConstructor(); else throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } else { throw CreateJsonReaderException("Unexpected end. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } return true; case 'N': ParseNumberNaN(); return true; case 'I': ParseNumberPositiveInfinity(); return true; case '-': if (PeekNext() == 'I') ParseNumberNegativeInfinity(); else ParseNumber(currentChar); return true; case '/': ParseComment(); return true; case 'u': ParseUndefined(); return true; case '{': SetToken(JsonToken.StartObject); return true; case '[': SetToken(JsonToken.StartArray); return true; case '}': SetToken(JsonToken.EndObject); return true; case ']': SetToken(JsonToken.EndArray); return true; case ',': SetToken(JsonToken.Undefined); return true; case ')': SetToken(JsonToken.EndConstructor); return true; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') { ParseNumber(currentChar); return true; } else { throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool EatWhitespace(char initialChar, bool oneOrMore, out char finalChar) { bool whitespace = false; char currentChar = initialChar; while (currentChar == ' ' || char.IsWhiteSpace(currentChar)) { whitespace = true; currentChar = MoveNext(); } finalChar = currentChar; return (!oneOrMore || whitespace); } private void ParseConstructor() { if (MatchValue('n', "new", true)) { char currentChar = MoveNext(); if (EatWhitespace(currentChar, true, out currentChar)) { while (char.IsLetter(currentChar)) { _buffer.Append(currentChar); currentChar = MoveNext(); } EatWhitespace(currentChar, false, out currentChar); if (currentChar != '(') throw CreateJsonReaderException("Unexpected character while parsing constructor: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); string constructorName = _buffer.ToString(); _buffer.Position = 0; SetToken(JsonToken.StartConstructor, constructorName); } } } private void ParseNumber(char firstChar) { char currentChar = firstChar; // parse until seperator character or end bool end = false; do { if (IsSeperator(currentChar)) { end = true; _lastChar = currentChar; } else { _buffer.Append(currentChar); } } while (!end && ((currentChar = MoveNext()) != '\0' || !_end)); string number = _buffer.ToString(); object numberValue; JsonToken numberType; bool nonBase10 = (firstChar == '0' && !number.StartsWith("0.", StringComparison.OrdinalIgnoreCase)); if (_readType == ReadType.ReadAsDecimal) { if (nonBase10) { // decimal.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberValue = Convert.ToDecimal(integer); } else { numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); } numberType = JsonToken.Float; } else { if (nonBase10) { numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberType = JsonToken.Integer; } else if (number.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || number.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) { numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture); numberType = JsonToken.Float; } else { try { numberValue = Convert.ToInt64(number, CultureInfo.InvariantCulture); } catch (OverflowException ex) { throw new JsonReaderException("JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex); } numberType = JsonToken.Integer; } } _buffer.Position = 0; SetToken(numberType, numberValue); } private void ParseComment() { // should have already parsed / character before reaching this method char currentChar = MoveNext(); if (currentChar == '*') { while ((currentChar = MoveNext()) != '\0' || !_end) { if (currentChar == '*') { if ((currentChar = MoveNext()) != '\0' || !_end) { if (currentChar == '/') { break; } else { _buffer.Append('*'); _buffer.Append(currentChar); } } } else { _buffer.Append(currentChar); } } } else { throw CreateJsonReaderException("Error parsing comment. Expected: *. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } SetToken(JsonToken.Comment, _buffer.ToString()); _buffer.Position = 0; } private bool MatchValue(char firstChar, string value) { char currentChar = firstChar; int i = 0; do { if (currentChar != value[i]) { break; } i++; } while (i < value.Length && ((currentChar = MoveNext()) != '\0' || !_end)); return (i == value.Length); } private bool MatchValue(char firstChar, string value, bool noTrailingNonSeperatorCharacters) { // will match value and then move to the next character, checking that it is a seperator character bool match = MatchValue(firstChar, value); if (!noTrailingNonSeperatorCharacters) { return match; } else { int c = PeekNext(); char next = (c != -1) ? (char) c : '\0'; bool matchAndNoTrainingNonSeperatorCharacters = (match && (next == '\0' || IsSeperator(next))); return matchAndNoTrainingNonSeperatorCharacters; } } private bool IsSeperator(char c) { switch (c) { case '}': case ']': case ',': return true; case '/': // check next character to see if start of a comment return (HasNext() && PeekNext() == '*'); case ')': if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart) return true; break; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: return true; default: if (char.IsWhiteSpace(c)) return true; break; } return false; } private void ParseTrue() { // check characters equal 'true' // and that it is followed by either a seperator character // or the text ends if (MatchValue('t', JsonConvert.True, true)) { SetToken(JsonToken.Boolean, true); } else { throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNull() { if (MatchValue('n', JsonConvert.Null, true)) { SetToken(JsonToken.Null); } else { throw CreateJsonReaderException("Error parsing null value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseUndefined() { if (MatchValue('u', JsonConvert.Undefined, true)) { SetToken(JsonToken.Undefined); } else { throw CreateJsonReaderException("Error parsing undefined value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseFalse() { if (MatchValue('f', JsonConvert.False, true)) { SetToken(JsonToken.Boolean, false); } else { throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberNegativeInfinity() { if (MatchValue('-', JsonConvert.NegativeInfinity, true)) { SetToken(JsonToken.Float, double.NegativeInfinity); } else { throw CreateJsonReaderException("Error parsing negative infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberPositiveInfinity() { if (MatchValue('I', JsonConvert.PositiveInfinity, true)) { SetToken(JsonToken.Float, double.PositiveInfinity); } else { throw CreateJsonReaderException("Error parsing positive infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberNaN() { if (MatchValue('N', JsonConvert.NaN, true)) { SetToken(JsonToken.Float, double.NaN); } else { throw CreateJsonReaderException("Error parsing NaN value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } /// <summary> /// Changes the state to closed. /// </summary> public override void Close() { base.Close(); if (_reader != null) _reader.Close(); if (_buffer != null) _buffer.Clear(); } /// <summary> /// Gets a value indicating whether the class can return line information. /// </summary> /// <returns> /// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>. /// </returns> public bool HasLineInfo() { return true; } /// <summary> /// Gets the current line number. /// </summary> /// <value> /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LineNumber { get { if (CurrentState == State.Start) return 0; return _currentLineNumber; } } /// <summary> /// Gets the current line position. /// </summary> /// <value> /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LinePosition { get { return _currentLinePosition; } } } }