context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO; namespace l2pvp { public partial class Skills : Form { Client c; GameServer gs; public Skills(Client _c, GameServer _gs) { InitializeComponent(); c = _c; gs = _gs; condition.Items.Add("Always"); condition.Items.Add("HP"); condition.Items.Add("Distance"); condition.Items.Add("Once"); compare.Items.Add("="); compare.Items.Add(">"); compare.Items.Add("<"); condition.SelectedIndex = 0; compare.SelectedIndex = 0; value.Text = "0"; //skill s = new skill(); //s.name = "fuck"; //s.id = 12203; //skill s1 = new skill(); //s1.name = "suck"; //s1.id = 12205; //skill s2 = new skill(); //s2.name = "duck"; //s2.id = 12204; //sl.Items.Add(s1); //sl.Items.Add(s2); //sl.Items.Add(s); } public void populateskilllist_d(List<skill> skilllist) { if (this.InvokeRequired) Invoke(new poplist(populateskilllist), new object[] { skilllist }); else populateskilllist(skilllist); } public delegate void poplist(List<skill> skilllist); public void populateskilllist(List<skill> skilllist) { sl.Items.Clear(); foreach (skill i in skilllist) { sl.Items.Add(i); } } private void Skills_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { //add to listview AttackSkills askill = new AttackSkills(); askill.comparison = compare.SelectedIndex; askill.condition = condition.SelectedIndex; int index = sl.SelectedIndex; if (index != -1) { string skillname = sl.Items[sl.SelectedIndex].ToString(); uint skillid = ((skill)sl.Items[sl.SelectedIndex]).id; foreach (skill s in c.skilllist) { if (s.id == skillid) { askill.useskill = s; } } } else return; try { askill.value = Convert.ToInt32(value.Text); } catch { askill.value = 0; } ListViewItem item = new ListViewItem(askill.useskill.name); item.SubItems.Add(condition.Items[askill.condition].ToString()); item.SubItems.Add(compare.Items[askill.comparison].ToString()); item.SubItems.Add(askill.value.ToString()); item.Tag = askill; listView1.Items.Add(item); } private void button3_Click(object sender, EventArgs e) { lock (c.aslock) { c.askills.Clear(); foreach (ListViewItem item in listView1.Items) { c.askills.Add((AttackSkills)item.Tag); } } this.Hide(); } private void button4_Click(object sender, EventArgs e) { this.Hide(); } private void button2_Click(object sender, EventArgs e) { ListView.SelectedListViewItemCollection ic = listView1.SelectedItems; foreach (ListViewItem i in ic) { listView1.Items.Remove(i); } } private void button5_Click(object sender, EventArgs e) { string fname = textBox2.Text; fname = "skills-" + fname; loadConfig(fname); } public void loadConfig(string fname) { StreamReader readfile; try { readfile = new StreamReader(new FileStream(fname, FileMode.Open), Encoding.UTF8); if (readfile == null) return; } catch { MessageBox.Show("couldn't open file {0} for reading", fname); return; } string line; int count; line = readfile.ReadLine(); try { count = Convert.ToInt32(line); } catch { count = 0; } listView1.Items.Clear(); for (int i = 0; i < count; i++) { try { line = readfile.ReadLine(); string[] items = line.Split(','); AttackSkills askill = new AttackSkills(); uint skillid = Convert.ToUInt32(items[0]); foreach (skill s in c.skilllist) { if (s.id == skillid) { askill.useskill = s; } } askill.condition = Convert.ToInt32(items[1]); askill.comparison = Convert.ToInt32(items[2]); askill.value = Convert.ToInt32(items[3]); ListViewItem item = new ListViewItem(askill.useskill.name); item.SubItems.Add(condition.Items[askill.condition].ToString()); item.SubItems.Add(compare.Items[askill.comparison].ToString()); item.SubItems.Add(askill.value.ToString()); item.Tag = askill; listView1.Items.Add(item); } catch { } } readfile.Close(); lock (c.aslock) { c.askills.Clear(); foreach (ListViewItem item in listView1.Items) { c.askills.Add((AttackSkills)item.Tag); } } } private void button6_Click(object sender, EventArgs e) { //file format //Count //<skill id> <condition id> <comparison id> <value> string fname = textBox2.Text; fname = "skills-" + fname; saveConfig(fname); } public void saveConfig(string fname) { StreamWriter writefile = new StreamWriter(new FileStream(fname, FileMode.Create), Encoding.UTF8); int count = listView1.Items.Count; writefile.WriteLine(count.ToString()); foreach (ListViewItem i in listView1.Items) { AttackSkills a = (AttackSkills)i.Tag; writefile.WriteLine("{0},{1},{2},{3}", a.useskill.id, a.condition, a.comparison, a.value); } writefile.Flush(); writefile.Close(); } public void loadconfig_d(string fname) { if (this.InvokeRequired) Invoke(new loadconfig(loadConfig), new object[] { fname }); else loadConfig(fname); } public delegate void loadconfig(string fname); } }
using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Codecs.Pulsing { /* * 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. */ // TODO: we now inline based on total TF of the term, // but it might be better to inline by "net bytes used" // so that a term that has only 1 posting but a huge // payload would not be inlined. Though this is // presumably rare in practice... /// <summary> /// Writer for the pulsing format. /// <para/> /// Wraps another postings implementation and decides /// (based on total number of occurrences), whether a terms /// postings should be inlined into the term dictionary, /// or passed through to the wrapped writer. /// <para/> /// @lucene.experimental /// </summary> public sealed class PulsingPostingsWriter : PostingsWriterBase { internal static readonly string CODEC = "PulsedPostingsWriter"; internal static readonly string SUMMARY_EXTENSION = "smy"; // recording field summary // To add a new version, increment from the last one, and // change VERSION_CURRENT to point to your new version: internal static readonly int VERSION_START = 0; internal static readonly int VERSION_META_ARRAY = 1; internal static readonly int VERSION_CURRENT = VERSION_META_ARRAY; private readonly SegmentWriteState _segmentState; private IndexOutput _termsOut; private readonly List<FieldMetaData> _fields; private IndexOptions _indexOptions; private bool _storePayloads; // information for wrapped PF, in current field private int _longsSize; private long[] _longs; private bool _absolute; private class PulsingTermState : BlockTermState { internal byte[] bytes; internal BlockTermState wrappedState; public override string ToString() { if (bytes != null) { return "inlined"; } return "not inlined wrapped=" + wrappedState; } } // one entry per position private readonly Position[] _pending; private int _pendingCount = 0; // -1 once we've hit too many positions private Position _currentDoc; // first Position entry of current doc private sealed class Position { internal BytesRef payload; internal int termFreq; // only incremented on first position for a given doc internal int pos; internal int docID; internal int startOffset; internal int endOffset; } private class FieldMetaData { internal int FieldNumber { get; private set; } /// <summary> /// NOTE: This was longsSize (field) in Lucene. /// </summary> internal int Int64sSize { get; private set; } public FieldMetaData(int number, int size) { FieldNumber = number; Int64sSize = size; } } // TODO: -- lazy init this? ie, if every single term // was inlined (eg for a "primary key" field) then we // never need to use this fallback? Fallback writer for // non-inlined terms: private readonly PostingsWriterBase _wrappedPostingsWriter; /// <summary> /// If the total number of positions (summed across all docs /// for this term) is less than or equal <paramref name="maxPositions"/>, then the postings are /// inlined into terms dict. /// </summary> public PulsingPostingsWriter(SegmentWriteState state, int maxPositions, PostingsWriterBase wrappedPostingsWriter) { _pending = new Position[maxPositions]; for (var i = 0; i < maxPositions; i++) { _pending[i] = new Position(); } _fields = new List<FieldMetaData>(); // We simply wrap another postings writer, but only call // on it when tot positions is >= the cutoff: _wrappedPostingsWriter = wrappedPostingsWriter; _segmentState = state; } public override void Init(IndexOutput termsOut) { _termsOut = termsOut; CodecUtil.WriteHeader(termsOut, CODEC, VERSION_CURRENT); termsOut.WriteVInt32(_pending.Length); // encode maxPositions in header _wrappedPostingsWriter.Init(termsOut); } public override BlockTermState NewTermState() { var state = new PulsingTermState { wrappedState = _wrappedPostingsWriter.NewTermState() }; return state; } public override void StartTerm() { if (Debugging.AssertsEnabled) Debugging.Assert(_pendingCount == 0); } // TODO: -- should we NOT reuse across fields? would // be cleaner /// <summary> /// Currently, this instance is re-used across fields, so /// our parent calls setField whenever the field changes. /// </summary> public override int SetField(FieldInfo fieldInfo) { _indexOptions = fieldInfo.IndexOptions; _storePayloads = fieldInfo.HasPayloads; _absolute = false; _longsSize = _wrappedPostingsWriter.SetField(fieldInfo); _longs = new long[_longsSize]; _fields.Add(new FieldMetaData(fieldInfo.Number, _longsSize)); return 0; } //private bool DEBUG; // LUCENENET NOTE: Not used public override void StartDoc(int docId, int termDocFreq) { if (Debugging.AssertsEnabled) Debugging.Assert(docId >= 0, () => "Got DocID=" + docId); if (_pendingCount == _pending.Length) { Push(); _wrappedPostingsWriter.FinishDoc(); } if (_pendingCount != -1) { if (Debugging.AssertsEnabled) Debugging.Assert(_pendingCount < _pending.Length); _currentDoc = _pending[_pendingCount]; _currentDoc.docID = docId; if (_indexOptions == IndexOptions.DOCS_ONLY) { _pendingCount++; } else if (_indexOptions == IndexOptions.DOCS_AND_FREQS) { _pendingCount++; _currentDoc.termFreq = termDocFreq; } else { _currentDoc.termFreq = termDocFreq; } } else { // We've already seen too many docs for this term -- // just forward to our fallback writer _wrappedPostingsWriter.StartDoc(docId, termDocFreq); } } public override void AddPosition(int position, BytesRef payload, int startOffset, int endOffset) { if (_pendingCount == _pending.Length) { Push(); } if (_pendingCount == -1) { // We've already seen too many docs for this term -- // just forward to our fallback writer _wrappedPostingsWriter.AddPosition(position, payload, startOffset, endOffset); } else { // buffer up Position pos = _pending[_pendingCount++]; pos.pos = position; pos.startOffset = startOffset; pos.endOffset = endOffset; pos.docID = _currentDoc.docID; if (payload != null && payload.Length > 0) { if (pos.payload == null) { pos.payload = BytesRef.DeepCopyOf(payload); } else { pos.payload.CopyBytes(payload); } } else if (pos.payload != null) { pos.payload.Length = 0; } } } public override void FinishDoc() { if (_pendingCount == -1) { _wrappedPostingsWriter.FinishDoc(); } } private readonly RAMOutputStream _buffer = new RAMOutputStream(); /// <summary> /// Called when we are done adding docs to this term. /// </summary> public override void FinishTerm(BlockTermState state) { var state2 = (PulsingTermState)state; if (Debugging.AssertsEnabled) Debugging.Assert(_pendingCount > 0 || _pendingCount == -1); if (_pendingCount == -1) { state2.wrappedState.DocFreq = state2.DocFreq; state2.wrappedState.TotalTermFreq = state2.TotalTermFreq; state2.bytes = null; _wrappedPostingsWriter.FinishTerm(state2.wrappedState); } else { // There were few enough total occurrences for this // term, so we fully inline our postings data into // terms dict, now: // TODO: it'd be better to share this encoding logic // in some inner codec that knows how to write a // single doc / single position, etc. This way if a // given codec wants to store other interesting // stuff, it could use this pulsing codec to do so if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) { var lastDocID = 0; var pendingIDX = 0; var lastPayloadLength = -1; var lastOffsetLength = -1; while (pendingIDX < _pendingCount) { var doc = _pending[pendingIDX]; var delta = doc.docID - lastDocID; lastDocID = doc.docID; // if (DEBUG) System.out.println(" write doc=" + doc.docID + " freq=" + doc.termFreq); if (doc.termFreq == 1) { _buffer.WriteVInt32((delta << 1) | 1); } else { _buffer.WriteVInt32(delta << 1); _buffer.WriteVInt32(doc.termFreq); } var lastPos = 0; var lastOffset = 0; for (var posIDX = 0; posIDX < doc.termFreq; posIDX++) { var pos = _pending[pendingIDX++]; if (Debugging.AssertsEnabled) Debugging.Assert(pos.docID == doc.docID); var posDelta = pos.pos - lastPos; lastPos = pos.pos; var payloadLength = pos.payload == null ? 0 : pos.payload.Length; if (_storePayloads) { if (payloadLength != lastPayloadLength) { _buffer.WriteVInt32((posDelta << 1) | 1); _buffer.WriteVInt32(payloadLength); lastPayloadLength = payloadLength; } else { _buffer.WriteVInt32(posDelta << 1); } } else { _buffer.WriteVInt32(posDelta); } if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) { //System.out.println("write=" + pos.startOffset + "," + pos.endOffset); var offsetDelta = pos.startOffset - lastOffset; var offsetLength = pos.endOffset - pos.startOffset; if (offsetLength != lastOffsetLength) { _buffer.WriteVInt32(offsetDelta << 1 | 1); _buffer.WriteVInt32(offsetLength); } else { _buffer.WriteVInt32(offsetDelta << 1); } lastOffset = pos.startOffset; lastOffsetLength = offsetLength; } if (payloadLength > 0) { if (Debugging.AssertsEnabled) Debugging.Assert(_storePayloads); _buffer.WriteBytes(pos.payload.Bytes, 0, pos.payload.Length); } } } } else if (_indexOptions == IndexOptions.DOCS_AND_FREQS) { int lastDocId = 0; for (int posIdx = 0; posIdx < _pendingCount; posIdx++) { Position doc = _pending[posIdx]; int delta = doc.docID - lastDocId; if (Debugging.AssertsEnabled) Debugging.Assert(doc.termFreq != 0); if (doc.termFreq == 1) { _buffer.WriteVInt32((delta << 1) | 1); } else { _buffer.WriteVInt32(delta << 1); _buffer.WriteVInt32(doc.termFreq); } lastDocId = doc.docID; } } else if (_indexOptions == IndexOptions.DOCS_ONLY) { int lastDocId = 0; for (int posIdx = 0; posIdx < _pendingCount; posIdx++) { Position doc = _pending[posIdx]; _buffer.WriteVInt32(doc.docID - lastDocId); lastDocId = doc.docID; } } state2.bytes = new byte[(int)_buffer.GetFilePointer()]; _buffer.WriteTo(state2.bytes, 0); _buffer.Reset(); } _pendingCount = 0; } public override void EncodeTerm(long[] empty, DataOutput output, FieldInfo fieldInfo, BlockTermState state, bool abs) { var _state = (PulsingTermState)state; if (Debugging.AssertsEnabled) Debugging.Assert(empty.Length == 0); _absolute = _absolute || abs; if (_state.bytes == null) { _wrappedPostingsWriter.EncodeTerm(_longs, _buffer, fieldInfo, _state.wrappedState, _absolute); for (var i = 0; i < _longsSize; i++) { output.WriteVInt64(_longs[i]); } _buffer.WriteTo(output); _buffer.Reset(); _absolute = false; } else { output.WriteVInt32(_state.bytes.Length); output.WriteBytes(_state.bytes, 0, _state.bytes.Length); _absolute = _absolute || abs; } } protected override void Dispose(bool disposing) { _wrappedPostingsWriter.Dispose(); if (_wrappedPostingsWriter is PulsingPostingsWriter || VERSION_CURRENT < VERSION_META_ARRAY) { return; } var summaryFileName = IndexFileNames.SegmentFileName(_segmentState.SegmentInfo.Name, _segmentState.SegmentSuffix, SUMMARY_EXTENSION); IndexOutput output = null; try { output = _segmentState.Directory.CreateOutput(summaryFileName, _segmentState.Context); CodecUtil.WriteHeader(output, CODEC, VERSION_CURRENT); output.WriteVInt32(_fields.Count); foreach (var field in _fields) { output.WriteVInt32(field.FieldNumber); output.WriteVInt32(field.Int64sSize); } output.Dispose(); } finally { IOUtils.DisposeWhileHandlingException(output); } } /// <summary> /// Pushes pending positions to the wrapped codec. /// </summary> private void Push() { if (Debugging.AssertsEnabled) Debugging.Assert(_pendingCount == _pending.Length); _wrappedPostingsWriter.StartTerm(); // Flush all buffered docs if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) { Position doc = null; foreach (var pos in _pending) { if (doc == null) { doc = pos; _wrappedPostingsWriter.StartDoc(doc.docID, doc.termFreq); } else if (doc.docID != pos.docID) { if (Debugging.AssertsEnabled) Debugging.Assert(pos.docID > doc.docID); _wrappedPostingsWriter.FinishDoc(); doc = pos; _wrappedPostingsWriter.StartDoc(doc.docID, doc.termFreq); } _wrappedPostingsWriter.AddPosition(pos.pos, pos.payload, pos.startOffset, pos.endOffset); } //wrappedPostingsWriter.finishDoc(); } else { foreach (var doc in _pending) { _wrappedPostingsWriter.StartDoc(doc.docID, _indexOptions == IndexOptions.DOCS_ONLY ? 0 : doc.termFreq); } } _pendingCount = -1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach001.freach001 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { // Implicit and Explicit Numeric Conversions. Test will throw a runtime exception if it fails. [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 0; sbyte[] x1 = new sbyte[] { 1, 2, 3 } ; byte[] x2 = new byte[] { 1, 2, 3 } ; short[] x3 = new short[] { 1, 2, 3 } ; ushort[] x4 = new ushort[] { 1, 2, 3 } ; int[] x5 = new int[] { 1, 2, 3 } ; uint[] x6 = new uint[] { 1, 2, 3 } ; long[] x7 = new long[] { 1, 2, 3 } ; ulong[] x8 = new ulong[] { 1, 2, 3 } ; char[] x9 = new char[] { '1', '2', '3' } ; float[] x10 = new float[] { 1.1f, 2.2f, 3.3f } ; double[] x11 = new double[] { 1.1, 2.2, 3.35 } ; decimal[] x12 = new decimal[] { 1.1m, 22.2m, 33.3m } ; // IMPLICIT NUMERIC CONVERSIONS // sybte to short, int, long, float, double, decimal foreach (short y in (dynamic)x1) i++; foreach (int y in (dynamic)x1) i++; foreach (long y in (dynamic)x1) i++; foreach (float y in (dynamic)x1) i++; foreach (double y in (dynamic)x1) i++; foreach (decimal y in (dynamic)x1) i++; // byte to short, ushort, int, uint, long, ulong, float, double, decimal foreach (short y in (dynamic)x2) i++; foreach (ushort y in (dynamic)x2) i++; foreach (int y in (dynamic)x2) i++; foreach (uint y in (dynamic)x2) i++; foreach (long y in (dynamic)x2) i++; foreach (ulong y in (dynamic)x2) i++; foreach (float y in (dynamic)x2) i++; foreach (double y in (dynamic)x2) i++; foreach (decimal y in (dynamic)x2) i++; // short to int, long, float, double, decimal foreach (int y in (dynamic)x3) i++; foreach (long y in (dynamic)x3) i++; foreach (float y in (dynamic)x3) i++; foreach (double y in (dynamic)x3) i++; foreach (decimal y in (dynamic)x3) i++; // ushort to int, uint, long, ulong, float, double, decimal foreach (int y in (dynamic)x4) i++; foreach (uint y in (dynamic)x4) i++; foreach (long y in (dynamic)x4) i++; foreach (ulong y in (dynamic)x4) i++; foreach (float y in (dynamic)x4) i++; foreach (double y in (dynamic)x4) i++; foreach (decimal y in (dynamic)x4) i++; // int to long, float, double, decimal foreach (long y in (dynamic)x5) i++; foreach (float y in (dynamic)x5) i++; foreach (double y in (dynamic)x5) i++; foreach (decimal y in (dynamic)x5) i++; // uint to long, ulong, float, double, decimal foreach (long y in (dynamic)x6) i++; foreach (ulong y in (dynamic)x6) i++; foreach (float y in (dynamic)x6) i++; foreach (double y in (dynamic)x6) i++; foreach (decimal y in (dynamic)x6) i++; // long to float, double, decimal foreach (float y in (dynamic)x7) i++; foreach (double y in (dynamic)x7) i++; foreach (decimal y in (dynamic)x7) i++; // ulong to float, double, decimal foreach (float y in (dynamic)x8) i++; foreach (double y in (dynamic)x8) i++; foreach (decimal y in (dynamic)x8) i++; // char to ushort, int, uint, long, ulong, float, double, decimal foreach (ushort y in (dynamic)x9) i++; foreach (int y in (dynamic)x9) i++; foreach (uint y in (dynamic)x9) i++; foreach (long y in (dynamic)x9) i++; foreach (ulong y in (dynamic)x9) i++; foreach (float y in (dynamic)x9) i++; foreach (double y in (dynamic)x9) i++; foreach (decimal y in (dynamic)x9) i++; // float to double foreach (double y in (dynamic)x10) i++; // EXPLICIT NUMERIC CONVERSIONS // sbyte to byte, ushort, uint, ulong char foreach (byte y in (dynamic)x1) i++; foreach (ushort y in (dynamic)x1) i++; foreach (uint y in (dynamic)x1) i++; foreach (ulong y in (dynamic)x1) i++; foreach (char y in (dynamic)x1) i++; // byte to sbyte, char foreach (sbyte y in (dynamic)x2) i++; foreach (char y in (dynamic)x2) i++; // short to sbyte, byte, ushort, uint, ulong, char foreach (sbyte y in (dynamic)x3) i++; foreach (byte y in (dynamic)x3) i++; foreach (ushort y in (dynamic)x3) i++; foreach (uint y in (dynamic)x3) i++; foreach (ulong y in (dynamic)x3) i++; foreach (char y in (dynamic)x3) i++; // ushort to sbyte, byte, short, char foreach (sbyte y in (dynamic)x4) i++; foreach (byte y in (dynamic)x4) i++; foreach (short y in (dynamic)x4) i++; foreach (char y in (dynamic)x4) i++; // int to sbyte, byte, short, ushort, uint, ulong, char foreach (sbyte y in (dynamic)x5) i++; foreach (byte y in (dynamic)x5) i++; foreach (short y in (dynamic)x5) i++; foreach (ushort y in (dynamic)x5) i++; foreach (uint y in (dynamic)x5) i++; foreach (ulong y in (dynamic)x5) i++; foreach (char y in (dynamic)x5) i++; // uint to sbyte, byte, short, ushort, int, char foreach (sbyte y in (dynamic)x6) i++; foreach (byte y in (dynamic)x6) i++; foreach (short y in (dynamic)x6) i++; foreach (ushort y in (dynamic)x6) i++; foreach (int y in (dynamic)x6) i++; foreach (char y in (dynamic)x6) i++; // long to sbyte, byte, short, ushort, int, uint, ulong, char foreach (sbyte y in (dynamic)x7) i++; foreach (byte y in (dynamic)x7) i++; foreach (short y in (dynamic)x7) i++; foreach (ushort y in (dynamic)x7) i++; foreach (int y in (dynamic)x7) i++; foreach (uint y in (dynamic)x7) i++; foreach (ulong y in (dynamic)x7) i++; foreach (char y in (dynamic)x7) i++; // ulong to sbyte, byte, short, ushort, int, uint, ulong, char foreach (sbyte y in (dynamic)x8) i++; foreach (byte y in (dynamic)x8) i++; foreach (short y in (dynamic)x8) i++; foreach (ushort y in (dynamic)x8) i++; foreach (int y in (dynamic)x8) i++; foreach (uint y in (dynamic)x8) i++; foreach (ulong y in (dynamic)x8) i++; foreach (char y in (dynamic)x8) i++; // char to sbyte, byte, short foreach (sbyte y in (dynamic)x9) i++; foreach (byte y in (dynamic)x9) i++; foreach (short y in (dynamic)x9) i++; // float to sybte, byte, short, ushort, int, uint, long, ulong, char, decimal foreach (sbyte y in (dynamic)x10) i++; foreach (byte y in (dynamic)x10) i++; foreach (short y in (dynamic)x10) i++; foreach (ushort y in (dynamic)x10) i++; foreach (int y in (dynamic)x10) i++; foreach (uint y in (dynamic)x10) i++; foreach (long y in (dynamic)x10) i++; foreach (ulong y in (dynamic)x10) i++; foreach (char y in (dynamic)x10) i++; foreach (decimal y in (dynamic)x10) i++; // double to sbyte, short, ushort, int, uint, long, ulong, char, float, decimal foreach (sbyte y in (dynamic)x11) i++; foreach (short y in (dynamic)x11) i++; foreach (ushort y in (dynamic)x11) i++; foreach (int y in (dynamic)x11) i++; foreach (uint y in (dynamic)x11) i++; foreach (long y in (dynamic)x11) i++; foreach (ulong y in (dynamic)x11) i++; foreach (char y in (dynamic)x11) i++; foreach (float y in (dynamic)x11) i++; foreach (decimal y in (dynamic)x11) i++; // decimal to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double foreach (sbyte y in (dynamic)x12) i++; foreach (byte y in (dynamic)x12) i++; foreach (short y in (dynamic)x12) i++; foreach (ushort y in (dynamic)x12) i++; foreach (int y in (dynamic)x12) i++; foreach (uint y in (dynamic)x12) i++; foreach (long y in (dynamic)x12) i++; foreach (ulong y in (dynamic)x12) i++; foreach (char y in (dynamic)x12) i++; foreach (float y in (dynamic)x12) i++; foreach (double y in (dynamic)x12) i++; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach002.freach002 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class A { } public class B : A { } public interface I1 { } public interface I2 : I1 { } public class CI1 : I1 { } public class CI2 : I2 { } public class Test { // Implicit and Explicit Reference Conversions. Test will throw a runtime exception if it fails. [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 0; // IMPLICIT REFERENCE CONVERSIONS // Reference type to object Test[] x1 = new Test[] { new Test(), new Test()} ; foreach (object y in (dynamic)x1) i++; // Class-Type S to Class-Type T, S is derived from T B[] x2 = new B[] { new B(), new B()} ; foreach (A y in (dynamic)x2) i++; // Class-Type S to Interface-Type T, S implements T CI1[] x3 = new CI1[] { new CI1(), new CI1()} ; foreach (I1 y in (dynamic)x3) i++; // Interface-Type S to Interface-Type T, S is derived from T I2[] x4 = new I2[] { new CI2(), new CI2()} ; foreach (I1 y in (dynamic)x4) i++; // From array-type to System.Array int[][] x5 = new int[][] { new int[] { 1, 2, 3 } , new int[] { 4, 5, 6 } } ; foreach (System.Array y in (dynamic)x5) i++; // EXPLICIT REFERENCE CONVERSIONS // object to reference-type object[] xr1 = new object[] { new Test(), new Test()} ; foreach (Test y in (dynamic)xr1) i++; // Class-Type S to Class-Type T, S is base class from T A[] xr2 = new A[] { new B(), new B()} ; foreach (B y in (dynamic)xr2) i++; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach003.freach003 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public struct S { } public class Test { // Boxing and Unboxing Conversions. Test will throw a runtime exception if it fails. [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 0; // Boxing Conversions int[] x1 = new int[] { 1, 2, 3 } ; S[] x2 = new S[] { new S(), new S()} ; decimal[] x3 = new decimal[] { 1m, 2m, 3m } ; int?[] x4 = new int?[] { 1, 2, 3 } ; uint?[] x5 = new uint?[] { 1, 2, 3 } ; decimal?[] x6 = new decimal?[] { 1m, 2m, 3m } ; // Boxing to object foreach (object y in (dynamic)x1) i++; foreach (object y in (dynamic)x2) i++; foreach (object y in (dynamic)x3) i++; foreach (object y in (dynamic)x4) i++; foreach (object y in (dynamic)x5) i++; foreach (object y in (dynamic)x6) i++; // Boxing to System.ValueType foreach (System.ValueType y in (dynamic)x1) i++; foreach (System.ValueType y in (dynamic)x2) i++; foreach (System.ValueType y in (dynamic)x3) i++; foreach (System.ValueType y in (dynamic)x4) i++; foreach (System.ValueType y in (dynamic)x5) i++; foreach (System.ValueType y in (dynamic)x6) i++; // Unboxing Conversions object[] xo1 = new object[] { 1, 2, 3 } ; object[] xo2 = new object[] { new S(), new S()} ; object[] xo3 = new object[] { 1m, 2m, 3m } ; object[] xo4 = new object[] { (int ? )1, (int ? )2, (int ? )3 } ; object[] xo5 = new object[] { (uint ? )1, (uint ? )2, (uint ? )3 } ; object[] xo6 = new object[] { (decimal ? )1m, (decimal ? )2m, (decimal ? )3m } ; // Unboxing from object foreach (object y in (dynamic)xo1) i++; foreach (object y in (dynamic)xo2) i++; foreach (object y in (dynamic)xo3) i++; foreach (object y in (dynamic)xo4) i++; foreach (object y in (dynamic)xo5) i++; foreach (object y in (dynamic)xo6) i++; // Unboxing Conversions System.ValueType[] xv1 = new System.ValueType[] { 1, 2, 3 } ; System.ValueType[] xv2 = new System.ValueType[] { new S(), new S()} ; System.ValueType[] xv3 = new System.ValueType[] { 1m, 2m, 3m } ; System.ValueType[] xv4 = new System.ValueType[] { (int ? )1, (int ? )2, (int ? )3 } ; System.ValueType[] xv5 = new System.ValueType[] { (uint ? )1, (uint ? )2, (uint ? )3 } ; System.ValueType[] xv6 = new System.ValueType[] { (decimal ? )1m, (decimal ? )2m, (decimal ? )3m } ; // Unboxing from System.ValueType foreach (System.ValueType y in (dynamic)xv1) i++; foreach (System.ValueType y in (dynamic)xv2) i++; foreach (System.ValueType y in (dynamic)xv3) i++; foreach (System.ValueType y in (dynamic)xv4) i++; foreach (System.ValueType y in (dynamic)xv5) i++; foreach (System.ValueType y in (dynamic)xv6) i++; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach004.freach004 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public enum color { Red, Blue, Green } public enum cars { Toyota, Lexus, BMW } public class Test { // Explicit Enum Conversions. Test will throw a runtime exception if it fails. [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 0; sbyte[] x1 = new sbyte[] { 1, 2, 3 } ; byte[] x2 = new byte[] { 1, 2, 3 } ; short[] x3 = new short[] { 1, 2, 3 } ; ushort[] x4 = new ushort[] { 1, 2, 3 } ; int[] x5 = new int[] { 1, 2, 3 } ; uint[] x6 = new uint[] { 1, 2, 3 } ; long[] x7 = new long[] { 1, 2, 3 } ; ulong[] x8 = new ulong[] { 1, 2, 3 } ; char[] x9 = new char[] { '1', '2', '3' } ; float[] x10 = new float[] { 1.1f, 2.2f, 3.3f } ; double[] x11 = new double[] { 1.1, 2.2, 3.35 } ; decimal[] x12 = new decimal[] { 1.1m, 22.2m, 33.3m } ; color[] x13 = new color[] { color.Red, color.Green } ; cars[] x14 = new cars[] { cars.Toyota, cars.BMW } ; // From sybte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal to enum-type foreach (color y in (dynamic)x1) i++; foreach (color y in (dynamic)x2) i++; foreach (color y in (dynamic)x3) i++; foreach (color y in (dynamic)x4) i++; foreach (color y in (dynamic)x5) i++; foreach (color y in (dynamic)x6) i++; foreach (color y in (dynamic)x7) i++; foreach (color y in (dynamic)x8) i++; foreach (color y in (dynamic)x9) i++; foreach (color y in (dynamic)x10) i++; foreach (color y in (dynamic)x11) i++; foreach (color y in (dynamic)x12) i++; // From enum type to sybte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal foreach (sbyte y in (dynamic)x13) i++; foreach (byte y in (dynamic)x13) i++; foreach (short y in (dynamic)x13) i++; foreach (ushort y in (dynamic)x13) i++; foreach (int y in (dynamic)x13) i++; foreach (uint y in (dynamic)x13) i++; foreach (long y in (dynamic)x13) i++; foreach (ulong y in (dynamic)x13) i++; foreach (char y in (dynamic)x13) i++; foreach (float y in (dynamic)x13) i++; foreach (double y in (dynamic)x13) i++; foreach (decimal y in (dynamic)x13) i++; // From one enum type to another enum type foreach (color y in (dynamic)x14) i++; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach005.freach005 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static implicit operator int (Test t) { return 5; } public static explicit operator decimal (Test t) { return 10m; } // Explicit/Implicit User-defined Conversions. Test will throw a runtime exception if it fails. [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 0; Test[] x1 = new Test[] { new Test(), new Test()} ; // User-defined Implicit conversions foreach (int y in (dynamic)x1) i++; foreach (long y in (dynamic)x1) i++; // User-defined Explicit conversions foreach (decimal y in (dynamic)x1) i++; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach006.freach006 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { // Nested foreach statements. Test will throw runtime exception if it fails. [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 0; int[][] v1 = new int[][] { new int[] { 4, 5 } , new int[] { 1, 2, 3 } } ; // Nested foreach statements foreach (dynamic y in (dynamic)v1) { i++; foreach (long z in y) i++; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach007.freach007 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { // Implicit and Explicit Nullable Numeric Conversions. Test will throw a runtime exception if it fails. [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 0; sbyte?[] x1 = new sbyte?[] { 1, 2, 3 } ; byte?[] x2 = new byte?[] { 1, 2, 3 } ; short?[] x3 = new short?[] { 1, 2, 3 } ; ushort?[] x4 = new ushort?[] { 1, 2, 3 } ; int?[] x5 = new int?[] { 1, 2, 3 } ; uint?[] x6 = new uint?[] { 1, 2, 3 } ; long?[] x7 = new long?[] { 1, 2, 3 } ; ulong?[] x8 = new ulong?[] { 1, 2, 3 } ; char?[] x9 = new char?[] { '1', '2', '3' } ; float?[] x10 = new float?[] { 1.1f, 2.2f, 3.3f } ; double?[] x11 = new double?[] { 1.1, 2.2, 3.35 } ; decimal?[] x12 = new decimal?[] { 1.1m, 22.2m, 33.3m } ; // IMPLICIT NUMERIC CONVERSIONS // sybte to short, int, long, float, double, decimal foreach (short? y in (dynamic)x1) i++; foreach (int? y in (dynamic)x1) i++; foreach (long? y in (dynamic)x1) i++; foreach (float? y in (dynamic)x1) i++; foreach (double? y in (dynamic)x1) i++; foreach (decimal? y in (dynamic)x1) i++; // byte to short, ushort, int, uint, long, ulong, float, double, decimal foreach (short? y in (dynamic)x2) i++; foreach (ushort? y in (dynamic)x2) i++; foreach (int? y in (dynamic)x2) i++; foreach (uint? y in (dynamic)x2) i++; foreach (long? y in (dynamic)x2) i++; foreach (ulong? y in (dynamic)x2) i++; foreach (float? y in (dynamic)x2) i++; foreach (double? y in (dynamic)x2) i++; foreach (decimal? y in (dynamic)x2) i++; // short to int, long, float, double, decimal foreach (int? y in (dynamic)x3) i++; foreach (long? y in (dynamic)x3) i++; foreach (float? y in (dynamic)x3) i++; foreach (double? y in (dynamic)x3) i++; foreach (decimal? y in (dynamic)x3) i++; // ushort to int, uint, long, ulong, float, double, decimal foreach (int? y in (dynamic)x4) i++; foreach (uint? y in (dynamic)x4) i++; foreach (long? y in (dynamic)x4) i++; foreach (ulong? y in (dynamic)x4) i++; foreach (float? y in (dynamic)x4) i++; foreach (double? y in (dynamic)x4) i++; foreach (decimal? y in (dynamic)x4) i++; // int to long, float, double, decimal foreach (long? y in (dynamic)x5) i++; foreach (float? y in (dynamic)x5) i++; foreach (double? y in (dynamic)x5) i++; foreach (decimal? y in (dynamic)x5) i++; // uint to long, ulong, float, double, decimal foreach (long? y in (dynamic)x6) i++; foreach (ulong? y in (dynamic)x6) i++; foreach (float? y in (dynamic)x6) i++; foreach (double? y in (dynamic)x6) i++; foreach (decimal? y in (dynamic)x6) i++; // long to float, double, decimal foreach (float? y in (dynamic)x7) i++; foreach (double? y in (dynamic)x7) i++; foreach (decimal? y in (dynamic)x7) i++; // ulong to float, double, decimal foreach (float? y in (dynamic)x8) i++; foreach (double? y in (dynamic)x8) i++; foreach (decimal? y in (dynamic)x8) i++; // char to ushort, int, uint, long, ulong, float, double, decimal foreach (ushort? y in (dynamic)x9) i++; foreach (int? y in (dynamic)x9) i++; foreach (uint? y in (dynamic)x9) i++; foreach (long? y in (dynamic)x9) i++; foreach (ulong? y in (dynamic)x9) i++; foreach (float? y in (dynamic)x9) i++; foreach (double? y in (dynamic)x9) i++; foreach (decimal? y in (dynamic)x9) i++; // float to double foreach (double y in (dynamic)x10) i++; // EXPLICIT NUMERIC CONVERSIONS // sbyte to byte, ushort, uint, ulong char foreach (byte? y in (dynamic)x1) i++; foreach (ushort? y in (dynamic)x1) i++; foreach (uint? y in (dynamic)x1) i++; foreach (ulong? y in (dynamic)x1) i++; foreach (char? y in (dynamic)x1) i++; // byte to sbyte, char foreach (sbyte? y in (dynamic)x2) i++; foreach (char? y in (dynamic)x2) i++; // short to sbyte, byte, ushort, uint, ulong, char foreach (sbyte? y in (dynamic)x3) i++; foreach (byte? y in (dynamic)x3) i++; foreach (ushort? y in (dynamic)x3) i++; foreach (uint? y in (dynamic)x3) i++; foreach (ulong? y in (dynamic)x3) i++; foreach (char? y in (dynamic)x3) i++; // ushort to sbyte, byte, short, char foreach (sbyte? y in (dynamic)x4) i++; foreach (byte? y in (dynamic)x4) i++; foreach (short? y in (dynamic)x4) i++; foreach (char? y in (dynamic)x4) i++; // int to sbyte, byte, short, ushort, uint, ulong, char foreach (sbyte? y in (dynamic)x5) i++; foreach (byte? y in (dynamic)x5) i++; foreach (short? y in (dynamic)x5) i++; foreach (ushort? y in (dynamic)x5) i++; foreach (uint? y in (dynamic)x5) i++; foreach (ulong? y in (dynamic)x5) i++; foreach (char? y in (dynamic)x5) i++; // uint to sbyte, byte, short, ushort, int, char foreach (sbyte? y in (dynamic)x6) i++; foreach (byte? y in (dynamic)x6) i++; foreach (short? y in (dynamic)x6) i++; foreach (ushort? y in (dynamic)x6) i++; foreach (int? y in (dynamic)x6) i++; foreach (char? y in (dynamic)x6) i++; // long to sbyte, byte, short, ushort, int, uint, ulong, char foreach (sbyte? y in (dynamic)x7) i++; foreach (byte? y in (dynamic)x7) i++; foreach (short? y in (dynamic)x7) i++; foreach (ushort? y in (dynamic)x7) i++; foreach (int? y in (dynamic)x7) i++; foreach (uint? y in (dynamic)x7) i++; foreach (ulong? y in (dynamic)x7) i++; foreach (char? y in (dynamic)x7) i++; // ulong to sbyte, byte, short, ushort, int, uint, ulong, char foreach (sbyte? y in (dynamic)x8) i++; foreach (byte? y in (dynamic)x8) i++; foreach (short? y in (dynamic)x8) i++; foreach (ushort? y in (dynamic)x8) i++; foreach (int? y in (dynamic)x8) i++; foreach (uint? y in (dynamic)x8) i++; foreach (ulong? y in (dynamic)x8) i++; foreach (char? y in (dynamic)x8) i++; // char to sbyte, byte, short foreach (sbyte? y in (dynamic)x9) i++; foreach (byte? y in (dynamic)x9) i++; foreach (short? y in (dynamic)x9) i++; // float to sybte, byte, short, ushort, int, uint, long, ulong, char, decimal foreach (sbyte? y in (dynamic)x10) i++; foreach (byte? y in (dynamic)x10) i++; foreach (short? y in (dynamic)x10) i++; foreach (ushort? y in (dynamic)x10) i++; foreach (int? y in (dynamic)x10) i++; foreach (uint? y in (dynamic)x10) i++; foreach (long? y in (dynamic)x10) i++; foreach (ulong? y in (dynamic)x10) i++; foreach (char? y in (dynamic)x10) i++; foreach (decimal? y in (dynamic)x10) i++; // double to sbyte, short, ushort, int, uint, long, ulong, char, float, decimal foreach (sbyte? y in (dynamic)x11) i++; foreach (short? y in (dynamic)x11) i++; foreach (ushort? y in (dynamic)x11) i++; foreach (int? y in (dynamic)x11) i++; foreach (uint? y in (dynamic)x11) i++; foreach (long? y in (dynamic)x11) i++; foreach (ulong? y in (dynamic)x11) i++; foreach (char? y in (dynamic)x11) i++; foreach (float? y in (dynamic)x11) i++; foreach (decimal? y in (dynamic)x11) i++; // decimal to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double foreach (sbyte? y in (dynamic)x12) i++; foreach (byte? y in (dynamic)x12) i++; foreach (short? y in (dynamic)x12) i++; foreach (ushort? y in (dynamic)x12) i++; foreach (int? y in (dynamic)x12) i++; foreach (uint? y in (dynamic)x12) i++; foreach (long? y in (dynamic)x12) i++; foreach (ulong? y in (dynamic)x12) i++; foreach (char? y in (dynamic)x12) i++; foreach (float? y in (dynamic)x12) i++; foreach (double? y in (dynamic)x12) i++; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach008.freach008 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections; public class MyCollection : IEnumerable { private int[] _items; public MyCollection() { _items = new int[5] { 1, 4, 3, 2, 5 } ; } public IEnumerator GetEnumerator() { return new MyEnumerator(this); } public class MyEnumerator : IEnumerator { private int _nIndex; private MyCollection _collection; public MyEnumerator(MyCollection coll) { _collection = coll; _nIndex = -1; } public bool MoveNext() { _nIndex++; return (_nIndex < _collection._items.GetLength(0)); } public void Reset() { _nIndex = -1; } public dynamic Current { get { return (_collection._items[_nIndex]); } } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyCollection col = new MyCollection(); int[] expected = new int[] { 1, 4, 3, 2, 5 }; int index = 0; foreach (int i in col) { if (i != expected[index]) { return 1; } index++; } return index - expected.Length; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach009.freach009 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections; public class MyCollection : IEnumerable { private int[] _items; public MyCollection() { _items = new int[5] { 1, 4, 3, 2, 5 } ; } IEnumerator IEnumerable.GetEnumerator() { return new MyEnumerator(this); } public class MyEnumerator : IEnumerator { private int _nIndex; private MyCollection _collection; public MyEnumerator(MyCollection coll) { _collection = coll; _nIndex = -1; } bool IEnumerator.MoveNext() { _nIndex++; return (_nIndex < _collection._items.GetLength(0)); } void IEnumerator.Reset() { _nIndex = -1; } dynamic IEnumerator.Current { get { return (_collection._items[_nIndex]); } } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyCollection col = new MyCollection(); int[] expected = new int[] { 1, 4, 3, 2, 5 }; int index = 0; foreach (int i in col) { if (i != expected[index]) { return 1; } index++; } return index - expected.Length; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach010.freach010 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections; public class MyCollection : IEnumerable { private int[] _items; public MyCollection() { _items = new int[5] { 1, 4, 3, 2, 6 } ; } public MyEnumerator GetEnumerator() { return new MyEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public class MyEnumerator : IEnumerator { private int _index; private MyCollection _collection; public MyEnumerator(MyCollection coll) { _collection = coll; _index = -1; } public bool MoveNext() { _index++; return (_index < _collection._items.GetLength(0)); } public void Reset() { _index = -1; } public dynamic Current { get { return (_collection._items[_index]); } } dynamic IEnumerator.Current { get { return (Current); } } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MyCollection col = new MyCollection(); byte[] expected = new byte[] { 1, 4, 3, 2, 6 }; int index = 0; foreach (byte i in col) { if (i != expected[index]) { return 1; } index++; } return index - expected.Length; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.freach.freach011.freach011 { // <Title> Dynamic in Foreach </Title> // <Description> // Conversions between elements in foreach expressions to the type of the identifier in the foreach loop // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class GenC<T> { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int result = 0; int flag = 1; flag = 1; dynamic darr = new string[2] { "aa", "bb" } ; try { foreach (int v in darr) { } } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { if (ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "string", "int")) { flag = 0; } } result += flag; flag = 1; dynamic darr2 = new string[2]; try { foreach (int v in darr2) { } } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { if (ErrorVerifier.Verify(ErrorMessageId.ValueCantBeNull, ex.Message, "int")) { flag = 0; } } result += flag; flag = 0; dynamic darr3 = new GenC<string>[2]; foreach (GenC<int> v in darr3) { if (v != null) flag++; } result += flag; return result; } } // </Code> }
using MonkeyOthello.Core; using MonkeyOthello.Engines; using MonkeyOthello.Tests.Engines; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Linq; using System.IO; using System.Configuration; using MonkeyOthello.Learning; using MonkeyOthello.Engines.V2; using MonkeyOthello.OpeningBook; namespace MonkeyOthello.Tests { static class Test { #region test data //113 private static string[] testData = new string[] { //"........b.wwbw..bbwbbwwwbwbbbwwwbbwbbwwwbbbwbwww..bbwbw....bb...", //"........b.wwbw..bbwbbwwwbwbbbwwwbbwbbwwwbbbwbwww..bbwbw.........", "..wwwww.b.wwbw..bbwbbwwwbwbbbwwwbbwbbwwwbbbwbwww..bbwbw....bbbbw", "wbbw.b...wwbwww.wwwwbwwwwwwbwbbbwwwwbwb.wwwwwbbb..wwbbb..wwwww..", "..w.bb.bw.wbbbbbwwwwbbbbwbwwwwbbwbbbwwbwwwbbbbbww.wbbbbw......bw", "bwwwwww..bwwwww..bbbwwww.bbbbbww.bbbbwww.bbbbbww..bbbbw...bbbbbw", "b.wbw....bwwww.bbbbbbbbbbbbbbbbbbbwbbbbbbbbwwbbbb.wwww....w.bbbb", "..bwb..b.bbwwwwwbbbwbbwbbwwbbbwbbwwwbwbbb.wwwwbbb.wwwb.b...wbbb.", "...bwwbb..bbbwwb.bbbbbwwbbwbbbb.bbbwbbbb.bbbwwbb..bbbbbb..bbbbwb", "..bbbbwb..bbbwbb.bbwwbbbwwwwbbbb.wwbbbbb.wwbbwbb.bbwww...bwwwww.", "..b.....wwbb.b..wwwbbbbbbwwwbbwwbbwbbwwwbbbwwwwwbwbbwb..bwwwwwww", "b.w.b...bb.bbw.wbbbbbbwwbbbbbwwwbwwwwwwwbwbwwww.bbwwww.b..wwwww.", "b..b....b.bbbb.bbbwwwwbbbbbbwbbbbwbwbbbbbwbwbwbbbwwwww..bwwwww..", "wbbb.ww.wbbbbw.bwbbwwb.bwbbwwbwbwwbwwww.wwbwwwwwwbwwww....ww..w.", "bbbbbbb...wwww.bbbbbbwwb.bwbwwwbbbbwwwwb.bbbwwwb..wwbww...wwwww.", "b.w.b...bb.bbw.wbbbbbbwwbbbbbwwwbwwwwwwwbwbwwww.bbwwww.b..wwwww.", "bbbbbbb...wwww.bbbbbbwwb.bwbwwwbbbbwwwwb.bbbwwwb..wwbww...wwwww.", "b..b..w.bbbbbw.bbwbwwwbbbwbbwbbbbwbwbbbbbwbbbwbbbbbbww..b.b.ww..", "b..b....b.bbbb.bbbwwwwbbbbbbwbbbbwbwbbbbbwbwbwbbbwwwww..bwwwww..", "...bbbb...bbbb.wbbbbbww.wbwbwww.wbbbbwwwbbbbbbww.bbbbbbw.wwwwww.", "..bbb.....bbbw.wwwwwbwwwbwwbbbbwwwbwwbbw.bwwbwbwb.wwbbbw..wwwwbw", "w..bbbb.bbbbbbb.wbwbwwbbwwbbwbbbwwbbwbbbw.wwwwbb..wwww.b..wwww..", "..bbbbb.wwbbbbb..wwbbbbwbbwwwbbwbbwwwbbwbbbbbwbww.wwwwww.....w.w", ".bbb....w.bbbb.wwbbbbbbbwbbwbbbbwbwbwwbbwwbbbbwbw.bbbwww...bww.w", "..wwwww.bbwwww.bbbbwwwbbbwbbwbwbbwbbwbbbbbwbbbbbb.wwww......www.", "w..bbb..bbbbbb..wbwbwbbbwbbwwbbbwbwbwbbbwbbwwwbb.bwwww.b..wwww..", ".bbbbbbb..wwbwb.wwwwwbww.wbwbwwb.bwbbwbb.wbbbbbb...bbbbb..wwwwww", "..bbbbbw..bbbbww..bbbwbw..bbwbbw.wbwwbbwwwbbwwwwwwbbbb.bbbbbbb..", ".wwwww...wwbbbb.wwwwbbbbwwwwbwb.wwwwwww.wbwwwwwwbbbwww..wwww..w.", "b.w.b...bb.bbb..bbbwwwwwbbbbbwwwbwbbwwbwbbwwbwwwbwwwwwwww....wbw", "...bbbb...bbbb.wbbbbbww.wbwbwww.wbbbbwwwbbbbbbww.bbbbbbw.wwwwww.", ".wbbbb.w..bbbb.w.wbwwwbw.bbwwwww.bbwwwbw.bwbwbww.bbbbww.wbwwwww.", "..wbbw.w..wwwwwbwwwwwwbbwwwbwbwbwwbwbwwbwbbbwbbbw.bbbbbb..bb....", "..bbbbb..bbbbbbbbbbwbbbbwbbbwbbbbbbbbwbb.bbbwww..bbbbwww....bbw.", "..w..bww...wbbbb..wwbbbwbbbbbbwwbbbbwbwwbwbbwwwwbbwwwww.bbbbb.w.", ".wwwww..b.wbbw.w.bbwwbwwwwbbwwb.wwwbwwbbwwbwbwbb..bbwbb...bbbbbb", "....w.....wwww.wwwwwbbbbwwwbwbbbwwwbwwbbwwbwwbwb.bbbbbbw.wwwwwww", ".ww.b.....wwbb..wbbwwbbbwbbbwwbbwbbbbbwbwbbbbwbb.bbbwb.b.bbbbbbb", "..wbbbbww.bbwwwwwbbbwwwwwbbwwbwwwwwwwwwww.wbbwwww.w..www...bbb..", ".wbbbb.w..bbbb.w.wbwwwbw.bbwwwww.bbwwwbw.bwbwbww.bbbbww.wbwwwww.", "..bbbb..w.bww...wwbbww..wbbwbwwwwbbbwwwwwbbbbwbw.bbwbbbw.bbbbbbw", ".bb.w....bbbww.bwbwbbwbbwwbwwbbbwwbwwwb.wwwbbwww.wwwwwww..bwwww.", ".....w....wwwwwwbbwbbbwb.bwwwwwbbbbwwbwbbbwbbwbbbbbbbbbbwbbbbb..", "w..bww..bwwbbbbbbbbwbbbbbbbbwbbb..bwwwb...wwbwww.wwwwwww.wwwwww.", "wwwwwbw...wwwww.bbwbbbbb.bbwwbbbbbbbbbbb.bwwwbbbb.wwww....wwwww.", "..w.wb..wwbwww..wwbbwbw.wbbwbbw.wbbbwbwwwwbwwwbwwbbbbbbwb.bb..bw", "..wbbw..wwwbbbbbwwbbbbbbwwwbbbwbwwwbwwww.wbbwb.w.bbbbw...b.wwww.", "..wbbb.....b.bwwwwbbwbwwwwbbwwww.wbwwbww.wwbbwwb.wwwwwwb.wwwwwww", "b.wwwww.bbwwwwb.bwbwwbbb.bwbbwbb.wbwbbbbw.bwbbbw...wwbbw..bw.wbw", "..bwww....bbbb...wbwbb.wwwbwwwwwwwbbwbwwwwbbbwbwwwwbbbbw..wbbbbw", "bbbbbb...bwbbbbbbbbwwbbwbbwbbbww.bwbbbw..bwbwbw...wwbwb...wwwwwb", "w.w.....w.wwwb..wwwwbwwbbwbbbwwbbwbwwbwbbbwwbbbbbwwbww.bwwwwww..", "....b.wb..bbbbbb..bbbbbb..bbbbw.wwbbbwwwwbbbbwwwbbbwwwwwbwwwwwww", ".bbbbbb.b.bbbb.bbbwwwwbbbbwwbwwbbbwbwbwb.wbwwwbbw.wwww.b...wbw..", ".wwwwww...wbbw..w.bwwbw..bbbwbwwbbbwbbwwbbwbbbbw.wbbbbbw..wbbbbw", "..wbbw...wwwwwbbbbwbwwwbbbbwbbwbbbbbbbwbbbbbbwbb..bbbb.b..bbbb..", "..wbbw..wwwbbbbbwwbbbbbbwwwbbbwbwwwbwwww.wbbwb.w.bbbbw...b.wwww.", "b..www...bwwwwwwbwbbbbwwbwbbbwbwbbbbbbbwbbbbbbbwb..bbbbw...w..bw", ".b.www....bbbb...wwbbb.wwwwwbwwwwwwbwbwwwwbbbwbwwwwbbbbw..wbbbbw", ".bbbbb...wwwwbbbwwwbwbb.bwbwwbbwbbwbwbbwbbbbbbww...bbbww....wbbw", "..bbbb.b..bwbbb.bbbbbbbbbbbbbbbbbbbbwbbbwbbbbbbb..bbbb...wwwwww.", ".wbw.....bbbwb..bwbwbw...wwwwwwbwwwwbwbbwwwwwbbbbwbwbbbb.bwwwwwb", ".wwwww....wbbw..bbbbbww.bbbwbww.bbbwwbwwbbbbwbww.wbbbbbw..bbbbbw", "wwwbbbbwbbbbbbbwwbwbwwww.wbwwwbwwwwwwbwwb.bbbwww...bbww......bw.", ".b.wwww...bbbw...wwbwb.wwwwwbbb.wwwbwbbbwwbbbwbbwwwbbbbb..wbbbbw", "..b.b.w.w.bbbb.b.bbbwbbbbbwbbwbbbwwwbwwbbwwwwbwbb.wwwwbb..wwww.b", ".wwwww...bbbbw.bbwbwwwbbbwwbwbbbbwbwbbb.wwwbwb.w.wwbbw...wwwwww.", "..bbbw...bbbbb..bwwbbbbbbbwwbbbbbwbbwwwwbbwbwwwwb.bwbww..b.wwww.", "..bbbbb.w.bbwb..wbbwbww.bbbbwww.bwwwwww.bwwwwwwwb.wwwww..bwwwwww", "..w.wb....wwwb.wbbwwwbwwbwwwbwwwbbbwwbwwwwwbwwbw..wwbbbb..wwwwww", "..bbbbbbw.bbbb.bwwbwbwwbwbwbwwwbwwbbwbwbwwwwwwbb...w.bwb....bbww", "...bw....bbwwb.bwwbwwbbbwwwbwbbb.wwbbbbbbwwbbbwb..wwwwwb.bwwwbbb", "..wbwwwbwbbbbwwbwbbbwbwbwwwwbwwbwbwbwbwbwwbwwwbbw..bww.b.....w..", "..bbw..w..bwwwbbwwbbwwwbwbbwwwwwwbwwwwwwwwwwwww.wbwww...wwwwww..", "..wwwww..bbbww.wbbbwwwwwbbbwwwbwbbwbwwwwbwbbbwwwbbbbbb..b.b...b.", ".bbbbbb...bbwb..wwbwbwwbwwwbwwwwwwwwbbwb.wwwbbw..wwbwww...bwwwwb", ".bbb..wwb.bwbwbbwbwbwwbbwbbwwwbwwbwwbw..wwwwwww.wbwww...wwwwww..", "..wwww....wwwwb.bbwwwbbwbwwwbwbwwwwwwwbbbbbwbwbw.bbbww..bwwwww..", ".bbbbbbb.bbw.wb.wbbwwbwbwbbbbw.wwbwbbww.wbbwwb..wbbbbbb..wwwww..", "wbbbwb...bbbbw..wbwwwwwbwwbwwwbbwwwwwbwbwwwbwwbb..wbww.b..wwww..", "..wbb...bbwbbb..bbbwwwbwbbwbbbbbbbbwbwbb.bbbwbbbwwbwbbb..wwbbw..", "bbbbbbb..bwwwb.w.wbbbbbw.wwbbwbw.wwwwbbw..wwbwbw...wbbbw.wwwwwww", "b.w..w.b.bwwwwww.bbwbbwwbbbbbwbwwbwwwwww..bbbbbw..bbbbbw..bbbbbw", ".bbbbb..b.bbbbw.bbwbbwb.bwwwbbbbbwwbwbbwbwbbbbb.bbbwww..bb...www", "wwwwwww..wbbbw.w.wwbbbbw.wbwbbbwwwwwbwwwb.wwbwbw..wwbbbw...wb.bw", ".bbbwww..bbwwwwwwbwwwwwwwwbbbwwwwbwbbbwwwwbbwbbbw.bbb.....bbw...", "wwwwwww..wbbbw.w.wwbbbbw.wbwbbbwwwwwbwwwb.wwbwbw..wwbbbw...wb.bw", "..w.wb..w.wwww...wbbwwbb.bwbbbwbwbbbbwwbwwwbbbbbw.bwbbbb.bbbbbwb", "..ww....w.www...wwwbbwbbwwbbbbwbwbwwbbwwbbwwwbbbb.bwwwbb.bbbbwwb", ".wwwww..b.wbbw..bwbwbbw.bbbwbwwwbbbbwwwwbbbbww.b.bbbbbw...wwwwww", "...wbb..bb.wbbb.bbbbwwwwbbbbbwwwbbwbwwww.wbwbwwww.bbbb...wwwwwww", "..wwww.bbbwwwwb.bbbwwbwwwbbbbwbbbbbbbww.bbbwbw.w.bbw.w...bbb.www", "w.wbbbbw.wbbbbb.bbwbbwb..bwwbwbwbbbwbbbwwbbbbbbw..bbbbb....wwww.", "..bb.b....bbbb.bwwwwwwbb.bwbwbbbbbbbbbbbbbbbbbwbb.wwwwwb..bwwwwb", "..wwwb..b.wwbb..bbbbwbbbbbbwbbbbbbwbwwbb.bwbwbwww.bbbbw...wbbbbw", "bbbbbw..bwwb.w..bbbwww..bbwwwww.bwwbwbw.bwbbwwbww.bbwbb..wwbbbbw", "..bbbbb.w.bbbb.bwbbbbbbbwbbbbbwbwbwbwww.b.wwwww..bwwww...bbbbbbb", "w.wbbbbw.wbbbbb.bbwbbwb..bwwbwbwbbbwbbbwwbbbbbbw..bbbbb....wwww.", "..wbbbbw..bwwwwwwbwbwbwwbbbwwwbww.wbwbww.wbwbwww..bbwww..bbbbw..", "..bbbb....bbbb..wwwwwbwbwwwwwwbbwwwbwwbbwwbwbwb.wbbbbbbw...bbbbw", ".bbbbbb.wwwwbw..wwwbwbw.wbwwwwb.wbbbbbbbwwwwwww.w.wbww....wbwwww", ".wwwwww...bbbb..b.bbwbbbwwbbwbb.bwbbwbb.bwwbbbb.wwwwbwb..bbbbbbb", /* some trivial positions: */ "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww..", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwb.", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwbw..", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwbww.", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwbw...", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwbwbw....", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbwbw...", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbwb...", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbwb..", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbwb.", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbwbbbbbbbwbbbbbwb.", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwbwwwwwwwbwwwwbbb.", }; #endregion public static void TrainOpeningBook() { Func<IEngine> tutorFunc = ()=> new MonkeyOthello.Engines.X.EdaxEngine { Timeout = 60, UpdateProgress = (r) => Console.WriteLine(r) }; var trainer = new Trainer(); trainer.Train(tutorFunc, 4); } public static void ValidateDeepLearningResult() { var engine = new MonkeyOthello.Engines.X.EdaxEngine { Timeout = 60, UpdateProgress = (r) => Console.WriteLine(r) }; var file = @"E:\projects\MonkeyOthello\tests\k-dl-32\knowledge\32-2017-03-25-02.k"; var lines = File.ReadAllLines(file); var correct = 0; var i = 0; foreach (var line in lines) { var sp = line.Split(','); var ownp = ulong.Parse(sp[0]); var oppp = ulong.Parse(sp[1]); var eval = int.Parse(sp[2]); var bb = new BitBoard(ownp, oppp); var r = engine.Search(bb, 16); if (eval >= 0 && r.Score >= 0 || eval < 0 && r.Score < 0) { correct++; } if ((i + 1) % 10 == 0) { Console.WriteLine("Correct " + correct + "/" + (i + 1) + ", " + Math.Round(((double)correct / (double)(i + 1) * 100), 2) + "%"); } i++; } } public static void Fight() { // EdaxEngine, MonkeyV2Engine, Pilot, DeepLearningEngine var engines = new IEngine[] { new DeepLearningEngine { Allied = new MonkeyOthello.Engines.X.EdaxEngine() }, new MonkeyOthello.Engines.X.EdaxEngine() }; IColosseum game = new Colosseum(); game.Fight(engines); } public static void TestEndGameEngine() { var board = new BitBoard(23502599851429632UL, 560695349311UL); Console.WriteLine(board.Draw("black")); var engine = new ZebraEngine(); var r = engine.Search(board, board.EmptyPiecesCount()); Console.WriteLine(r); } public static void TestEndGameSearch() { if (File.Exists("test-data.txt")) { testData = File.ReadAllLines("test-data.txt"); } var color = 'w'; var sw = new Stopwatch(); var engines = new IEngine[] { //new MCTSEngine(), //new MonkeyEngineV10(), //new MonkeyEngine(), new ZebraEngine(), new EdaxEngine(), //new AlphaBetaEngine(), }; Console.WriteLine(string.Join(" vs. ", engines.Select(c => c.Name))); var ts = new TimeSpan[engines.Length]; sw.Start(); var length = Math.Min(20, testData.Length);// 10;// = bds.Length; for (var i = 0; i < length; i++) { var board = BitBoard.Parse(testData[i], color == 'b'); int empties = board.EmptyPiecesCount(); var index = 0; while (index < engines.Length) { var r = engines[index].Search(board, empties); Console.WriteLine($"[{engines[index].Name}] r{index + 1}: {r}"); ts[index] += r.TimeSpan; index++; } Console.WriteLine(); } sw.Stop(); for (var i = 0; i < ts.Length; i++) { Console.WriteLine($"[{engines[i].Name}]total (exclude console's time): {ts[i]}"); } Console.WriteLine($"total: {sw.Elapsed}"); } public static void TestFlips() { var board = new BitBoard(9246146104748420220UL, 8659321588746490112UL); var moves = Rule.FindMoves(board); var empties = board.EmptyPieces.Indices(); var invalidMoves = empties.Except(moves); foreach (var im in invalidMoves) { var flipBits = Rule.FindFlips(board, im); Console.WriteLine(flipBits); } } public static void TestBitBoard() { var board1 = new BitBoard(9246146104748420220UL, 8659321588746490112UL); var board2 = new BitBoard(8659321588746490112UL, 9246146104748420220UL); var board3 = new BitBoard(9246146104748420220UL, 8659321588746490112UL); Console.WriteLine($"b1 hash: {board1.GetHashCode()}"); Console.WriteLine($"b2 hash: {board2.GetHashCode()}"); Console.WriteLine($"b1==b2? {board1 == board2}"); Console.WriteLine($"b1==b3? {board1 == board2}"); var dict = new Dictionary<BitBoard, int>(); dict.Add(board1, 1); dict.Add(board2, 2); dict.Add(board3, 3); } public static void TestV2IndexToV3Index() { int[] worst2best = new int[] { /*B2*/ 20 , 25 , 65 , 70 , /*B1*/ 11 , 16 , 19 , 26 , 64 , 71 , 74 , 79 , /*C2*/ 21 , 24 , 29 , 34 , 56 , 61 , 66 , 69 , /*D2*/ 22 , 23 , 38 , 43 , 47 , 52 , 67 , 68 , /*D3*/ 31 , 32 , 39 , 42 , 48 , 51 , 58 , 59 , /*D1*/ 13 , 14 , 37 , 44 , 46 , 53 , 76 , 77 , /*C3*/ 30 , 33 , 57 , 60 , /*C1*/ 12 , 15 , 28 , 35 , 55 , 62 , 75 , 78 , /*A1*/ 10 , 17 , 73 , 80 , /*D4*/ 40 , 41 , 49 , 50 }; var v3indexList = worst2best.Reverse().Select(V2IndexToV3Index).ToArray(); var t = string.Join(",", v3indexList); Console.WriteLine(t); var t2 = string.Join(",", v3indexList.Select(SquareToString)); Console.WriteLine(t2); } public static int V2IndexToV3Index(this int index) { var m = (index - 9) % 9 - 1; var n = (index - 9) / 9; return n * 8 + m; } public static string SquareToString(int square) { var m = square / 8; var n = square % 8; var y = m + 1; var x = Convert.ToChar(n + 65); return x.ToString() + y.ToString(); } public static void GenTestData() { var depth = 20; var rand = new Random(); var lines = new List<string>(); for (var i = 0; i < 10; i++) { var board = BitBoard.NewGame(); while (board.EmptyPiecesCount() > depth) { var moves = Rule.FindMoves(board); if (moves.Length == 0) { board = board.Switch(); moves = Rule.FindMoves(board); if (moves.Length == 0) { break; } } var index = rand.Next(0, moves.Length); var pos = moves[index]; board = Rule.MoveSwitch(board, pos); } if (board.EmptyPiecesCount() > depth) { continue; } var btext = board.Draw(); lines.Add(btext); Console.WriteLine(btext); } File.WriteAllLines("test-data.txt", lines); } public static void TestLinkedList() { var squareList = new LinkedList<int>(new[] { 5, 2, 0, 1, 3, 1, 4 }); Action<LinkedList<int>> printList = list => { Console.WriteLine(string.Join(",", list)); }; Console.WriteLine($"now: "); printList(squareList); for (var current = squareList.First; current != null; current = current.Next) { var next = current.Next; squareList.Remove(current); Console.WriteLine($"remove: {current.Value}"); printList(squareList); if (next == null) { squareList.AddLast(current); } else { squareList.AddBefore(next, current); } Console.WriteLine($"add: {current.Value}"); printList(squareList); //Console.WriteLine(current.Value); } } } }
using Foundation; using System; using System.Collections.Generic; using System.Threading.Tasks; using UIKit; using zsquared; namespace vitavol { public partial class VC_SCSiteOnDate : UIViewController { // We got here because the site coordinator wants to manage the calendar // for a site on a date. C_Global Global; C_VitaUser LoggedInUser; C_VitaSite SelectedSite; C_YMD SelectedDate; C_CalendarEntry SelectedCalendarEntry; public VC_SCSiteOnDate(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; Global = myAppDelegate.Global; LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); SelectedSite = Global.GetSiteFromSlugNoFetch(Global.SelectedSiteSlug); SelectedDate = Global.SelectedDate; SelectedCalendarEntry = SelectedSite.GetCalendarEntryForDate(SelectedDate); #if DEBUG if ((LoggedInUser == null) || (SelectedSite == null) || (SelectedDate == null) || (SelectedCalendarEntry == null) ) throw new ApplicationException("missing value(s)"); #endif L_SiteName.Text = SelectedSite.Name; L_Date.Text = Global.SelectedDate.ToString("mmm dd, yyyy"); B_SaveCalendarException.Enabled = CalendarOrShiftsAreDirty(SelectedCalendarEntry); SW_IsOpen.ValueChanged += (sender, e) => { SelectedCalendarEntry.Dirty = true; B_SaveCalendarException.Enabled = true; }; B_Back.TouchUpInside += async (sender, e) => { if (!SelectedCalendarEntry.Dirty) { PerformSegue("Segue_SCSiteOnDateToSCSiteCalendar", this); return; } C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox( this, "Save Changes?", "Changes have been made. Save them?", C_MessageBox.E_MessageBoxButtons.YesNo); if (mbres != C_MessageBox.E_MessageBoxResults.Yes) { PerformSegue("Segue_SCSiteOnDateToSCSiteCalendar", this); return; } EnableUI(false); AI_Busy.StartAnimating(); bool success = await UpdateCalendarAndShifts(); AI_Busy.StopAnimating(); EnableUI(true); if (success) PerformSegue("Segue_SCSiteOnDateToSCSiteCalendar", this); C_MessageBox.E_MessageBoxResults mbres1 = await C_MessageBox.MessageBox(this, "Error", "Unable to create the calendar entry.", C_MessageBox.E_MessageBoxButtons.Ok); }; B_SaveCalendarException.TouchUpInside += async (sender, e) => { AI_Busy.StartAnimating(); EnableUI(false); bool success = await UpdateCalendarAndShifts(); AI_Busy.StopAnimating(); EnableUI(true); if (!success) { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Error", "Unable to update the calendar entry.", C_MessageBox.E_MessageBoxButtons.Ok); return; } PerformSegue("Segue_SCSiteOnDateToSCSiteCalendar", this); }; SW_IsOpen.On = SelectedCalendarEntry.SiteIsOpen; AI_Busy.StartAnimating(); Task.Run(async () => { if (!SelectedCalendarEntry.HaveShifts) { List<C_WorkShift> shifts = await Global.FetchAllShiftsForCalendarEntry(LoggedInUser.Token, SelectedSite.Slug, SelectedCalendarEntry); } UIApplication.SharedApplication.InvokeOnMainThread( new Action(() => { AI_Busy.StopAnimating(); // setup the table view with the list of names C_ShiftsTableSource signUpTableSource = new C_ShiftsTableSource(SelectedCalendarEntry, Global, this, "Segue_SCSiteOnDateToShiftDetails"); TV_Shifts.Source = signUpTableSource; TV_Shifts.ReloadData(); })); }); } private async Task<bool> UpdateCalendarAndShifts() { bool success = true; try { SelectedCalendarEntry.SiteIsOpen = SW_IsOpen.On; // update the entry if (SelectedCalendarEntry.Dirty) { C_IOResult ior1 = await Global.UpdateCalendarEntry(SelectedSite, LoggedInUser.Token, SelectedCalendarEntry); success &= ior1.Success; } if (success) { // now update all of the shifts foreach (C_WorkShift ws in SelectedCalendarEntry.WorkShifts) { if (ws.Dirty) { C_IOResult ior2 = await Global.UpdateShift(LoggedInUser.Token, SelectedSite.Slug, ws, SelectedCalendarEntry); success &= ior2.Success; if (!success) break; } } } // if we have already pre-fetched the site schedule for the site, we need to adjust // the choice for now is to simple remove from the cache and force a re-fetch Global.RemoveSiteFromSiteCache(SelectedSite.Slug); } catch (Exception e) { Console.WriteLine(e.Message); success = false; } return success; } public override void ViewDidAppear(bool animated) { // set the standard background color View.BackgroundColor = C_Common.StandardBackground; } private bool CalendarOrShiftsAreDirty(C_CalendarEntry calEntry) { bool res = calEntry.Dirty; foreach (C_WorkShift ws in calEntry.WorkShifts) res |= ws.Dirty; return res; } private void EnableUI(bool en) { B_Back.Enabled = en; B_SaveCalendarException.Enabled = en && CalendarOrShiftsAreDirty(SelectedCalendarEntry); SW_IsOpen.Enabled = en; TV_Shifts.UserInteractionEnabled = en; } } }
// 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. // Author: api.anash@gmail.com (Anash P. Oommen) using System; using System.IO; using System.Net; using System.Text; using System.Threading; namespace Google.Api.Ads.Common.Util.Reports { /// <summary> /// Represents a report response from the server. /// </summary> public class ReportResponse : IDisposable { /// <summary> /// The report contents in memory. /// </summary> private byte[] contents; /// <summary> /// The underlying HTTP web response. /// </summary> private WebResponse response; /// <summary> /// Flag to keep track if this report response has been disposed. /// </summary> private bool disposed = false; /// <summary> /// Delegate to be triggered when asynchronous report download is completed /// successfully. /// </summary> public delegate void OnDownloadSuccessCallback(byte[] contents); /// <summary> /// Delegate to be triggered when asynchronous report save is completed /// successfully. /// </summary> public delegate void OnSaveSuccessCallback(); /// <summary> /// Delegate to be triggered when asynchronous report download fails. /// </summary> public delegate void OnFailedCallback(AdsReportsException exception); /// <summary> /// Initializes a new instance of the <see cref="ReportResponse"/> class. /// </summary> /// <param name="response">The underlying HTTP web response.</param> public ReportResponse(WebResponse response) { if (response == null) { throw new ArgumentNullException("Response cannot be null."); } this.response = response; } /// <summary> /// The callback that will be triggered when the asynchronous report /// download is completed successfully. /// </summary> public OnDownloadSuccessCallback OnDownloadSuccess { get; set; } /// <summary> /// The callback that will be triggered when the asynchronous report /// save is completed successfully. /// </summary> public OnSaveSuccessCallback OnSaveSuccess { get; set; } /// <summary> /// Gets the callback that will be triggered when the asynchronous report /// download fails. /// </summary> public OnFailedCallback OnFailed { get; set; } /// <summary> /// Gets the report contents as a stream. /// </summary> public Stream Stream { get { this.EnsureStreamIsOpen(); return response.GetResponseStream(); } } /// <summary> /// Gets the path to the downloaded report. /// </summary> public string Path { get; private set; } /// <summary> /// Saves the report to a specified path and closes the underlying stream. /// </summary> /// <param name="path">The path to which report is saved.</param> /// <exception cref="AdsReportsException">If there was an error saving the report.</exception> public void Save(string path) { this.EnsureStreamIsOpen(); try { using (FileStream fileStream = File.OpenWrite(path)) { fileStream.SetLength(0); MediaUtilities.CopyStream(this.Stream, fileStream); this.CloseWebResponse(); } this.Path = path; } catch (Exception e) { throw new AdsReportsException("Failed to save report. See inner exception " + "for more details.", e); } } /// <summary> /// Saves the report to a specified path asynchronously and closes the underlying stream. /// <see cref="OnSaveSuccess"/> callback will be triggered when the download completes /// successfully, and <see cref="OnFailed"/> callback will be triggered when the download /// fails. /// </summary> /// <param name="path">The path to which report is saved.</param> /// <exception cref="AdsReportsException">If there was an error saving the report.</exception> public void SaveAsync(string path) { Thread asyncThread = new Thread(new ThreadStart(delegate() { try { Save(path); if (this.OnSaveSuccess != null) { this.OnSaveSuccess(); } } catch (AdsReportsException e) { if (this.OnFailed != null) { this.OnFailed(e); } else { throw; } } })); asyncThread.Start(); } /// <summary> /// Downloads the report to memory and closes the underlying stream. /// </summary> /// <exception cref="AdsReportsException">If there was an error downloading the report. /// </exception> public byte[] Download() { this.EnsureStreamIsOpen(); try { MemoryStream memStream = new MemoryStream(); MediaUtilities.CopyStream(this.Stream, memStream); this.contents = memStream.ToArray(); this.CloseWebResponse(); } catch (Exception e) { throw new AdsReportsException("Failed to download report. See inner exception " + "for more details.", e); } return this.contents; } /// <summary> /// Downloads the report to memory asynchronously and closes the underlying stream. /// <see cref="OnDownloadSuccess"/> callback will be triggered when the download completes /// successfully, and <see cref="OnFailed"/> callback will be triggered when the download /// fails. /// </summary> /// <exception cref="AdsReportsException">If there was an error downloading the report. /// </exception> public void DownloadAsync() { Thread asyncThread = new Thread(new ThreadStart(delegate() { try { byte[] contents = Download(); if (this.OnDownloadSuccess != null) { this.OnDownloadSuccess(contents); } } catch (AdsReportsException e) { if (this.OnFailed != null) { this.OnFailed(e); } else { throw; } } })); asyncThread.Start(); } /// <summary> /// Checks to ensure that the underlying stream has not been closed. /// </summary> /// <exception cref="AdsReportsException">If the underlying stream has been closed. /// </exception> private void EnsureStreamIsOpen() { if (response == null) { throw new AdsReportsException("Cannot access a closed report response stream."); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, /// or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and /// unmanaged resources; <c>false</c> to release only unmanaged resources. /// </param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { this.CloseWebResponse(); } disposed = true; } } /// <summary> /// Closes the underlying HTTP web response. /// </summary> private void CloseWebResponse() { if (response != null) { response.Close(); response = null; } } /// <summary> /// Finalizes an instance of the <see cref="ReportResponse"/> class. /// </summary> ~ReportResponse() { this.Dispose(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; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableDivideTests { #region Test methods [Fact] public static void CheckNullableByteDivideTest() { byte?[] array = new byte?[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteDivide(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteDivideTest() { sbyte?[] array = new sbyte?[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteDivide(array[i], array[j]); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortDivideTest(bool useInterpreter) { ushort?[] array = new ushort?[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortDivideTest(bool useInterpreter) { short?[] array = new short?[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntDivideTest(bool useInterpreter) { uint?[] array = new uint?[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntDivideTest(bool useInterpreter) { int?[] array = new int?[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongDivideTest(bool useInterpreter) { ulong?[] array = new ulong?[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongDivideTest(bool useInterpreter) { long?[] array = new long?[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatDivideTest(bool useInterpreter) { float?[] array = new float?[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleDivideTest(bool useInterpreter) { double?[] array = new double?[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalDivideTest(bool useInterpreter) { decimal?[] array = new decimal?[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalDivide(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckNullableCharDivideTest() { char?[] array = new char?[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharDivide(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteDivide(byte? a, byte? b) { Expression aExp = Expression.Constant(a, typeof(byte?)); Expression bExp = Expression.Constant(b, typeof(byte?)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } private static void VerifyNullableSByteDivide(sbyte? a, sbyte? b) { Expression aExp = Expression.Constant(a, typeof(sbyte?)); Expression bExp = Expression.Constant(b, typeof(sbyte?)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } private static void VerifyNullableUShortDivide(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Divide( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort)(a / b), f()); } private static void VerifyNullableShortDivide(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Divide( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((short)(a / b), f()); } private static void VerifyNullableUIntDivide(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Divide( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyNullableIntDivide(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Divide( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyNullableULongDivide(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Divide( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyNullableLongDivide(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Divide( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyNullableFloatDivide(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Divide( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyNullableDoubleDivide(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Divide( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyNullableDecimalDivide(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Divide( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyNullableCharDivide(char? a, char? b) { Expression aExp = Expression.Constant(a, typeof(char?)); Expression bExp = Expression.Constant(b, typeof(char?)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } #endregion } }
using System.Collections.Generic; using Content.Shared.ActionBlocker; using Content.Shared.CCVar; using Content.Shared.Friction; using Content.Shared.MobState.Components; using Content.Shared.Movement.Components; using Content.Shared.Pulling.Components; using JetBrains.Annotations; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Physics.Controllers; using Robust.Shared.Utility; namespace Content.Shared.Movement { /// <summary> /// Handles player and NPC mob movement. /// NPCs are handled server-side only. /// </summary> public abstract class SharedMoverController : VirtualController { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private ActionBlockerSystem _blocker = default!; [Dependency] private readonly SharedPhysicsSystem _physics = default!; private bool _relativeMovement; /// <summary> /// Cache the mob movement calculation to re-use elsewhere. /// </summary> public Dictionary<EntityUid, bool> UsedMobMovement = new(); public override void Initialize() { base.Initialize(); var configManager = IoCManager.Resolve<IConfigurationManager>(); configManager.OnValueChanged(CCVars.RelativeMovement, SetRelativeMovement, true); UpdatesBefore.Add(typeof(SharedTileFrictionController)); } private void SetRelativeMovement(bool value) => _relativeMovement = value; public override void Shutdown() { base.Shutdown(); var configManager = IoCManager.Resolve<IConfigurationManager>(); configManager.UnsubValueChanged(CCVars.RelativeMovement, SetRelativeMovement); } public override void UpdateAfterSolve(bool prediction, float frameTime) { base.UpdateAfterSolve(prediction, frameTime); UsedMobMovement.Clear(); } protected Angle GetParentGridAngle(TransformComponent xform, IMoverComponent mover) { if (xform.GridID == GridId.Invalid || !_mapManager.TryGetGrid(xform.GridID, out var grid)) return mover.LastGridAngle; return grid.WorldRotation; } /// <summary> /// A generic kinematic mover for entities. /// </summary> protected void HandleKinematicMovement(IMoverComponent mover, PhysicsComponent physicsComponent) { var (walkDir, sprintDir) = mover.VelocityDir; var transform = EntityManager.GetComponent<TransformComponent>(mover.Owner); var parentRotation = GetParentGridAngle(transform, mover); // Regular movement. // Target velocity. var total = walkDir * mover.CurrentWalkSpeed + sprintDir * mover.CurrentSprintSpeed; var worldTotal = _relativeMovement ? parentRotation.RotateVec(total) : total; if (transform.GridID != GridId.Invalid) mover.LastGridAngle = parentRotation; if (worldTotal != Vector2.Zero) transform.LocalRotation = transform.GridID != GridId.Invalid ? total.ToWorldAngle() : worldTotal.ToWorldAngle(); _physics.SetLinearVelocity(physicsComponent, worldTotal); } /// <summary> /// Movement while considering actionblockers, weightlessness, etc. /// </summary> protected void HandleMobMovement( IMoverComponent mover, PhysicsComponent physicsComponent, IMobMoverComponent mobMover, TransformComponent xform) { DebugTools.Assert(!UsedMobMovement.ContainsKey(mover.Owner)); if (!UseMobMovement(physicsComponent)) { UsedMobMovement[mover.Owner] = false; return; } UsedMobMovement[mover.Owner] = true; var weightless = mover.Owner.IsWeightless(physicsComponent, mapManager: _mapManager, entityManager: EntityManager); var (walkDir, sprintDir) = mover.VelocityDir; // Handle wall-pushes. if (weightless) { // No gravity: is our entity touching anything? var touching = IsAroundCollider(_physics, xform, mobMover, physicsComponent); if (!touching) { if (xform.GridID != GridId.Invalid) mover.LastGridAngle = GetParentGridAngle(xform, mover); xform.WorldRotation = physicsComponent.LinearVelocity.GetDir().ToAngle(); return; } } // Regular movement. // Target velocity. // This is relative to the map / grid we're on. var total = walkDir * mover.CurrentWalkSpeed + sprintDir * mover.CurrentSprintSpeed; var parentRotation = GetParentGridAngle(xform, mover); var worldTotal = _relativeMovement ? parentRotation.RotateVec(total) : total; DebugTools.Assert(MathHelper.CloseToPercent(total.Length, worldTotal.Length)); if (weightless) worldTotal *= mobMover.WeightlessStrength; if (xform.GridID != GridId.Invalid) mover.LastGridAngle = parentRotation; if (worldTotal != Vector2.Zero) { // This should have its event run during island solver soooo xform.DeferUpdates = true; xform.LocalRotation = xform.GridID != GridId.Invalid ? total.ToWorldAngle() : worldTotal.ToWorldAngle(); xform.DeferUpdates = false; HandleFootsteps(mover, mobMover); } _physics.SetLinearVelocity(physicsComponent, worldTotal); } public bool UseMobMovement(EntityUid uid) { return UsedMobMovement.TryGetValue(uid, out var used) && used; } protected bool UseMobMovement(PhysicsComponent body) { return body.BodyStatus == BodyStatus.OnGround && EntityManager.HasComponent<MobStateComponent>(body.Owner) && // If we're being pulled then don't mess with our velocity. (!EntityManager.TryGetComponent(body.Owner, out SharedPullableComponent? pullable) || !pullable.BeingPulled) && _blocker.CanMove((body).Owner); } /// <summary> /// Used for weightlessness to determine if we are near a wall. /// </summary> public static bool IsAroundCollider(SharedPhysicsSystem broadPhaseSystem, TransformComponent transform, IMobMoverComponent mover, IPhysBody collider) { var enlargedAABB = collider.GetWorldAABB().Enlarged(mover.GrabRange); foreach (var otherCollider in broadPhaseSystem.GetCollidingEntities(transform.MapID, enlargedAABB)) { if (otherCollider == collider) continue; // Don't try to push off of yourself! // Only allow pushing off of anchored things that have collision. if (otherCollider.BodyType != BodyType.Static || !otherCollider.CanCollide || ((collider.CollisionMask & otherCollider.CollisionLayer) == 0 && (otherCollider.CollisionMask & collider.CollisionLayer) == 0) || (IoCManager.Resolve<IEntityManager>().TryGetComponent(otherCollider.Owner, out SharedPullableComponent? pullable) && pullable.BeingPulled)) { continue; } return true; } return false; } // TODO: Need a predicted client version that only plays for our own entity and then have server-side ignore our session (for that entity only) protected virtual void HandleFootsteps(IMoverComponent mover, IMobMoverComponent mobMover) {} } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactories; using Microsoft.Azure.Management.DataFactories.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories { /// <summary> /// Operations for managing data slice runs. /// </summary> internal partial class DataSliceRunOperations : IServiceOperations<DataPipelineManagementClient>, IDataSliceRunOperations { /// <summary> /// Initializes a new instance of the DataSliceRunOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DataSliceRunOperations(DataPipelineManagementClient client) { this._client = client; } private DataPipelineManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.DataPipelineManagementClient. /// </summary> public DataPipelineManagementClient Client { get { return this._client; } } /// <summary> /// Gets logs for a data slice run /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='dataSliceRunId'> /// Required. A unique data slice run instance id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The data slice run get logs operation response. /// </returns> public async Task<DataSliceRunGetLogsResponse> GetLogsAsync(string resourceGroupName, string dataFactoryName, string dataSliceRunId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataSliceRunId == null) { throw new ArgumentNullException("dataSliceRunId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("dataSliceRunId", dataSliceRunId); Tracing.Enter(invocationId, this, "GetLogsAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/runs/" + dataSliceRunId.Trim() + "/logInfo?"; url = url + "api-version=2014-10-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DataSliceRunGetLogsResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSliceRunGetLogsResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Uri dataSliceRunLogsSASUriInstance = TypeConversion.TryParseUri(((string)responseDoc)); result.DataSliceRunLogsSASUri = dataSliceRunLogsSASUriInstance; } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the first page of data slice run instances with the link to /// the next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='dataSliceStartTime'> /// Required. The start time of the data slice queried in round-trip /// ISO 8601 format. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data slice runs operation response. /// </returns> public async Task<DataSliceRunListResponse> ListAsync(string resourceGroupName, string dataFactoryName, string tableName, string dataSliceStartTime, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (dataSliceStartTime == null) { throw new ArgumentNullException("dataSliceStartTime"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("dataSliceStartTime", dataSliceStartTime); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/tables/" + tableName.Trim() + "/sliceruns?"; url = url + "startTime=" + Uri.EscapeDataString(dataSliceStartTime.Trim()); url = url + "&api-version=2014-10-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DataSliceRunListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSliceRunListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataSliceRun dataSliceRunInstance = new DataSliceRun(); result.DataSliceRuns.Add(dataSliceRunInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataSliceRunInstance.Id = idInstance; } JToken tableNameValue = valueValue["tableName"]; if (tableNameValue != null && tableNameValue.Type != JTokenType.Null) { string tableNameInstance = ((string)tableNameValue); dataSliceRunInstance.TableName = tableNameInstance; } JToken pipelineNameValue = valueValue["pipelineName"]; if (pipelineNameValue != null && pipelineNameValue.Type != JTokenType.Null) { string pipelineNameInstance = ((string)pipelineNameValue); dataSliceRunInstance.PipelineName = pipelineNameInstance; } JToken activityNameValue = valueValue["activityName"]; if (activityNameValue != null && activityNameValue.Type != JTokenType.Null) { string activityNameInstance = ((string)activityNameValue); dataSliceRunInstance.ActivityName = activityNameInstance; } JToken computeClusterNameValue = valueValue["computeClusterName"]; if (computeClusterNameValue != null && computeClusterNameValue.Type != JTokenType.Null) { string computeClusterNameInstance = ((string)computeClusterNameValue); dataSliceRunInstance.ComputeClusterName = computeClusterNameInstance; } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dataSliceRunInstance.Status = statusInstance; } JToken processingStartTimeValue = valueValue["processingStartTime"]; if (processingStartTimeValue != null && processingStartTimeValue.Type != JTokenType.Null) { DateTime processingStartTimeInstance = ((DateTime)processingStartTimeValue); dataSliceRunInstance.ProcessingStartTime = processingStartTimeInstance; } JToken processingEndTimeValue = valueValue["processingEndTime"]; if (processingEndTimeValue != null && processingEndTimeValue.Type != JTokenType.Null) { DateTime processingEndTimeInstance = ((DateTime)processingEndTimeValue); dataSliceRunInstance.ProcessingEndTime = processingEndTimeInstance; } JToken batchTimeValue = valueValue["batchTime"]; if (batchTimeValue != null && batchTimeValue.Type != JTokenType.Null) { DateTime batchTimeInstance = ((DateTime)batchTimeValue); dataSliceRunInstance.BatchTime = batchTimeInstance; } JToken percentCompleteValue = valueValue["percentComplete"]; if (percentCompleteValue != null && percentCompleteValue.Type != JTokenType.Null) { int percentCompleteInstance = ((int)percentCompleteValue); dataSliceRunInstance.PercentComplete = percentCompleteInstance; } JToken dataSliceStartValue = valueValue["dataSliceStart"]; if (dataSliceStartValue != null && dataSliceStartValue.Type != JTokenType.Null) { DateTime dataSliceStartInstance = ((DateTime)dataSliceStartValue); dataSliceRunInstance.DataSliceStart = dataSliceStartInstance; } JToken dataSliceEndValue = valueValue["dataSliceEnd"]; if (dataSliceEndValue != null && dataSliceEndValue.Type != JTokenType.Null) { DateTime dataSliceEndInstance = ((DateTime)dataSliceEndValue); dataSliceRunInstance.DataSliceEnd = dataSliceEndInstance; } JToken timestampValue = valueValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); dataSliceRunInstance.Timestamp = timestampInstance; } JToken retryAttemptValue = valueValue["retryAttempt"]; if (retryAttemptValue != null && retryAttemptValue.Type != JTokenType.Null) { int retryAttemptInstance = ((int)retryAttemptValue); dataSliceRunInstance.RetryAttempt = retryAttemptInstance; } JToken hasLogsValue = valueValue["hasLogs"]; if (hasLogsValue != null && hasLogsValue.Type != JTokenType.Null) { bool hasLogsInstance = ((bool)hasLogsValue); dataSliceRunInstance.HasLogs = hasLogsInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dataSliceRunInstance.Type = typeInstance; } JToken propertiesSequenceElement = ((JToken)valueValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); dataSliceRunInstance.Properties.Add(propertiesKey, propertiesValue); } } JToken errorMessageValue = valueValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); dataSliceRunInstance.ErrorMessage = errorMessageInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the next page of run instances with the link to the next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next data slice runs page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data slice runs operation response. /// </returns> public async Task<DataSliceRunListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); Tracing.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = nextLink.Trim(); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DataSliceRunListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSliceRunListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataSliceRun dataSliceRunInstance = new DataSliceRun(); result.DataSliceRuns.Add(dataSliceRunInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataSliceRunInstance.Id = idInstance; } JToken tableNameValue = valueValue["tableName"]; if (tableNameValue != null && tableNameValue.Type != JTokenType.Null) { string tableNameInstance = ((string)tableNameValue); dataSliceRunInstance.TableName = tableNameInstance; } JToken pipelineNameValue = valueValue["pipelineName"]; if (pipelineNameValue != null && pipelineNameValue.Type != JTokenType.Null) { string pipelineNameInstance = ((string)pipelineNameValue); dataSliceRunInstance.PipelineName = pipelineNameInstance; } JToken activityNameValue = valueValue["activityName"]; if (activityNameValue != null && activityNameValue.Type != JTokenType.Null) { string activityNameInstance = ((string)activityNameValue); dataSliceRunInstance.ActivityName = activityNameInstance; } JToken computeClusterNameValue = valueValue["computeClusterName"]; if (computeClusterNameValue != null && computeClusterNameValue.Type != JTokenType.Null) { string computeClusterNameInstance = ((string)computeClusterNameValue); dataSliceRunInstance.ComputeClusterName = computeClusterNameInstance; } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dataSliceRunInstance.Status = statusInstance; } JToken processingStartTimeValue = valueValue["processingStartTime"]; if (processingStartTimeValue != null && processingStartTimeValue.Type != JTokenType.Null) { DateTime processingStartTimeInstance = ((DateTime)processingStartTimeValue); dataSliceRunInstance.ProcessingStartTime = processingStartTimeInstance; } JToken processingEndTimeValue = valueValue["processingEndTime"]; if (processingEndTimeValue != null && processingEndTimeValue.Type != JTokenType.Null) { DateTime processingEndTimeInstance = ((DateTime)processingEndTimeValue); dataSliceRunInstance.ProcessingEndTime = processingEndTimeInstance; } JToken batchTimeValue = valueValue["batchTime"]; if (batchTimeValue != null && batchTimeValue.Type != JTokenType.Null) { DateTime batchTimeInstance = ((DateTime)batchTimeValue); dataSliceRunInstance.BatchTime = batchTimeInstance; } JToken percentCompleteValue = valueValue["percentComplete"]; if (percentCompleteValue != null && percentCompleteValue.Type != JTokenType.Null) { int percentCompleteInstance = ((int)percentCompleteValue); dataSliceRunInstance.PercentComplete = percentCompleteInstance; } JToken dataSliceStartValue = valueValue["dataSliceStart"]; if (dataSliceStartValue != null && dataSliceStartValue.Type != JTokenType.Null) { DateTime dataSliceStartInstance = ((DateTime)dataSliceStartValue); dataSliceRunInstance.DataSliceStart = dataSliceStartInstance; } JToken dataSliceEndValue = valueValue["dataSliceEnd"]; if (dataSliceEndValue != null && dataSliceEndValue.Type != JTokenType.Null) { DateTime dataSliceEndInstance = ((DateTime)dataSliceEndValue); dataSliceRunInstance.DataSliceEnd = dataSliceEndInstance; } JToken timestampValue = valueValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); dataSliceRunInstance.Timestamp = timestampInstance; } JToken retryAttemptValue = valueValue["retryAttempt"]; if (retryAttemptValue != null && retryAttemptValue.Type != JTokenType.Null) { int retryAttemptInstance = ((int)retryAttemptValue); dataSliceRunInstance.RetryAttempt = retryAttemptInstance; } JToken hasLogsValue = valueValue["hasLogs"]; if (hasLogsValue != null && hasLogsValue.Type != JTokenType.Null) { bool hasLogsInstance = ((bool)hasLogsValue); dataSliceRunInstance.HasLogs = hasLogsInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dataSliceRunInstance.Type = typeInstance; } JToken propertiesSequenceElement = ((JToken)valueValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); dataSliceRunInstance.Properties.Add(propertiesKey, propertiesValue); } } JToken errorMessageValue = valueValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); dataSliceRunInstance.ErrorMessage = errorMessageInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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.Runtime.InteropServices; using System.Runtime.Serialization; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Security; using System.Globalization; namespace System.Reflection { internal class RuntimeModule : Module { internal RuntimeModule() { throw new NotSupportedException(); } #region FCalls [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private extern static void GetType(RuntimeModule module, String className, bool throwOnError, bool ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); [DllImport(JitHelpers.QCall)] private static extern bool nIsTransientInternal(RuntimeModule module); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static RuntimeType[] GetTypes(RuntimeModule module); internal RuntimeType[] GetDefinedTypes() { return GetTypes(GetNativeHandle()); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool IsResource(RuntimeModule module); #endregion #region Module overrides private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments) { if (genericArguments == null) return null; int size = genericArguments.Length; RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size]; for (int i = 0; i < size; i++) { Type typeArg = genericArguments[i]; if (typeArg == null) throw new ArgumentException(SR.Argument_InvalidGenericInstArray); typeArg = typeArg.UnderlyingSystemType; if (typeArg == null) throw new ArgumentException(SR.Argument_InvalidGenericInstArray); if (!(typeArg is RuntimeType)) throw new ArgumentException(SR.Argument_InvalidGenericInstArray); typeHandleArgs[i] = typeArg.GetTypeHandleInternal(); } return typeHandleArgs; } public override byte[] ResolveSignature(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef) throw new ArgumentException(SR.Format(SR.Argument_InvalidToken, tk, this), nameof(metadataToken)); ConstArray signature; if (tk.IsMemberRef) signature = MetadataImport.GetMemberRefProps(metadataToken); else signature = MetadataImport.GetSignatureFromToken(metadataToken); byte[] sig = new byte[signature.Length]; for (int i = 0; i < signature.Length; i++) sig[i] = signature[i]; return sig; } public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { if (!tk.IsMethodDef && !tk.IsMethodSpec) { if (!tk.IsMemberRef) throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, tk, this), nameof(metadataToken)); unsafe { ConstArray sig = MetadataImport.GetMemberRefProps(tk); if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, tk, this), nameof(metadataToken)); } } IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle); if (declaringType.IsGenericType || declaringType.IsArray) { MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk)); if (tk.IsMethodSpec) tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType)); declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); } return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle); } catch (BadImageFormatException e) { throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e); } } private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef) throw new ArgumentOutOfRangeException(nameof(metadataToken), String.Format(CultureInfo.CurrentUICulture, SR.Format(SR.Argument_InvalidToken, tk, this))); int tkDeclaringType; string fieldName; fieldName = MetadataImport.GetName(tk).ToString(); tkDeclaringType = MetadataImport.GetParentToken(tk); Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); declaringType.GetFields(); try { return declaringType.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); } catch { throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this), nameof(metadataToken)); } } public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { IRuntimeFieldInfo fieldHandle = null; if (!tk.IsFieldDef) { if (!tk.IsMemberRef) throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this), nameof(metadataToken)); unsafe { ConstArray sig = MetadataImport.GetMemberRefProps(tk); if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field) throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this), nameof(metadataToken)); } fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); } fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs); RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value); if (declaringType.IsGenericType || declaringType.IsArray) { int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken); declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); } return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle); } catch (MissingFieldException) { return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments); } catch (BadImageFormatException e) { throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e); } } public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (tk.IsGlobalTypeDefToken) throw new ArgumentException(SR.Format(SR.Argument_ResolveModuleType, tk), nameof(metadataToken)); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef) throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { Type t = GetModuleHandleImpl().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType(); if (t == null) throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken)); return t; } catch (BadImageFormatException e) { throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e); } } public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (tk.IsProperty) throw new ArgumentException(SR.InvalidOperation_PropertyInfoNotAvailable); if (tk.IsEvent) throw new ArgumentException(SR.InvalidOperation_EventInfoNotAvailable); if (tk.IsMethodSpec || tk.IsMethodDef) return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsFieldDef) return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec) return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsMemberRef) { if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); ConstArray sig = MetadataImport.GetMemberRefProps(tk); unsafe { if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) { return ResolveField(tk, genericTypeArguments, genericMethodArguments); } else { return ResolveMethod(tk, genericTypeArguments, genericMethodArguments); } } } throw new ArgumentException(SR.Format(SR.Argument_ResolveMember, tk, this), nameof(metadataToken)); } public override string ResolveString(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); if (!tk.IsString) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, SR.Argument_ResolveString, metadataToken, ToString())); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException(nameof(metadataToken), String.Format(CultureInfo.CurrentUICulture, SR.Format(SR.Argument_InvalidToken, tk, this))); string str = MetadataImport.GetUserString(metadataToken); if (str == null) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, SR.Argument_ResolveString, metadataToken, ToString())); return str; } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine); } public override int MDStreamVersion { get { return ModuleHandle.GetMDStreamVersion(GetNativeHandle()); } } #endregion #region Data Members #pragma warning disable 169 // If you add any data members, you need to update the native declaration ReflectModuleBaseObject. private RuntimeType m_runtimeType; private RuntimeAssembly m_runtimeAssembly; private IntPtr m_pRefClass; private IntPtr m_pData; private IntPtr m_pGlobals; private IntPtr m_pFields; #pragma warning restore 169 #endregion #region Protected Virtuals protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (RuntimeType == null) return null; if (types == null) { return RuntimeType.GetMethod(name, bindingAttr); } else { return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } } #endregion #region Internal Members internal RuntimeType RuntimeType { get { if (m_runtimeType == null) m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle()); return m_runtimeType; } } internal bool IsTransientInternal() { return RuntimeModule.nIsTransientInternal(this.GetNativeHandle()); } internal MetadataImport MetadataImport { get { unsafe { return ModuleHandle.GetMetadataImport(GetNativeHandle()); } } } #endregion #region ICustomAttributeProvider Members public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region Public Virtuals public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override Type GetType(String className, bool throwOnError, bool ignoreCase) { // throw on null strings regardless of the value of "throwOnError" if (className == null) throw new ArgumentNullException(nameof(className)); RuntimeType retType = null; Object keepAlive = null; GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); GC.KeepAlive(keepAlive); return retType; } internal string GetFullyQualifiedName() { String fullyQualifiedName = null; GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName)); return fullyQualifiedName; } public override String FullyQualifiedName { get { return GetFullyQualifiedName(); } } public override Type[] GetTypes() { return GetTypes(GetNativeHandle()); } #endregion #region Public Members public override Guid ModuleVersionId { get { unsafe { Guid mvid; MetadataImport.GetScopeProps(out mvid); return mvid; } } } public override int MetadataToken { get { return ModuleHandle.GetToken(GetNativeHandle()); } } public override bool IsResource() { return IsResource(GetNativeHandle()); } public override FieldInfo[] GetFields(BindingFlags bindingFlags) { if (RuntimeType == null) return new FieldInfo[0]; return RuntimeType.GetFields(bindingFlags); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException(nameof(name)); if (RuntimeType == null) return null; return RuntimeType.GetField(name, bindingAttr); } public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { if (RuntimeType == null) return new MethodInfo[0]; return RuntimeType.GetMethods(bindingFlags); } public override String ScopeName { get { string scopeName = null; GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName)); return scopeName; } } public override String Name { get { String s = GetFullyQualifiedName(); #if !FEATURE_PAL int i = s.LastIndexOf('\\'); #else int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar); #endif if (i == -1) return s; return s.Substring(i + 1); } } public override Assembly Assembly { get { return GetRuntimeAssembly(); } } internal RuntimeAssembly GetRuntimeAssembly() { return m_runtimeAssembly; } protected override ModuleHandle GetModuleHandleImpl() { return new ModuleHandle(this); } internal RuntimeModule GetNativeHandle() { return this; } #endregion } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Perception\AISense_Hearing.h:64 namespace UnrealEngine { [ManageType("ManageAISense_Hearing")] public partial class ManageAISense_Hearing : UAISense_Hearing, IManageWrapper { public ManageAISense_Hearing(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_RegisterMakeNoiseDelegate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_CleanseInvalidSources(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UAISense_Hearing_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods protected override void RegisterMakeNoiseDelegate() => E__Supper__UAISense_Hearing_RegisterMakeNoiseDelegate(this); public override void CleanseInvalidSources() => E__Supper__UAISense_Hearing_CleanseInvalidSources(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UAISense_Hearing_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UAISense_Hearing_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UAISense_Hearing_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UAISense_Hearing_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UAISense_Hearing_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UAISense_Hearing_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UAISense_Hearing_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UAISense_Hearing_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UAISense_Hearing_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UAISense_Hearing_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UAISense_Hearing_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UAISense_Hearing_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UAISense_Hearing_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UAISense_Hearing_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UAISense_Hearing_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageAISense_Hearing self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageAISense_Hearing(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageAISense_Hearing>(PtrDesc); } } }
// 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 Xunit; namespace System.Data.SqlClient.Tests { public class ExceptionTest { // test connection string private string connectionString = "server=tcp:server,1432;database=test;uid=admin;pwd=SQLDB;connect timeout=60;"; // data value and server consts private const string badServer = "NotAServer"; private const string sqlsvrBadConn = "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."; private const string execReaderFailedMessage = "ExecuteReader requires an open and available Connection. The connection's current state is closed."; private const string orderIdQuery = "select orderid from orders where orderid < 10250"; [Fact] public void ExceptionTests() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); // tests improper server name thrown from constructor of tdsparser SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), sqlsvrBadConn, VerifyException); } [Fact] public void VariousExceptionTests() { // Test exceptions - makes sure they are only thrown from upper layers SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { using (SqlCommand command = sqlConnection.CreateCommand()) { command.CommandText = orderIdQuery; VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage); } } } [Fact] public void IndependentConnectionExceptionTestOpenConnection() { // Test exceptions for existing connection to ensure proper exception and call stack SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), sqlsvrBadConn, VerifyException); } } [Fact] public void IndependentConnectionExceptionTestExecuteReader() { // Test exceptions for existing connection to ensure proper exception and call stack SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { using (SqlCommand command = new SqlCommand(orderIdQuery, sqlConnection)) { VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage); } } } [Theory] [InlineData(@"np:\\.\pipe\sqlbad\query")] [InlineData(@"np:\\.\pipe\MSSQL$NonExistentInstance\sql\query")] [InlineData(@"\\.\pipe\sqlbad\query")] [InlineData(@"\\.\pipe\MSSQL$NonExistentInstance\sql\query")] [InlineData(@"np:\\localhost\pipe\sqlbad\query")] [InlineData(@"np:\\localhost\pipe\MSSQL$NonExistentInstance\sqlbad\query")] [InlineData(@"\\localhost\pipe\sqlbad\query")] [InlineData(@"\\localhost\pipe\MSSQL$NonExistentInstance\sqlbad\query")] [PlatformSpecific(TestPlatforms.Windows)] // Named pipes with the given input strings are not supported on Unix public void NamedPipeTest(string dataSource) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = dataSource; builder.ConnectTimeout = 1; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { string expectedErrorMsg = "(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"; VerifyConnectionFailure<SqlException>(() => connection.Open(), expectedErrorMsg); } } public static bool IsUsingManagedSNI() => ManualTesting.Tests.DataTestUtility.IsUsingManagedSNI(); [ConditionalFact(nameof(IsUsingManagedSNI))] public void NamedPipeInvalidConnStringTest_ManagedSNI() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.ConnectTimeout = 1; string invalidConnStringError = "(provider: Named Pipes Provider, error: 25 - Connection string is not valid)"; string fakeServerName = Guid.NewGuid().ToString("N"); // Using forward slashes builder.DataSource = "np://" + fakeServerName + "/pipe/sql/query"; OpenBadConnection(builder.ConnectionString, invalidConnStringError); // Without pipe token builder.DataSource = @"np:\\" + fakeServerName + @"\sql\query"; OpenBadConnection(builder.ConnectionString, invalidConnStringError); // Without a pipe name builder.DataSource = @"np:\\" + fakeServerName + @"\pipe"; OpenBadConnection(builder.ConnectionString, invalidConnStringError); // Nothing after server builder.DataSource = @"np:\\" + fakeServerName; OpenBadConnection(builder.ConnectionString, invalidConnStringError); // No leading slashes builder.DataSource = @"np:" + fakeServerName + @"\pipe\sql\query"; OpenBadConnection(builder.ConnectionString, invalidConnStringError); // No server name builder.DataSource = @"np:\\\pipe\sql\query"; OpenBadConnection(builder.ConnectionString, invalidConnStringError); // Nothing but slashes builder.DataSource = @"np:\\\\\"; OpenBadConnection(builder.ConnectionString, invalidConnStringError); } private void GenerateConnectionException(string connectionString) { using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); using (SqlCommand command = sqlConnection.CreateCommand()) { command.CommandText = orderIdQuery; command.ExecuteReader(); } } } private TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage, Func<TException, bool> exVerifier) where TException : Exception { TException ex = Assert.Throws<TException>(connectAction); // Some exception messages are different between Framework and Core if(!PlatformDetection.IsFullFramework) { Assert.Contains(expectedExceptionMessage, ex.Message); } Assert.True(exVerifier(ex), "FAILED Exception verifier failed on the exception."); return ex; } private void OpenBadConnection(string connectionString, string errorMsg) { using (SqlConnection conn = new SqlConnection(connectionString)) { VerifyConnectionFailure<SqlException>(() => conn.Open(), errorMsg); } } private TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage) where TException : Exception { return VerifyConnectionFailure<TException>(connectAction, expectedExceptionMessage, (ex) => true); } private bool VerifyException(SqlException exception) { VerifyException(exception, 1); return true; } private bool VerifyException(SqlException exception, int count, int? errorNumber = null, int? errorState = null, int? severity = null) { Assert.NotEmpty(exception.Errors); Assert.Equal(count, exception.Errors.Count); // Ensure that all errors have an error-level severity for (int i = 0; i < count; i++) { Assert.InRange(exception.Errors[i].Class, 10, byte.MaxValue); } // Check the properties of the exception populated by the server are correct if (errorNumber.HasValue) { Assert.Equal(errorNumber.Value, exception.Number); } if (errorState.HasValue) { Assert.Equal(errorState.Value, exception.State); } if (severity.HasValue) { Assert.Equal(severity.Value, exception.Class); } if ((errorNumber.HasValue) && (errorState.HasValue) && (severity.HasValue)) { string expected = $"Error Number:{errorNumber.Value},State:{errorState.Value},Class:{severity.Value}"; Assert.Contains(expected, exception.ToString()); } return true; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ContactFolderChildFoldersCollectionRequest. /// </summary> public partial class ContactFolderChildFoldersCollectionRequest : BaseRequest, IContactFolderChildFoldersCollectionRequest { /// <summary> /// Constructs a new ContactFolderChildFoldersCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ContactFolderChildFoldersCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified ContactFolder to the collection via POST. /// </summary> /// <param name="contactFolder">The ContactFolder to add.</param> /// <returns>The created ContactFolder.</returns> public System.Threading.Tasks.Task<ContactFolder> AddAsync(ContactFolder contactFolder) { return this.AddAsync(contactFolder, CancellationToken.None); } /// <summary> /// Adds the specified ContactFolder to the collection via POST. /// </summary> /// <param name="contactFolder">The ContactFolder to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ContactFolder.</returns> public System.Threading.Tasks.Task<ContactFolder> AddAsync(ContactFolder contactFolder, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<ContactFolder>(contactFolder, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IContactFolderChildFoldersCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IContactFolderChildFoldersCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<ContactFolderChildFoldersCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest Expand(Expression<Func<ContactFolder, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest Select(Expression<Func<ContactFolder, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IContactFolderChildFoldersCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using OTFontFileVal; using OTFontFile; using System.IO; namespace FontVal { public class Program : Driver.DriverCallbacks { ReportFileDestination m_ReportFileDestination; string m_sReportFixedDir; List<string> m_reportFiles = new List<string>(); List<string> m_captions = new List<string>(); static void ErrOut(string s) { Console.WriteLine(s); } static void StdOut(string s) { Console.WriteLine(s); } // ================================================================ // Callbacks for Driver.DriverCallbacks interface // ================================================================ public void OnException(Exception e) { ErrOut("Error: " + e.Message); DeleteTempFiles(); } public void OnReportsReady() { StdOut("Reports are ready!"); } public void OnBeginRasterTest(string label) { StdOut("Begin Raster Test: " + label); } public void OnBeginTableTest(DirectoryEntry de) { StdOut("Table Test: " + (string)de.tag); } public void OnTestProgress(object oParam) { string s = (string)oParam; if (s == null) { s = ""; } StdOut("Progress: " + s); } public void OnCloseReportFile(string sReportFile) { StdOut("Complete: " + sReportFile); // copy the xsl file to the same directory as the report // // This has to be done for each file because the if we are // putting the report on the font's directory, there may // be a different directory for each font. Driver.CopyXslFile(sReportFile); } public void OnOpenReportFile(string sReportFile, string fpath) { m_captions.Add(fpath); m_reportFiles.Add(sReportFile); } public void OnCancel() { DeleteTempFiles(); } public void OnOTFileValChange(OTFileVal fontFile) { } public string GetReportFileName(string sFontFile) { string sReportFile = null; switch (m_ReportFileDestination) { case ReportFileDestination.TempFiles: string sTemp = Path.GetTempFileName(); sReportFile = sTemp + ".report.xml"; File.Move(sTemp, sReportFile); break; case ReportFileDestination.FixedDir: sReportFile = m_sReportFixedDir + Path.DirectorySeparatorChar + Path.GetFileName(sFontFile) + ".report.xml"; break; case ReportFileDestination.SameDirAsFont: sReportFile = sFontFile + ".report.xml"; break; } return sReportFile; } public void OnBeginFontTest(string fname, int nth, int nFonts) { string label = fname + " (file " + (nth + 1) + " of " + nFonts + ")"; StdOut(label); } public void DeleteTempFiles() { if (m_ReportFileDestination == ReportFileDestination.TempFiles) { for (int i = 0; i < m_reportFiles.Count; i++) { File.Delete(m_reportFiles[i]); } } } static void Usage() { Console.WriteLine("Usage: FontValidator [options]"); Console.WriteLine("Options"); Console.WriteLine("<to be written>"); Console.WriteLine(""); } [DllImport("Kernel32.dll")] private static extern Boolean FreeConsole(); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { if (args.Length == 0) { try { FreeConsole(); } catch (Exception e ) { // FreeConsole() is neither available nor relevant // on non-windows. } Application.Run(new Form1()); return ; } bool err = false; string reportDir = null; ReportFileDestination rfd = ReportFileDestination.TempFiles; List<string> sFileList = new List<string>(); ValidatorParameters vp = new ValidatorParameters(); int i,j; for (i = 0; i < args.Length; i++) { if ("-file" == args[i]) { j = i + 1; if (j == args.Length) { ErrOut("Argument required for \"" + args[j-1] + "\""); err = true; break; } for (;j < args.Length; j++) { if (args[j][0] == '-' || args[j][0] == '+') { j--; break; } sFileList.Add(args[j]); } if (j == i) { ErrOut("Argument required for \"" + args[i] + "\""); err = true; break; } i = j; } else if ("+table" == args[i]) { j = i + 1; if (j == args.Length) { ErrOut("Argument required for \"" + args[j-1] + "\""); err = true; break; } for (; j < args.Length; j++) { if (args[j][0] == '-' || args[j][0] == '+') { j--; break; } vp.AddTable(args[j]); } if (j == i) { ErrOut("Argument required for \"" + args[i] + "\""); err = true; break; } i = j; } else if ("-table" == args[i]) { j = i + 1; if (j == args.Length) { ErrOut("Argument required for \"" + args[j - 1] + "\""); err = true; break; } for (; j < args.Length; j++) { if (args[j][0] == '-' || args[j][0] == '+') { j--; break; } vp.RemoveTableFromList(args[j]); } if (j == i) { ErrOut("Argument required for \"" + args[i] + "\""); err = true; break; } i = j; } else if ("-all-tables" == args[i]) { vp.SetAllTables(); } else if ("-only-tables" == args[i]) { vp.ClearTables(); } else if ("-report-dir" == args[i]) { i++; if (i < args.Length) { reportDir = args[i]; rfd = ReportFileDestination.FixedDir; } else { ErrOut("Argument required for \"" + args[i - 1] + "\""); err = true; } } else if ("-report-in-font-dir" == args[i]) { rfd = ReportFileDestination.SameDirAsFont; } else { ErrOut("Unknown argument: \"" + args[i] + "\""); err = true; } } if (err) { Usage(); return ; } //Ready to run Validator v = new Validator(); vp.SetupValidator(v); Program p = new Program(); p.m_ReportFileDestination = rfd; p.m_sReportFixedDir = reportDir; Driver drv = new Driver(p); drv.RunValidation(v, sFileList.ToArray()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ProvidersOperations operations. /// </summary> internal partial class ProvidersOperations : Microsoft.Rest.IServiceOperations<ResourceManagementClient>, IProvidersOperations { /// <summary> /// Initializes a new instance of the ProvidersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProvidersOperations(ResourceManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ResourceManagementClient /// </summary> public ResourceManagementClient Client { get; private set; } /// <summary> /// Unregisters provider from a subscription. /// </summary> /// <param name='resourceProviderNamespace'> /// Namespace of the resource provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Provider>> UnregisterWithHttpMessagesAsync(string resourceProviderNamespace, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceProviderNamespace == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceProviderNamespace"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Unregister", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/unregister").ToString(); _url = _url.Replace("{resourceProviderNamespace}", System.Uri.EscapeDataString(resourceProviderNamespace)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Provider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Provider>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Registers provider to be used with a subscription. /// </summary> /// <param name='resourceProviderNamespace'> /// Namespace of the resource provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Provider>> RegisterWithHttpMessagesAsync(string resourceProviderNamespace, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceProviderNamespace == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceProviderNamespace"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Register", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register").ToString(); _url = _url.Replace("{resourceProviderNamespace}", System.Uri.EscapeDataString(resourceProviderNamespace)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Provider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Provider>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of resource providers. /// </summary> /// <param name='top'> /// Query parameters. If null is passed returns all deployments. /// </param> /// <param name='expand'> /// The $expand query parameter. e.g. To include property aliases in response, /// use $expand=resourceTypes/aliases. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Provider>>> ListWithHttpMessagesAsync(int? top = default(int?), string expand = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("top", top); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, this.Client.SerializationSettings).Trim('"')))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Provider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Provider>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a resource provider. /// </summary> /// <param name='resourceProviderNamespace'> /// Namespace of the resource provider. /// </param> /// <param name='expand'> /// The $expand query parameter. e.g. To include property aliases in response, /// use $expand=resourceTypes/aliases. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Provider>> GetWithHttpMessagesAsync(string resourceProviderNamespace, string expand = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceProviderNamespace == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceProviderNamespace"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("expand", expand); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}").ToString(); _url = _url.Replace("{resourceProviderNamespace}", System.Uri.EscapeDataString(resourceProviderNamespace)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Provider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Provider>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of resource providers. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Provider>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Provider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Provider>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using NUnit.Framework; namespace FileHelpers.Tests { [TestFixture] public class MultiRecords { private MultiRecordEngine engine; [Test] public void MultpleRecordsFile() { engine = new MultiRecordEngine(new RecordTypeSelector(CustomSelector), typeof (OrdersVerticalBar), typeof (CustomersSemiColon), typeof (SampleType)); object[] res = engine.ReadFile(FileTest.Good.MultiRecord1.Path); Assert.AreEqual(12, res.Length); Assert.AreEqual(12, engine.TotalRecords); Assert.AreEqual(typeof (OrdersVerticalBar), res[0].GetType()); Assert.AreEqual(typeof (OrdersVerticalBar), res[1].GetType()); Assert.AreEqual(typeof (CustomersSemiColon), res[2].GetType()); Assert.AreEqual(typeof (SampleType), res[5].GetType()); } [Test] public void MultpleRecordsFileAsync() { engine = new MultiRecordEngine(new RecordTypeSelector(CustomSelector), typeof (OrdersVerticalBar), typeof (CustomersSemiColon), typeof (SampleType)); var res = new ArrayList(); engine.BeginReadFile(FileTest.Good.MultiRecord1.Path); foreach (var o in engine) res.Add(o); Assert.AreEqual(12, res.Count); Assert.AreEqual(12, engine.TotalRecords); Assert.AreEqual(typeof (OrdersVerticalBar), res[0].GetType()); Assert.AreEqual(typeof (OrdersVerticalBar), res[1].GetType()); Assert.AreEqual(typeof (CustomersSemiColon), res[2].GetType()); Assert.AreEqual(typeof (SampleType), res[5].GetType()); } [Test] public void MultpleRecordsWriteAsync() { engine = new MultiRecordEngine(new RecordTypeSelector(CustomSelector), typeof (OrdersVerticalBar), typeof (CustomersSemiColon), typeof (SampleType)); object[] records = engine.ReadFile(FileTest.Good.MultiRecord1.Path); engine.BeginWriteFile("tempoMulti.txt"); foreach (var o in records) engine.WriteNext(o); engine.Close(); File.Delete("tempoMulti.txt"); object[] res = engine.ReadFile(FileTest.Good.MultiRecord1.Path); Assert.AreEqual(12, res.Length); Assert.AreEqual(12, engine.TotalRecords); Assert.AreEqual(typeof (OrdersVerticalBar), res[0].GetType()); Assert.AreEqual(typeof (OrdersVerticalBar), res[1].GetType()); Assert.AreEqual(typeof (CustomersSemiColon), res[2].GetType()); Assert.AreEqual(typeof (SampleType), res[5].GetType()); } [Test] public void MultpleRecordsFileAsyncBad() { engine = new MultiRecordEngine(typeof (OrdersVerticalBar), typeof (CustomersSemiColon), typeof (SampleType)); engine.RecordSelector = new RecordTypeSelector(CustomSelector); Assert.Throws<FileHelpersException>( () => { foreach (var o in engine) o.ToString(); }); } [Test] public void MultpleRecordsFileRW() { engine = new MultiRecordEngine(typeof (OrdersVerticalBar), typeof (CustomersSemiColon), typeof (SampleType)); engine.RecordSelector = new RecordTypeSelector(CustomSelector); object[] res2 = engine.ReadFile(FileTest.Good.MultiRecord1.Path); Assert.AreEqual(12, res2.Length); Assert.AreEqual(12, engine.TotalRecords); engine.WriteFile("tempMR.txt", res2); object[] res = engine.ReadFile("tempMR.txt"); File.Delete("tempMR.txt"); Assert.AreEqual(12, res.Length); Assert.AreEqual(12, engine.TotalRecords); Assert.AreEqual(typeof (OrdersVerticalBar), res[0].GetType()); Assert.AreEqual(typeof (OrdersVerticalBar), res[1].GetType()); Assert.AreEqual(typeof (CustomersSemiColon), res[2].GetType()); Assert.AreEqual(typeof (SampleType), res[5].GetType()); } [Test] public void NoTypes() { Assert.Throws<BadUsageException>(() => new MultiRecordEngine(new Type[] {})); } [Test] public void NullTypeArray() { Assert.Throws<BadUsageException>(() => new MultiRecordEngine((Type[]) null)); } [Test] public void NoSelector() { engine = new MultiRecordEngine(typeof (CustomersVerticalBar), typeof (CustomersTab)); } [Test] public void TwiceSameType() { Assert.Throws<BadUsageException>(() => new MultiRecordEngine(typeof (CustomersVerticalBar), typeof (CustomersVerticalBar))); } [Test] public void OneType() { Assert.Throws<BadUsageException>(() => new MultiRecordEngine(typeof (CustomersVerticalBar))); } [Test] public void NullTypes() { Assert.Throws<BadUsageException>(() => new MultiRecordEngine(typeof (CustomersVerticalBar), null)); } [Test] public void WhenSelectorReturnsTypeThatIsNotInEngine_ShouldThrowBadUsageException_WhenReadingFileAtATime() { engine = new MultiRecordEngine(new RecordTypeSelector(CustomSelectorReturningBadType), typeof (OrdersVerticalBar), typeof (CustomersSemiColon), typeof (SampleType)); Assert.Throws<BadUsageException>(() => engine.ReadFile(FileTest.Good.MultiRecord1.Path)); } [Test] public void WhenSelectorReturnsTypeThatIsNotInEngine_ShouldThrowBadUsageException_WhenReadingRecordAtATime() { engine = new MultiRecordEngine(new RecordTypeSelector(CustomSelectorReturningBadType), typeof (OrdersVerticalBar), typeof (CustomersSemiColon), typeof (SampleType)); engine.BeginReadFile(FileTest.Good.MultiRecord1.Path); Assert.Throws<BadUsageException>(() => engine.ReadNext()); } private Type CustomSelector(MultiRecordEngine engine, string record) { if (Char.IsLetter(record[0])) return typeof (CustomersSemiColon); else if (record.Length == 14) return typeof (SampleType); else return typeof (OrdersVerticalBar); } private Type CustomSelectorReturningBadType(MultiRecordEngine engine, string record) { return typeof (String); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 System.IO; using DiscUtils.Internal; using DiscUtils.Streams; namespace DiscUtils.Vdi { /// <summary> /// Represents a disk stored in VirtualBox (Sun xVM) format. /// </summary> public sealed class Disk : VirtualDisk { private SparseStream _content; private readonly DiskImageFile _diskImage; /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="path">The path to the disk.</param> /// <param name="access">The access requested to the disk.</param> public Disk(string path, FileAccess access) { FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None; var locator = new LocalFileLocator(string.Empty); _diskImage = new DiskImageFile(locator.Open(path, FileMode.Open, access, share), Ownership.Dispose); } /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="file">The file containing the disk image.</param> public Disk(DiskImageFile file) { _diskImage = file; } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are not supported. /// </summary> /// <param name="stream">The stream to read.</param> public Disk(Stream stream) { _diskImage = new DiskImageFile(stream); } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are not supported. /// </summary> /// <param name="stream">The stream to read.</param> /// <param name="ownsStream">Indicates if the new disk should take ownership of <paramref name="stream"/> lifetime.</param> public Disk(Stream stream, Ownership ownsStream) { _diskImage = new DiskImageFile(stream, ownsStream); } /// <summary> /// Gets the capacity of the disk (in bytes). /// </summary> public override long Capacity { get { return _diskImage.Capacity; } } /// <summary> /// Gets the content of the disk as a stream. /// </summary> /// <remarks>Note the returned stream is not guaranteed to be at any particular position. The actual position /// will depend on the last partition table/file system activity, since all access to the disk contents pass /// through a single stream instance. Set the stream position before accessing the stream.</remarks> public override SparseStream Content { get { if (_content == null) { _content = _diskImage.OpenContent(null, Ownership.None); } return _content; } } /// <summary> /// Gets the type of disk represented by this object. /// </summary> public override VirtualDiskClass DiskClass { get { return VirtualDiskClass.HardDisk; } } /// <summary> /// Gets information about the type of disk. /// </summary> /// <remarks>This property provides access to meta-data about the disk format, for example whether the /// BIOS geometry is preserved in the disk file.</remarks> public override VirtualDiskTypeInfo DiskTypeInfo { get { return DiskFactory.MakeDiskTypeInfo(_diskImage.IsSparse ? "dynamic" : "fixed"); } } /// <summary> /// Gets the geometry of the disk. /// </summary> public override Geometry Geometry { get { return _diskImage.Geometry; } } /// <summary> /// Gets the layers that make up the disk. /// </summary> public override IEnumerable<VirtualDiskLayer> Layers { get { yield return _diskImage; } } /// <summary> /// Initializes a stream as a fixed-sized VDI file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <returns>An object that accesses the stream as a VDI file.</returns> public static Disk InitializeFixed(Stream stream, Ownership ownsStream, long capacity) { return new Disk(DiskImageFile.InitializeFixed(stream, ownsStream, capacity)); } /// <summary> /// Initializes a stream as a dynamically-sized VDI file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <returns>An object that accesses the stream as a VDI file.</returns> public static Disk InitializeDynamic(Stream stream, Ownership ownsStream, long capacity) { return new Disk(DiskImageFile.InitializeDynamic(stream, ownsStream, capacity)); } /// <summary> /// Create a new differencing disk, possibly within an existing disk. /// </summary> /// <param name="fileSystem">The file system to create the disk on.</param> /// <param name="path">The path (or URI) for the disk to create.</param> /// <returns>The newly created disk.</returns> public override VirtualDisk CreateDifferencingDisk(DiscFileSystem fileSystem, string path) { throw new NotImplementedException("Differencing disks not implemented for the VDI format"); } /// <summary> /// Create a new differencing disk. /// </summary> /// <param name="path">The path (or URI) for the disk to create.</param> /// <returns>The newly created disk.</returns> public override VirtualDisk CreateDifferencingDisk(string path) { throw new NotImplementedException("Differencing disks not implemented for the VDI format"); } /// <summary> /// Disposes of underlying resources. /// </summary> /// <param name="disposing">Set to <c>true</c> if called within Dispose(), /// else <c>false</c>.</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_content != null) { _content.Dispose(); _content = null; } if (_diskImage != null) { _diskImage.Dispose(); } } } finally { base.Dispose(disposing); } } } }
using Movies.Models; using System; using System.Linq; using System.Web.Mvc; using Movies.ViewModels; using Movies.ViewModels.MovieViewModels; using System.Data.Entity.Core; namespace Movies.Controllers { public class MoviesController : Controller { private ApplicationDbContext dbContext; public MoviesController() { this.dbContext = new ApplicationDbContext(); } // // GET Movies/All [ActionName("All")] public ActionResult GetAll() { var movies = this.dbContext .Movies .Select(MovieVM.FromEntity); return View(movies); } // // GET Movies/Create [ActionName("Create")] [HttpGet] public ActionResult Create() { var model = GetCreateViewModel(); return PartialView(model); } // // Post Movies/Create [ActionName("Create")] [HttpPost] public ActionResult Create(CreateMovieVM model) { if (ModelState.IsValid) { this.dbContext.Movies.Add(new Movie() { Title = model.Title, Year = model.Year, LeadingActor = this.dbContext.Actors.Find(model.LeadingActorId), LeadingActress = this.dbContext.Actors.Find(model.LeadingActressId), Director = this.dbContext.Directors.Find(model.DirectorId) }); try { this.dbContext.SaveChanges(); return Content("Created!"); } catch(Exception ex) { var message = ex.Message; if (ex.InnerException != null) { message = ex.InnerException.Message; } return Content(message); } } return Content("Errors in model"); } // // Get Movies/Edit [ActionName("Edit")] [HttpGet] public ActionResult Edit(int? id) { if (id == null) { return Content("Select a moview please"); } var movie = GetMovieEditModel(id); return PartialView(movie); } // // Post Movies/Edit/1 [ActionName("Edit")] [HttpPost] public ActionResult Edit(EditMovieVM model) { if (ModelState.IsValid) { try { SaveEditedMovie(model); ViewBag.Info = "Edited!"; } catch(Exception ex) { var message = ex.Message; if (ex.InnerException != null) { message = ex.InnerException.Message; } ViewBag.Error = message; } } else { ViewBag.Error = "Could not save to DB."; } return Redirect("~/Movies/All"); } // // Get Movies/Details public ActionResult Details(int? id) { if (id == null) { return Redirect("~/Movies/All"); } var movie = GetDetails(id); return PartialView(movie); } // // Delete Movies/Delete/4 public ActionResult Delete(int? id) { if (id == null) { return Content("No movie seleted!"); } try { DeleteMovie(id); ViewBag.Info = "Deleted!"; } catch(EntityException ex) { var message = ex.Message; if (ex.InnerException != null) { message = ex.InnerException.Message; } ViewBag.Error = message; } return Content(ViewBag.Error ?? ViewBag.Info); } #region Private methods private MovieDetailsVM GetDetails(int? id) { var dbMovie = GetMovieFullInfo(id); return new MovieDetailsVM { Title = dbMovie.Title, Year = dbMovie.Year, LeadingActor = dbMovie.LeadingActor != null ? dbMovie.LeadingActor.Name : null, LeadingActress = dbMovie.LeadingActress != null ? dbMovie.LeadingActress.Name : null, Director = dbMovie.Director != null ? dbMovie.Director.Name : null, Studio = dbMovie.Studio != null ? dbMovie.Studio.Name : null }; } private Movie GetMovieFullInfo(int? id) { var movie = (Movie)this.dbContext.Movies .Include("LeadingActor") .Include("LeadingActress") .Include("Director") .Include("Studio") .FirstOrDefault(m => m.Id == id); return movie; } private void SaveEditedMovie(EditMovieVM model) { var movie = this.dbContext.Movies.Find(model.Id); movie.Title = model.Title; movie.Year = model.Year; movie.LeadingActor = model.LeadingActorId != null ? this.dbContext.Actors.Find(model.LeadingActorId) : null; movie.LeadingActress = model.LeadingActressId != null ? this.dbContext.Actors.Find(model.LeadingActressId) : null; movie.Director = model.DirectorId != null ? this.dbContext.Directors.Find(model.DirectorId) : null; this.dbContext.SaveChanges(); } private CreateMovieVM GetCreateViewModel() { var model = new CreateMovieVM { Actors = this.dbContext.Actors .Where(a => a.Sex.Name == "Male") .Select(PersonVM.FromEntity).ToList(), Actresses = this.dbContext.Actors .Where(a => a.Sex.Name == "Female") .Select(PersonVM.FromEntity).ToList(), Directors = this.dbContext.Directors.Select(PersonVM.FromEntity).ToList() }; return model; } private EditMovieVM GetMovieEditModel(int? id) { var dbMovie = GetMovieFullInfo(id); var movie = new EditMovieVM() { Id = dbMovie.Id, Title = dbMovie.Title, Year = dbMovie.Year }; movie.Actors = this.dbContext.Actors .Where(a => a.Sex.Name == "Male") .Select(PersonVM.FromEntity).ToList(); movie.Actresses = this.dbContext.Actors .Where(a => a.Sex.Name == "Female") .Select(PersonVM.FromEntity).ToList(); movie.Directors = this.dbContext.Directors.Select(PersonVM.FromEntity).ToList(); if (dbMovie.LeadingActor != null) { movie.SelectedActorId = dbMovie.LeadingActor.Id; } if (dbMovie.LeadingActress != null) { movie.SelectedActressId = dbMovie.LeadingActress.Id; } if (dbMovie.Director != null) { movie.DirectorId = dbMovie.Director.Id; } return movie; } private void DeleteMovie(int? id) { this.dbContext.Movies.Remove(this.dbContext.Movies.Find(id)); this.dbContext.SaveChanges(); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="GraphAssembly.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Annotations; using Akka.Pattern; using Akka.Streams.Stage; using static Akka.Streams.Implementation.Fusing.GraphInterpreter; namespace Akka.Streams.Implementation.Fusing { /// <summary> /// INTERNAL API /// /// A GraphAssembly represents a small stream processing graph to be executed by the interpreter. Instances of this /// class **must not** be mutated after construction. /// /// The array <see cref="OriginalAttributes"/> may contain the attribute information of the original atomic module, otherwise /// it must contain a none (otherwise the enclosing module could not overwrite attributes defined in this array). /// /// The arrays <see cref="Inlets"/> and <see cref="Outlets"/> correspond to the notion of a *connection* in the <see cref="GraphInterpreter"/>. Each slot /// *i* contains the input and output port corresponding to connection *i*. Slots where the graph is not closed (i.e. /// ports are exposed to the external world) are marked with null values. For example if an input port p is /// exposed, then Outlets[p] will contain a null. /// /// The arrays <see cref="InletOwners"/> and <see cref="OutletOwners"/> are lookup tables from a connection id(the index of the slot) /// to a slot in the <see cref="Stages"/> array, indicating which stage is the owner of the given input or output port. /// /// Slots which would correspond to non-existent stages(where the corresponding port is null since it represents /// the currently unknown external context) contain the value <see cref="GraphInterpreter.Boundary"/>. /// ///The current assumption by the infrastructure is that the layout of these arrays looks like this: /// /// +---------------------------------------+-----------------+ /// inOwners: | index to stages array | Boundary(-1) | /// +----------------+----------------------+-----------------+ /// ins: | exposed inputs | internal connections | nulls | /// +----------------+----------------------+-----------------+ /// outs: | nulls | internal connections | exposed outputs | /// +----------------+----------------------+-----------------+ /// outOwners: | Boundary(-1) | index to stages array | /// +----------------+----------------------------------------+ /// /// In addition, it is also assumed by the infrastructure that the order of exposed inputs and outputs in the /// corresponding segments of these arrays matches the exact same order of the ports in the <see cref="Shape"/>. /// </summary> [InternalApi] public sealed class GraphAssembly { /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <param name="stages">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <returns>TBD</returns> public static GraphAssembly Create(IList<Inlet> inlets, IList<Outlet> outlets, IList<IGraphStageWithMaterializedValue<Shape, object>> stages) { // add the contents of an iterator to an array starting at idx var inletsCount = inlets.Count; var outletsCount = outlets.Count; var connectionsCount = inletsCount + outletsCount; if (connectionsCount <= 0) throw new ArgumentException($"Sum of inlets ({inletsCount}) and outlets ({outletsCount}) must be > 0"); return new GraphAssembly( stages: stages.ToArray(), originalAttributes: SingleNoAttribute, inlets: Add(inlets, new Inlet[connectionsCount], 0), inletOwners: MarkBoundary(new int[connectionsCount], inletsCount, connectionsCount), outlets: Add(outlets, new Outlet[connectionsCount], inletsCount), outletOwners: MarkBoundary(new int[connectionsCount], 0, inletsCount)); } private static int[] MarkBoundary(int[] owners, int from, int to) { for (var i = from; i < to; i++) owners[i] = Boundary; return owners; } private static T[] Add<T>(IList<T> seq, T[] array, int idx) { foreach (var t in seq) array[idx++] = t; return array; } /// <summary> /// TBD /// </summary> public readonly IGraphStageWithMaterializedValue<Shape, object>[] Stages; /// <summary> /// TBD /// </summary> public readonly Attributes[] OriginalAttributes; /// <summary> /// TBD /// </summary> public readonly Inlet[] Inlets; /// <summary> /// TBD /// </summary> public readonly int[] InletOwners; /// <summary> /// TBD /// </summary> public readonly Outlet[] Outlets; /// <summary> /// TBD /// </summary> public readonly int[] OutletOwners; /// <summary> /// TBD /// </summary> /// <param name="stages">TBD</param> /// <param name="originalAttributes">TBD</param> /// <param name="inlets">TBD</param> /// <param name="inletOwners">TBD</param> /// <param name="outlets">TBD</param> /// <param name="outletOwners">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <returns>TBD</returns> public GraphAssembly(IGraphStageWithMaterializedValue<Shape, object>[] stages, Attributes[] originalAttributes, Inlet[] inlets, int[] inletOwners, Outlet[] outlets, int[] outletOwners) { if (inlets.Length != inletOwners.Length) throw new ArgumentException("'inlets' and 'inletOwners' must have the same length.", nameof(inletOwners)); if (inletOwners.Length != outlets.Length) throw new ArgumentException("'inletOwners' and 'outlets' must have the same length.", nameof(outlets)); if (outlets.Length != outletOwners.Length) throw new ArgumentException("'outlets' and 'outletOwners' must have the same length.", nameof(outletOwners)); Stages = stages; OriginalAttributes = originalAttributes; Inlets = inlets; InletOwners = inletOwners; Outlets = outlets; OutletOwners = outletOwners; } /// <summary> /// TBD /// </summary> public int ConnectionCount => Inlets.Length; /// <summary> /// Takes an interpreter and returns three arrays required by the interpreter containing the input, output port /// handlers and the stage logic instances. /// /// <para>Returns a tuple of</para> /// <para/> - lookup table for InHandlers /// <para/> - lookup table for OutHandlers /// <para/> - array of the logics /// <para/> - materialized value /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <param name="copiedModules">TBD</param> /// <param name="materializedValues">TBD</param> /// <param name="register">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <returns>TBD</returns> public Tuple<Connection[], GraphStageLogic[]> Materialize( Attributes inheritedAttributes, IModule[] copiedModules, IDictionary<IModule, object> materializedValues, Action<IMaterializedValueSource> register) { var logics = new GraphStageLogic[Stages.Length]; for (var i = 0; i < Stages.Length; i++) { // Port initialization loops, these must come first var shape = Stages[i].Shape; var idx = 0; var inletEnumerator = shape.Inlets.GetEnumerator(); while (inletEnumerator.MoveNext()) { var inlet = inletEnumerator.Current; if (inlet.Id != -1 && inlet.Id != idx) throw new ArgumentException($"Inlet {inlet} was shared among multiple stages. That is illegal."); inlet.Id = idx; idx++; } idx = 0; var outletEnumerator = shape.Outlets.GetEnumerator(); while (outletEnumerator.MoveNext()) { var outlet = outletEnumerator.Current; if (outlet.Id != -1 && outlet.Id != idx) throw new ArgumentException($"Outlet {outlet} was shared among multiple stages. That is illegal."); outlet.Id = idx; idx++; } var stage = Stages[i]; if (stage is IMaterializedValueSource) { var copy = ((IMaterializedValueSource) stage).CopySource(); register(copy); stage = (IGraphStageWithMaterializedValue<Shape, object>)copy; } var logicAndMaterialized = stage.CreateLogicAndMaterializedValue(inheritedAttributes.And(OriginalAttributes[i])); materializedValues[copiedModules[i]] = logicAndMaterialized.MaterializedValue; logics[i] = logicAndMaterialized.Logic; } var connections = new Connection[ConnectionCount]; for (var i = 0; i < ConnectionCount; i++) { var connection = new Connection(i, InletOwners[i], InletOwners[i] == Boundary ? null : logics[InletOwners[i]], OutletOwners[i], OutletOwners[i] == Boundary ? null : logics[OutletOwners[i]], null, null); connections[i] = connection; var inlet = Inlets[i]; if (inlet != null) { var owner = InletOwners[i]; var logic = logics[owner]; var h = logic.Handlers[inlet.Id] as IInHandler; if (h == null) throw new IllegalStateException($"No handler defined in stage {logic} for port {inlet}"); connection.InHandler = h; logic.PortToConn[inlet.Id] = connection; } var outlet = Outlets[i]; if (outlet != null) { var owner = OutletOwners[i]; var logic = logics[owner]; var inCount = logic.InCount; var h = logic.Handlers[outlet.Id + inCount] as IOutHandler; if (h == null) throw new IllegalStateException($"No handler defined in stage {logic} for port {outlet}"); connection.OutHandler = h; logic.PortToConn[outlet.Id + inCount] = connection; } } return Tuple.Create(connections, logics); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() { return "GraphAssembly\n " + "Stages: [" + string.Join<IGraphStageWithMaterializedValue<Shape, object>>(",", Stages) + "]\n " + "Attributes: [" + string.Join<Attributes>(",", OriginalAttributes) + "]\n " + "Inlets: [" + string.Join<Inlet>(",", Inlets) + "]\n " + "InOwners: [" + string.Join(",", InletOwners) + "]\n " + "Outlets: [" + string.Join<Outlet>(",", Outlets) + "]\n " + "OutOwners: [" + string.Join(",", OutletOwners) + "]"; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Hydra.Tools.ToolsPublic File: ExportTask.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Hydra.Tools { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Data.Providers; using Ecng.Serialization; using Ecng.Xaml; using Ecng.Xaml.Database; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Export; using StockSharp.Algo.Storages; using StockSharp.Hydra.Core; using StockSharp.Logging; using StockSharp.Xaml.PropertyGrid; using StockSharp.Localization; using StockSharp.Messages; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; [DisplayNameLoc(LocalizedStrings.Str3754Key)] [DescriptionLoc(LocalizedStrings.Str3767Key)] [Doc("http://stocksharp.com/doc/html/9e075b32-abb2-4fad-bfb2-b822dd7d9f30.htm")] [Icon("export_logo.png")] [TaskCategory(TaskCategories.Tool)] class ExportTask : BaseHydraTask { [TaskSettingsDisplayName(LocalizedStrings.Str3754Key)] [CategoryOrderLoc(LocalizedStrings.Str3754Key, 0)] [CategoryOrderLoc(LocalizedStrings.CandlesKey, 1)] [CategoryOrder("CSV", 2)] [CategoryOrderLoc(LocalizedStrings.Str3755Key, 3)] [CategoryOrderLoc(LocalizedStrings.GeneralKey, 4)] private sealed class ExportSettings : HydraTaskSettings { public ExportSettings(HydraTaskSettings settings) : base(settings) { } [CategoryLoc(LocalizedStrings.Str3754Key)] [DisplayNameLoc(LocalizedStrings.TypeKey)] [DescriptionLoc(LocalizedStrings.Str3756Key)] [PropertyOrder(0)] public ExportTypes ExportType { get { return ExtensionInfo[nameof(ExportType)].To<ExportTypes>(); } set { ExtensionInfo[nameof(ExportType)] = value.To<string>(); } } [CategoryLoc(LocalizedStrings.Str3754Key)] [DisplayNameLoc(LocalizedStrings.Str2282Key)] [DescriptionLoc(LocalizedStrings.Str3757Key)] [PropertyOrder(1)] public DateTime StartFrom { get { return ExtensionInfo[nameof(StartFrom)].To<DateTime>(); } set { ExtensionInfo[nameof(StartFrom)] = value.Ticks; } } [CategoryLoc(LocalizedStrings.Str3754Key)] [DisplayNameLoc(LocalizedStrings.Str3758Key)] [DescriptionLoc(LocalizedStrings.Str3759Key)] [PropertyOrder(2)] [Editor(typeof(FolderBrowserEditor), typeof(FolderBrowserEditor))] public string ExportFolder { get { return (string)ExtensionInfo[nameof(ExportFolder)]; } set { ExtensionInfo[nameof(ExportFolder)] = value; } } [CategoryLoc(LocalizedStrings.Str3754Key)] [DisplayNameLoc(LocalizedStrings.Str2284Key)] [DescriptionLoc(LocalizedStrings.Str3760Key)] [PropertyOrder(2)] public int Offset { get { return ExtensionInfo[nameof(Offset)].To<int>(); } set { ExtensionInfo[nameof(Offset)] = value; } } [CategoryLoc(LocalizedStrings.CandlesKey)] [DisplayNameLoc(LocalizedStrings.Str225Key)] [DescriptionLoc(LocalizedStrings.Str3761Key)] [PropertyOrder(3)] [Editor(typeof(CandleSettingsEditor), typeof(CandleSettingsEditor))] public CandleSeries CandleSettings { get { return (CandleSeries)ExtensionInfo[nameof(CandleSettings)]; } set { ExtensionInfo[nameof(CandleSettings)] = value; } } [CategoryLoc(LocalizedStrings.Str3755Key)] [DisplayNameLoc(LocalizedStrings.Str174Key)] [DescriptionLoc(LocalizedStrings.Str3762Key)] [PropertyOrder(0)] [Editor(typeof(DatabaseConnectionEditor), typeof(DatabaseConnectionEditor))] public DatabaseConnectionPair Connection { get { var provider = (string)ExtensionInfo.TryGetValue("ConnectionProvider"); var conStr = (string)ExtensionInfo.TryGetValue("ConnectionString"); if (provider == null || conStr == null) return null; var type = provider.To<Type>(); return DatabaseConnectionCache.Instance.GetConnection(DatabaseProviderRegistry.Providers.First(p => p.GetType() == type), conStr); } set { if (value == null) { ExtensionInfo.Remove("ConnectionProvider"); ExtensionInfo.Remove("ConnectionString"); } else { ExtensionInfo["ConnectionProvider"] = value.Provider.GetType().AssemblyQualifiedName; ExtensionInfo["ConnectionString"] = value.ConnectionString; } } } [CategoryLoc(LocalizedStrings.Str3755Key)] [DisplayNameLoc(LocalizedStrings.Str3763Key)] [DescriptionLoc(LocalizedStrings.Str3764Key)] [PropertyOrder(1)] public int BatchSize { get { return (int)ExtensionInfo[nameof(BatchSize)]; } set { ExtensionInfo[nameof(BatchSize)] = value; } } [CategoryLoc(LocalizedStrings.Str3755Key)] [DisplayNameLoc(LocalizedStrings.Str3765Key)] [DescriptionLoc(LocalizedStrings.Str3766Key)] [PropertyOrder(2)] public bool CheckUnique { get { return (bool)ExtensionInfo[nameof(CheckUnique)]; } set { ExtensionInfo[nameof(CheckUnique)] = value; } } [Category("CSV")] [DisplayNameLoc(LocalizedStrings.TemplateKey)] [DescriptionLoc(LocalizedStrings.TemplateKey, true)] [ExpandableObject] public TemplateTxtRegistry TemplateTxtRegistry { get { return (TemplateTxtRegistry)ExtensionInfo[nameof(TemplateTxtRegistry)]; } set { ExtensionInfo[nameof(TemplateTxtRegistry)] = value; } } [Category("CSV")] [DisplayNameLoc(LocalizedStrings.Str215Key)] [DescriptionLoc(LocalizedStrings.CsvHeaderKey, true)] public string Header { get { return (string)ExtensionInfo[nameof(Header)]; } set { ExtensionInfo[nameof(Header)] = value; } } public override HydraTaskSettings Clone() { var clone = (ExportSettings)base.Clone(); clone.CandleSettings = CandleSettings.Clone(); clone.TemplateTxtRegistry = TemplateTxtRegistry.Clone(); return clone; } } private ExportSettings _settings; public override HydraTaskSettings Settings => _settings; public override IEnumerable<DataType> SupportedDataTypes { get; } = new[] { DataType.Create(typeof(ExecutionMessage), ExecutionTypes.Tick), DataType.Create(typeof(ExecutionMessage), ExecutionTypes.OrderLog), DataType.Create(typeof(ExecutionMessage), ExecutionTypes.Transaction), DataType.Create(typeof(NewsMessage), null), DataType.Create(typeof(QuoteChangeMessage), null), DataType.Create(typeof(Level1ChangeMessage), null), }; protected override void ApplySettings(HydraTaskSettings settings) { _settings = new ExportSettings(settings); if (settings.IsDefault) { _settings.ExportType = ExportTypes.Txt; _settings.Offset = 1; _settings.ExportFolder = string.Empty; _settings.CandleSettings = new CandleSeries { CandleType = typeof(TimeFrameCandle), Arg = TimeSpan.FromMinutes(1) }; //_settings.ExportTemplate = "{OpenTime:yyyy-MM-dd HH:mm:ss};{OpenPrice};{HighPrice};{LowPrice};{ClosePrice};{TotalVolume}"; _settings.Interval = TimeSpan.FromDays(1); _settings.StartFrom = DateTime.Today; _settings.Connection = null; _settings.BatchSize = 50; _settings.CheckUnique = true; _settings.TemplateTxtRegistry = new TemplateTxtRegistry(); _settings.Header = string.Empty; } } protected override TimeSpan OnProcess() { if (_settings.ExportType == ExportTypes.Sql && _settings.Connection == null) { this.AddErrorLog(LocalizedStrings.Str3768); return TimeSpan.MaxValue; } var allSecurity = this.GetAllSecurity(); var supportedDataTypes = (allSecurity == null ? Enumerable.Empty<DataType>() : SupportedDataTypes.Intersect(allSecurity.DataTypes) ).ToArray(); this.AddInfoLog(LocalizedStrings.Str2306Params.Put(_settings.StartFrom)); Func<int, bool> isCancelled = count => !CanProcess(); var hasSecurities = false; foreach (var security in GetWorkingSecurities()) { hasSecurities = true; if (!CanProcess()) break; foreach (var t in (allSecurity == null ? security.DataTypes : supportedDataTypes)) { if (!CanProcess()) break; var dataType = t.MessageType; var arg = t.Arg; this.AddInfoLog(LocalizedStrings.Str3769Params.Put(security.Security.Id, dataType.Name, _settings.ExportType)); var fromStorage = StorageRegistry.GetStorage(security.Security, dataType, arg, _settings.Drive, _settings.StorageFormat); var from = fromStorage.GetFromDate(); var to = fromStorage.GetToDate(); if (from == null || to == null) { this.AddWarningLog(LocalizedStrings.Str3770); continue; } from = _settings.StartFrom.Max(from.Value); to = (DateTime.Today - TimeSpan.FromDays(_settings.Offset)).Min(to.Value); if (from > to) continue; BaseExporter exporter; if (_settings.ExportType == ExportTypes.Sql) { exporter = new DatabaseExporter(security.Security, arg, isCancelled, _settings.Connection) { BatchSize = _settings.BatchSize, CheckUnique = _settings.CheckUnique, }; } else { var path = _settings.ExportFolder; if (path.IsEmpty()) path = DriveCache.Instance.DefaultDrive.Path; var fileName = Path.Combine(path, security.Security.GetFileName( dataType, arg, from.Value, to.Value, _settings.ExportType)); switch (_settings.ExportType) { case ExportTypes.Excel: exporter = new ExcelExporter(security.Security, arg, isCancelled, fileName, () => this.AddErrorLog(LocalizedStrings.Str3771)); break; case ExportTypes.Xml: exporter = new XmlExporter(security.Security, arg, isCancelled, fileName); break; case ExportTypes.Txt: exporter = new TextExporter(security.Security, arg, isCancelled, fileName, GetTxtTemplate(dataType, arg), _settings.Header); break; case ExportTypes.StockSharpBin: exporter = new StockSharpExporter(security.Security, arg, isCancelled, DriveCache.Instance.GetDrive(path), StorageFormats.Binary); break; case ExportTypes.StockSharpCsv: exporter = new StockSharpExporter(security.Security, arg, isCancelled, DriveCache.Instance.GetDrive(path), StorageFormats.Csv); break; default: throw new ArgumentOutOfRangeException(); } } foreach (var date in from.Value.Range(to.Value, TimeSpan.FromDays(1))) { if (!CanProcess()) break; try { this.AddInfoLog(LocalizedStrings.Str3772Params.Put(security.Security.Id, dataType.Name, _settings.ExportType, date)); exporter.Export(dataType, fromStorage.Load(date)); } catch (Exception ex) { HandleError(ex); } } } } if (!hasSecurities) { this.AddWarningLog(LocalizedStrings.Str2292); return TimeSpan.MaxValue; } if (CanProcess()) { this.AddInfoLog(LocalizedStrings.Str2300); _settings.StartFrom = DateTime.Today - TimeSpan.FromDays(_settings.Offset); SaveSettings(); } return base.OnProcess(); } private string GetTxtTemplate(Type dataType, object arg) { if (dataType == null) throw new ArgumentNullException(nameof(dataType)); var registry = _settings.TemplateTxtRegistry; if (dataType == typeof(SecurityMessage)) return registry.TemplateTxtSecurity; else if (dataType == typeof(NewsMessage)) return registry.TemplateTxtNews; else if (dataType.IsCandleMessage()) return registry.TemplateTxtCandle; else if (dataType == typeof(Level1ChangeMessage)) return registry.TemplateTxtLevel1; else if (dataType == typeof(QuoteChangeMessage)) return registry.TemplateTxtDepth; else if (dataType == typeof(ExecutionMessage)) { if (arg == null) throw new ArgumentNullException(nameof(arg)); switch ((ExecutionTypes)arg) { case ExecutionTypes.Tick: return registry.TemplateTxtTick; case ExecutionTypes.Transaction: return registry.TemplateTxtTransaction; case ExecutionTypes.OrderLog: return registry.TemplateTxtOrderLog; default: throw new InvalidOperationException(LocalizedStrings.Str1122Params.Put(arg)); } } else throw new ArgumentOutOfRangeException(nameof(dataType), dataType, LocalizedStrings.Str721); } } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public delegate string GetPersistStringCallback(); public class DockContentHandler : IDisposable, IDockDragSource { public DockContentHandler(Form form) : this(form, null) { } public DockContentHandler(Form form, GetPersistStringCallback getPersistStringCallback) { if (!(form is IDockContent)) throw new ArgumentException(Strings.DockContent_Constructor_InvalidForm, "form"); m_form = form; m_getPersistStringCallback = getPersistStringCallback; m_events = new EventHandlerList(); Form.Disposed +=new EventHandler(Form_Disposed); Form.TextChanged += new EventHandler(Form_TextChanged); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { DockPanel = null; if (m_autoHideTab != null) m_autoHideTab.Dispose(); if (m_tab != null) m_tab.Dispose(); Form.Disposed -= new EventHandler(Form_Disposed); Form.TextChanged -= new EventHandler(Form_TextChanged); m_events.Dispose(); } } private Form m_form; public Form Form { get { return m_form; } } public IDockContent Content { get { return Form as IDockContent; } } private IDockContent m_previousActive = null; public IDockContent PreviousActive { get { return m_previousActive; } internal set { m_previousActive = value; } } private IDockContent m_nextActive = null; public IDockContent NextActive { get { return m_nextActive; } internal set { m_nextActive = value; } } private EventHandlerList m_events; private EventHandlerList Events { get { return m_events; } } private bool m_allowEndUserDocking = true; public bool AllowEndUserDocking { get { return m_allowEndUserDocking; } set { m_allowEndUserDocking = value; } } private double m_autoHidePortion = 0.25; public double AutoHidePortion { get { return m_autoHidePortion; } set { if (value <= 0) throw(new ArgumentOutOfRangeException(Strings.DockContentHandler_AutoHidePortion_OutOfRange)); if (m_autoHidePortion == value) return; m_autoHidePortion = value; if (DockPanel == null) return; if (DockPanel.ActiveAutoHideContent == Content) DockPanel.PerformLayout(); } } private bool m_closeButton = true; public bool CloseButton { get { return m_closeButton; } set { if (m_closeButton == value) return; m_closeButton = value; if (Pane != null) if (Pane.ActiveContent.DockHandler == this) Pane.RefreshChanges(); } } private bool m_closeButtonVisible = true; /// <summary> /// Determines whether the close button is visible on the content /// </summary> public bool CloseButtonVisible { get { return m_closeButtonVisible; } set { m_closeButtonVisible = value; } } private DockState DefaultDockState { get { if (ShowHint != DockState.Unknown && ShowHint != DockState.Hidden) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; return DockState.Unknown; } } private DockState DefaultShowState { get { if (ShowHint != DockState.Unknown) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; if ((DockAreas & DockAreas.Float) != 0) return DockState.Float; return DockState.Unknown; } } private DockAreas m_allowedAreas = DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | DockAreas.DockBottom | DockAreas.Document | DockAreas.Float; public DockAreas DockAreas { get { return m_allowedAreas; } set { if (m_allowedAreas == value) return; if (!DockHelper.IsDockStateValid(DockState, value)) throw(new InvalidOperationException(Strings.DockContentHandler_DockAreas_InvalidValue)); m_allowedAreas = value; if (!DockHelper.IsDockStateValid(ShowHint, m_allowedAreas)) ShowHint = DockState.Unknown; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { if (m_dockState == value) return; DockPanel.SuspendLayout(true); if (value == DockState.Hidden) IsHidden = true; else SetDockState(false, value, Pane); DockPanel.ResumeLayout(true, true); } } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } set { if (m_dockPanel == value) return; Pane = null; if (m_dockPanel != null) m_dockPanel.RemoveContent(Content); if (m_tab != null) { m_tab.Dispose(); m_tab = null; } if (m_autoHideTab != null) { m_autoHideTab.Dispose(); m_autoHideTab = null; } m_dockPanel = value; if (m_dockPanel != null) { m_dockPanel.AddContent(Content); Form.TopLevel = false; Form.FormBorderStyle = FormBorderStyle.None; Form.ShowInTaskbar = false; Form.WindowState = FormWindowState.Normal; if (Win32Helper.IsRunningOnMono) return; NativeMethods.SetWindowPos(Form.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } } public Icon Icon { get { return Form.Icon; } } public DockPane Pane { get { return IsFloat ? FloatPane : PanelPane; } set { if (Pane == value) return; DockPanel.SuspendLayout(true); DockPane oldPane = Pane; SuspendSetDockState(); FloatPane = (value == null ? null : (value.IsFloat ? value : FloatPane)); PanelPane = (value == null ? null : (value.IsFloat ? PanelPane : value)); ResumeSetDockState(IsHidden, value != null ? value.DockState : DockState.Unknown, oldPane); DockPanel.ResumeLayout(true, true); } } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } set { if (m_isHidden == value) return; SetDockState(value, VisibleState, Pane); } } private string m_tabText = null; public string TabText { get { return m_tabText == null || m_tabText == "" ? Form.Text : m_tabText; } set { if (m_tabText == value) return; m_tabText = value; if (Pane != null) Pane.RefreshChanges(); } } private DockState m_visibleState = DockState.Unknown; public DockState VisibleState { get { return m_visibleState; } set { if (m_visibleState == value) return; SetDockState(IsHidden, value, Pane); } } private bool m_isFloat = false; public bool IsFloat { get { return m_isFloat; } set { if (m_isFloat == value) return; DockState visibleState = CheckDockState(value); if (visibleState == DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_IsFloat_InvalidValue); SetDockState(IsHidden, visibleState, Pane); } } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public DockState CheckDockState(bool isFloat) { DockState dockState; if (isFloat) { if (!IsDockStateValid(DockState.Float)) dockState = DockState.Unknown; else dockState = DockState.Float; } else { dockState = (PanelPane != null) ? PanelPane.DockState : DefaultDockState; if (dockState != DockState.Unknown && !IsDockStateValid(dockState)) dockState = DockState.Unknown; } return dockState; } private DockPane m_panelPane = null; public DockPane PanelPane { get { return m_panelPane; } set { if (m_panelPane == value) return; if (value != null) { if (value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_DockPane_InvalidValue); } DockPane oldPane = Pane; if (m_panelPane != null) RemoveFromPane(m_panelPane); m_panelPane = value; if (m_panelPane != null) { m_panelPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : m_panelPane.DockState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private void RemoveFromPane(DockPane pane) { pane.RemoveContent(Content); SetPane(null); if (pane.Contents.Count == 0) pane.Dispose(); } private DockPane m_floatPane = null; public DockPane FloatPane { get { return m_floatPane; } set { if (m_floatPane == value) return; if (value != null) { if (!value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_FloatPane_InvalidValue); } DockPane oldPane = Pane; if (m_floatPane != null) RemoveFromPane(m_floatPane); m_floatPane = value; if (m_floatPane != null) { m_floatPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : VisibleState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private int m_countSetDockState = 0; private void SuspendSetDockState() { m_countSetDockState ++; } private void ResumeSetDockState() { m_countSetDockState --; if (m_countSetDockState < 0) m_countSetDockState = 0; } internal bool IsSuspendSetDockState { get { return m_countSetDockState != 0; } } private void ResumeSetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { ResumeSetDockState(); SetDockState(isHidden, visibleState, oldPane); } internal void SetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { if (IsSuspendSetDockState) return; if (DockPanel == null && visibleState != DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_NullPanel); if (visibleState == DockState.Hidden || (visibleState != DockState.Unknown && !IsDockStateValid(visibleState))) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_InvalidState); DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); SuspendSetDockState(); DockState oldDockState = DockState; if (m_isHidden != isHidden || oldDockState == DockState.Unknown) { m_isHidden = isHidden; } m_visibleState = visibleState; m_dockState = isHidden ? DockState.Hidden : visibleState; if (visibleState == DockState.Unknown) Pane = null; else { m_isFloat = (m_visibleState == DockState.Float); if (Pane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); else if (Pane.DockState != visibleState) { if (Pane.Contents.Count == 1) Pane.SetDockState(visibleState); else Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); } } if (Form.ContainsFocus) { if (DockState == DockState.Hidden || DockState == DockState.Unknown) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(Content); } } } SetPaneAndVisible(Pane); if (oldPane != null && !oldPane.IsDisposed && oldDockState == oldPane.DockState) RefreshDockPane(oldPane); if (Pane != null && DockState == Pane.DockState) { if ((Pane != oldPane) || (Pane == oldPane && oldDockState != oldPane.DockState)) { // Avoid early refresh of hidden AutoHide panes if ((Pane.DockWindow == null || Pane.DockWindow.Visible || Pane.IsHidden) && !Pane.IsAutoHide) { RefreshDockPane(Pane); } } } if (oldDockState != DockState) { if (DockState == DockState.Hidden || DockState == DockState.Unknown || DockHelper.IsDockStateAutoHide(DockState)) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.RemoveFromList(Content); } } else if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.AddToList(Content); } ResetAutoHidePortion(oldDockState, DockState); OnDockStateChanged(EventArgs.Empty); } ResumeSetDockState(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private void ResetAutoHidePortion(DockState oldState, DockState newState) { if (oldState == newState || DockHelper.ToggleAutoHideState(oldState) == newState) return; switch (newState) { case DockState.DockTop: case DockState.DockTopAutoHide: AutoHidePortion = DockPanel.DockTopPortion; break; case DockState.DockLeft: case DockState.DockLeftAutoHide: AutoHidePortion = DockPanel.DockLeftPortion; break; case DockState.DockBottom: case DockState.DockBottomAutoHide: AutoHidePortion = DockPanel.DockBottomPortion; break; case DockState.DockRight: case DockState.DockRightAutoHide: AutoHidePortion = DockPanel.DockRightPortion; break; } } private static void RefreshDockPane(DockPane pane) { pane.RefreshChanges(); pane.ValidateActiveContent(); } internal string PersistString { get { return GetPersistStringCallback == null ? Form.GetType().ToString() : GetPersistStringCallback(); } } private GetPersistStringCallback m_getPersistStringCallback = null; public GetPersistStringCallback GetPersistStringCallback { get { return m_getPersistStringCallback; } set { m_getPersistStringCallback = value; } } private bool m_hideOnClose = false; public bool HideOnClose { get { return m_hideOnClose; } set { m_hideOnClose = value; } } private DockState m_showHint = DockState.Unknown; public DockState ShowHint { get { return m_showHint; } set { if (!DockHelper.IsDockStateValid(value, DockAreas)) throw (new InvalidOperationException(Strings.DockContentHandler_ShowHint_InvalidValue)); if (m_showHint == value) return; m_showHint = value; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } internal set { if (m_isActivated == value) return; m_isActivated = value; } } public bool IsDockStateValid(DockState dockState) { if (DockPanel != null && dockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) return false; else return DockHelper.IsDockStateValid(dockState, DockAreas); } private ContextMenu m_tabPageContextMenu = null; public ContextMenu TabPageContextMenu { get { return m_tabPageContextMenu; } set { m_tabPageContextMenu = value; } } private string m_toolTipText = null; public string ToolTipText { get { return m_toolTipText; } set { m_toolTipText = value; } } public void Activate() { if (DockPanel == null) Form.Activate(); else if (Pane == null) Show(DockPanel); else { IsHidden = false; Pane.ActiveContent = Content; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) { Form.Activate(); return; } else if (DockHelper.IsDockStateAutoHide(DockState)) { if (DockPanel.ActiveAutoHideContent != Content) { DockPanel.ActiveAutoHideContent = null; return; } } if (Form.ContainsFocus) return; if (Win32Helper.IsRunningOnMono) return; DockPanel.ContentFocusManager.Activate(Content); } } public void GiveUpFocus() { if (!Win32Helper.IsRunningOnMono) DockPanel.ContentFocusManager.GiveUpFocus(Content); } private IntPtr m_activeWindowHandle = IntPtr.Zero; internal IntPtr ActiveWindowHandle { get { return m_activeWindowHandle; } set { m_activeWindowHandle = value; } } public void Hide() { IsHidden = true; } internal void SetPaneAndVisible(DockPane pane) { SetPane(pane); SetVisible(); } private void SetPane(DockPane pane) { if (pane != null && pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) { if (Form.Parent is DockPane) SetParent(null); if (Form.MdiParent != DockPanel.ParentForm) { FlagClipWindow = true; Form.MdiParent = DockPanel.ParentForm; } } else { FlagClipWindow = true; if (Form.MdiParent != null) Form.MdiParent = null; if (Form.TopLevel) Form.TopLevel = false; SetParent(pane); } } internal void SetVisible() { bool visible; if (IsHidden) visible = false; else if (Pane != null && Pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) visible = true; else if (Pane != null && Pane.ActiveContent == Content) visible = true; else if (Pane != null && Pane.ActiveContent != Content) visible = false; else visible = Form.Visible; if (Form.Visible != visible) Form.Visible = visible; } private void SetParent(Control value) { if (Form.Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool bRestoreFocus = false; if (Form.ContainsFocus) { // Suggested as a fix for a memory leak by bugreports if (value == null && !IsFloat) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(this.Content); } } else { DockPanel.SaveFocus(); bRestoreFocus = true; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Form.Parent = value; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (bRestoreFocus) Activate(); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public void Show() { if (DockPanel == null) Form.Show(); else Show(DockPanel); } public void Show(DockPanel dockPanel) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (DockState == DockState.Unknown) Show(dockPanel, DefaultShowState); else Activate(); } public void Show(DockPanel dockPanel, DockState dockState) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (dockState == DockState.Unknown || dockState == DockState.Hidden) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidDockState)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (dockState == DockState.Float && FloatPane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, true); else if (PanelPane == null) { DockPane paneExisting = null; foreach (DockPane pane in DockPanel.Panes) if (pane.DockState == dockState) { paneExisting = pane; break; } if (paneExisting == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, dockState, true); else Pane = paneExisting; } DockState = dockState; dockPanel.ResumeLayout(true, true); //we'll resume the layout before activating to ensure that the position Activate(); //and size of the form are finally processed before the form is shown } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (FloatPane == null) { IsHidden = true; // to reduce the screen flicker FloatPane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, false); FloatPane.FloatWindow.StartPosition = FormStartPosition.Manual; } FloatPane.FloatWindow.Bounds = floatWindowBounds; Show(dockPanel, DockState.Float); Activate(); dockPanel.ResumeLayout(true, true); } public void Show(DockPane pane, IDockContent beforeContent) { if (pane == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullPane)); if (beforeContent != null && pane.Contents.IndexOf(beforeContent) == -1) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidBeforeContent)); pane.DockPanel.SuspendLayout(true); DockPanel = pane.DockPanel; Pane = pane; pane.SetContentIndex(Content, pane.Contents.IndexOf(beforeContent)); Show(); pane.DockPanel.ResumeLayout(true, true); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { if (previousPane == null) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); if (DockHelper.IsDockStateAutoHide(previousPane.DockState)) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); previousPane.DockPanel.SuspendLayout(true); DockPanel = previousPane.DockPanel; DockPanel.DockPaneFactory.CreateDockPane(Content, previousPane, alignment, proportion, true); Show(); previousPane.DockPanel.ResumeLayout(true, true); } public void Close() { DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); Form.Close(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private DockPaneStripBase.Tab m_tab = null; internal DockPaneStripBase.Tab GetTab(DockPaneStripBase dockPaneStrip) { if (m_tab == null) m_tab = dockPaneStrip.CreateTab(Content); return m_tab; } private IDisposable m_autoHideTab = null; internal IDisposable AutoHideTab { get { return m_autoHideTab; } set { m_autoHideTab = value; } } #region Events private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion private void Form_Disposed(object sender, EventArgs e) { Dispose(); } private void Form_TextChanged(object sender, EventArgs e) { if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshAutoHideStrip(); else if (Pane != null) { if (Pane.FloatWindow != null) Pane.FloatWindow.SetText(); Pane.RefreshChanges(); } } private bool m_flagClipWindow = false; internal bool FlagClipWindow { get { return m_flagClipWindow; } set { if (m_flagClipWindow == value) return; m_flagClipWindow = value; if (m_flagClipWindow) Form.Region = new Region(Rectangle.Empty); else Form.Region = null; } } private ContextMenuStrip m_tabPageContextMenuStrip = null; public ContextMenuStrip TabPageContextMenuStrip { get { return m_tabPageContextMenuStrip; } set { m_tabPageContextMenuStrip = value; } } #region IDockDragSource Members Control IDragSource.DragControl { get { return Form; } } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (Pane == pane && pane.DisplayingContents.Count == 1) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Size size; DockPane floatPane = this.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; Point location; Rectangle rectPane = Pane.ClientRectangle; if (DockState == DockState.Document) { if (Pane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) location = new Point(rectPane.Left, rectPane.Bottom - size.Height); else location = new Point(rectPane.Left, rectPane.Top); } else { location = new Point(rectPane.Left, rectPane.Bottom); location.Y -= size.Height; } location = Pane.PointToScreen(location); if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { DockPane pane = DockPanel.DockPaneFactory.CreateDockPane(Content, floatWindowBounds, true); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { bool samePane = (Pane == pane); if (!samePane) Pane = pane; if (contentIndex == -1 || !samePane) pane.SetContentIndex(Content, contentIndex); else { DockContentCollection contents = pane.Contents; int oldIndex = contents.IndexOf(Content); int newIndex = contentIndex; if (oldIndex < newIndex) { newIndex += 1; if (newIndex > contents.Count -1) newIndex = -1; } pane.SetContentIndex(Content, newIndex); } } else { DockPane paneFrom = DockPanel.DockPaneFactory.CreateDockPane(Content, pane.DockState, true); INestedPanesContainer container = pane.NestedPanesContainer; if (dockStyle == DockStyle.Left) paneFrom.DockTo(container, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) paneFrom.DockTo(container, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) paneFrom.DockTo(container, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) paneFrom.DockTo(container, pane, DockAlignment.Bottom, 0.5); paneFrom.DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); DockPane pane; if (dockStyle == DockStyle.Top) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockTop, true); else if (dockStyle == DockStyle.Bottom) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockBottom, true); else if (dockStyle == DockStyle.Left) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockLeft, true); else if (dockStyle == DockStyle.Right) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockRight, true); else if (dockStyle == DockStyle.Fill) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Document, true); else return; } #endregion } }
// // DockGroupItem.cs // // Author: // Lluis Sanchez Gual // // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using Gtk; namespace Pinta.Docking { internal class DockGroupItem: DockObject { DockItem item; bool visibleFlag; DockItemStatus status; Gdk.Rectangle floatRect; Gtk.PositionType barDocPosition; int autoHideSize = -1; public DockItem Item { get { return item; } set { item = value; } } public string Id { get { return item.Id; } } public DockGroupItem (DockFrame frame, DockItem item): base (frame) { this.item = item; visibleFlag = item.Visible; } internal override void GetDefaultSize (out int width, out int height) { width = item.DefaultWidth; height = item.DefaultHeight; } internal override void GetMinSize (out int width, out int height) { Requisition req = SizeRequest (); width = req.Width; height = req.Height; } internal override Requisition SizeRequest () { var req = item.Widget.SizeRequest (); if (ParentGroup.Type != DockGroupType.Tabbed || ParentGroup.VisibleObjects.Count == 1) { var tr = item.TitleTab.SizeRequest (); req.Height += tr.Height; return req; } else return req; } public override void SizeAllocate (Gdk.Rectangle newAlloc) { if ((ParentGroup.Type != DockGroupType.Tabbed || ParentGroup.VisibleObjects.Count == 1) && (item.Behavior & DockItemBehavior.NoGrip) == 0) { var tr = newAlloc; tr.Height = item.TitleTab.SizeRequest ().Height; item.TitleTab.SizeAllocate (tr); var wr = newAlloc; wr.Y += tr.Height; wr.Height -= tr.Height; item.Widget.SizeAllocate (wr); } else item.Widget.SizeAllocate (newAlloc); base.SizeAllocate (newAlloc); } public override bool Expand { get { return item.Expand; } } internal override void QueueResize () { item.Widget.QueueResize (); } internal override bool GetDockTarget (DockItem item, int px, int py, out DockDelegate dockDelegate, out Gdk.Rectangle rect) { return GetDockTarget (item, px, py, Allocation, out dockDelegate, out rect); } public bool GetDockTarget (DockItem item, int px, int py, Gdk.Rectangle rect, out DockDelegate dockDelegate, out Gdk.Rectangle outrect) { outrect = Gdk.Rectangle.Zero; dockDelegate = null; if (item != this.item && this.item.Visible && rect.Contains (px, py)) { // Check if the item is allowed to be docked here var s = Frame.GetRegionStyleForObject (this); int xdockMargin = (int) ((double)rect.Width * (1.0 - DockFrame.ItemDockCenterArea)) / 2; int ydockMargin = (int) ((double)rect.Height * (1.0 - DockFrame.ItemDockCenterArea)) / 2; DockPosition pos; /* if (ParentGroup.Type == DockGroupType.Tabbed) { rect = new Gdk.Rectangle (rect.X + xdockMargin, rect.Y + ydockMargin, rect.Width - xdockMargin*2, rect.Height - ydockMargin*2); pos = DockPosition.CenterAfter; }*/ if (px <= rect.X + xdockMargin && ParentGroup.Type != DockGroupType.Horizontal) { if (s.SingleColumnMode.Value) return false; outrect = new Gdk.Rectangle (rect.X, rect.Y, xdockMargin, rect.Height); pos = DockPosition.Left; } else if (px >= rect.Right - xdockMargin && ParentGroup.Type != DockGroupType.Horizontal) { if (s.SingleColumnMode.Value) return false; outrect = new Gdk.Rectangle (rect.Right - xdockMargin, rect.Y, xdockMargin, rect.Height); pos = DockPosition.Right; } else if (py <= rect.Y + ydockMargin && ParentGroup.Type != DockGroupType.Vertical) { if (s.SingleRowMode.Value) return false; outrect = new Gdk.Rectangle (rect.X, rect.Y, rect.Width, ydockMargin); pos = DockPosition.Top; } else if (py >= rect.Bottom - ydockMargin && ParentGroup.Type != DockGroupType.Vertical) { if (s.SingleRowMode.Value) return false; outrect = new Gdk.Rectangle (rect.X, rect.Bottom - ydockMargin, rect.Width, ydockMargin); pos = DockPosition.Bottom; } else { outrect = new Gdk.Rectangle (rect.X + xdockMargin, rect.Y + ydockMargin, rect.Width - xdockMargin*2, rect.Height - ydockMargin*2); pos = DockPosition.Center; } dockDelegate = delegate (DockItem dit) { DockGroupItem it = ParentGroup.AddObject (dit, pos, Id); it.SetVisible (true); ParentGroup.FocusItem (it); }; return true; } return false; } internal override void Dump (int ind) { Console.WriteLine (new string (' ', ind) + item.Id + " size:" + Size + " alloc:" + Allocation); } internal override void Write (XmlWriter writer) { base.Write (writer); writer.WriteAttributeString ("id", item.Id); writer.WriteAttributeString ("visible", visibleFlag.ToString ()); writer.WriteAttributeString ("status", status.ToString ()); if (status == DockItemStatus.AutoHide) writer.WriteAttributeString ("autoHidePosition", barDocPosition.ToString ()); if (autoHideSize != -1) writer.WriteAttributeString ("autoHideSize", autoHideSize.ToString ()); if (!floatRect.Equals (Gdk.Rectangle.Zero)) { writer.WriteAttributeString ("floatX", floatRect.X.ToString ()); writer.WriteAttributeString ("floatY", floatRect.Y.ToString ()); writer.WriteAttributeString ("floatWidth", floatRect.Width.ToString ()); writer.WriteAttributeString ("floatHeight", floatRect.Height.ToString ()); } } internal override void Read (XmlReader reader) { base.Read (reader); visibleFlag = bool.Parse (reader.GetAttribute ("visible")) && !item.IsPositionMarker; status = (DockItemStatus) Enum.Parse (typeof (DockItemStatus), reader.GetAttribute ("status")); int fx=0, fy=0, fw=0, fh=0; string s = reader.GetAttribute ("floatX"); if (s != null) fx = int.Parse (s); s = reader.GetAttribute ("floatY"); if (s != null) fy = int.Parse (s); s = reader.GetAttribute ("floatWidth"); if (s != null) fw = int.Parse (s); s = reader.GetAttribute ("floatHeight"); if (s != null) fh = int.Parse (s); s = reader.GetAttribute ("autoHidePosition"); if (s != null) barDocPosition = (PositionType) Enum.Parse (typeof (PositionType), s); s = reader.GetAttribute ("autoHideSize"); if (s != null) autoHideSize = int.Parse (s); floatRect = new Gdk.Rectangle (fx, fy, fw, fh); } public override void CopyFrom (DockObject ob) { base.CopyFrom (ob); DockGroupItem it = (DockGroupItem)ob; item = it.item; visibleFlag = it.visibleFlag; floatRect = it.floatRect; } internal override bool Visible { get { return visibleFlag && status == DockItemStatus.Dockable; } } internal bool VisibleFlag { get { return visibleFlag; } } public DockItemStatus Status { get { return status; } set { if (status == value) return; DockItemStatus oldValue = status; status = value; if (status == DockItemStatus.Floating) { if (floatRect.Equals (Gdk.Rectangle.Zero)) { int x, y; item.Widget.TranslateCoordinates (item.Widget.Toplevel, 0, 0, out x, out y); Gtk.Window win = Frame.Toplevel as Window; if (win != null) { int wx, wy; win.GetPosition (out wx, out wy); floatRect = new Gdk.Rectangle (wx + x, wy + y, Allocation.Width, Allocation.Height); } } item.SetFloatMode (floatRect); } else if (status == DockItemStatus.AutoHide) { SetBarDocPosition (); item.SetAutoHideMode (barDocPosition, GetAutoHideSize (barDocPosition)); } else item.ResetMode (); if (oldValue == DockItemStatus.Dockable || status == DockItemStatus.Dockable) { // Update visibility if changing from/to dockable mode if (ParentGroup != null) ParentGroup.UpdateVisible (this); } } } void SetBarDocPosition () { // Determine the best position for docking the item if (Allocation.IsEmpty) { int uniqueTrue = -1; int uniqueFalse = -1; for (int n=0; n<4; n++) { bool inMargin = IsNextToMargin ((PositionType) n, false); if (inMargin) { if (uniqueTrue == -1) uniqueTrue = n; else uniqueTrue = -2; } else { if (uniqueFalse == -1) uniqueFalse = n; else uniqueFalse = -2; } } if (uniqueTrue >= 0) { barDocPosition = (PositionType) uniqueTrue; autoHideSize = 200; return; } else if (uniqueFalse >= 0) { barDocPosition = (PositionType) uniqueFalse; switch (barDocPosition) { case PositionType.Left: barDocPosition = PositionType.Right; break; case PositionType.Right: barDocPosition = PositionType.Left; break; case PositionType.Top: barDocPosition = PositionType.Bottom; break; case PositionType.Bottom: barDocPosition = PositionType.Top; break; } autoHideSize = 200; return; } // If the item is in a group, use the dock location of other items DockObject current = this; do { if (EstimateBarDocPosition (current.ParentGroup, current, out barDocPosition, out autoHideSize)) return; current = current.ParentGroup; } while (current.ParentGroup != null); // Can't find a good location. Just guess. barDocPosition = PositionType.Bottom; autoHideSize = 200; return; } barDocPosition = CalcBarDocPosition (); } bool EstimateBarDocPosition (DockGroup grp, DockObject ignoreChild, out PositionType pos, out int size) { foreach (DockObject ob in grp.Objects) { if (ob == ignoreChild) continue; if (ob is DockGroup) { if (EstimateBarDocPosition ((DockGroup)ob, null, out pos, out size)) return true; } else if (ob is DockGroupItem) { DockGroupItem it = (DockGroupItem) ob; if (it.status == DockItemStatus.AutoHide) { pos = it.barDocPosition; size = it.autoHideSize; return true; } if (!it.Allocation.IsEmpty) { pos = it.CalcBarDocPosition (); size = it.GetAutoHideSize (pos); return true; } } } pos = PositionType.Bottom; size = 0; return false; } PositionType CalcBarDocPosition () { if (Allocation.Width < Allocation.Height) { int mid = Allocation.Left + Allocation.Width / 2; if (mid > Frame.Allocation.Left + Frame.Allocation.Width / 2) return PositionType.Right; else return PositionType.Left; } else { int mid = Allocation.Top + Allocation.Height / 2; if (mid > Frame.Allocation.Top + Frame.Allocation.Height / 2) return PositionType.Bottom; else return PositionType.Top; } } internal void SetVisible (bool value) { if (visibleFlag != value) { visibleFlag = value; if (visibleFlag) item.ShowWidget (); else item.HideWidget (); if (ParentGroup != null) ParentGroup.UpdateVisible (this); } } internal override void StoreAllocation () { base.StoreAllocation (); if (Status == DockItemStatus.Floating) floatRect = item.FloatingPosition; else if (Status == DockItemStatus.AutoHide) autoHideSize = item.AutoHideSize; } internal override void RestoreAllocation () { base.RestoreAllocation (); item.UpdateVisibleStatus (); if (Status == DockItemStatus.Floating) item.SetFloatMode (floatRect); else if (Status == DockItemStatus.AutoHide) item.SetAutoHideMode (barDocPosition, GetAutoHideSize (barDocPosition)); else item.ResetMode (); if (!visibleFlag) item.HideWidget (); } int GetAutoHideSize (Gtk.PositionType pos) { if (autoHideSize != -1) return autoHideSize; if (pos == PositionType.Left || pos == PositionType.Right) return Allocation.Width; else return Allocation.Height; } public Gdk.Rectangle FloatRect { get { return floatRect; } set { floatRect = value; } } public override string ToString () { return "[DockItem " + Item.Id + "]"; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.CodeAnalysis.Sarif.Converters { [TestClass] public class FortifyConverterTests { [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void FortifyConverter_Convert_NullInput() { new FortifyConverter().Convert(null, null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void FortifyConverter_Convert_NullOutput() { using (var input = new MemoryStream()) { new FortifyConverter().Convert(input, null); } } private struct Builder { public string RuleId; public string InstanceId; public string Category; public string Kingdom; public string Abstract; public string AbstractCustom; public string Priority; public FortifyPathElement PrimaryOrSink; public FortifyPathElement Source; public ImmutableArray<int> CweIds; public FortifyIssue ToImmutable() { return new FortifyIssue ( ruleId: this.RuleId, iid: this.InstanceId, category: this.Category, kingdom: this.Kingdom, abs: this.Abstract, abstractCustom: this.AbstractCustom, priority: this.Priority, primaryOrSink: this.PrimaryOrSink, source: this.Source, cweIds: this.CweIds ); } } private static readonly FortifyPathElement s_dummyPathElement = new FortifyPathElement("filePath", 1729, "int Foo::Bar(string const&) const&&"); private static readonly FortifyPathElement s_dummyPathSourceElement = new FortifyPathElement("sourceFilePath", 42, null); private static Builder GetBasicBuilder() { return new Builder { Category = "cat", Kingdom = "king", PrimaryOrSink = FortifyConverterTests.s_dummyPathElement }; } private static FortifyIssue GetBasicIssue() { return FortifyConverterTests.GetBasicBuilder().ToImmutable(); } [TestMethod] public void FortifyConverter_Convert_RuleIdIsKingdomAndCategory() { Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(FortifyConverterTests.GetBasicIssue()); Assert.AreEqual("cat", result.RuleId); } [TestMethod] public void FortifyConverter_Convert_ToolFingerprintIsIid() { Builder builder = FortifyConverterTests.GetBasicBuilder(); builder.InstanceId = "a"; Result resultA = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual("a", resultA.ToolFingerprintContribution); builder.InstanceId = null; // IID is optional Result resultNull = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.IsNull(resultNull.ToolFingerprintContribution); } [TestMethod] public void FortifyConverter_Convert_ShortMessageIsUnset() { Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(FortifyConverterTests.GetBasicIssue()); } [TestMethod] public void FortifyConverter_Convert_FullMessageFallsBackToCategoryIfNoAbstractPresent() { Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(FortifyConverterTests.GetBasicIssue()); result.Message.Should().Contain("cat"); } [TestMethod] public void FortifyConverter_Convert_FullMessageUsesAbstractIfPresent() { Builder builder = FortifyConverterTests.GetBasicBuilder(); builder.Abstract = "Some abstract message"; Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual("Some abstract message", result.Message); } [TestMethod] public void FortifyConverter_Convert_FullMessageUsesAbstractCustomIfPresent() { Builder builder = FortifyConverterTests.GetBasicBuilder(); builder.AbstractCustom = "Some abstract custom message"; Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual("Some abstract custom message", result.Message); } [TestMethod] public void FortifyConverter_Convert_ConcatenatesAbstractsIfBothPresent() { Builder builder = FortifyConverterTests.GetBasicBuilder(); builder.Abstract = "Some abstract message"; builder.AbstractCustom = "Some abstract custom message"; Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual("Some abstract message" + Environment.NewLine + "Some abstract custom message", result.Message); } [TestMethod] public void FortifyConverter_Convert_KingdomIsInProperties() { Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(FortifyConverterTests.GetBasicIssue()); result.PropertyNames.Count.Should().Be(1); result.GetProperty("kingdom").Should().Be("king"); } [TestMethod] public void FortifyConverter_Convert_FillsInPriorityIfFriorityPresent() { Builder builder = FortifyConverterTests.GetBasicBuilder(); Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.IsTrue(result.Properties == null || !result.PropertyNames.Contains("priority"), "Priority was set to a null value."); builder.Priority = "HIGH"; result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual("HIGH", result.GetProperty("priority")); } [TestMethod] public void FortifyConverter_Convert_FillsInCweIfPresent() { Builder builder = FortifyConverterTests.GetBasicBuilder(); Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.IsTrue(result.Properties == null || !result.Properties.ContainsKey("cwe"), "CWE was filled in when no CWEs were present."); builder.CweIds = ImmutableArray.Create(24, 42, 1729); result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual("24, 42, 1729", result.GetProperty("cwe")); } [TestMethod] public void FortifyConverter_Convert_FillsInFortifyRuleIdIfPresent() { Builder builder = FortifyConverterTests.GetBasicBuilder(); Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.IsTrue(result.Properties == null || !result.PropertyNames.Contains("fortifyRuleId"), "Fortify RuleID was filled in when no ruleId was present."); builder.RuleId = "abc"; result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual("abc", result.GetProperty("fortifyRuleId")); } [TestMethod] public void FortifyConverter_Convert_UsesPrimaryAsMainLocation() { Builder builder = FortifyConverterTests.GetBasicBuilder(); builder.Source = FortifyConverterTests.s_dummyPathSourceElement; Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual(1, result.Locations.Count); Assert.AreEqual("filePath", result.Locations.First().ResultFile.Uri.ToString()); Assert.IsTrue(result.Locations.First().ResultFile.Region.ValueEquals(new Region { StartLine = 1729 })); } [TestMethod] public void FortifyConverter_Convert_DoesNotFillInCodeFlowWhenOnlyPrimaryIsPresent() { Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(GetBasicIssue()); Assert.IsNull(result.CodeFlows); } [TestMethod] public void FortifyConverter_Convert_FillsInCodeFlowWhenSourceIsPresent() { Builder builder = FortifyConverterTests.GetBasicBuilder(); builder.Source = FortifyConverterTests.s_dummyPathSourceElement; Result result = FortifyConverter.ConvertFortifyIssueToSarifIssue(builder.ToImmutable()); Assert.AreEqual(1, result.CodeFlows.Count); IList<AnnotatedCodeLocation> flowLocations = result.CodeFlows.First().Locations; Assert.AreEqual("sourceFilePath", flowLocations[0].PhysicalLocation.Uri.ToString()); Assert.IsTrue(flowLocations[0].PhysicalLocation.Region.ValueEquals(new Region { StartLine = 42 })); Assert.AreEqual("filePath", flowLocations[1].PhysicalLocation.Uri.ToString()); Assert.IsTrue(flowLocations[1].PhysicalLocation.Region.ValueEquals(new Region { StartLine = 1729 })); } } }
using log4net; /* * Copyright (c) Contributors * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Scripting; using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "JsonStoreScriptModule")] public class JsonStoreScriptModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IConfig m_config = null; private bool m_enabled = false; private Scene m_scene = null; private IScriptModuleComms m_comms; private IJsonStoreModule m_store; private Dictionary<UUID,HashSet<UUID>> m_scriptStores = new Dictionary<UUID,HashSet<UUID>>(); #region Region Module interface // ----------------------------------------------------------------- /// <summary> /// Name of this shared module is it's class name /// </summary> // ----------------------------------------------------------------- public string Name { get { return this.GetType().Name; } } // ----------------------------------------------------------------- /// <summary> /// Initialise this shared module /// </summary> /// <param name="scene">this region is getting initialised</param> /// <param name="source">nini config, we are not using this</param> // ----------------------------------------------------------------- public void Initialise(IConfigSource config) { try { if ((m_config = config.Configs["JsonStore"]) == null) { // There is no configuration, the module is disabled // m_log.InfoFormat("[JsonStoreScripts] no configuration info"); return; } m_enabled = m_config.GetBoolean("Enabled", m_enabled); } catch (Exception e) { m_log.ErrorFormat("[JsonStoreScripts]: initialization error: {0}", e.Message); return; } if (m_enabled) m_log.DebugFormat("[JsonStoreScripts]: module is enabled"); } // ----------------------------------------------------------------- /// <summary> /// everything is loaded, perform post load configuration /// </summary> // ----------------------------------------------------------------- public void PostInitialise() { } // ----------------------------------------------------------------- /// <summary> /// Nothing to do on close /// </summary> // ----------------------------------------------------------------- public void Close() { } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void AddRegion(Scene scene) { scene.EventManager.OnScriptReset += HandleScriptReset; scene.EventManager.OnRemoveScript += HandleScriptReset; } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void RemoveRegion(Scene scene) { scene.EventManager.OnScriptReset -= HandleScriptReset; scene.EventManager.OnRemoveScript -= HandleScriptReset; // need to remove all references to the scene in the subscription // list to enable full garbage collection of the scene object } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- private void HandleScriptReset(uint localID, UUID itemID) { HashSet<UUID> stores; lock (m_scriptStores) { if (! m_scriptStores.TryGetValue(itemID, out stores)) return; m_scriptStores.Remove(itemID); } foreach (UUID id in stores) m_store.DestroyStore(id); } // ----------------------------------------------------------------- /// <summary> /// Called when all modules have been added for a region. This is /// where we hook up events /// </summary> // ----------------------------------------------------------------- public void RegionLoaded(Scene scene) { if (m_enabled) { m_scene = scene; m_comms = m_scene.RequestModuleInterface<IScriptModuleComms>(); if (m_comms == null) { m_log.ErrorFormat("[JsonStoreScripts]: ScriptModuleComms interface not defined"); m_enabled = false; return; } m_store = m_scene.RequestModuleInterface<IJsonStoreModule>(); if (m_store == null) { m_log.ErrorFormat("[JsonStoreScripts]: JsonModule interface not defined"); m_enabled = false; return; } try { m_comms.RegisterScriptInvocations(this); m_comms.RegisterConstants(this); } catch (Exception e) { // See http://opensimulator.org/mantis/view.php?id=5971 for more information m_log.WarnFormat("[JsonStoreScripts]: script method registration failed; {0}", e.Message); m_enabled = false; } } } /// ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public Type ReplaceableInterface { get { return null; } } #endregion #region ScriptConstantsInterface [ScriptConstant] public static readonly int JSON_NODETYPE_UNDEF = (int)JsonStoreNodeType.Undefined; [ScriptConstant] public static readonly int JSON_NODETYPE_OBJECT = (int)JsonStoreNodeType.Object; [ScriptConstant] public static readonly int JSON_NODETYPE_ARRAY = (int)JsonStoreNodeType.Array; [ScriptConstant] public static readonly int JSON_NODETYPE_VALUE = (int)JsonStoreNodeType.Value; [ScriptConstant] public static readonly int JSON_VALUETYPE_UNDEF = (int)JsonStoreValueType.Undefined; [ScriptConstant] public static readonly int JSON_VALUETYPE_BOOLEAN = (int)JsonStoreValueType.Boolean; [ScriptConstant] public static readonly int JSON_VALUETYPE_INTEGER = (int)JsonStoreValueType.Integer; [ScriptConstant] public static readonly int JSON_VALUETYPE_FLOAT = (int)JsonStoreValueType.Float; [ScriptConstant] public static readonly int JSON_VALUETYPE_STRING = (int)JsonStoreValueType.String; #endregion #region ScriptInvocationInteface // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonAttachObjectStore(UUID hostID, UUID scriptID) { UUID uuid = UUID.Zero; if (! m_store.AttachObjectStore(hostID)) GenerateRuntimeError("Failed to create Json store"); return hostID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonCreateStore(UUID hostID, UUID scriptID, string value) { UUID uuid = UUID.Zero; if (! m_store.CreateStore(value, ref uuid)) GenerateRuntimeError("Failed to create Json store"); lock (m_scriptStores) { if (! m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID] = new HashSet<UUID>(); m_scriptStores[scriptID].Add(uuid); } return uuid; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonDestroyStore(UUID hostID, UUID scriptID, UUID storeID) { lock(m_scriptStores) { if (m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID].Remove(storeID); } return m_store.DestroyStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonTestStore(UUID hostID, UUID scriptID, UUID storeID) { return m_store.TestStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonRezAtRoot(UUID hostID, UUID scriptID, string item, Vector3 pos, Vector3 vel, Quaternion rot, string param) { UUID reqID = UUID.Random(); Util.FireAndForget(o => DoJsonRezObject(hostID, scriptID, reqID, item, pos, vel, rot, param)); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID reqID = UUID.Random(); Util.FireAndForget(o => DoJsonReadNotecard(reqID, hostID, scriptID, storeID, path, notecardIdentifier)); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonWriteNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string name) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonWriteNotecard(reqID,hostID,scriptID,storeID,path,name); }); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonList2Path(UUID hostID, UUID scriptID, object[] pathlist) { string ipath = ConvertList2Path(pathlist); string opath; if (JsonStore.CanonicalPathExpression(ipath,out opath)) return opath; // This won't parse if passed to the other routines as opposed to // returning an empty string which is a valid path and would overwrite // the entire store return "**INVALID**"; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetNodeType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetNodeType(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetValueType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetValueType(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonSetValue(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID,path,value,false) ? 1 : 0; } [ScriptInvocation] public int JsonSetJson(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID,path,value,true) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonRemoveValue(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.RemoveValue(storeID,path) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetArrayLength(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.GetArrayLength(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonGetValue(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID,path,false,out value); return value; } [ScriptInvocation] public string JsonGetJson(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID,path,true, out value); return value; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonTakeValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonTakeValue(scriptID,reqID,storeID,path,false); }); return reqID; } [ScriptInvocation] public UUID JsonTakeValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonTakeValue(scriptID,reqID,storeID,path,true); }); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonReadValue(scriptID,reqID,storeID,path,false); }); return reqID; } [ScriptInvocation] public UUID JsonReadValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonReadValue(scriptID,reqID,storeID,path,true); }); return reqID; } #endregion // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void GenerateRuntimeError(string msg) { m_log.InfoFormat("[JsonStore] runtime error: {0}",msg); throw new Exception("JsonStore Runtime Error: " + msg); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void DispatchValue(UUID scriptID, UUID reqID, string value) { m_comms.DispatchReply(scriptID,1,value,reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonTakeValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.TakeValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.ReadValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadNotecard( UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID assetID; if (!UUID.TryParse(notecardIdentifier, out assetID)) { SceneObjectPart part = m_scene.GetSceneObjectPart(hostID); assetID = ScriptUtils.GetAssetIdFromItemName(part, notecardIdentifier, (int)AssetType.Notecard); } AssetBase a = m_scene.AssetService.Get(assetID.ToString()); if (a == null) GenerateRuntimeError(String.Format("Unable to find notecard asset {0}", assetID)); if (a.Type != (sbyte)AssetType.Notecard) GenerateRuntimeError(String.Format("Invalid notecard asset {0}", assetID)); m_log.DebugFormat("[JsonStoreScripts]: read notecard in context {0}",storeID); try { string jsondata = SLUtil.ParseNotecardToString(a.Data); int result = m_store.SetValue(storeID, path, jsondata,true) ? 1 : 0; m_comms.DispatchReply(scriptID, result, "", reqID.ToString()); return; } catch(SLUtil.NotANotecardFormatException e) { m_log.WarnFormat("[JsonStoreScripts]: Notecard parsing failed; assetId {0} at line number {1}", assetID.ToString(), e.lineNumber); } catch (Exception e) { m_log.WarnFormat("[JsonStoreScripts]: Json parsing failed; {0}", e.Message); } GenerateRuntimeError(String.Format("Json parsing failed for {0}", assetID)); m_comms.DispatchReply(scriptID, 0, "", reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonWriteNotecard(UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string name) { string data; if (! m_store.GetValue(storeID,path,true, out data)) { m_comms.DispatchReply(scriptID,0,UUID.Zero.ToString(),reqID.ToString()); return; } SceneObjectPart host = m_scene.GetSceneObjectPart(hostID); // Create new asset UUID assetID = UUID.Random(); AssetBase asset = new AssetBase(assetID, name, (sbyte)AssetType.Notecard, host.OwnerID.ToString()); asset.Description = "Json store"; int textLength = data.Length; data = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " + textLength.ToString() + "\n" + data + "}\n"; asset.Data = Util.UTF8.GetBytes(data); m_scene.AssetService.Store(asset); // Create Task Entry TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ResetIDs(host.UUID); taskItem.ParentID = host.UUID; taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch(); taskItem.Name = asset.Name; taskItem.Description = asset.Description; taskItem.Type = (int)AssetType.Notecard; taskItem.InvType = (int)InventoryType.Notecard; taskItem.OwnerID = host.OwnerID; taskItem.CreatorID = host.OwnerID; taskItem.BasePermissions = (uint)PermissionMask.All; taskItem.CurrentPermissions = (uint)PermissionMask.All; taskItem.EveryonePermissions = 0; taskItem.NextPermissions = (uint)PermissionMask.All; taskItem.GroupID = host.GroupID; taskItem.GroupPermissions = 0; taskItem.Flags = 0; taskItem.PermsGranter = UUID.Zero; taskItem.PermsMask = 0; taskItem.AssetID = asset.FullID; host.Inventory.AddInventoryItem(taskItem, false); m_comms.DispatchReply(scriptID,1,assetID.ToString(),reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// Convert a list of values that are path components to a single string path /// </summary> // ----------------------------------------------------------------- protected static Regex m_ArrayPattern = new Regex("^([0-9]+|\\+)$"); private string ConvertList2Path(object[] pathlist) { string path = ""; for (int i = 0; i < pathlist.Length; i++) { string token = ""; if (pathlist[i] is string) { token = pathlist[i].ToString(); // Check to see if this is a bare number which would not be a valid // identifier otherwise if (m_ArrayPattern.IsMatch(token)) token = '[' + token + ']'; } else if (pathlist[i] is int) { token = "[" + pathlist[i].ToString() + "]"; } else { token = "." + pathlist[i].ToString() + "."; } path += token + "."; } return path; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonRezObject(UUID hostID, UUID scriptID, UUID reqID, string name, Vector3 pos, Vector3 vel, Quaternion rot, string param) { if (Double.IsNaN(rot.X) || Double.IsNaN(rot.Y) || Double.IsNaN(rot.Z) || Double.IsNaN(rot.W)) { GenerateRuntimeError("Invalid rez rotation"); return; } SceneObjectGroup host = m_scene.GetSceneObjectGroup(hostID); if (host == null) { GenerateRuntimeError(String.Format("Unable to find rezzing host '{0}'",hostID)); return; } // hpos = host.RootPart.GetWorldPosition() // float dist = (float)llVecDist(hpos, pos); // if (dist > m_ScriptDistanceFactor * 10.0f) // return; TaskInventoryItem item = host.RootPart.Inventory.GetInventoryItem(name); if (item == null) { GenerateRuntimeError(String.Format("Unable to find object to rez '{0}'",name)); return; } if (item.InvType != (int)InventoryType.Object) { GenerateRuntimeError("Can't create requested object; object is missing from database"); return; } List<SceneObjectGroup> objlist; List<Vector3> veclist; bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist); if (! success) { GenerateRuntimeError("Failed to create object"); return; } int totalPrims = 0; foreach (SceneObjectGroup group in objlist) totalPrims += group.PrimCount; if (! m_scene.Permissions.CanRezObject(totalPrims, item.OwnerID, pos)) { GenerateRuntimeError("Not allowed to create the object"); return; } if (! m_scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) host.RootPart.Inventory.RemoveInventoryItem(item.ItemID); } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup group = objlist[i]; Vector3 curpos = pos + veclist[i]; if (group.IsAttachment == false && group.RootPart.Shape.State != 0) { group.RootPart.AttachedPos = group.AbsolutePosition; group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint; } group.FromPartID = host.RootPart.UUID; m_scene.AddNewSceneObject(group, true, curpos, rot, vel); UUID storeID = group.UUID; if (! m_store.CreateStore(param, ref storeID)) { GenerateRuntimeError("Unable to create jsonstore for new object"); continue; } // We can only call this after adding the scene object, since the scene object references the scene // to find out if scripts should be activated at all. group.RootPart.SetDieAtEdge(true); group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 3); group.ResumeScripts(); group.ScheduleGroupForFullUpdate(); // send the reply back to the host object, use the integer param to indicate the number // of remaining objects m_comms.DispatchReply(scriptID, objlist.Count-i-1, group.RootPart.UUID.ToString(), reqID.ToString()); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using NPoco; using StackExchange.Profiling; using Umbraco.Cms.Infrastructure.Migrations.Install; using Umbraco.Cms.Infrastructure.Persistence.FaultHandling; using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.Persistence { /// <summary> /// Extends NPoco Database for Umbraco. /// </summary> /// <remarks> /// <para>Is used everywhere in place of the original NPoco Database object, and provides additional features /// such as profiling, retry policies, logging, etc.</para> /// <para>Is never created directly but obtained from the <see cref="UmbracoDatabaseFactory"/>.</para> /// </remarks> public class UmbracoDatabase : Database, IUmbracoDatabase { private readonly ILogger<UmbracoDatabase> _logger; private readonly IBulkSqlInsertProvider _bulkSqlInsertProvider; private readonly DatabaseSchemaCreatorFactory _databaseSchemaCreatorFactory; private readonly RetryPolicy _connectionRetryPolicy; private readonly RetryPolicy _commandRetryPolicy; private readonly IEnumerable<IMapper> _mapperCollection; private readonly Guid _instanceGuid = Guid.NewGuid(); private List<CommandInfo> _commands; #region Ctor /// <summary> /// Initializes a new instance of the <see cref="UmbracoDatabase"/> class. /// </summary> /// <remarks> /// <para>Used by UmbracoDatabaseFactory to create databases.</para> /// <para>Also used by DatabaseBuilder for creating databases and installing/upgrading.</para> /// </remarks> public UmbracoDatabase( string connectionString, ISqlContext sqlContext, DbProviderFactory provider, ILogger<UmbracoDatabase> logger, IBulkSqlInsertProvider bulkSqlInsertProvider, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory, RetryPolicy connectionRetryPolicy = null, RetryPolicy commandRetryPolicy = null, IEnumerable<IMapper> mapperCollection = null) : base(connectionString, sqlContext.DatabaseType, provider, sqlContext.SqlSyntax.DefaultIsolationLevel) { SqlContext = sqlContext; _logger = logger; _bulkSqlInsertProvider = bulkSqlInsertProvider; _databaseSchemaCreatorFactory = databaseSchemaCreatorFactory; _connectionRetryPolicy = connectionRetryPolicy; _commandRetryPolicy = commandRetryPolicy; _mapperCollection = mapperCollection; Init(); } /// <summary> /// Initializes a new instance of the <see cref="UmbracoDatabase"/> class. /// </summary> /// <remarks>Internal for unit tests only.</remarks> internal UmbracoDatabase( DbConnection connection, ISqlContext sqlContext, ILogger<UmbracoDatabase> logger, IBulkSqlInsertProvider bulkSqlInsertProvider) : base(connection, sqlContext.DatabaseType, sqlContext.SqlSyntax.DefaultIsolationLevel) { SqlContext = sqlContext; _logger = logger; _bulkSqlInsertProvider = bulkSqlInsertProvider; Init(); } private void Init() { EnableSqlTrace = EnableSqlTraceDefault; NPocoDatabaseExtensions.ConfigureNPocoBulkExtensions(); if (_mapperCollection != null) { Mappers.AddRange(_mapperCollection); } } #endregion /// <inheritdoc /> public ISqlContext SqlContext { get; } #region Temp // work around NPoco issue https://github.com/schotime/NPoco/issues/517 while we wait for the fix public override DbCommand CreateCommand(DbConnection connection, CommandType commandType, string sql, params object[] args) { var command = base.CreateCommand(connection, commandType, sql, args); if (!DatabaseType.IsSqlCe()) return command; foreach (DbParameter parameter in command.Parameters) { if (parameter.Value == DBNull.Value) parameter.DbType = DbType.String; } return command; } #endregion #region Testing, Debugging and Troubleshooting private bool _enableCount; #if DEBUG_DATABASES private int _spid = -1; private const bool EnableSqlTraceDefault = true; #else private string _instanceId; private const bool EnableSqlTraceDefault = false; #endif /// <inheritdoc /> public string InstanceId => #if DEBUG_DATABASES _instanceGuid.ToString("N").Substring(0, 8) + ':' + _spid; #else _instanceId ??= _instanceGuid.ToString("N").Substring(0, 8); #endif /// <inheritdoc /> public bool InTransaction { get; private set; } protected override void OnBeginTransaction() { base.OnBeginTransaction(); InTransaction = true; } protected override void OnAbortTransaction() { InTransaction = false; base.OnAbortTransaction(); } protected override void OnCompleteTransaction() { InTransaction = false; base.OnCompleteTransaction(); } /// <summary> /// Gets or sets a value indicating whether to log all executed Sql statements. /// </summary> internal bool EnableSqlTrace { get; set; } /// <summary> /// Gets or sets a value indicating whether to count all executed Sql statements. /// </summary> public bool EnableSqlCount { get => _enableCount; set { _enableCount = value; if (_enableCount == false) { SqlCount = 0; } } } /// <summary> /// Gets the count of all executed Sql statements. /// </summary> public int SqlCount { get; private set; } internal bool LogCommands { get => _commands != null; set => _commands = value ? new List<CommandInfo>() : null; } internal IEnumerable<CommandInfo> Commands => _commands; public int BulkInsertRecords<T>(IEnumerable<T> records) => _bulkSqlInsertProvider.BulkInsertRecords(this, records); /// <summary> /// Returns the <see cref="DatabaseSchemaResult"/> for the database /// </summary> public DatabaseSchemaResult ValidateSchema() { var dbSchema = _databaseSchemaCreatorFactory.Create(this); var databaseSchemaValidationResult = dbSchema.ValidateSchema(); return databaseSchemaValidationResult; } /// <summary> /// Returns true if Umbraco database tables are detected to be installed /// </summary> public bool IsUmbracoInstalled() => ValidateSchema().DetermineHasInstalledVersion(); #endregion #region OnSomething // TODO: has new interceptors to replace OnSomething? protected override DbConnection OnConnectionOpened(DbConnection connection) { if (connection == null) throw new ArgumentNullException(nameof(connection)); #if DEBUG_DATABASES // determines the database connection SPID for debugging if (DatabaseType.IsSqlServer()) { using (var command = connection.CreateCommand()) { command.CommandText = "SELECT @@SPID"; _spid = Convert.ToInt32(command.ExecuteScalar()); } } else { // includes SqlCE _spid = 0; } #endif // wrap the connection with a profiling connection that tracks timings connection = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current); // wrap the connection with a retrying connection if (_connectionRetryPolicy != null || _commandRetryPolicy != null) connection = new RetryDbConnection(connection, _connectionRetryPolicy, _commandRetryPolicy); return connection; } #if DEBUG_DATABASES protected override void OnConnectionClosing(DbConnection conn) { _spid = -1; base.OnConnectionClosing(conn); } #endif protected override void OnException(Exception ex) { _logger.LogError(ex, "Exception ({InstanceId}).", InstanceId); _logger.LogDebug("At:\r\n{StackTrace}", Environment.StackTrace); if (EnableSqlTrace == false) _logger.LogDebug("Sql:\r\n{Sql}", CommandToString(LastSQL, LastArgs)); base.OnException(ex); } private DbCommand _cmd; protected override void OnExecutingCommand(DbCommand cmd) { // if no timeout is specified, and the connection has a longer timeout, use it if (OneTimeCommandTimeout == 0 && CommandTimeout == 0 && cmd.Connection.ConnectionTimeout > 30) cmd.CommandTimeout = cmd.Connection.ConnectionTimeout; if (EnableSqlTrace) _logger.LogDebug("SQL Trace:\r\n{Sql}", CommandToString(cmd).Replace("{", "{{").Replace("}", "}}")); // TODO: these escapes should be builtin #if DEBUG_DATABASES // detects whether the command is already in use (eg still has an open reader...) DatabaseDebugHelper.SetCommand(cmd, InstanceId + " [T" + System.Threading.Thread.CurrentThread.ManagedThreadId + "]"); var refsobj = DatabaseDebugHelper.GetReferencedObjects(cmd.Connection); if (refsobj != null) _logger.LogDebug("Oops!" + Environment.NewLine + refsobj); #endif _cmd = cmd; base.OnExecutingCommand(cmd); } private string CommandToString(DbCommand cmd) => CommandToString(cmd.CommandText, cmd.Parameters.Cast<DbParameter>().Select(x => x.Value).ToArray()); private string CommandToString(string sql, object[] args) { var text = new StringBuilder(); #if DEBUG_DATABASES text.Append(InstanceId); text.Append(": "); #endif NPocoSqlExtensions.ToText(sql, args, text); return text.ToString(); } protected override void OnExecutedCommand(DbCommand cmd) { if (_enableCount) SqlCount++; _commands?.Add(new CommandInfo(cmd)); base.OnExecutedCommand(cmd); } #endregion // used for tracking commands public class CommandInfo { public CommandInfo(IDbCommand cmd) { Text = cmd.CommandText; var parameters = new List<ParameterInfo>(); foreach (IDbDataParameter parameter in cmd.Parameters) parameters.Add(new ParameterInfo(parameter)); Parameters = parameters.ToArray(); } public string Text { get; } public ParameterInfo[] Parameters { get; } } // used for tracking commands public class ParameterInfo { public ParameterInfo(IDbDataParameter parameter) { Name = parameter.ParameterName; Value = parameter.Value; DbType = parameter.DbType; Size = parameter.Size; } public string Name { get; } public object Value { get; } public DbType DbType { get; } public int Size { get; } } } }
using System.Threading.Tasks; using System.IO; using Aspose.Tasks; using Aspose.Tasks.Saving; using System.Diagnostics; namespace Aspose.Tasks.Live.Demos.UI.Models { ///<Summary> /// AsposeTasksConversion class to convert tasks file to other format ///</Summary> public class AsposeTasksConversion : TasksBase { private Response ProcessTask(string fileName, string folderName, string outFileExtension, bool createZip, bool checkNumberofPages, ActionDelegate action) { Aspose.Tasks.Live.Demos.UI.Models.License.SetAsposeTasksLicense(); return Process(this.GetType().Name, fileName, folderName, outFileExtension, createZip, checkNumberofPages, (new StackTrace()).GetFrame(5).GetMethod().Name, action); } ///<Summary> /// ConvertProjectToPdf method to convert project to pdf format ///</Summary> public Response ConvertProjectToPdf(string fileName, string folderName, string outputType) { return ProcessTask(fileName, folderName, ".pdf", false, false, delegate (string inFilePath, string outPath, string zipOutFolder) { Project project = new Project(inFilePath); PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); if (outputType == "pdfa_1b") { pdfSaveOptions.Compliance = PdfCompliance.PdfA1b; } else if (outputType == "pdfa_1a") { pdfSaveOptions.Compliance = PdfCompliance.PdfA1a; } else if (outputType == "pdf_15") { pdfSaveOptions.Compliance = PdfCompliance.Pdf15; } project.Save(outPath, (SaveOptions)pdfSaveOptions); }); } ///<Summary> /// ConvertProjectToHtml method to convert project to html format ///</Summary> public Response ConvertProjectToHtml(string fileName, string folderName) { return ProcessTask(fileName, folderName, ".html", true, false, delegate (string inFilePath, string outPath, string zipOutFolder) { Project project = new Project(inFilePath); project.Save(outPath, SaveFileFormat.HTML); }); } ///<Summary> /// ConvertProjectToPrimavera method to convert project to Primavera format ///</Summary> public Response ConvertProjectToPrimavera(string fileName, string folderName, string outputType) { if (outputType.Equals("xml") || outputType.Equals("xer") || outputType.Equals("txt") || outputType.Equals("xlsx") || outputType.Equals("xls")) { SaveFileFormat format = SaveFileFormat.TXT; if (outputType.Equals("xlsx") || outputType.Equals("xls")) { format = SaveFileFormat.XLSX; } else if (outputType.Equals("xml")) { format = SaveFileFormat.PrimaveraP6XML; } else if (outputType.Equals("xer")) { format = SaveFileFormat.PrimaveraXER; } return ProcessTask(fileName, folderName, "." + outputType, false, false, delegate (string inFilePath, string outPath, string zipOutFolder) { Project project = new Project(inFilePath); if (outputType.Equals("xls")) { var xlsxOutPath = outPath + "x"; project.Save(xlsxOutPath, format); Aspose.Tasks.Live.Demos.UI.Models.License.SetAsposeCellsLicense(); var workbook = new Aspose.Cells.Workbook(xlsxOutPath); workbook.Save(outPath, Aspose.Cells.SaveFormat.Excel97To2003); } else { project.Save(outPath, format); } }); } return new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }; } public Response ConvertProjectToExchange(string fileName, string folderName, string outputType) { return ProcessTask( fileName, folderName, "." + outputType, false, false, delegate (string inFilePath, string outPath, string zipOutFolder) { Project project = new Project(inFilePath); project.Save(outPath, SaveFileFormat.MPX); }); } ///<Summary> /// ConvertProjectToImages method to convert project to Images format ///</Summary> public Response ConvertProjectToImages(string fileName, string folderName, string outputType) { if (outputType.Equals("bmp") || outputType.Equals("jpg") || outputType.Equals("png")) { SaveFileFormat format = SaveFileFormat.BMP; if (outputType.Equals("jpg")) { format = SaveFileFormat.JPEG; } else if (outputType.Equals("png")) { format = SaveFileFormat.PNG; } else if (outputType.Equals("svg")) { format = SaveFileFormat.SVG; } else if (outputType.Equals("xps")) { format = SaveFileFormat.XPS; } //ImageSaveOptions imageSaveOptions = new ImageSaveOptions(format); return ProcessTask(fileName, folderName, "." + outputType, true, false, delegate (string inFilePath, string outPath, string zipOutFolder) { Project project = new Project(inFilePath); project.Save(outPath, format); }); } return new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }; } ///<Summary> /// ConvertProjectToSingleImage method to convert project to Image format ///</Summary> public Response ConvertProjectToSingleImage(string fileName, string folderName, string outputType) { if (outputType.Equals("tiff") || outputType.Equals("svg") || outputType.Equals("xps")) { SaveFileFormat format = SaveFileFormat.TIFF; if (outputType.Equals("svg")) { format = SaveFileFormat.SVG; } else if (outputType.Equals("xps")) { format = SaveFileFormat.XPS; } return ProcessTask(fileName, folderName, "." + outputType, false, false, delegate (string inFilePath, string outPath, string zipOutFolder) { Project project = new Project(inFilePath); project.Save(outPath, format); }); } return new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }; } ///<Summary> /// ConvertFile ///</Summary> public Response ConvertFile(string fileName, string folderName, string outputType) { outputType = outputType.ToLower(); if (outputType.StartsWith("pdf")) { return ConvertProjectToPdf(fileName, folderName, outputType); } else if (outputType.Equals("html")) { return ConvertProjectToHtml(fileName, folderName); } else if (outputType.Equals("bmp") || outputType.Equals("jpg") || outputType.Equals("png")) { return ConvertProjectToImages(fileName, folderName, outputType); } else if (outputType.Equals("tiff") || outputType.Equals("svg") || outputType.Equals("xps")) { return ConvertProjectToSingleImage(fileName, folderName, outputType); } else if (outputType.Equals("xml") || outputType.Equals("xer") || outputType.Equals("txt") || outputType.Equals("xlsx") || outputType.Equals("xls")) { return ConvertProjectToPrimavera(fileName, folderName, outputType); } if (outputType.Equals("mpx")) { return ConvertProjectToExchange(fileName, folderName, outputType); } return new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }; } } }
using UnityEngine; using Tuples; using Obstacles; using System; public enum EnvironmentType { GROUND, WATER } public class NextResult { public Tuple<EnvironmentType, bool, float, float> tile; public Tuple<BaseObstacle, BaseObstacle, BaseObstacle> obstacles; public Tuple<BaseItem, BaseItem, BaseItem> items; } public class LevelGenerator : MonoBehaviour { private static LevelGenerator instance; public static LevelGenerator Instance { get { if (instance == null) instance = (LevelGenerator)GameObject.FindObjectOfType(typeof(LevelGenerator)); return instance; } } private int N_Calls = 0; public int N_Game_Calls { get { return N_Calls - (int) (Camera.main.orthographicSize * 2.0f * Camera.main.aspect / Config.Instance.TileWidth) - Config.Instance.N_BufferedTiles; } } public int N_Game_Calls_Without_Buffer { get { return N_Calls - (int) (Camera.main.orthographicSize * 2.0f * Camera.main.aspect / Config.Instance.TileWidth); } } public bool IsWon { get { return N_Game_Calls >= Config.Instance.N_TotalTiles; } } private Tuple<BaseObstacle, BaseObstacle, BaseObstacle> last; private System.Random rand = new System.Random(); private EnvironmentType environment = EnvironmentType.GROUND; private int sameEnvironmentDuration = 1; public NextResult Next() { if (Config.Instance.IsTutorial) { NextResult result = new NextResult(); result.obstacles = NextTutorialObstacles(); result.tile = Tuple.Create(environment, sameEnvironmentDuration == 0, result.obstacles.Item1.X, result.obstacles.Item2.Y); result.items = Tuple.Create((BaseItem) new NoItem(), (BaseItem) new NoItem(), (BaseItem) new NoItem()); return result; } else { NextResult result = new NextResult(); result.obstacles = NextObstacles(); result.tile = Tuple.Create(environment, sameEnvironmentDuration == 0, result.obstacles.Item1.X, result.obstacles.Item2.Y); result.items = GetItems(N_Calls * (Config.Instance.TileWidth-1), result.obstacles.Item1, result.obstacles.Item2, result.obstacles.Item3); return result; } } private Tuple<BaseObstacle, BaseObstacle, BaseObstacle> NextTutorialObstacles() { Config config = Config.Instance; if (N_Calls >= config.N_TotalTiles) { if (environment == EnvironmentType.GROUND && N_Calls == config.N_TotalTiles) { sameEnvironmentDuration = 0; environment = EnvironmentType.WATER; } else sameEnvironmentDuration++; return ObstacleLessNext(); } sameEnvironmentDuration++; if (N_Calls == 100){ sameEnvironmentDuration = 0; environment = EnvironmentType.WATER; } else if (N_Calls == 145) { sameEnvironmentDuration = 0; environment = EnvironmentType.GROUND; } float nextX = N_Calls * config.TileWidth; BaseObstacle bottomObstacle = (Tutorial.BottomObstacles[N_Calls] == '.') ? (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.BOTTOM): (environment == EnvironmentType.GROUND) ? BaseObstacle.ConstructGroundByVerticalType(nextX, ObstacleVerticalType.BOTTOM): BaseObstacle.ConstructWaterByVerticalType(nextX, ObstacleVerticalType.BOTTOM); BaseObstacle middleObstacle = (Tutorial.MiddleObstacles[N_Calls] == '.') ? (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.MIDDLE): (environment == EnvironmentType.GROUND) ? BaseObstacle.ConstructGroundByVerticalType(nextX, ObstacleVerticalType.MIDDLE): BaseObstacle.ConstructWaterByVerticalType(nextX, ObstacleVerticalType.MIDDLE); BaseObstacle topObstacle = (Tutorial.TopObstacles[N_Calls] == '.') ? (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.TOP): (environment == EnvironmentType.GROUND) ? BaseObstacle.ConstructGroundByVerticalType(nextX, ObstacleVerticalType.TOP): BaseObstacle.ConstructWaterByVerticalType(nextX, ObstacleVerticalType.TOP); N_Calls++; return Tuple.Create(bottomObstacle, middleObstacle, topObstacle); } private Tuple<BaseObstacle, BaseObstacle, BaseObstacle> NextObstacles() { Config config = Config.Instance; if (N_Calls >= config.N_TotalTiles) { if (environment == EnvironmentType.GROUND && N_Calls == config.N_TotalTiles) { sameEnvironmentDuration = 0; environment = EnvironmentType.WATER; } else sameEnvironmentDuration++; return ObstacleLessNext(); } if (N_Calls < config.N_BlankTiles) { return ObstacleLessNext(); } if (environment == EnvironmentType.GROUND) { if (sameEnvironmentDuration > config.GroundThreshold) { if (rand.NextDouble() < config.P_ground2water*(sameEnvironmentDuration-config.GroundThreshold)) { sameEnvironmentDuration = 0; environment = EnvironmentType.WATER; return ObstacleLessNext(); } } sameEnvironmentDuration++; return NextGround(); } else { if (sameEnvironmentDuration > config.WaterThreshold) { if (rand.NextDouble() < config.P_water2ground*(sameEnvironmentDuration-config.WaterThreshold)) { sameEnvironmentDuration = 0; environment = EnvironmentType.GROUND; return ObstacleLessNext(); } } sameEnvironmentDuration++; return NextWater(); } } private Tuple<BaseObstacle, BaseObstacle, BaseObstacle> NextGround() { Config config = Config.Instance; float nextX = N_Calls * config.TileWidth; BaseObstacle[] obstacles = new BaseObstacle[3]; obstacles[0] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.BOTTOM); obstacles[1] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.MIDDLE); obstacles[2] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.TOP); if (N_Calls > config.N_BlankTiles) { int n_empty = 0; int[] empties = {-1,-1,-1}; int i = 0; foreach (BaseObstacle obstacle in last.ToArray()) { if (obstacle.IsEmpty) { empties[n_empty] = i; n_empty++; } i++; } if (n_empty == 0) { obstacles[0] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.BOTTOM); obstacles[1] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.MIDDLE); obstacles[2] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.TOP); } else if (n_empty == 1) { obstacles[empties[0]] = (BaseObstacle) new NoObstacle(nextX, (ObstacleVerticalType) empties[0]); for (int j=0; j<3; j++) { if (j != empties[0]) { if (rand.NextDouble() < config.P_1) { obstacles[j] = BaseObstacle.ConstructGroundByVerticalType(nextX, (ObstacleVerticalType) j); } else { obstacles[j] = (BaseObstacle) new NoObstacle(nextX, (ObstacleVerticalType) j); } } } } else if (n_empty == 2) { obstacles[empties[0]] = (BaseObstacle) new NoObstacle(nextX, (ObstacleVerticalType) empties[0]); obstacles[empties[1]] = (BaseObstacle) new NoObstacle(nextX, (ObstacleVerticalType) empties[1]); for (int j=0; j<3; j++) { if (j != empties[0] && j != empties[1]) { if (rand.NextDouble() < config.P_2) { obstacles[j] = BaseObstacle.ConstructGroundByVerticalType(nextX, (ObstacleVerticalType) j); } else { obstacles[j] = (BaseObstacle) new NoObstacle(nextX, (ObstacleVerticalType) j); } } } } else if (n_empty == 3) { int k = rand.Next(3); obstacles[k] = (BaseObstacle) new NoObstacle(nextX, (ObstacleVerticalType) k); for (int j=0; j<3; j++) { if (j != k) { if (rand.NextDouble() < config.P_3) { obstacles[j] = BaseObstacle.ConstructGroundByVerticalType(nextX, (ObstacleVerticalType) j); } else { obstacles[j] = (BaseObstacle) new NoObstacle(nextX, (ObstacleVerticalType) j); } } } } } N_Calls++; Tuple<BaseObstacle, BaseObstacle, BaseObstacle> next_round = Tuple.Create(obstacles[0], obstacles[1], obstacles[2]); last = next_round; return next_round; } private int lastWaterFree = 0; private Tuple<BaseObstacle, BaseObstacle, BaseObstacle> NextWater() { Config config = Config.Instance; float nextX = N_Calls * config.TileWidth; BaseObstacle[] obstacles = new BaseObstacle[3]; obstacles[0] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.BOTTOM); obstacles[1] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.MIDDLE); obstacles[2] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.TOP); int free = lastWaterFree; int other = 1 - free; free += Math.Sign(free); other += Math.Sign(other); if (rand.NextDouble() < config.P_waterObstacle) { obstacles[other] = BaseObstacle.ConstructWaterByVerticalType(nextX, (ObstacleVerticalType) other); } else { if (rand.Next(2) == 1) { lastWaterFree = 1 - lastWaterFree; } } N_Calls++; Tuple<BaseObstacle, BaseObstacle, BaseObstacle> next_round = Tuple.Create(obstacles[0], obstacles[1], obstacles[2]); last = next_round; return next_round; } private Tuple<BaseObstacle, BaseObstacle, BaseObstacle> ObstacleLessNext() { Config config = Config.Instance; float nextX = N_Calls * config.TileWidth; BaseObstacle[] obstacles = new BaseObstacle[3]; obstacles[0] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.BOTTOM); obstacles[1] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.MIDDLE); obstacles[2] = (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.TOP); N_Calls++; Tuple<BaseObstacle, BaseObstacle, BaseObstacle> next_round = Tuple.Create((BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.BOTTOM), (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.MIDDLE), (BaseObstacle) new NoObstacle(nextX, ObstacleVerticalType.TOP)); last = next_round; return next_round; } private Tuple<BaseItem, BaseItem, BaseItem> GetItems(float startedOn, BaseObstacle bottomObstacle, BaseObstacle middleObstacle, BaseObstacle topObstacle) { Config conf = Config.Instance; BaseItem bottom = (BaseItem) new NoItem(); BaseItem middle = (BaseItem) new NoItem(); BaseItem top = (BaseItem) new NoItem(); if (N_Calls > Config.Instance.N_TotalTiles) { return Tuple.Create(bottom, middle, top); } if (bottomObstacle.IsEmpty) { float factor = (environment == EnvironmentType.WATER) ? conf.WaterEnergyDiscountFactor : 1.0f; if (rand.NextDouble() < factor*conf.P_can) { bottom = (BaseItem) new EnergyItem(startedOn); } } if (middleObstacle.IsEmpty && environment != EnvironmentType.WATER) { if (rand.NextDouble() < conf.P_mushroom) { middle = (BaseItem) new MushroomItem(startedOn); } } if (topObstacle.IsEmpty) { if (rand.NextDouble() < conf.P_jesus) { top = (BaseItem) new JesusItem(startedOn); } } return Tuple.Create(bottom, middle, top); } void Start () {} void Update () {} }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Globalization; using System.IO; using System.Runtime.InteropServices; namespace SharpDX.IO { /// <summary> /// Windows File Helper. /// </summary> public class NativeFileStream : Stream { private bool canRead; private bool canWrite; private bool canSeek; private IntPtr handle; private long position; /// <summary> /// Initializes a new instance of the <see cref="NativeFileStream"/> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileMode">The file mode.</param> /// <param name="access">The access mode.</param> /// <param name="share">The share mode.</param> public unsafe NativeFileStream(string fileName, NativeFileMode fileMode, NativeFileAccess access, NativeFileShare share = NativeFileShare.Read) { #if WINDOWS_UWP //uint newAccess = 0; //const int FILE_ATTRIBUTE_NORMAL = 0x00000080; //const int FILE_FLAG_RANDOM_ACCESS = 0x10000000; //const int FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000; //var extendedParams = default(NativeFile.CREATEFILE2_EXTENDED_PARAMETERS); //extendedParams.dwSize = (uint)Utilities.SizeOf<NativeFile.CREATEFILE2_EXTENDED_PARAMETERS>(); //extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; //extendedParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS; //extendedParams.dwSecurityQosFlags = 0; //extendedParams.lpSecurityAttributes = IntPtr.Zero; //extendedParams.hTemplateFile = IntPtr.Zero; //if ((access & NativeFileAccess.Read) != 0) //{ // // Sets GENERIC_READ // newAccess |= 0x00120089; //} //if ((access & NativeFileAccess.Write) != 0) //{ // newAccess |= 0x00120116; //} //if ((access & NativeFileAccess.Execute) != 0) //{ // newAccess |= 0x001200a0; //} //handle = NativeFile.Create(fileName, (NativeFileAccess)newAccess, share, fileMode, new IntPtr(&extendedParams)); handle = NativeFile.Create(fileName, access, share, fileMode, IntPtr.Zero); #else handle = NativeFile.Create(fileName, access, share, IntPtr.Zero, fileMode, NativeFileOptions.None, IntPtr.Zero); #endif if (handle == new IntPtr(-1)) { var lastWin32Error = MarshalGetLastWin32Error(); if (lastWin32Error == 2) { throw new FileNotFoundException("Unable to find file", fileName); } var lastError = Result.GetResultFromWin32Error(lastWin32Error); throw new IOException(string.Format(CultureInfo.InvariantCulture, "Unable to open file {0}", fileName), lastError.Code); } canRead = 0 != (access & NativeFileAccess.Read); canWrite = 0 != (access & NativeFileAccess.Write); // TODO how setup correctly canSeek flags? // Kernel32.GetFileType(SafeFileHandle handle); is not available on W8CORE canSeek = true; } public IntPtr Handle { get { return handle; } } private static int MarshalGetLastWin32Error() { return Marshal.GetLastWin32Error(); } /// <inheritdoc/> public override void Flush() { if (!NativeFile.FlushFileBuffers(handle)) throw new IOException("Unable to flush stream", MarshalGetLastWin32Error()); } /// <inheritdoc/> public override long Seek(long offset, SeekOrigin origin) { long newPosition; if (!NativeFile.SetFilePointerEx(handle, offset, out newPosition, origin)) throw new IOException("Unable to seek to this position", MarshalGetLastWin32Error()); position = newPosition; return position; } /// <inheritdoc/> public override void SetLength(long value) { long newPosition; if (!NativeFile.SetFilePointerEx(handle, value, out newPosition, SeekOrigin.Begin)) throw new IOException("Unable to seek to this position", MarshalGetLastWin32Error()); if (!NativeFile.SetEndOfFile(handle)) throw new IOException("Unable to set the new length", MarshalGetLastWin32Error()); if (position < value) { Seek(position, SeekOrigin.Begin); } else { Seek(0, SeekOrigin.End); } } /// <inheritdoc/> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer"); unsafe { fixed (void* pbuffer = buffer) return Read((IntPtr) pbuffer, offset, count); } } /// <summary> /// Reads a block of bytes from the stream and writes the data in a given buffer. /// </summary> /// <param name="buffer">When this method returns, contains the specified buffer with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed. </param> /// <param name="count">The maximum number of bytes to read. </param> /// <exception cref="ArgumentNullException">array is null. </exception> /// <returns>The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.</returns> public int Read(IntPtr buffer, int offset, int count) { if (buffer == IntPtr.Zero) throw new ArgumentNullException("buffer"); int numberOfBytesRead; unsafe { void* pbuffer = (byte*) buffer + offset; { if (!NativeFile.ReadFile(handle, (IntPtr)pbuffer, count, out numberOfBytesRead, IntPtr.Zero)) throw new IOException("Unable to read from file", MarshalGetLastWin32Error()); } position += numberOfBytesRead; } return numberOfBytesRead; } /// <inheritdoc/> public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer"); unsafe { fixed (void* pbuffer = buffer) Write((IntPtr)pbuffer, offset, count); } } /// <summary> /// Writes a block of bytes to this stream using data from a buffer. /// </summary> /// <param name="buffer">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream. </param> /// <param name="count">The number of bytes to be written to the current stream. </param> public void Write(IntPtr buffer, int offset, int count) { if (buffer == IntPtr.Zero) throw new ArgumentNullException("buffer"); int numberOfBytesWritten; unsafe { void* pbuffer = (byte*) buffer + offset; { if (!NativeFile.WriteFile(handle, (IntPtr)pbuffer, count, out numberOfBytesWritten, IntPtr.Zero)) throw new IOException("Unable to write to file", MarshalGetLastWin32Error()); } position += numberOfBytesWritten; } } /// <inheritdoc/> public override bool CanRead { get { return canRead; } } /// <inheritdoc/> public override bool CanSeek { get { return canSeek; } } /// <inheritdoc/> public override bool CanWrite { get { return canWrite; } } /// <inheritdoc/> public override long Length { get { long length; if (!NativeFile.GetFileSizeEx(handle, out length)) throw new IOException("Unable to get file length", MarshalGetLastWin32Error()); return length; } } /// <inheritdoc/> public override long Position { get { return position; } set { Seek(value, SeekOrigin.Begin); position = value; } } protected override void Dispose(bool disposing) { Utilities.CloseHandle(handle); handle = IntPtr.Zero; base.Dispose(disposing); } } }
/* insert license info here */ using System; using System.Collections; using NHibernate; using NHibernate.Expression; namespace Business.Data.Laboratorio { /// <summary> /// Generated by MyGeneration using the NHibernate Object Mapping template /// </summary> [Serializable] public sealed class SolicitudScreening: Business.BaseDataAccess { #region Private Members private bool m_isChanged; private int m_idsolicitudscreening; private int m_idsolicitudscreeningorigen; private Protocolo m_idprotocolo; private int m_numerotarjeta; private string m_medicoSolicitante; private string m_apellidoMaterno; private string m_apellidoPaterno; private string m_nombreParentesco; private int m_numerodocumentoParentesco; private DateTime m_fechaNacimientoParentesco; private int m_idLugarControl; private string m_horanacimiento; private int m_edadgestacional; private decimal m_peso; private bool m_primeramuestra; private string m_motivorepeticion; private DateTime m_fechaextraccion; private string m_horaextraccion; private bool m_ingestaleche24horas; private string m_tipoalimentacion; private bool m_antibiotico; private bool m_transfusion; private bool m_corticoides; private bool m_dopamina; private bool m_enfermedadtiroideamaterna; private string m_antecedentesmaternos; private bool m_corticoidesmaterno; private DateTime m_fechacargaorigen; private DateTime m_fechaenvioorigen; #endregion #region Default ( Empty ) Class Constuctor /// <summary> /// default constructor /// </summary> public SolicitudScreening() { m_idsolicitudscreening = 0; m_idsolicitudscreeningorigen = 0; m_idprotocolo = new Protocolo(); m_numerotarjeta=0; m_medicoSolicitante=String.Empty; m_apellidoMaterno=String.Empty; m_apellidoPaterno=String.Empty; m_nombreParentesco=String.Empty; m_numerodocumentoParentesco=0; m_fechaNacimientoParentesco=DateTime.MinValue; m_idLugarControl=0; m_horanacimiento = String.Empty; m_edadgestacional = 0; m_peso = 0; m_primeramuestra = false; m_fechaextraccion = DateTime.MinValue; m_horaextraccion = String.Empty; m_ingestaleche24horas = false; m_tipoalimentacion = String.Empty; m_antibiotico = false; m_transfusion = false; m_corticoides = false; m_dopamina = false; m_enfermedadtiroideamaterna = false; m_antecedentesmaternos = String.Empty; m_corticoidesmaterno = false; m_fechacargaorigen = DateTime.MinValue; m_fechaenvioorigen = DateTime.MinValue; } #endregion // End of Default ( Empty ) Class Constuctor #region Required Fields Only Constructor /// <summary> /// required (not null) fields only constructor /// </summary> public SolicitudScreening( Protocolo idprotocolo, int idsolicitudscreeningorigen, int numerotarjeta, string medicoSolicitante, string apellidoMaterno, string apellidoPaterno, string nombreParentesco, int numerodocumentoParentesco, DateTime fechaNacimientoParentesco, int idLugarControl, string horanacimiento, int edadgestacional, decimal peso, bool prematuro, bool primeramuestra, DateTime fechaextraccion, string horaextraccion, bool ingestaleche24horas, string tipoalimentacion, bool antibiotico, bool transfusion, bool corticoides, bool dopamina, bool enfermedadtiroideamaterna, string antecedentesmaternos, bool corticoidesmaterno ) : this() { m_idprotocolo = idprotocolo; m_idsolicitudscreeningorigen = idsolicitudscreeningorigen; m_numerotarjeta= numerotarjeta; m_medicoSolicitante=medicoSolicitante; m_apellidoMaterno= apellidoMaterno; m_apellidoPaterno=apellidoPaterno; m_nombreParentesco=nombreParentesco; m_numerodocumentoParentesco=numerodocumentoParentesco; m_fechaNacimientoParentesco = fechaNacimientoParentesco; m_idLugarControl = idLugarControl; m_horanacimiento = horanacimiento; m_edadgestacional = edadgestacional; m_peso = peso; m_primeramuestra = primeramuestra; m_fechaextraccion = fechaextraccion; m_horaextraccion = horaextraccion; m_ingestaleche24horas = ingestaleche24horas; m_tipoalimentacion = tipoalimentacion; m_antibiotico = antibiotico; m_transfusion = transfusion; m_corticoides = corticoides; m_dopamina = dopamina; m_enfermedadtiroideamaterna = enfermedadtiroideamaterna; m_antecedentesmaternos = antecedentesmaternos; m_corticoidesmaterno = corticoidesmaterno; } #endregion // End Required Fields Only Constructor #region Public Properties public int IdSolicitudScreening { get { return m_idsolicitudscreening; } set { m_isChanged |= ( m_idsolicitudscreening != value ); m_idsolicitudscreening = value; } } public int IdSolicitudScreeningOrigen { get { return m_idsolicitudscreeningorigen; } set { m_isChanged |= (m_idsolicitudscreeningorigen != value); m_idsolicitudscreeningorigen = value; } } public Protocolo IdProtocolo { get { return m_idprotocolo; } set { m_isChanged |= ( m_idprotocolo != value ); m_idprotocolo = value; } } public int NumeroTarjeta { get { return m_numerotarjeta; } set { m_isChanged |= (m_numerotarjeta != value); m_numerotarjeta = value; } } public String MedicoSolicitante { get { return m_medicoSolicitante; } set { m_isChanged |= (m_medicoSolicitante != value); m_medicoSolicitante = value; } } public String ApellidoMaterno { get { return m_apellidoMaterno; } set { m_isChanged |= (m_apellidoMaterno != value); m_apellidoMaterno = value; } } public String ApellidoPaterno { get { return m_apellidoPaterno; } set { m_isChanged |= (m_apellidoPaterno != value); m_apellidoPaterno = value; } } public String NombreParentesco { get { return m_nombreParentesco; } set { m_isChanged |= (m_nombreParentesco != value); m_nombreParentesco = value; } } public int NumerodocumentoParentesco { get { return m_numerodocumentoParentesco; } set { m_isChanged |= (m_numerodocumentoParentesco != value); m_numerodocumentoParentesco = value; } } public DateTime FechaNacimientoParentesco { get { return m_fechaNacimientoParentesco; } set { m_isChanged |= (m_fechaNacimientoParentesco != value); m_fechaNacimientoParentesco = value; } } public int IdLugarControl { get { return m_idLugarControl; } set { m_isChanged |= (m_idLugarControl != value); m_idLugarControl = value; } } /// <summary> /// /////////////////////////// /// </summary> public String MotivoRepeticion { get { return m_motivorepeticion; } set { m_isChanged |= (m_motivorepeticion != value); m_motivorepeticion = value; } } public string HoraNacimiento { get { return m_horanacimiento; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for HoraNacimiento", value, "null"); if( value.Length > 5) throw new ArgumentOutOfRangeException("Invalid value for HoraNacimiento", value, value.ToString()); m_isChanged |= (m_horanacimiento != value); m_horanacimiento = value; } } public int EdadGestacional { get { return m_edadgestacional; } set { m_isChanged |= ( m_edadgestacional != value ); m_edadgestacional = value; } } public decimal Peso { get { return m_peso; } set { m_isChanged |= ( m_peso != value ); m_peso = value; } } public bool PrimeraMuestra { get { return m_primeramuestra; } set { m_isChanged |= ( m_primeramuestra != value ); m_primeramuestra = value; } } public DateTime FechaExtraccion { get { return m_fechaextraccion; } set { m_isChanged |= ( m_fechaextraccion != value ); m_fechaextraccion = value; } } public string HoraExtraccion { get { return m_horaextraccion; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for HoraExtraccion", value, "null"); if( value.Length > 5) throw new ArgumentOutOfRangeException("Invalid value for HoraExtraccion", value, value.ToString()); m_isChanged |= (m_horaextraccion != value); m_horaextraccion = value; } } public bool IngestaLeche24Horas { get { return m_ingestaleche24horas; } set { m_isChanged |= ( m_ingestaleche24horas != value ); m_ingestaleche24horas = value; } } public String TipoAlimentacion { get { return m_tipoalimentacion; } set { m_isChanged |= ( m_tipoalimentacion != value ); m_tipoalimentacion = value; } } public bool Antibiotico { get { return m_antibiotico; } set { m_isChanged |= ( m_antibiotico != value ); m_antibiotico = value; } } public bool Transfusion { get { return m_transfusion; } set { m_isChanged |= ( m_transfusion != value ); m_transfusion = value; } } public bool Corticoides { get { return m_corticoides; } set { m_isChanged |= ( m_corticoides != value ); m_corticoides = value; } } public bool Dopamina { get { return m_dopamina; } set { m_isChanged |= ( m_dopamina != value ); m_dopamina = value; } } public bool EnfermedadTiroideaMaterna { get { return m_enfermedadtiroideamaterna; } set { m_isChanged |= ( m_enfermedadtiroideamaterna != value ); m_enfermedadtiroideamaterna = value; } } public string AntecedentesMaternos { get { return m_antecedentesmaternos; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for AntecedentesMaternos", value, "null"); if( value.Length > 1073741823) throw new ArgumentOutOfRangeException("Invalid value for AntecedentesMaternos", value, value.ToString()); m_isChanged |= (m_antecedentesmaternos != value); m_antecedentesmaternos = value; } } public bool CorticoidesMaterno { get { return m_corticoidesmaterno; } set { m_isChanged |= (m_corticoidesmaterno != value); m_corticoidesmaterno = value; } } public DateTime FechaCargaOrigen { get { return m_fechacargaorigen; } set { m_isChanged |= (m_fechacargaorigen != value); m_fechacargaorigen = value; } } public DateTime FechaEnvioOrigen { get { return m_fechaenvioorigen; } set { m_isChanged |= (m_fechaenvioorigen != value); m_fechaenvioorigen = value; } } public int GetCantidadAlarmas() { int i = 0; AlarmaScreening oDetalle = new AlarmaScreening(); ISession m_session = NHibernateHttpModule.CurrentSession; ICriteria crit = m_session.CreateCriteria(typeof(AlarmaScreening)); crit.Add(Expression.Eq("IdSolicitudScreening", this)); IList items = crit.List(); i=items.Count; return i; } /// <summary> /// Returns whether or not the object has changed it's values. /// </summary> public bool IsChanged { get { return m_isChanged; } } #endregion public void EliminarAlarmas() { AlarmaScreening oDetalle = new AlarmaScreening(); ISession m_session = NHibernateHttpModule.CurrentSession; ICriteria crit = m_session.CreateCriteria(typeof(AlarmaScreening)); crit.Add(Expression.Eq("IdSolicitudScreening", this)); IList items = crit.List(); foreach (AlarmaScreening oDet in items) { oDet.Delete(); } } public void GuardarDescripcionAlarma(string descripcionAlarma, SolicitudScreening oSolicitud, int user) { AlarmaScreening oRegistro = new AlarmaScreening(); oRegistro.IdSolicitudScreening = this; oRegistro.Descripcion = descripcionAlarma; oRegistro.IdUsuarioRegistro =user; oRegistro.FechaRegistro = DateTime.Now; oRegistro.Save(); } public void GuardarParentesco() { //Parentesco oDetalle = new Parentesco(); ISession m_session2 = NHibernateHttpModule.CurrentSession; ICriteria crit2 = m_session2.CreateCriteria(typeof(Parentesco)); crit2.Add(Expression.Eq("IdPaciente", this.IdProtocolo.IdPaciente)); IList items2 = crit2.List(); foreach (Parentesco oDet in items2) { oDet.Delete(); } Parentesco par = new Parentesco(); par.Apellido = this.ApellidoMaterno; par.Nombre = this.NombreParentesco; par.IdTipoDocumento = 1; // Convert.ToInt32(ddlTipoDocP.SelectedValue); par.IdPaciente = this.IdProtocolo.IdPaciente; par.TipoParentesco = "Madre"; par.NumeroDocumento = this.NumerodocumentoParentesco; par.FechaNacimiento = this.FechaNacimientoParentesco; par.IdProvincia = -1; par.IdPais = 54; par.IdUsuario = this.IdProtocolo.IdUsuarioRegistro; //guardo la fecha actual de modificacion par.FechaModificacion = DateTime.Now; par.Save(); } } }
using System; using System.Runtime.Serialization; using AonWeb.FluentHttp.HAL.Serialization; using Newtonsoft.Json; namespace AonWeb.FluentHttp.Tests.Helpers { public class TestResource : HalResource, IEquatable<TestResource> { public string StringProperty { get; set; } public int IntProperty { get; set; } public bool BoolProperty { get; set; } public DateTimeOffset DateOffsetProperty { get; set; } public DateTime DateProperty { get; set; } #region Equality public bool Equals(TestResource other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!DateProperty.Equals(other.DateProperty)) return false; if (!DateOffsetProperty.Equals(other.DateOffsetProperty) && DateOffsetProperty != DateTimeOffset.MinValue && other.DateOffsetProperty != DateTimeOffset.MinValue) return false; if (!BoolProperty.Equals(other.BoolProperty)) return false; if (IntProperty != other.IntProperty) return false; if (!string.Equals(StringProperty, other.StringProperty)) return false; if (ReferenceEquals(Links, other.Links)) return true; if (ReferenceEquals(null, other.Links)) return false; if (ReferenceEquals(null, Links)) return false; if (!Links.Equals(other.Links)) return false; return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; var other = obj as TestResource; return other != null && Equals(other); } public override int GetHashCode() { unchecked { int hashCode = DateProperty.GetHashCode(); hashCode = (hashCode * 397) ^ DateOffsetProperty.GetHashCode(); hashCode = (hashCode * 397) ^ BoolProperty.GetHashCode(); hashCode = (hashCode * 397) ^ IntProperty; hashCode = (hashCode * 397) ^ StringProperty.GetHashCode(); hashCode = (hashCode * 397) ^ Links.GetHashCode(); return hashCode; } } public static bool operator ==(TestResource left, TestResource right) { return Equals(left, right); } public static bool operator !=(TestResource left, TestResource right) { return !Equals(left, right); } #endregion #region HalDefaults [JsonIgnore] public const string SerializedDefault1 = @"{ ""stringProperty"": ""TestString"", ""intProperty"": 2, ""boolProperty"": true, ""dateOffsetProperty"": ""2000-01-01T00:00:00-05:00"", ""dateProperty"": ""2000-01-01T00:00:00"", ""_links"": { ""self"": { ""href"": ""http://link.com/self/1"", ""templated"": false }, ""template"": { ""href"": ""http://link.com/self/1/child/{child-id}"", ""templated"": true }, ""nontemplate"": { ""href"": ""http://link.com/self/1/child/1"", ""templated"": false } } }"; [JsonIgnore] public const string SerializedDefault2 = ""; public static TestResource Default1() { return new TestResource { StringProperty = "TestString", IntProperty = 2, BoolProperty = true, DateOffsetProperty = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.FromHours(-5)), DateProperty = new DateTime(2000, 1, 1, 0, 0, 0), Links = new HyperMediaLinks() { new HyperMediaLink { Rel = "self", Href= "http://link.com/self/1" }, new HyperMediaLink { Rel = "template", Href= "http://link.com/self/1/child/{child-id}", Templated = true }, new HyperMediaLink { Rel = "nontemplate", Href= "http://link.com/self/1/child/1", Templated = false } } }; } public static TestResource Default2() { return new TestResource { StringProperty = "TestString2", IntProperty = 2, BoolProperty = false, DateOffsetProperty = new DateTimeOffset(2000, 1, 2, 0, 0, 0, TimeSpan.FromHours(-5)), DateProperty = new DateTime(2000, 1, 2, 0, 0, 0), Links = new HyperMediaLinks() { new HyperMediaLink { Rel = "self", Href= "http://link.com/self/2" }, new HyperMediaLink { Rel = "template", Href= "http://link.com/self/2/child/{child-id}", Templated = true }, new HyperMediaLink { Rel = "nontemplate", Href= "http://link.com/self/2/child/2", Templated = false } } }; } #endregion } public class SubTestResource : TestResource { public bool SubBoolProperty { get; set; } public bool? SubNullableBoolProperty { get; set; } #region Defaults public new static SubTestResource Default1() { return new SubTestResource { SubBoolProperty = false, StringProperty = "TestString", IntProperty = 2, BoolProperty = true, DateOffsetProperty = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.FromHours(-5)), DateProperty = new DateTime(2000, 1, 1, 0, 0, 0), Links = new HyperMediaLinks() { new HyperMediaLink { Rel = "self", Href= "http://link.com/self/1" }, new HyperMediaLink { Rel = "template", Href= "http://link.com/self/1/child/{child-id}", Templated = true }, new HyperMediaLink { Rel = "nontemplate", Href= "http://link.com/self/1/child/1", Templated = false } } }; } #endregion } public class AlternateTestResource : HalResource { public string Result { get; set; } } }
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 SysModulo class. /// </summary> [Serializable] public partial class SysModuloCollection : ActiveList<SysModulo, SysModuloCollection> { public SysModuloCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysModuloCollection</returns> public SysModuloCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysModulo 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 Sys_Modulo table. /// </summary> [Serializable] public partial class SysModulo : ActiveRecord<SysModulo>, IActiveRecord { #region .ctors and Default Settings public SysModulo() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysModulo(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysModulo(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysModulo(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("Sys_Modulo", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdModulo = new TableSchema.TableColumn(schema); colvarIdModulo.ColumnName = "idModulo"; colvarIdModulo.DataType = DbType.Int32; colvarIdModulo.MaxLength = 0; colvarIdModulo.AutoIncrement = true; colvarIdModulo.IsNullable = false; colvarIdModulo.IsPrimaryKey = true; colvarIdModulo.IsForeignKey = false; colvarIdModulo.IsReadOnly = false; colvarIdModulo.DefaultSetting = @""; colvarIdModulo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdModulo); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 50; 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 colvarUrl = new TableSchema.TableColumn(schema); colvarUrl.ColumnName = "url"; colvarUrl.DataType = DbType.AnsiString; colvarUrl.MaxLength = 500; colvarUrl.AutoIncrement = false; colvarUrl.IsNullable = true; colvarUrl.IsPrimaryKey = false; colvarUrl.IsForeignKey = false; colvarUrl.IsReadOnly = false; colvarUrl.DefaultSetting = @""; colvarUrl.ForeignKeyTableName = ""; schema.Columns.Add(colvarUrl); TableSchema.TableColumn colvarIcono = new TableSchema.TableColumn(schema); colvarIcono.ColumnName = "icono"; colvarIcono.DataType = DbType.AnsiString; colvarIcono.MaxLength = 500; colvarIcono.AutoIncrement = false; colvarIcono.IsNullable = true; colvarIcono.IsPrimaryKey = false; colvarIcono.IsForeignKey = false; colvarIcono.IsReadOnly = false; colvarIcono.DefaultSetting = @""; colvarIcono.ForeignKeyTableName = ""; schema.Columns.Add(colvarIcono); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 100; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = true; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarOrden = new TableSchema.TableColumn(schema); colvarOrden.ColumnName = "orden"; colvarOrden.DataType = DbType.Int32; colvarOrden.MaxLength = 0; colvarOrden.AutoIncrement = false; colvarOrden.IsNullable = false; colvarOrden.IsPrimaryKey = false; colvarOrden.IsForeignKey = false; colvarOrden.IsReadOnly = false; colvarOrden.DefaultSetting = @"((0))"; colvarOrden.ForeignKeyTableName = ""; schema.Columns.Add(colvarOrden); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_Modulo",schema); } } #endregion #region Props [XmlAttribute("IdModulo")] [Bindable(true)] public int IdModulo { get { return GetColumnValue<int>(Columns.IdModulo); } set { SetColumnValue(Columns.IdModulo, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Url")] [Bindable(true)] public string Url { get { return GetColumnValue<string>(Columns.Url); } set { SetColumnValue(Columns.Url, value); } } [XmlAttribute("Icono")] [Bindable(true)] public string Icono { get { return GetColumnValue<string>(Columns.Icono); } set { SetColumnValue(Columns.Icono, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("Orden")] [Bindable(true)] public int Orden { get { return GetColumnValue<int>(Columns.Orden); } set { SetColumnValue(Columns.Orden, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.SysMenuCollection colSysMenuRecords; public DalSic.SysMenuCollection SysMenuRecords { get { if(colSysMenuRecords == null) { colSysMenuRecords = new DalSic.SysMenuCollection().Where(SysMenu.Columns.IdModulo, IdModulo).Load(); colSysMenuRecords.ListChanged += new ListChangedEventHandler(colSysMenuRecords_ListChanged); } return colSysMenuRecords; } set { colSysMenuRecords = value; colSysMenuRecords.ListChanged += new ListChangedEventHandler(colSysMenuRecords_ListChanged); } } void colSysMenuRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysMenuRecords[e.NewIndex].IdModulo = IdModulo; } } #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(string varNombre,string varUrl,string varIcono,string varDescripcion,int varOrden) { SysModulo item = new SysModulo(); item.Nombre = varNombre; item.Url = varUrl; item.Icono = varIcono; item.Descripcion = varDescripcion; item.Orden = varOrden; 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 varIdModulo,string varNombre,string varUrl,string varIcono,string varDescripcion,int varOrden) { SysModulo item = new SysModulo(); item.IdModulo = varIdModulo; item.Nombre = varNombre; item.Url = varUrl; item.Icono = varIcono; item.Descripcion = varDescripcion; item.Orden = varOrden; 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 IdModuloColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn UrlColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IconoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn OrdenColumn { get { return Schema.Columns[5]; } } #endregion #region Columns Struct public struct Columns { public static string IdModulo = @"idModulo"; public static string Nombre = @"nombre"; public static string Url = @"url"; public static string Icono = @"icono"; public static string Descripcion = @"descripcion"; public static string Orden = @"orden"; } #endregion #region Update PK Collections public void SetPKValues() { if (colSysMenuRecords != null) { foreach (DalSic.SysMenu item in colSysMenuRecords) { if (item.IdModulo != IdModulo) { item.IdModulo = IdModulo; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colSysMenuRecords != null) { colSysMenuRecords.SaveAll(); } } #endregion } }
using Lucene.Net.Attributes; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; using BitSet = J2N.Collections.BitSet; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; [TestFixture] public class TestFixedBitSet : BaseDocIdSetTestCase<FixedBitSet> { public override FixedBitSet CopyOf(BitSet bs, int length) { FixedBitSet set = new FixedBitSet(length); for (int doc = bs.NextSetBit(0); doc != -1; doc = bs.NextSetBit(doc + 1)) { set.Set(doc); } return set; } internal virtual void DoGet(BitSet a, FixedBitSet b) { int max = b.Length; for (int i = 0; i < max; i++) { if (a.Get(i) != b.Get(i)) { Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.Get(i)); } } } internal virtual void DoNextSetBit(BitSet a, FixedBitSet b) { int aa = -1, bb = -1; do { aa = a.NextSetBit(aa + 1); bb = bb < b.Length - 1 ? b.NextSetBit(bb + 1) : -1; Assert.AreEqual(aa, bb); } while (aa >= 0); } internal virtual void DoPrevSetBit(BitSet a, FixedBitSet b) { int aa = a.Length + Random.Next(100); int bb = aa; do { // aa = a.PrevSetBit(aa-1); aa--; while ((aa >= 0) && (aa >= a.Length || !a.Get(aa))) { aa--; } if (b.Length == 0) { bb = -1; } else if (bb > b.Length - 1) { bb = b.PrevSetBit(b.Length - 1); } else if (bb < 1) { bb = -1; } else { bb = bb >= 1 ? b.PrevSetBit(bb - 1) : -1; } Assert.AreEqual(aa, bb); } while (aa >= 0); } // test interleaving different FixedBitSetIterator.Next()/skipTo() internal virtual void DoIterate(BitSet a, FixedBitSet b, int mode) { if (mode == 1) { DoIterate1(a, b); } if (mode == 2) { DoIterate2(a, b); } } internal virtual void DoIterate1(BitSet a, FixedBitSet b) { int aa = -1, bb = -1; DocIdSetIterator iterator = b.GetIterator(); do { aa = a.NextSetBit(aa + 1); bb = (bb < b.Length && Random.NextBoolean()) ? iterator.NextDoc() : iterator.Advance(bb + 1); Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb); } while (aa >= 0); } internal virtual void DoIterate2(BitSet a, FixedBitSet b) { int aa = -1, bb = -1; DocIdSetIterator iterator = b.GetIterator(); do { aa = a.NextSetBit(aa + 1); bb = Random.NextBoolean() ? iterator.NextDoc() : iterator.Advance(bb + 1); Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb); } while (aa >= 0); } internal virtual void DoRandomSets(int maxSize, int iter, int mode) { BitSet a0 = null; FixedBitSet b0 = null; for (int i = 0; i < iter; i++) { int sz = TestUtil.NextInt32(Random, 2, maxSize); BitSet a = new BitSet(sz); FixedBitSet b = new FixedBitSet(sz); // test the various ways of setting bits if (sz > 0) { int nOper = Random.Next(sz); for (int j = 0; j < nOper; j++) { int idx; idx = Random.Next(sz); a.Set(idx); b.Set(idx); idx = Random.Next(sz); a.Clear(idx); b.Clear(idx); idx = Random.Next(sz); a.Flip(idx, idx + 1); b.Flip(idx, idx + 1); idx = Random.Next(sz); a.Flip(idx, idx + 1); b.Flip(idx, idx + 1); bool val2 = b.Get(idx); bool val = b.GetAndSet(idx); Assert.IsTrue(val2 == val); Assert.IsTrue(b.Get(idx)); if (!val) { b.Clear(idx); } Assert.IsTrue(b.Get(idx) == val); } } // test that the various ways of accessing the bits are equivalent DoGet(a, b); // test ranges, including possible extension int fromIndex, toIndex; fromIndex = Random.Next(sz / 2); toIndex = fromIndex + Random.Next(sz - fromIndex); BitSet aa = (BitSet)a.Clone(); aa.Flip(fromIndex, toIndex); FixedBitSet bb = b.Clone(); bb.Flip(fromIndex, toIndex); DoIterate(aa, bb, mode); // a problem here is from flip or doIterate fromIndex = Random.Next(sz / 2); toIndex = fromIndex + Random.Next(sz - fromIndex); aa = (BitSet)a.Clone(); aa.Clear(fromIndex, toIndex); bb = b.Clone(); bb.Clear(fromIndex, toIndex); DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit DoPrevSetBit(aa, bb); fromIndex = Random.Next(sz / 2); toIndex = fromIndex + Random.Next(sz - fromIndex); aa = (BitSet)a.Clone(); aa.Set(fromIndex, toIndex); bb = b.Clone(); bb.Set(fromIndex, toIndex); DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit DoPrevSetBit(aa, bb); if (b0 != null && b0.Length <= b.Length) { Assert.AreEqual(a.Cardinality, b.Cardinality()); BitSet a_and = (BitSet)a.Clone(); a_and.And(a0); BitSet a_or = (BitSet)a.Clone(); a_or.Or(a0); BitSet a_xor = (BitSet)a.Clone(); a_xor.Xor(a0); BitSet a_andn = (BitSet)a.Clone(); a_andn.AndNot(a0); FixedBitSet b_and = b.Clone(); Assert.AreEqual(b, b_and); b_and.And(b0); FixedBitSet b_or = b.Clone(); b_or.Or(b0); FixedBitSet b_xor = b.Clone(); b_xor.Xor(b0); FixedBitSet b_andn = b.Clone(); b_andn.AndNot(b0); Assert.AreEqual(a0.Cardinality, b0.Cardinality()); Assert.AreEqual(a_or.Cardinality, b_or.Cardinality()); DoIterate(a_and, b_and, mode); DoIterate(a_or, b_or, mode); DoIterate(a_andn, b_andn, mode); DoIterate(a_xor, b_xor, mode); Assert.AreEqual(a_and.Cardinality, b_and.Cardinality()); Assert.AreEqual(a_or.Cardinality, b_or.Cardinality()); Assert.AreEqual(a_xor.Cardinality, b_xor.Cardinality()); Assert.AreEqual(a_andn.Cardinality, b_andn.Cardinality()); } a0 = a; b0 = b; } } // large enough to flush obvious bugs, small enough to run in <.5 sec as part of a // larger testsuite. [Test] public virtual void TestSmall() { DoRandomSets(AtLeast(1200), AtLeast(1000), 1); DoRandomSets(AtLeast(1200), AtLeast(1000), 2); } [Test, LuceneNetSpecific] public void TestClearSmall() { FixedBitSet a = new FixedBitSet(30); // 0110010111001000101101001001110...0 int[] onesA = { 1, 2, 5, 7, 8, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 }; for (int i = 0; i < onesA.size(); i++) { a.Set(onesA[i]); } FixedBitSet b = new FixedBitSet(30); // 0110000001001000101101001001110...0 int[] onesB = { 1, 2, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 }; for (int i = 0; i < onesB.size(); i++) { b.Set(onesB[i]); } a.Clear(5, 9); Assert.True(a.Equals(b)); a.Clear(9, 10); Assert.False(a.Equals(b)); a.Set(9); Assert.True(a.Equals(b)); } [Test, LuceneNetSpecific] public void TestClearLarge() { int iters = AtLeast(1000); for (int it = 0; it < iters; it++) { Random random = new Random(); int sz = AtLeast(1200); FixedBitSet a = new FixedBitSet(sz); FixedBitSet b = new FixedBitSet(sz); int from = random.Next(sz - 1); int to = random.Next(from, sz); for (int i = 0; i < sz / 2; i++) { int index = random.Next(sz - 1); a.Set(index); if (index < from || index >= to) { b.Set(index); } } a.Clear(from, to); Assert.True(a.Equals(b)); } } // uncomment to run a bigger test (~2 minutes). /* public void testBig() { doRandomSets(2000,200000, 1); doRandomSets(2000,200000, 2); } */ [Test] public virtual void TestEquals() { // this test can't handle numBits==0: int numBits = Random.Next(2000) + 1; FixedBitSet b1 = new FixedBitSet(numBits); FixedBitSet b2 = new FixedBitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); for (int iter = 0; iter < 10 * RandomMultiplier; iter++) { int idx = Random.Next(numBits); if (!b1.Get(idx)) { b1.Set(idx); Assert.IsFalse(b1.Equals(b2)); Assert.IsFalse(b2.Equals(b1)); b2.Set(idx); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); } } // try different type of object Assert.IsFalse(b1.Equals(new object())); } [Test] public virtual void TestHashCodeEquals() { // this test can't handle numBits==0: int numBits = Random.Next(2000) + 1; FixedBitSet b1 = new FixedBitSet(numBits); FixedBitSet b2 = new FixedBitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); for (int iter = 0; iter < 10 * RandomMultiplier; iter++) { int idx = Random.Next(numBits); if (!b1.Get(idx)) { b1.Set(idx); Assert.IsFalse(b1.Equals(b2)); Assert.IsFalse(b1.GetHashCode() == b2.GetHashCode()); b2.Set(idx); Assert.AreEqual(b1, b2); Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); } } } [Test] public virtual void TestSmallBitSets() { // Make sure size 0-10 bit sets are OK: for (int numBits = 0; numBits < 10; numBits++) { FixedBitSet b1 = new FixedBitSet(numBits); FixedBitSet b2 = new FixedBitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); Assert.AreEqual(0, b1.Cardinality()); if (numBits > 0) { b1.Set(0, numBits); Assert.AreEqual(numBits, b1.Cardinality()); b1.Flip(0, numBits); Assert.AreEqual(0, b1.Cardinality()); } } } private FixedBitSet MakeFixedBitSet(int[] a, int numBits) { FixedBitSet bs; if (Random.NextBoolean()) { int bits2words = FixedBitSet.Bits2words(numBits); long[] words = new long[bits2words + Random.Next(100)]; for (int i = bits2words; i < words.Length; i++) { words[i] = Random.NextInt64(); } bs = new FixedBitSet(words, numBits); } else { bs = new FixedBitSet(numBits); } foreach (int e in a) { bs.Set(e); } return bs; } private BitSet MakeBitSet(int[] a) { BitSet bs = new BitSet(); foreach (int e in a) { bs.Set(e); } return bs; } private void CheckPrevSetBitArray(int[] a, int numBits) { FixedBitSet obs = MakeFixedBitSet(a, numBits); BitSet bs = MakeBitSet(a); DoPrevSetBit(bs, obs); } [Test] public virtual void TestPrevSetBit() { CheckPrevSetBitArray(new int[] { }, 0); CheckPrevSetBitArray(new int[] { 0 }, 1); CheckPrevSetBitArray(new int[] { 0, 2 }, 3); } private void CheckNextSetBitArray(int[] a, int numBits) { FixedBitSet obs = MakeFixedBitSet(a, numBits); BitSet bs = MakeBitSet(a); DoNextSetBit(bs, obs); } [Test] public virtual void TestNextBitSet() { int[] setBits = new int[0 + Random.Next(1000)]; for (int i = 0; i < setBits.Length; i++) { setBits[i] = Random.Next(setBits.Length); } CheckNextSetBitArray(setBits, setBits.Length + Random.Next(10)); CheckNextSetBitArray(new int[0], setBits.Length + Random.Next(10)); } [Test] public virtual void TestEnsureCapacity() { FixedBitSet bits = new FixedBitSet(5); bits.Set(1); bits.Set(4); FixedBitSet newBits = FixedBitSet.EnsureCapacity(bits, 8); // grow within the word Assert.IsTrue(newBits.Get(1)); Assert.IsTrue(newBits.Get(4)); newBits.Clear(1); // we align to 64-bits, so even though it shouldn't have, it re-allocated a long[1] Assert.IsTrue(bits.Get(1)); Assert.IsFalse(newBits.Get(1)); newBits.Set(1); newBits = FixedBitSet.EnsureCapacity(newBits, newBits.Length - 2); // reuse Assert.IsTrue(newBits.Get(1)); bits.Set(1); newBits = FixedBitSet.EnsureCapacity(bits, 72); // grow beyond one word Assert.IsTrue(newBits.Get(1)); Assert.IsTrue(newBits.Get(4)); newBits.Clear(1); // we grew the long[], so it's not shared Assert.IsTrue(bits.Get(1)); Assert.IsFalse(newBits.Get(1)); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcvsv = Google.Cloud.Video.Stitcher.V1; using sys = System; namespace Google.Cloud.Video.Stitcher.V1 { /// <summary>Resource name for the <c>VodSession</c> resource.</summary> public sealed partial class VodSessionName : gax::IResourceName, sys::IEquatable<VodSessionName> { /// <summary>The possible contents of <see cref="VodSessionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c>. /// </summary> ProjectLocationVodSession = 1, } private static gax::PathTemplate s_projectLocationVodSession = new gax::PathTemplate("projects/{project}/locations/{location}/vodSessions/{vod_session}"); /// <summary>Creates a <see cref="VodSessionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="VodSessionName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static VodSessionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new VodSessionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="VodSessionName"/> with the pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="VodSessionName"/> constructed from the provided ids.</returns> public static VodSessionName FromProjectLocationVodSession(string projectId, string locationId, string vodSessionId) => new VodSessionName(ResourceNameType.ProjectLocationVodSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), vodSessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(vodSessionId, nameof(vodSessionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="VodSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VodSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c>. /// </returns> public static string Format(string projectId, string locationId, string vodSessionId) => FormatProjectLocationVodSession(projectId, locationId, vodSessionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="VodSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VodSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c>. /// </returns> public static string FormatProjectLocationVodSession(string projectId, string locationId, string vodSessionId) => s_projectLocationVodSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(vodSessionId, nameof(vodSessionId))); /// <summary>Parses the given resource name string into a new <see cref="VodSessionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c></description> /// </item> /// </list> /// </remarks> /// <param name="vodSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="VodSessionName"/> if successful.</returns> public static VodSessionName Parse(string vodSessionName) => Parse(vodSessionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="VodSessionName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="vodSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="VodSessionName"/> if successful.</returns> public static VodSessionName Parse(string vodSessionName, bool allowUnparsed) => TryParse(vodSessionName, allowUnparsed, out VodSessionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VodSessionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c></description> /// </item> /// </list> /// </remarks> /// <param name="vodSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="VodSessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string vodSessionName, out VodSessionName result) => TryParse(vodSessionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VodSessionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="vodSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="VodSessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string vodSessionName, bool allowUnparsed, out VodSessionName result) { gax::GaxPreconditions.CheckNotNull(vodSessionName, nameof(vodSessionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationVodSession.TryParseName(vodSessionName, out resourceName)) { result = FromProjectLocationVodSession(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(vodSessionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private VodSessionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string vodSessionId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; VodSessionId = vodSessionId; } /// <summary> /// Constructs a new instance of a <see cref="VodSessionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> public VodSessionName(string projectId, string locationId, string vodSessionId) : this(ResourceNameType.ProjectLocationVodSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), vodSessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(vodSessionId, nameof(vodSessionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>VodSession</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string VodSessionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationVodSession: return s_projectLocationVodSession.Expand(ProjectId, LocationId, VodSessionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as VodSessionName); /// <inheritdoc/> public bool Equals(VodSessionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(VodSessionName a, VodSessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(VodSessionName a, VodSessionName b) => !(a == b); } /// <summary>Resource name for the <c>LiveSession</c> resource.</summary> public sealed partial class LiveSessionName : gax::IResourceName, sys::IEquatable<LiveSessionName> { /// <summary>The possible contents of <see cref="LiveSessionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/liveSessions/{live_session}</c>. /// </summary> ProjectLocationLiveSession = 1, } private static gax::PathTemplate s_projectLocationLiveSession = new gax::PathTemplate("projects/{project}/locations/{location}/liveSessions/{live_session}"); /// <summary>Creates a <see cref="LiveSessionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="LiveSessionName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static LiveSessionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new LiveSessionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="LiveSessionName"/> with the pattern /// <c>projects/{project}/locations/{location}/liveSessions/{live_session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="liveSessionId">The <c>LiveSession</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="LiveSessionName"/> constructed from the provided ids.</returns> public static LiveSessionName FromProjectLocationLiveSession(string projectId, string locationId, string liveSessionId) => new LiveSessionName(ResourceNameType.ProjectLocationLiveSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), liveSessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(liveSessionId, nameof(liveSessionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="LiveSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/liveSessions/{live_session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="liveSessionId">The <c>LiveSession</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="LiveSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/liveSessions/{live_session}</c>. /// </returns> public static string Format(string projectId, string locationId, string liveSessionId) => FormatProjectLocationLiveSession(projectId, locationId, liveSessionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="LiveSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/liveSessions/{live_session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="liveSessionId">The <c>LiveSession</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="LiveSessionName"/> with pattern /// <c>projects/{project}/locations/{location}/liveSessions/{live_session}</c>. /// </returns> public static string FormatProjectLocationLiveSession(string projectId, string locationId, string liveSessionId) => s_projectLocationLiveSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(liveSessionId, nameof(liveSessionId))); /// <summary>Parses the given resource name string into a new <see cref="LiveSessionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/liveSessions/{live_session}</c></description> /// </item> /// </list> /// </remarks> /// <param name="liveSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="LiveSessionName"/> if successful.</returns> public static LiveSessionName Parse(string liveSessionName) => Parse(liveSessionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="LiveSessionName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/liveSessions/{live_session}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="liveSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="LiveSessionName"/> if successful.</returns> public static LiveSessionName Parse(string liveSessionName, bool allowUnparsed) => TryParse(liveSessionName, allowUnparsed, out LiveSessionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="LiveSessionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/liveSessions/{live_session}</c></description> /// </item> /// </list> /// </remarks> /// <param name="liveSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="LiveSessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string liveSessionName, out LiveSessionName result) => TryParse(liveSessionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="LiveSessionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/liveSessions/{live_session}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="liveSessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="LiveSessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string liveSessionName, bool allowUnparsed, out LiveSessionName result) { gax::GaxPreconditions.CheckNotNull(liveSessionName, nameof(liveSessionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationLiveSession.TryParseName(liveSessionName, out resourceName)) { result = FromProjectLocationLiveSession(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(liveSessionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private LiveSessionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string liveSessionId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LiveSessionId = liveSessionId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="LiveSessionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/liveSessions/{live_session}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="liveSessionId">The <c>LiveSession</c> ID. Must not be <c>null</c> or empty.</param> public LiveSessionName(string projectId, string locationId, string liveSessionId) : this(ResourceNameType.ProjectLocationLiveSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), liveSessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(liveSessionId, nameof(liveSessionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>LiveSession</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LiveSessionId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationLiveSession: return s_projectLocationLiveSession.Expand(ProjectId, LocationId, LiveSessionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as LiveSessionName); /// <inheritdoc/> public bool Equals(LiveSessionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(LiveSessionName a, LiveSessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(LiveSessionName a, LiveSessionName b) => !(a == b); } public partial class VodSession { /// <summary> /// <see cref="gcvsv::VodSessionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcvsv::VodSessionName VodSessionName { get => string.IsNullOrEmpty(Name) ? null : gcvsv::VodSessionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class LiveSession { /// <summary> /// <see cref="gcvsv::LiveSessionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcvsv::LiveSessionName LiveSessionName { get => string.IsNullOrEmpty(Name) ? null : gcvsv::LiveSessionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ExtensionRequest. /// </summary> public partial class ExtensionRequest : BaseRequest, IExtensionRequest { /// <summary> /// Constructs a new ExtensionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ExtensionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Extension using POST. /// </summary> /// <param name="extensionToCreate">The Extension to create.</param> /// <returns>The created Extension.</returns> public System.Threading.Tasks.Task<Extension> CreateAsync(Extension extensionToCreate) { return this.CreateAsync(extensionToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Extension using POST. /// </summary> /// <param name="extensionToCreate">The Extension to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Extension.</returns> public async System.Threading.Tasks.Task<Extension> CreateAsync(Extension extensionToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Extension>(extensionToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Extension. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Extension. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Extension>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Extension. /// </summary> /// <returns>The Extension.</returns> public System.Threading.Tasks.Task<Extension> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Extension. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Extension.</returns> public async System.Threading.Tasks.Task<Extension> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Extension>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Extension using PATCH. /// </summary> /// <param name="extensionToUpdate">The Extension to update.</param> /// <returns>The updated Extension.</returns> public System.Threading.Tasks.Task<Extension> UpdateAsync(Extension extensionToUpdate) { return this.UpdateAsync(extensionToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Extension using PATCH. /// </summary> /// <param name="extensionToUpdate">The Extension to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Extension.</returns> public async System.Threading.Tasks.Task<Extension> UpdateAsync(Extension extensionToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Extension>(extensionToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IExtensionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IExtensionRequest Expand(Expression<Func<Extension, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IExtensionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IExtensionRequest Select(Expression<Func<Extension, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="extensionToInitialize">The <see cref="Extension"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Extension extensionToInitialize) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace OutOfMemory.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 Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HWPF.SPRM { using System; using System.Collections; using NPOI.HWPF.UserModel; using NPOI.Util; using NPOI.Util.Collections; public class ParagraphSprmUncompressor : SprmUncompressor { public ParagraphSprmUncompressor() { } public static ParagraphProperties UncompressPAP(ParagraphProperties parent, byte[] grpprl, int Offset) { ParagraphProperties newProperties = null; newProperties = (ParagraphProperties)parent.Clone(); SprmIterator sprmIt = new SprmIterator(grpprl, Offset); while (sprmIt.HasNext()) { SprmOperation sprm = sprmIt.Next(); // PAPXs can contain table sprms if the paragraph marks the end of a // table row if (sprm.Type == SprmOperation.TYPE_PAP) { UncompressPAPOperation(newProperties, sprm); } } return newProperties; } /** * Performs an operation on a ParagraphProperties object. Used to uncompress * from a papx. * * @param newPAP The ParagraphProperties object to perform the operation on. * @param operand The operand that defines the operation. * @param param The operation's parameter. * @param varParam The operation's variable length parameter. * @param grpprl The original papx. * @param offset The current offset in the papx. * @param spra A part of the sprm that defined this operation. */ static void UncompressPAPOperation(ParagraphProperties newPAP, SprmOperation sprm) { switch (sprm.Operation) { case 0: newPAP.SetIstd(sprm.Operand); break; case 0x1: // Used only for piece table grpprl's not for PAPX // int istdFirst = LittleEndian.Getshort (varParam, 2); // int istdLast = LittleEndian.Getshort (varParam, 4); // if ((newPAP.GetIstd () > istdFirst) || (newPAP.GetIstd () <= istdLast)) // { // permuteIstd (newPAP, varParam, opSize); // } break; case 0x2: if (newPAP.GetIstd() <= 9 || newPAP.GetIstd() >= 1) { byte paramTmp = (byte)sprm.Operand; newPAP.SetIstd(newPAP.GetIstd() + paramTmp); newPAP.SetLvl((byte)(newPAP.GetLvl() + paramTmp)); if (((paramTmp >> 7) & 0x01) == 1) { newPAP.SetIstd(Math.Max(newPAP.GetIstd(), 1)); } else { newPAP.SetIstd(Math.Min(newPAP.GetIstd(), 9)); } } break; case 0x3: // Physical justification of the paragraph newPAP.SetJc((byte)sprm.Operand); break; case 0x4: newPAP.SetFSideBySide(sprm.Operand!=0); break; case 0x5: newPAP.SetFKeep(sprm.Operand!=0); break; case 0x6: newPAP.SetFKeepFollow(sprm.Operand!=0); break; case 0x7: newPAP.SetFPageBreakBefore(sprm.Operand!=0); break; case 0x8: newPAP.SetBrcl((byte)sprm.Operand); break; case 0x9: newPAP.SetBrcp((byte)sprm.Operand); break; case 0xa: newPAP.SetIlvl((byte)sprm.Operand); break; case 0xb: newPAP.SetIlfo(sprm.Operand); break; case 0xc: newPAP.SetFNoLnn(sprm.Operand!=0); break; case 0xd: /**handle tabs . variable parameter. seperate Processing needed*/ handleTabs(newPAP, sprm); break; case 0xe: newPAP.SetDxaRight(sprm.Operand); break; case 0xf: newPAP.SetDxaLeft(sprm.Operand); break; case 0x10: // sprmPNest is only stored in grpprls linked to a piece table. newPAP.SetDxaLeft(newPAP.GetDxaLeft() + sprm.Operand); newPAP.SetDxaLeft(Math.Max(0, newPAP.GetDxaLeft())); break; case 0x11: newPAP.SetDxaLeft1(sprm.Operand); break; case 0x12: newPAP.SetLspd(new LineSpacingDescriptor(sprm.Grpprl, sprm.GrpprlOffset)); break; case 0x13: newPAP.SetDyaBefore(sprm.Operand); break; case 0x14: newPAP.SetDyaAfter(sprm.Operand); break; case 0x15: // fast saved only //ApplySprmPChgTabs (newPAP, varParam, opSize); break; case 0x16: newPAP.SetFInTable(sprm.Operand!=0); break; case 0x17: newPAP.SetFTtp(sprm.Operand!=0); break; case 0x18: newPAP.SetDxaAbs(sprm.Operand); break; case 0x19: newPAP.SetDyaAbs(sprm.Operand); break; case 0x1a: newPAP.SetDxaWidth(sprm.Operand); break; case 0x1b: byte param = (byte)sprm.Operand; /** @todo handle paragraph postioning*/ byte pcVert = (byte)((param & 0x0c) >> 2); byte pcHorz = (byte)(param & 0x03); if (pcVert != 3) { newPAP.SetPcVert(pcVert); } if (pcHorz != 3) { newPAP.SetPcHorz(pcHorz); } break; // BrcXXX1 is older Version. Brc is used case 0x1c: //newPAP.SetBrcTop1((short)param); break; case 0x1d: //newPAP.SetBrcLeft1((short)param); break; case 0x1e: //newPAP.SetBrcBottom1((short)param); break; case 0x1f: //newPAP.SetBrcRight1((short)param); break; case 0x20: //newPAP.SetBrcBetween1((short)param); break; case 0x21: //newPAP.SetBrcBar1((byte)param); break; case 0x22: newPAP.SetDxaFromText(sprm.Operand); break; case 0x23: newPAP.SetWr((byte)sprm.Operand); break; case 0x24: newPAP.SetBrcTop(new BorderCode(sprm.Grpprl, sprm.GrpprlOffset)); break; case 0x25: newPAP.SetBrcLeft(new BorderCode(sprm.Grpprl, sprm.GrpprlOffset)); break; case 0x26: newPAP.SetBrcBottom(new BorderCode(sprm.Grpprl, sprm.GrpprlOffset)); break; case 0x27: newPAP.SetBrcRight(new BorderCode(sprm.Grpprl, sprm.GrpprlOffset)); break; case 0x28: newPAP.SetBrcBetween(new BorderCode(sprm.Grpprl, sprm.GrpprlOffset)); break; case 0x29: newPAP.SetBrcBar(new BorderCode(sprm.Grpprl, sprm.GrpprlOffset)); break; case 0x2a: newPAP.SetFNoAutoHyph(sprm.Operand!=0); break; case 0x2b: newPAP.SetDyaHeight(sprm.Operand); break; case 0x2c: newPAP.SetDcs(new DropCapSpecifier((short)sprm.Operand)); break; case 0x2d: newPAP.SetShd(new ShadingDescriptor((short)sprm.Operand)); break; case 0x2e: newPAP.SetDyaFromText(sprm.Operand); break; case 0x2f: newPAP.SetDxaFromText(sprm.Operand); break; case 0x30: newPAP.SetFLocked(sprm.Operand!=0); break; case 0x31: newPAP.SetFWidowControl(sprm.Operand!=0); break; case 0x32: //undocumented break; case 0x33: newPAP.SetFKinsoku(sprm.Operand!=0); break; case 0x34: newPAP.SetFWordWrap(sprm.Operand!=0); break; case 0x35: newPAP.SetFOverflowPunct(sprm.Operand!=0); break; case 0x36: newPAP.SetFTopLinePunct(sprm.Operand!=0); break; case 0x37: newPAP.SetFAutoSpaceDE(sprm.Operand!=0); break; case 0x38: newPAP.SetFAutoSpaceDN(sprm.Operand!=0); break; case 0x39: newPAP.SetWAlignFont(sprm.Operand); break; case 0x3a: newPAP.SetFontAlign((short)sprm.Operand); break; case 0x3b: //obsolete break; case 0x3e: byte[] buf = new byte[sprm.Size - 3]; Array.Copy(buf, 0, sprm.Grpprl, sprm.GrpprlOffset, buf.Length); newPAP.SetAnld(buf); break; case 0x3f: //don't really need this. spec is confusing regarding this //sprm byte[] varParam = sprm.Grpprl; int offset = sprm.GrpprlOffset; newPAP.SetFPropRMark(varParam[offset]!=0); newPAP.SetIbstPropRMark(LittleEndian.GetShort(varParam, offset + 1)); newPAP.SetDttmPropRMark(new DateAndTime(varParam, offset + 3)); break; case 0x40: // This condition commented out, as Word seems to set outline levels even for // paragraph with other styles than Heading 1..9, even though specification // does not say so. See bug 49820 for discussion. //if (newPAP.GetIstd () < 1 && newPAP.GetIstd () > 9) //{ newPAP.SetLvl((byte)sprm.Operand); //} break; case 0x41: // undocumented break; case 0x43: //pap.fNumRMIns newPAP.SetFNumRMIns(sprm.Operand!=0); break; case 0x44: //undocumented break; case 0x45: if (sprm.SizeCode == 6) { byte[] buf1 = new byte[sprm.Size - 3]; Array.Copy(buf1, 0, sprm.Grpprl, sprm.GrpprlOffset, buf1.Length); newPAP.SetNumrm(buf1); } else { /**@todo handle large PAPX from data stream*/ } break; case 0x47: newPAP.SetFUsePgsuSettings(sprm.Operand!=0); break; case 0x48: newPAP.SetFAdjustRight(sprm.Operand!=0); break; case 0x49: // sprmPItap -- 0x6649 newPAP.SetItap(sprm.Operand); break; case 0x4a: // sprmPDtap -- 0x664a newPAP.SetItap((byte)(newPAP.GetItap() + sprm.Operand)); break; case 0x4b: // sprmPFInnerTableCell -- 0x244b newPAP.SetFInnerTableCell(sprm.Operand!=0); break; case 0x4c: // sprmPFInnerTtp -- 0x244c newPAP.SetFTtpEmbedded(sprm.Operand!=0); break; case 0x61: // sprmPJc newPAP.SetJustificationLogical((byte)sprm.Operand); break; default: break; } } private static void handleTabs(ParagraphProperties pap, SprmOperation sprm) { byte[] grpprl = sprm.Grpprl; int offset = sprm.GrpprlOffset; int delSize = grpprl[offset++]; int[] tabPositions = pap.GetRgdxaTab(); byte[] tabDescriptors = pap.GetRgtbd(); Hashtable tabMap = new Hashtable(); for (int x = 0; x < tabPositions.Length; x++) { tabMap.Add(tabPositions[x], tabDescriptors[x]); } for (int x = 0; x < delSize; x++) { tabMap.Remove(LittleEndian.GetShort(grpprl, offset)); offset += LittleEndianConsts.SHORT_SIZE; } int addSize = grpprl[offset++]; int start = offset; for (int x = 0; x < addSize; x++) { int key = LittleEndian.GetShort(grpprl, offset); Byte val = grpprl[start + ((LittleEndianConsts.SHORT_SIZE * addSize) + x)]; tabMap.Add(key, val); offset += LittleEndianConsts.SHORT_SIZE; } tabPositions = new int[tabMap.Count]; tabDescriptors = new byte[tabPositions.Length]; ArrayList list = new ArrayList(); IEnumerator keyIT = tabMap.Keys.GetEnumerator(); while (keyIT.MoveNext()) { list.Add(keyIT.Current); } list.Sort(); for (int x = 0; x < tabPositions.Length; x++) { int key = (int)list[x]; tabPositions[x] = key; tabDescriptors[x] = (byte)tabMap[key]; } pap.SetRgdxaTab(tabPositions); pap.SetRgtbd(tabDescriptors); } // private static void handleTabsAgain(ParagraphProperties pap, SprmOperation sprm) // { // byte[] grpprl = sprm.Grpprl; // int offset = sprm.GrpprlOffset; // int delSize = grpprl[Offset++]; // int[] tabPositions = pap.GetRgdxaTab(); // byte[] tabDescriptors = pap.GetRgtbd(); // // HashMap tabMap = new HashMap(); // for (int x = 0; x < tabPositions.Length; x++) // { // tabMap.Put(Int32.ValueOf(tabPositions[x]), Byte.ValueOf(tabDescriptors[x])); // } // // for (int x = 0; x < delSize; x++) // { // tabMap.Remove(Int32.valueOf(LittleEndian.getInt(grpprl, Offset))); // offset += LittleEndian.INT_SIZE;; // } // // int AddSize = grpprl[Offset++]; // for (int x = 0; x < AddSize; x++) // { // Integer key = Int32.ValueOf(LittleEndian.getInt(grpprl, Offset)); // Byte val = Byte.ValueOf(grpprl[(LittleEndian.INT_SIZE * (AddSize - x)) + x]); // tabMap.Put(key, val); // offset += LittleEndian.INT_SIZE; // } // // tabPositions = new int[tabMap.Count]; // tabDescriptors = new byte[tabPositions.Length]; // ArrayList list = new ArrayList(); // // Iterator keyIT = tabMap.keySet().iterator(); // while (keyIT.hasNext()) // { // list.Add(keyIT.next()); // } // Collections.sort(list); // // for (int x = 0; x < tabPositions.Length; x++) // { // Integer key = ((Integer)list.Get(x)); // tabPositions[x] = key.intValue(); // tabDescriptors[x] = ((Byte)tabMap.Get(key)).byteValue(); // } // // pap.SetRgdxaTab(tabPositions); // pap.SetRgtbd(tabDescriptors); // } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests { public class OperatorOverloadsHaveNamedAlternatesTests : DiagnosticAnalyzerTestBase { #region Boilerplate protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new OperatorOverloadsHaveNamedAlternatesAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new OperatorOverloadsHaveNamedAlternatesAnalyzer(); } private static DiagnosticResult GetCA2225CSharpDefaultResultAt(int line, int column, string alternateName, string operatorName) { // Provide a method named '{0}' as a friendly alternate for operator {1}. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageDefault, alternateName, operatorName); return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message); } private static DiagnosticResult GetCA2225CSharpPropertyResultAt(int line, int column, string alternateName, string operatorName) { // Provide a property named '{0}' as a friendly alternate for operator {1}. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageProperty, alternateName, operatorName); return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message); } private static DiagnosticResult GetCA2225CSharpMultipleResultAt(int line, int column, string alternateName1, string alternateName2, string operatorName) { // Provide a method named '{0}' or '{1}' as an alternate for operator {2} string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageMultiple, alternateName1, alternateName2, operatorName); return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message); } private static DiagnosticResult GetCA2225CSharpVisibilityResultAt(int line, int column, string alternateName, string operatorName) { // Mark {0} as public because it is a friendly alternate for operator {1}. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageVisibility, alternateName, operatorName); return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message); } private static DiagnosticResult GetCA2225BasicDefaultResultAt(int line, int column, string alternateName, string operatorName) { // Provide a method named '{0}' as a friendly alternate for operator {1}. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageDefault, alternateName, operatorName); return GetBasicResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message); } #endregion #region C# tests [Fact] public void HasAlternateMethod_CSharp() { VerifyCSharp(@" class C { public static C operator +(C left, C right) { return new C(); } public static C Add(C left, C right) { return new C(); } } "); } [Fact] public void HasMultipleAlternatePrimary_CSharp() { VerifyCSharp(@" class C { public static C operator %(C left, C right) { return new C(); } public static C Mod(C left, C right) { return new C(); } } "); } [Fact] public void HasMultipleAlternateSecondary_CSharp() { VerifyCSharp(@" class C { public static C operator %(C left, C right) { return new C(); } public static C Remainder(C left, C right) { return new C(); } } "); } [Fact] public void HasAppropriateConversionAlternate_CSharp() { VerifyCSharp(@" class C { public static implicit operator int(C item) { return 0; } public int ToInt32() { return 0; } } "); } [Fact] public void MissingAlternateMethod_CSharp() { VerifyCSharp(@" class C { public static C operator +(C left, C right) { return new C(); } } ", GetCA2225CSharpDefaultResultAt(4, 30, "Add", "op_Addition")); } [Fact] public void MissingAlternateProperty_CSharp() { VerifyCSharp(@" class C { public static bool operator true(C item) { return true; } public static bool operator false(C item) { return false; } } ", GetCA2225CSharpPropertyResultAt(4, 33, "IsTrue", "op_True")); } [Fact] public void MissingMultipleAlternates_CSharp() { VerifyCSharp(@" class C { public static C operator %(C left, C right) { return new C(); } } ", GetCA2225CSharpMultipleResultAt(4, 30, "Mod", "Remainder", "op_Modulus")); } [Fact] public void ImproperAlternateMethodVisibility_CSharp() { VerifyCSharp(@" class C { public static C operator +(C left, C right) { return new C(); } protected static C Add(C left, C right) { return new C(); } } ", GetCA2225CSharpVisibilityResultAt(5, 24, "Add", "op_Addition")); } [Fact] public void ImproperAlternatePropertyVisibility_CSharp() { VerifyCSharp(@" class C { public static bool operator true(C item) { return true; } public static bool operator false(C item) { return false; } private bool IsTrue => true; } ", GetCA2225CSharpVisibilityResultAt(6, 18, "IsTrue", "op_True")); } [Fact] public void StructHasAlternateMethod_CSharp() { VerifyCSharp(@" struct C { public static C operator +(C left, C right) { return new C(); } public static C Add(C left, C right) { return new C(); } } "); } #endregion // // Since the analyzer is symbol-based, only a few VB tests are added as a sanity check // #region VB tests [Fact] public void HasAlternateMethod_VisualBasic() { VerifyBasic(@" Class C Public Shared Operator +(left As C, right As C) As C Return New C() End Operator Public Shared Function Add(left As C, right As C) As C Return New C() End Function End Class "); } [Fact] public void MissingAlternateMethod_VisualBasic() { VerifyBasic(@" Class C Public Shared Operator +(left As C, right As C) As C Return New C() End Operator End Class ", GetCA2225BasicDefaultResultAt(3, 28, "Add", "op_Addition")); } [Fact] public void StructHasAlternateMethod_VisualBasic() { VerifyBasic(@" Structure C Public Shared Operator +(left As C, right As C) As C Return New C() End Operator Public Shared Function Add(left As C, right As C) As C Return New C() End Function End Structure "); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; using DeOps.Implementation; using DeOps.Services.Trust; namespace DeOps.Services.Profile { public partial class EditProfile : DeOps.Interface.CustomIconForm { public OpCore Core; TrustService Links; public ProfileService Profiles; public ProfileView MainView; List<ProfileTemplate> Templates = new List<ProfileTemplate>(); public Dictionary<string, string> TextFields = new Dictionary<string, string>(); public Dictionary<string, string> FileFields = new Dictionary<string, string>(); public EditProfile(ProfileService control, ProfileView view) { InitializeComponent(); Core = control.Core; Links = Core.Trust; Profiles = control; MainView = view; TextFields = new Dictionary<string, string>(view.TextFields); FileFields = new Dictionary<string, string>(view.FileFields); } private void EditProfile_Load(object sender, EventArgs e) { RefreshTemplates(); } private void RefreshTemplates() { Templates.Clear(); // list chain of command first List<ulong> highers = Links.GetUplinkIDs(Core.UserID, 0); highers.Reverse(); highers.Add(Links.LocalTrust.UserID); // list higher level users, indent also // dont repeat names using same template+ int space = 0; foreach (ulong id in highers) { ProfileTemplate add = GetTemplate(id); if (add == null || add.Hash == null) continue; foreach(ProfileTemplate template in TemplateCombo.Items) if (Utilities.MemCompare(add.Hash, template.Hash)) continue; for (int i = 0; i < space; i++) add.User = " " + add.User; TemplateCombo.Items.Add(add); space += 4; } // sort rest alphabetically List<ProfileTemplate> templates = new List<ProfileTemplate>(); // read profile header file Profiles.ProfileMap.LockReading(delegate() { foreach (ulong id in Profiles.ProfileMap.Keys) { ProfileTemplate add = GetTemplate(id); if (add == null || add.Hash == null) continue; bool dupe = false; foreach (ProfileTemplate template in TemplateCombo.Items) if (Utilities.MemCompare(add.Hash, template.Hash)) dupe = true; foreach (ProfileTemplate template in templates) if (Utilities.MemCompare(add.Hash, template.Hash)) dupe = true; if (!dupe) templates.Add(add); } }); // add space between chain items and other items if (TemplateCombo.Items.Count > 0 && templates.Count > 0) TemplateCombo.Items.Add(new ProfileTemplate(true, false)); templates.Sort(); foreach (ProfileTemplate template in templates) TemplateCombo.Items.Add(template); // select local template ProfileTemplate local = GetTemplate(Core.UserID); if(local != null) foreach (ProfileTemplate template in TemplateCombo.Items) if (Utilities.MemCompare(local.Hash, template.Hash)) { TemplateCombo.SelectedItem = template; break; } } private ProfileTemplate GetTemplate(ulong id) { OpProfile profile = Profiles.GetProfile(id); if (profile == null) return null; ProfileTemplate template = new ProfileTemplate(false, true); template.User = Core.GetName(id); ; template.FilePath = Profiles.GetFilePath(profile); template.FileKey = profile.File.Header.FileKey; if (!profile.Loaded) Profiles.LoadProfile(profile.UserID); try { using (TaggedStream stream = new TaggedStream(template.FilePath, Core.GuiProtocol)) using (IVCryptoStream crypto = IVCryptoStream.Load(stream, template.FileKey)) { int buffSize = 4096; byte[] buffer = new byte[4096]; long bytesLeft = profile.EmbeddedStart; while (bytesLeft > 0) { int readSize = (bytesLeft > (long)buffSize) ? buffSize : (int)bytesLeft; int read = crypto.Read(buffer, 0, readSize); bytesLeft -= (long)read; } foreach (ProfileAttachment attach in profile.Attached) if (attach.Name.StartsWith("template")) { byte[] html = new byte[attach.Size]; crypto.Read(html, 0, (int)attach.Size); template.Html = UTF8Encoding.UTF8.GetString(html); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); template.Hash = sha1.ComputeHash(html); break; } } } catch { return null; } return template; } int NewCount = 0; private void LinkNew_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ProfileTemplate newTemplate = new ProfileTemplate(false, false); newTemplate.User = "New"; newTemplate.Html = ""; if (NewCount > 0) newTemplate.User += " " + NewCount.ToString(); NewCount++; EditTemplate edit = new EditTemplate(newTemplate, this); edit.ShowDialog(this); } private void LinkEdit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (TemplateCombo.SelectedItem == null) return; ProfileTemplate template = (ProfileTemplate)TemplateCombo.SelectedItem; if (template.Inactive) return; // if ondisk, copy before editing if (template.OnDisk) { ProfileTemplate copy = new ProfileTemplate(false, false); copy.User = template.User + " (edited)"; copy.User = copy.User.TrimStart(new char[] { ' ' }); copy.Html = template.Html; template = copy; } EditTemplate edit = new EditTemplate(template, this); edit.ShowDialog(this); } private void LinkPreview_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (TemplateCombo.SelectedItem == null) return; ProfileTemplate template = (ProfileTemplate) TemplateCombo.SelectedItem; if (template.Inactive) return; PreviewTemplate preview = new PreviewTemplate(template.Html, this); preview.ShowDialog(this); } public void TemplateCombo_SelectedIndexChanged(object sender, EventArgs e) { FieldsCombo.Items.Clear(); ValueTextBox.Text = ""; if (TemplateCombo.SelectedItem == null) return; ProfileTemplate template = (ProfileTemplate)TemplateCombo.SelectedItem; if (template.Inactive) return; List<TemplateTag> tags = new List<TemplateTag>(); // extract tag names from html string html = template.Html; // replace fields while (html.Contains("<?")) { int start = html.IndexOf("<?"); int end = html.IndexOf("?>"); if (end == -1) break; string fulltag = html.Substring(start, end + 2 - start); string tag = fulltag.Substring(2, fulltag.Length - 4); string[] parts = tag.Split(new char[] { ':' }); if (parts.Length == 2) { if (parts[0] == "text") tags.Add(new TemplateTag(parts[1], ProfileFieldType.Text)); else if (parts[0] == "file") tags.Add(new TemplateTag(parts[1], ProfileFieldType.File)); } html = html.Replace(fulltag, ""); } tags.Sort(); bool motdAdded = false; // add just 1 to change foreach (TemplateTag tag in tags) { // if motd for this project, allow if (tag.Name.StartsWith("MOTD")) if (!motdAdded) { tag.Name = "MOTD"; motdAdded = true; } else continue; FieldsCombo.Items.Add(tag); } if (FieldsCombo.Items.Count > 0) { FieldsCombo.SelectedItem = FieldsCombo.Items[0]; FieldsCombo_SelectedIndexChanged(null, null); } } private void FieldsCombo_SelectedIndexChanged(object sender, EventArgs e) { if (FieldsCombo.SelectedItem == null) return; TemplateTag tag = (TemplateTag)FieldsCombo.SelectedItem; if (tag.FieldType == ProfileFieldType.Text) { LinkBrowse.Enabled = false; ValueTextBox.ReadOnly = false; } else { LinkBrowse.Enabled = true; ValueTextBox.ReadOnly = true; } // set value text if (tag.FieldType == ProfileFieldType.Text) { string fieldName = tag.Name; if (fieldName == "MOTD") fieldName = "MOTD-" + MainView.GetProjectID().ToString(); if (TextFields.ContainsKey(fieldName)) ValueTextBox.Text = TextFields[fieldName]; else ValueTextBox.Text = ""; } else if (tag.FieldType == ProfileFieldType.File && FileFields.ContainsKey(tag.Name)) ValueTextBox.Text = FileFields[tag.Name]; else ValueTextBox.Text = "Click Browse to select a file"; ValueTextBox_TextChanged(null, null); } private void ValueTextBox_TextChanged(object sender, EventArgs e) { if (FieldsCombo.SelectedItem == null) return; TemplateTag tag = (TemplateTag) FieldsCombo.SelectedItem; if (tag.FieldType == ProfileFieldType.Text) { string fieldName = tag.Name; if (fieldName == "MOTD") fieldName = "MOTD-" + MainView.GetProjectID().ToString(); TextFields[fieldName] = ValueTextBox.Text; } if (tag.FieldType == ProfileFieldType.File) FileFields[tag.Name] = ValueTextBox.Text; } private void LinkBrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (FieldsCombo.SelectedItem == null) return; TemplateTag tag = (TemplateTag)FieldsCombo.SelectedItem; OpenFileDialog open = new OpenFileDialog(); open.Multiselect = true; open.Title = "Browse for File"; open.Filter = "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { ValueTextBox.Text = open.FileName; FileFields[tag.Name] = open.FileName; } } private void ButtonOK_Click(object sender, EventArgs e) { if (TemplateCombo.SelectedItem == null) { Close(); return; } ProfileTemplate template = (ProfileTemplate)TemplateCombo.SelectedItem; if (template.Inactive) { Close(); return; } // remove text fields that are not in template List<string> removeKeys = new List<string>(); foreach (string key in TextFields.Keys) if (!key.StartsWith("MOTD") && !template.Html.Contains("<?text:" + key)) removeKeys.Add(key); foreach (string key in removeKeys) TextFields.Remove(key); // remove files that are not in template removeKeys.Clear(); foreach (string key in FileFields.Keys) if (!template.Html.Contains("<?file:" + key)) removeKeys.Add(key); foreach (string key in removeKeys) FileFields.Remove(key); // save profile will also update underlying interface Profiles.SaveLocal(template.Html, TextFields, FileFields); Close(); } private void ButtonCancel_Click(object sender, EventArgs e) { Close(); } } public class ProfileTemplate : IComparable { public bool Inactive; public bool OnDisk; public string User = ""; public string FilePath; public byte[] FileKey; public string Html = ""; public byte[] Hash; public ProfileTemplate(bool inactive, bool ondisk) { Inactive = inactive; OnDisk = ondisk; } public override string ToString() { return User; } public int CompareTo(object obj) { return User.CompareTo(((ProfileTemplate)obj).User); } } public class TemplateTag : IComparable { public string Name ; public ProfileFieldType FieldType; public TemplateTag(string name, ProfileFieldType type) { Name = name; FieldType = type; } public override string ToString() { return Name; } public int CompareTo(object obj) { return Name.CompareTo(((TemplateTag)obj).Name); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Serialization; using Microsoft.VisualStudio.Services.Agent.Util; namespace Agent.Plugins.Repository { public sealed class TeeCliManager : TfsVCCliManager, ITfsVCCliManager { public override TfsVCFeatures Features => TfsVCFeatures.Eula; protected override string Switch => "-"; public static readonly int RetriesOnFailure = 3; public string FilePath => Path.Combine(ExecutionContext.Variables.GetValueOrDefault("agent.homedirectory")?.Value, "externals", "tee", "tf"); // TODO: Remove AddAsync after last-saved-checkin-metadata problem is fixed properly. public async Task AddAsync(string localPath) { ArgUtil.NotNullOrEmpty(localPath, nameof(localPath)); await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "add", localPath); } public void CleanupProxySetting() { // no-op for TEE. } public async Task EulaAsync() { await RunCommandAsync(FormatFlags.All, "eula", "-accept"); } public async Task GetAsync(string localPath, bool quiet = false) { ArgUtil.NotNullOrEmpty(localPath, nameof(localPath)); await RunCommandAsync(FormatFlags.OmitCollectionUrl, quiet, 3, "get", $"-version:{SourceVersion}", "-recursive", "-overwrite", localPath); } public string ResolvePath(string serverPath) { ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath)); string localPath = RunPorcelainCommandAsync("resolvePath", $"-workspace:{WorkspaceName}", serverPath).GetAwaiter().GetResult(); localPath = localPath?.Trim(); // Paths outside of the root mapping return empty. // Paths within a cloaked directory return "null". if (string.IsNullOrEmpty(localPath) || string.Equals(localPath, "null", StringComparison.OrdinalIgnoreCase)) { return string.Empty; } return localPath; } public Task ScorchAsync() { throw new NotSupportedException(); } public void SetupProxy(string proxyUrl, string proxyUsername, string proxyPassword) { if (!string.IsNullOrEmpty(proxyUrl)) { Uri proxy = UrlUtil.GetCredentialEmbeddedUrl(new Uri(proxyUrl), proxyUsername, proxyPassword); AdditionalEnvironmentVariables["http_proxy"] = proxy.AbsoluteUri; } } public void SetupClientCertificate(string clientCert, string clientCertKey, string clientCertArchive, string clientCertPassword) { ExecutionContext.Debug("Convert client certificate from 'pkcs' format to 'jks' format."); string toolPath = WhichUtil.Which("keytool", true, ExecutionContext); string jksFile = Path.Combine(ExecutionContext.Variables.GetValueOrDefault("agent.tempdirectory")?.Value, $"{Guid.NewGuid()}.jks"); string argLine; if (!string.IsNullOrEmpty(clientCertPassword)) { argLine = $"-importkeystore -srckeystore \"{clientCertArchive}\" -srcstoretype pkcs12 -destkeystore \"{jksFile}\" -deststoretype JKS -srcstorepass \"{clientCertPassword}\" -deststorepass \"{clientCertPassword}\""; } else { argLine = $"-importkeystore -srckeystore \"{clientCertArchive}\" -srcstoretype pkcs12 -destkeystore \"{jksFile}\" -deststoretype JKS"; } ExecutionContext.Command($"{toolPath} {argLine}"); using (var processInvoker = new ProcessInvoker(ExecutionContext)) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { if (!string.IsNullOrEmpty(args.Data)) { ExecutionContext.Output(args.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { if (!string.IsNullOrEmpty(args.Data)) { ExecutionContext.Output(args.Data); } }; processInvoker.ExecuteAsync(ExecutionContext.Variables.GetValueOrDefault("system.defaultworkingdirectory")?.Value, toolPath, argLine, null, true, CancellationToken.None).GetAwaiter().GetResult(); if (!string.IsNullOrEmpty(clientCertPassword)) { ExecutionContext.Debug($"Set TF_ADDITIONAL_JAVA_ARGS=-Djavax.net.ssl.keyStore={jksFile} -Djavax.net.ssl.keyStorePassword={clientCertPassword}"); AdditionalEnvironmentVariables["TF_ADDITIONAL_JAVA_ARGS"] = $"-Djavax.net.ssl.keyStore={jksFile} -Djavax.net.ssl.keyStorePassword={clientCertPassword}"; } else { ExecutionContext.Debug($"Set TF_ADDITIONAL_JAVA_ARGS=-Djavax.net.ssl.keyStore={jksFile}"); AdditionalEnvironmentVariables["TF_ADDITIONAL_JAVA_ARGS"] = $"-Djavax.net.ssl.keyStore={jksFile}"; } } } public async Task ShelveAsync(string shelveset, string commentFile, bool move) { ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset)); ArgUtil.NotNullOrEmpty(commentFile, nameof(commentFile)); // TODO: Remove parameter move after last-saved-checkin-metadata problem is fixed properly. if (move) { await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "shelve", $"-workspace:{WorkspaceName}", "-move", "-replace", "-recursive", $"-comment:@{commentFile}", shelveset); return; } await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "shelve", $"-workspace:{WorkspaceName}", "-saved", "-replace", "-recursive", $"-comment:@{commentFile}", shelveset); } public async Task<ITfsVCShelveset> ShelvesetsAsync(string shelveset) { ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset)); string output = await RunPorcelainCommandAsync("shelvesets", "-format:xml", $"-workspace:{WorkspaceName}", shelveset); string xml = ExtractXml(output); // Deserialize the XML. // The command returns a non-zero exit code if the shelveset is not found. // The assertions performed here should never fail. var serializer = new XmlSerializer(typeof(TeeShelvesets)); ArgUtil.NotNullOrEmpty(xml, nameof(xml)); using (var reader = new StringReader(xml)) { var teeShelvesets = serializer.Deserialize(reader) as TeeShelvesets; ArgUtil.NotNull(teeShelvesets, nameof(teeShelvesets)); ArgUtil.NotNull(teeShelvesets.Shelvesets, nameof(teeShelvesets.Shelvesets)); ArgUtil.Equal(1, teeShelvesets.Shelvesets.Length, nameof(teeShelvesets.Shelvesets.Length)); return teeShelvesets.Shelvesets[0]; } } public async Task<ITfsVCStatus> StatusAsync(string localPath) { ArgUtil.NotNullOrEmpty(localPath, nameof(localPath)); string output = await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "status", "-recursive", "-nodetect", "-format:xml", localPath); string xml = ExtractXml(output); var serializer = new XmlSerializer(typeof(TeeStatus)); using (var reader = new StringReader(xml ?? string.Empty)) { return serializer.Deserialize(reader) as TeeStatus; } } public bool TestEulaAccepted() { // Resolve the path to the XML file containing the EULA-accepted flag. string homeDirectory = Environment.GetEnvironmentVariable("HOME"); if (!string.IsNullOrEmpty(homeDirectory) && Directory.Exists(homeDirectory)) { string tfDataDirectory = (PlatformUtil.RunningOnMacOS) ? Path.Combine("Library", "Application Support", "Microsoft") : ".microsoft"; string xmlFile = Path.Combine( homeDirectory, tfDataDirectory, "Team Foundation", "4.0", "Configuration", "TEE-Mementos", "com.microsoft.tfs.client.productid.xml"); if (File.Exists(xmlFile)) { // Load and deserialize the XML. string xml = File.ReadAllText(xmlFile, Encoding.UTF8); XmlSerializer serializer = new XmlSerializer(typeof(ProductIdData)); using (var reader = new StringReader(xml ?? string.Empty)) { var data = serializer.Deserialize(reader) as ProductIdData; return string.Equals(data?.Eula?.Value ?? string.Empty, "true", StringComparison.OrdinalIgnoreCase); } } } return false; } public override async Task<bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace) { ArgUtil.NotNull(workspace, nameof(workspace)); try { await RunCommandAsync("workspace", "-delete", $"{workspace.Name};{workspace.Owner}"); return true; } catch (Exception ex) { ExecutionContext.Warning(ex.Message); return false; } } public async Task UndoAsync(string localPath) { ArgUtil.NotNullOrEmpty(localPath, nameof(localPath)); await RunCommandAsync(FormatFlags.OmitCollectionUrl, "undo", "-recursive", localPath); } public async Task UnshelveAsync(string shelveset, bool failOnNonZeroExitCode = true) { ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset)); await RunCommandAsync(FormatFlags.OmitCollectionUrl, false, failOnNonZeroExitCode, "unshelve", "-format:detailed", $"-workspace:{WorkspaceName}", shelveset); } public async Task WorkfoldCloakAsync(string serverPath) { ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath)); await RunCommandAsync(3, "workfold", "-cloak", $"-workspace:{WorkspaceName}", serverPath); } public async Task WorkfoldMapAsync(string serverPath, string localPath) { ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath)); ArgUtil.NotNullOrEmpty(localPath, nameof(localPath)); await RunCommandAsync(3, "workfold", "-map", $"-workspace:{WorkspaceName}", serverPath, localPath); } public Task WorkfoldUnmapAsync(string serverPath) { throw new NotSupportedException(); } public async Task WorkspaceDeleteAsync(ITfsVCWorkspace workspace) { ArgUtil.NotNull(workspace, nameof(workspace)); await RunCommandAsync("workspace", "-delete", $"{workspace.Name};{workspace.Owner}"); } public async Task WorkspaceNewAsync() { await RunCommandAsync("workspace", "-new", "-location:local", "-permission:Public", WorkspaceName); } public async Task<ITfsVCWorkspace[]> WorkspacesAsync(bool matchWorkspaceNameOnAnyComputer = false) { // Build the args. var args = new List<string>(); args.Add("workspaces"); if (matchWorkspaceNameOnAnyComputer) { args.Add(WorkspaceName); args.Add($"-computer:*"); } args.Add("-format:xml"); // Run the command. TfsVCPorcelainCommandResult result = await TryRunPorcelainCommandAsync(FormatFlags.None, RetriesOnFailure, args.ToArray()); ArgUtil.NotNull(result, nameof(result)); if (result.Exception != null) { // Check if the workspace name was specified and the command returned exit code 1. if (matchWorkspaceNameOnAnyComputer && result.Exception.ExitCode == 1) { // Ignore the error. This condition can indicate the workspace was not found. return new ITfsVCWorkspace[0]; } // Dump the output and throw. result.Output?.ForEach(x => ExecutionContext.Output(x ?? string.Empty)); throw result.Exception; } // Note, string.join gracefully handles a null element within the IEnumerable<string>. string output = string.Join(Environment.NewLine, result.Output ?? new List<string>()) ?? string.Empty; string xml = ExtractXml(output); // Deserialize the XML. var serializer = new XmlSerializer(typeof(TeeWorkspaces)); using (var reader = new StringReader(xml)) { return (serializer.Deserialize(reader) as TeeWorkspaces) ?.Workspaces ?.Cast<ITfsVCWorkspace>() .ToArray(); } } public override async Task WorkspacesRemoveAsync(ITfsVCWorkspace workspace) { ArgUtil.NotNull(workspace, nameof(workspace)); await RunCommandAsync("workspace", $"-remove:{workspace.Name};{workspace.Owner}"); } private static string ExtractXml(string output) { // tf commands that output XML, may contain information messages preceeding the XML content. // // For example, the workspaces subcommand returns a non-XML message preceeding the XML when there are no workspaces. // // Also for example, when JAVA_TOOL_OPTIONS is set, a message like "Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8" // may preceed the XML content. output = output ?? string.Empty; int xmlIndex = output.IndexOf("<?xml"); if (xmlIndex > 0) { return output.Substring(xmlIndex); } return output; } //////////////////////////////////////////////////////////////////////////////// // Product ID data objects (required for testing whether the EULA has been accepted). //////////////////////////////////////////////////////////////////////////////// [XmlRoot(ElementName = "ProductIdData", Namespace = "")] public sealed class ProductIdData { [XmlElement(ElementName = "eula-14.0", Namespace = "")] public Eula Eula { get; set; } } public sealed class Eula { [XmlAttribute(AttributeName = "value", Namespace = "")] public string Value { get; set; } } } //////////////////////////////////////////////////////////////////////////////// // tf shelvesets data objects //////////////////////////////////////////////////////////////////////////////// [XmlRoot(ElementName = "shelvesets", Namespace = "")] public sealed class TeeShelvesets { [XmlElement(ElementName = "shelveset", Namespace = "")] public TeeShelveset[] Shelvesets { get; set; } } public sealed class TeeShelveset : ITfsVCShelveset { [XmlAttribute(AttributeName = "date", Namespace = "")] public string Date { get; set; } [XmlAttribute(AttributeName = "name", Namespace = "")] public string Name { get; set; } [XmlAttribute(AttributeName = "owner", Namespace = "")] public string Owner { get; set; } [XmlElement(ElementName = "comment", Namespace = "")] public string Comment { get; set; } } //////////////////////////////////////////////////////////////////////////////// // tf status data objects. //////////////////////////////////////////////////////////////////////////////// [XmlRoot(ElementName = "status", Namespace = "")] public sealed class TeeStatus : ITfsVCStatus { // Elements. [XmlArray(ElementName = "candidate-pending-changes", Namespace = "")] [XmlArrayItem(ElementName = "pending-change", Namespace = "")] public TeePendingChange[] CandidatePendingChanges { get; set; } [XmlArray(ElementName = "pending-changes", Namespace = "")] [XmlArrayItem(ElementName = "pending-change", Namespace = "")] public TeePendingChange[] PendingChanges { get; set; } // Interface-only properties. [XmlIgnore] public IEnumerable<ITfsVCPendingChange> AllAdds { get { return PendingChanges?.Where(x => string.Equals(x.ChangeType, "add", StringComparison.OrdinalIgnoreCase)); } } [XmlIgnore] public bool HasPendingChanges => PendingChanges?.Any() ?? false; } public sealed class TeePendingChange : ITfsVCPendingChange { [XmlAttribute(AttributeName = "change-type", Namespace = "")] public string ChangeType { get; set; } [XmlAttribute(AttributeName = "computer", Namespace = "")] public string Computer { get; set; } [XmlAttribute(AttributeName = "date", Namespace = "")] public string Date { get; set; } [XmlAttribute(AttributeName = "file-type", Namespace = "")] public string FileType { get; set; } [XmlAttribute(AttributeName = "local-item", Namespace = "")] public string LocalItem { get; set; } [XmlAttribute(AttributeName = "lock", Namespace = "")] public string Lock { get; set; } [XmlAttribute(AttributeName = "owner", Namespace = "")] public string Owner { get; set; } [XmlAttribute(AttributeName = "server-item", Namespace = "")] public string ServerItem { get; set; } [XmlAttribute(AttributeName = "version", Namespace = "")] public string Version { get; set; } [XmlAttribute(AttributeName = "workspace", Namespace = "")] public string Workspace { get; set; } } //////////////////////////////////////////////////////////////////////////////// // tf workspaces data objects. //////////////////////////////////////////////////////////////////////////////// [XmlRoot(ElementName = "workspaces", Namespace = "")] public sealed class TeeWorkspaces { [XmlElement(ElementName = "workspace", Namespace = "")] public TeeWorkspace[] Workspaces { get; set; } } public sealed class TeeWorkspace : ITfsVCWorkspace { // Attributes. [XmlAttribute(AttributeName = "server", Namespace = "")] public string CollectionUrl { get; set; } [XmlAttribute(AttributeName = "comment", Namespace = "")] public string Comment { get; set; } [XmlAttribute(AttributeName = "computer", Namespace = "")] public string Computer { get; set; } [XmlAttribute(AttributeName = "name", Namespace = "")] public string Name { get; set; } [XmlAttribute(AttributeName = "owner", Namespace = "")] public string Owner { get; set; } // Elements. [XmlElement(ElementName = "working-folder", Namespace = "")] public TeeMapping[] TeeMappings { get; set; } // Interface-only properties. [XmlIgnore] public ITfsVCMapping[] Mappings => TeeMappings?.Cast<ITfsVCMapping>().ToArray(); } public sealed class TeeMapping : ITfsVCMapping { [XmlIgnore] public bool Cloak => string.Equals(MappingType, "cloak", StringComparison.OrdinalIgnoreCase); [XmlAttribute(AttributeName = "depth", Namespace = "")] public string Depth { get; set; } [XmlAttribute(AttributeName = "local-item", Namespace = "")] public string LocalPath { get; set; } [XmlAttribute(AttributeName = "type", Namespace = "")] public string MappingType { get; set; } [XmlIgnore] public bool Recursive => string.Equals(Depth, "full", StringComparison.OrdinalIgnoreCase); [XmlAttribute(AttributeName = "server-item")] public string ServerPath { get; set; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/21/2008 9:28:29 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; namespace DotSpatial.Data { /// <summary> /// This can be used as a component to work as a DataManager. This also provides the /// very important DefaultDataManager property, which is where the developer controls /// what DataManager should be used for their project. /// </summary> public class DataManager : IDataManager { #region Private Variables // If this doesn't exist, a new one is created when you "get" this data manager. private static IDataManager _defaultDataManager; private IEnumerable<IDataProvider> _dataProviders; private string _dialogReadFilter; private string _dialogWriteFilter; private string _imageReadFilter; private string _imageWriteFilter; private bool _loadInRam = true; private string _rasterReadFilter; private string _rasterWriteFilter; private string _vectorReadFilter; private string _vectorWriteFilter; /// <summary> /// Gets or sets the implementation of IDataManager for the project to use when /// accessing data. This is THE place where the DataManager can be replaced /// by a different data manager. If you add this data manager to your /// project, this will automatically set itself as the DefaultDataManager. /// However, since each DM will do this, you may have to control this manually /// if you add more than one DataManager to the project in order to set the /// one that will be chosen. /// </summary> public static IDataManager DefaultDataManager { get { return _defaultDataManager ?? (_defaultDataManager = new DataManager()); } set { _defaultDataManager = value; } } #endregion #region Constructors /// <summary> /// Creates a new instance of the DataManager class. A data manager is more or less /// just a list of data providers to use. The very important /// DataManager.DefaultDataManager property controls which DataManager will be used /// to load data. By default, each DataManager sets itself as the default in its /// constructor. /// </summary> public DataManager() { Configure(); } private void Configure() { _defaultDataManager = this; PreferredProviders = new Dictionary<string, IDataProvider>(); // Provide a number of default providers _dataProviders = new List<IDataProvider> { new ShapefileDataProvider(), new BinaryRasterProvider(), new DotNetImageProvider() }; } #endregion #region Methods /// <summary> /// Creates a new class of vector that matches the given fileName. /// </summary> /// <param name="fileName">The string fileName from which to create a vector.</param> /// <param name="featureType">Specifies the type of feature for this vector file</param> /// <returns>An IFeatureSet that allows working with the dataset.</returns> public IFeatureSet CreateVector(string fileName, FeatureType featureType) { return CreateVector(fileName, featureType, ProgressHandler); } /// <summary> /// Creates a new class of vector that matches the given fileName. /// </summary> /// <param name="fileName">The string fileName from which to create a vector.</param> /// <param name="featureType">Specifies the type of feature for this vector file</param> /// <param name="progHandler">Overrides the default progress handler with the specified progress handler</param> /// <returns>An IFeatureSet that allows working with the dataset.</returns> /// <exception cref="ArgumentNullException">Raised when fileName is null.</exception> /// <exception cref="IOException">Raised when suitable DataProvider not found.</exception> public IFeatureSet CreateVector(string fileName, FeatureType featureType, IProgressHandler progHandler) { if (fileName == null) throw new ArgumentNullException("fileName", "fileName should be not null"); // To Do: Add Customization that allows users to specify which plugins to use in priority order. // First check for the extension in the preferred plugins list var ext = Path.GetExtension(fileName); IDataProvider pdp; if (PreferredProviders.TryGetValue(ext, out pdp)) { var vp = pdp as IVectorProvider; if (vp != null) { var result = vp.CreateNew(fileName, featureType, true, progHandler); if (result != null) return result; } // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (var dp in DataProviders.OfType<IVectorProvider>()) { if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) { // attempt to open with the fileName. var result = dp.CreateNew(fileName, featureType, true, progHandler); if (result != null) return result; } } throw new IOException(DataStrings.FileTypeNotSupported); } /// <summary> /// Checks a dialog filter and returns a list of just the extensions. /// </summary> /// <param name="dialogFilter">The Dialog Filter to read extensions from</param> /// <returns>A list of extensions</returns> public virtual List<string> GetSupportedExtensions(string dialogFilter) { List<string> extensions = new List<string>(); string[] formats = dialogFilter.Split('|'); char[] wild = { '*' }; // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { string ext = potentialExtension.TrimStart(wild); if (extensions.Contains(ext) == false) extensions.Add(ext); } } return extensions; } /// <summary> /// This can help determine what kind of file format a file is, without actually opening the file. /// </summary> /// <param name="fileName"></param> /// <returns></returns> public virtual DataFormat GetFileFormat(string fileName) { string ext = Path.GetExtension(fileName); foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) { IVectorProvider vp = dp as IVectorProvider; if (vp != null) return DataFormat.Vector; IRasterProvider rp = dp as IRasterProvider; if (rp != null) return DataFormat.Raster; IImageDataProvider ip = dp as IImageDataProvider; if (ip != null) return DataFormat.Image; return DataFormat.Custom; } } return DataFormat.Custom; } /// <summary> /// Instead of opening the specified file, this simply determines the correct /// provider, and requests that the provider check the feature type for vector /// formats. /// </summary> /// <param name="fileName"></param> /// <returns></returns> public virtual FeatureType GetFeatureType(string fileName) { string ext = Path.GetExtension(fileName); if (GetFileFormat(fileName) != DataFormat.Vector) return FeatureType.Unspecified; foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) { IVectorProvider vp = dp as IVectorProvider; if (vp == null) continue; return vp.GetFeatureType(fileName); } } return FeatureType.Unspecified; } /// <summary> /// Opens the specified fileName, returning an IRaster. This will return null if a manager /// either returns the wrong data format. /// </summary> /// <param name="fileName">The string fileName to open</param> /// <returns>An IRaster loaded from the specified file.</returns> public virtual IRaster OpenRaster(string fileName) { return OpenFileAsIRaster(fileName, true, ProgressHandler); } /// <summary> /// Opens the specified fileName, returning an IRaster. This will return null if a manager /// either returns the wrong data format. /// </summary> /// <param name="fileName">The string fileName to open</param> /// <param name="inRam">boolean, true if this should be loaded into ram</param> /// <param name="prog">a progress interface</param> /// <returns>An IRaster loaded from the specified file</returns> public virtual IRaster OpenRaster(string fileName, bool inRam, IProgressHandler prog) { return OpenFileAsIRaster(fileName, inRam, prog); } /// <summary> /// Opens a specified file as an IFeatureSet /// </summary> /// <param name="fileName">The string fileName to open</param> /// <param name="inRam">boolean, true if this should be loaded into ram</param> /// <param name="prog">a progress interface</param> /// <returns>An IFeatureSet loaded from the specified file</returns> public virtual IFeatureSet OpenVector(string fileName, bool inRam, IProgressHandler prog) { return OpenFile(fileName, inRam, prog) as IFeatureSet; } /// <summary> /// Opens the file as an Image and returns an IImageData object for interacting with the file. /// </summary> /// <param name="fileName">The string fileName</param> /// <returns>An IImageData object</returns> public virtual IImageData OpenImage(string fileName) { return OpenFile(fileName, LoadInRam, ProgressHandler) as IImageData; } /// <summary> /// Opens the file as an Image and returns an IImageData object /// </summary> /// <param name="fileName">The string fileName to open</param> /// <param name="progressHandler">The progressHandler to receive progress updates</param> /// <returns>An IImageData</returns> public virtual IImageData OpenImage(string fileName, IProgressHandler progressHandler) { return OpenFile(fileName, LoadInRam, progressHandler) as IImageData; } /// <summary> /// Attempts to call the open fileName method for any IDataProvider plugin /// that matches the extension on the string. /// </summary> /// <param name="fileName">A String fileName to attempt to open.</param> public virtual IDataSet OpenFile(string fileName) { return OpenFile(fileName, LoadInRam, ProgressHandler); } /// <summary> /// Attempts to call the open fileName method for any IDataProvider plugin /// that matches the extension on the string. /// </summary> /// <param name="fileName">A String fileName to attempt to open.</param> /// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this DataManager.</param> public virtual IDataSet OpenFile(string fileName, bool inRam) { return OpenFile(fileName, inRam, ProgressHandler); } /// <summary> /// Attempts to call the open fileName method for any IDataProvider plugin /// that matches the extension on the string. /// </summary> /// <param name="fileName">A String fileName to attempt to open.</param> /// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this DataManager.</param> /// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this DataManager.</param> public virtual IDataSet OpenFile(string fileName, bool inRam, IProgressHandler progressHandler) { // To Do: Add Customization that allows users to specify which plugins to use in priority order. // First check for the extension in the preferred plugins list //Fix by Jiri Kadlec - on Unix and Mac the path is case sensitive //on windows it is case insensitive. This check ensures that both //*.SHP and *.shp files can be opened on Windows. //PlatformID platform = Environment.OSVersion.Platform; //if (platform != PlatformID.MacOSX && platform != PlatformID.Unix) //{ // fileName = fileName.ToLower(); //} // * Removed all "ToLower()" calculations here, since we only want // the extension comparison to be converted to lower, not the filename itself. string ext = Path.GetExtension(fileName); if (ext != null) { // Fix by Ted Dunsford, moved "ToLower" operation from the previous // location on the filename which would mess up the actual filename // identification, and only use the lower case for the extent testing. ext = ext.ToLower(); IDataSet result; if (PreferredProviders.ContainsKey(ext)) { result = PreferredProviders[ext].Open(fileName); if (result != null) return result; // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (!GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) continue; // attempt to open with the fileName. dp.ProgressHandler = ProgressHandler; result = dp.Open(fileName); if (result != null) return result; } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } /// <summary> /// Creates a new image using an appropriate data provider /// </summary> /// <param name="fileName">The string fileName to open an image for</param> /// <param name="width">The integer width in pixels</param> /// <param name="height">The integer height in pixels</param> /// <param name="bandType">The band color type</param> /// <returns>An IImageData interface allowing access to image data</returns> public virtual IImageData CreateImage(string fileName, int width, int height, ImageBandType bandType) { return CreateImage(fileName, width, height, LoadInRam, ProgressHandler, bandType); } /// <summary> /// Creates a new image using an appropriate data provider /// </summary> /// <param name="fileName">The string fileName to open an image for</param> /// <param name="width">The integer width in pixels</param> /// <param name="height">The integer height in pixels</param> /// <param name="inRam">Boolean, true if the entire file should be created in memory</param> /// <param name="bandType">The band color type</param> /// <returns>An IImageData interface allowing access to image data</returns> public virtual IImageData CreateImage(string fileName, int width, int height, bool inRam, ImageBandType bandType) { return CreateImage(fileName, width, height, inRam, ProgressHandler, bandType); } /// <summary> /// Creates a new image using an appropriate data provider /// </summary> /// <param name="fileName">The string fileName to open an image for</param> /// <param name="width">The integer width in pixels</param> /// <param name="height">The integer height in pixels</param> /// <param name="inRam">Boolean, true if the entire file should be created in memory</param> /// <param name="progHandler">A Progress handler</param> /// <param name="bandType">The band color type</param> /// <returns>An IImageData interface allowing access to image data</returns> public virtual IImageData CreateImage(string fileName, int width, int height, bool inRam, IProgressHandler progHandler, ImageBandType bandType) { // First check for the extension in the preferred plugins list fileName = fileName.ToLower(); string ext = Path.GetExtension(fileName); if (ext != null) { IImageData result; if (PreferredProviders.ContainsKey(ext)) { IImageDataProvider rp = PreferredProviders[ext] as IImageDataProvider; if (rp != null) { result = rp.Create(fileName, width, height, inRam, progHandler, bandType); if (result != null) return result; } // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogWriteFilter).Contains(ext)) { IImageDataProvider rp = dp as IImageDataProvider; if (rp != null) { // attempt to open with the fileName. result = rp.Create(fileName, width, height, inRam, progHandler, bandType); if (result != null) return result; } } } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } /// <summary> /// Creates a new raster using the specified raster provider and the Data Manager's Progress Handler, /// as well as its LoadInRam property. /// </summary> /// <param name="name">The fileName of the new file to create.</param> /// <param name="driverCode">The string code identifying the driver to use to create the raster. If no code is specified /// the manager will attempt to match the extension with a code specified in the Dialog write filter. </param> /// <param name="xSize">The number of columns in the raster</param> /// <param name="ySize">The number of rows in the raster</param> /// <param name="numBands">The number of bands in the raster</param> /// <param name="dataType">The data type for the raster</param> /// <param name="options">Any additional, driver specific options for creation</param> /// <returns>An IRaster representing the created raster.</returns> public virtual IRaster CreateRaster(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options) { // First check for the extension in the preferred plugins list string ext = Path.GetExtension(name).ToLower(); if (ext != null) { IRaster result; if (PreferredProviders.ContainsKey(ext)) { IRasterProvider rp = PreferredProviders[ext] as IRasterProvider; if (rp != null) { result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options); if (result != null) return result; } // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogWriteFilter).Contains(ext)) { IRasterProvider rp = dp as IRasterProvider; if (rp != null) { // attempt to open with the fileName. result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options); if (result != null) return result; } } } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } /// <summary> /// Opens the file making sure it can be returned as an IRaster. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="inRam">if set to <c>true</c> [in ram].</param> /// <param name="progressHandler">The progress handler.</param> /// <returns></returns> public virtual IRaster OpenFileAsIRaster(string fileName, bool inRam, IProgressHandler progressHandler) { // First check for the extension in the preferred plugins list string ext = Path.GetExtension(fileName); if (ext != null) { ext = ext.ToLower(); IRaster result; if (PreferredProviders.ContainsKey(ext)) { result = PreferredProviders[ext].Open(fileName) as IRaster; if (result != null) return result; // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (!GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) continue; // attempt to open with the fileName. dp.ProgressHandler = ProgressHandler; result = dp.Open(fileName) as IRaster; if (result != null) return result; } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } #endregion #region Properties /// <summary> /// Gets or sets the list of IDataProviders that should be used in the project. /// </summary> [Browsable(false)] [ImportMany(AllowRecomposition = true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IEnumerable<IDataProvider> DataProviders { get { return _dataProviders; } set { _dataProviders = value; _imageReadFilter = null; _imageWriteFilter = null; _rasterReadFilter = null; _rasterWriteFilter = null; _vectorReadFilter = null; _vectorWriteFilter = null; OnProvidersLoaded(value); } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open files.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string DialogReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_dialogReadFilter != null) return _dialogReadFilter; var rasterExtensions = new List<string>(); var vectorExtensions = new List<string>(); var imageExtensions = new List<string>(); var extensions = PreferredProviders.Select(item => item.Key).ToList(); foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogReadFilter.Split('|'); // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { if (extensions.Contains(potentialExtension) == false) { extensions.Add(potentialExtension); if (dp is IRasterProvider) rasterExtensions.Add(potentialExtension); if (dp is IVectorProvider) if (potentialExtension != "*.shx" && potentialExtension != "*.dbf") vectorExtensions.Add(potentialExtension); if (dp is IImageDataProvider) imageExtensions.Add(potentialExtension); } } } } // We now have a list of all the file extensions supported extensions.Remove("*.dbf"); extensions.Remove("*.shx"); var result = new StringBuilder("All Supported Formats|" + String.Join(";", extensions.ToArray())); if (vectorExtensions.Count > 0) result.Append("|Vectors|" + String.Join(";", vectorExtensions.ToArray())); if (rasterExtensions.Count > 0) result.Append("|Rasters|" + String.Join(";", rasterExtensions.ToArray())); if (imageExtensions.Count > 0) result.Append("|Images|" + String.Join(";", imageExtensions.ToArray())); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { // we don't have to check for uniqueness here because it is enforced by the HashTable result.AppendFormat("| [{0}] - {1}| {0}", item.Key, item.Value.Name); } // Now add each of the individual lines, prepended with the provider name foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogReadFilter.Split('|'); string potentialFormat = null; for (int i = 0; i < formats.Length; i++) { if (i % 2 == 0) { // For descriptions, prepend the name: potentialFormat = "|" + dp.Name + " - " + formats[i]; } else { // don't add this format if it was already added by a "preferred data provider" if (PreferredProviders.ContainsKey(formats[i]) == false) { string res = formats[i].Replace(";*.shx", String.Empty).Replace("*.shx", String.Empty); res = res.Replace(";*.dbf", String.Empty).Replace("*.dbf", String.Empty); if (formats[i] != "*.shx" && formats[i] != "*.shp") { result.Append(potentialFormat); result.Append("|" + res); } } } } } result.Append("|All Files (*.*) |*.*"); return result.ToString(); } set { _dialogReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save files.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string DialogWriteFilter { get { // Setting this to something overrides the default if (_dialogWriteFilter != null) return _dialogWriteFilter; var rasterExtensions = new List<string>(); var vectorExtensions = new List<string>(); var imageExtensions = new List<string>(); var extensions = PreferredProviders.Select(item => item.Key).ToList(); foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogWriteFilter.Split('|'); // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { if (extensions.Contains(potentialExtension) == false) { extensions.Add(potentialExtension); if (dp is IRasterProvider) rasterExtensions.Add(potentialExtension); if (dp is IVectorProvider) vectorExtensions.Add(potentialExtension); if (dp is IImageDataProvider) imageExtensions.Add(potentialExtension); } } } } // We now have a list of all the file extensions supported var result = new StringBuilder("All Supported Formats|" + String.Join(";", extensions.ToArray())); if (vectorExtensions.Count > 0) result.Append("|Vectors|" + String.Join(";", vectorExtensions.ToArray())); if (rasterExtensions.Count > 0) result.Append("|Rasters|" + String.Join(";", rasterExtensions.ToArray())); if (imageExtensions.Count > 0) result.Append("|Images|" + String.Join(";", imageExtensions.ToArray())); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { // we don't have to check for uniqueness here because it is enforced by the HashTable result.AppendFormat("| [{0}] - {1}| {0}", item.Key, item.Value.Name); } // Now add each of the individual lines, prepended with the provider name foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogWriteFilter.Split('|'); string potentialFormat = null; for (int i = 0; i < formats.Length; i++) { if (i % 2 == 0) { // For descriptions, prepend the name: potentialFormat = "|" + dp.Name + " - " + formats[i]; } else { if (PreferredProviders.ContainsKey(formats[i]) == false) { result.Append(potentialFormat); result.Append("|" + formats[i]); } } } } result.Append("|All Files (*.*) |*.*"); return result.ToString(); } set { _dialogWriteFilter = value; } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files that are specifically raster formats. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open rasters.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string RasterReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_rasterReadFilter != null) return _rasterReadFilter; return GetReadFilter<IRasterProvider>("Rasters"); } set { _rasterReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save rasters.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string RasterWriteFilter { get { // Setting this to something overrides the default if (_rasterWriteFilter != null) return _rasterWriteFilter; return GetWriteFilter<IRasterProvider>("Rasters"); } set { _rasterWriteFilter = value; } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open vectors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string VectorReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_vectorReadFilter != null) return _vectorReadFilter; return GetReadFilter<IVectorProvider>("Vectors"); } set { _vectorReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save vectors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string VectorWriteFilter { get { // Setting this to something overrides the default if (_vectorWriteFilter != null) return _vectorWriteFilter; return GetWriteFilter<IVectorProvider>("Vectors"); } set { _vectorWriteFilter = value; } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open images.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string ImageReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_imageReadFilter != null) return _imageReadFilter; return GetReadFilter<IImageDataProvider>("Images"); } set { _imageReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save images.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string ImageWriteFilter { get { // Setting this to something overrides the default if (_imageWriteFilter != null) return _imageWriteFilter; return GetWriteFilter<IImageDataProvider>("Images"); } set { _imageWriteFilter = value; } } /// <summary> /// Sets the default condition for how this data manager should try to load layers. /// This will be overridden if the inRam property is specified as a parameter. /// </summary> [Category("Behavior")] [Description("Gets or sets the default condition for subsequent load operations which may be overridden by specifying inRam in the parameters.")] public bool LoadInRam { get { return _loadInRam; } set { _loadInRam = value; } } /// <summary> /// Gets or sets a dictionary of IDataProviders with corresponding extensions. The /// standard order is to try to load the data using a PreferredProvider. If that /// fails, then it will check the list of dataProviders, and finally, if that fails, /// it will check the plugin Data Providers in directories. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual Dictionary<string, IDataProvider> PreferredProviders { get; set; } /// <summary> /// Gets or sets a progress handler for any open operations that are intiated by this /// DataManager and don't override this value with an IProgressHandler specified in the parameters. /// </summary> [Category("Handlers")] [Description("Gets or sets the object that implements the IProgressHandler interface for recieving status messages.")] public virtual IProgressHandler ProgressHandler { get; set; } private string GetFilter<T>(string description, Func<IDataProvider, string> dpFilter) where T : IDataProvider { var extensions = new List<string>(); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { if (item.Value is T) { // we don't have to check for uniqueness here because it is enforced by the HashTable extensions.Add(item.Key); } } foreach (IDataProvider dp in DataProviders) { string[] formats = dpFilter(dp).Split('|'); // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { if (extensions.Contains(potentialExtension) == false) { if (dp is T) extensions.Add(potentialExtension); } } } } var result = new StringBuilder(); // We now have a list of all the file extensions supported if (extensions.Count > 0) result.Append(String.Format("{0}|", description) + String.Join(";", extensions.ToArray())); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { if (item.Value is T) { // we don't have to check for uniqueness here because it is enforced by the HashTable result.AppendFormat("| [{0}] - {1}| {0}", item.Key, item.Value.Name); } } // Now add each of the individual lines, prepended with the provider name foreach (IDataProvider dp in DataProviders) { string[] formats = dpFilter(dp).Split('|'); string potentialFormat = null; for (int i = 0; i < formats.Length; i++) { if (i % 2 == 0) { // For descriptions, prepend the name: potentialFormat = "|" + dp.Name + " - " + formats[i]; } else { // don't add this format if it was already added by a "preferred data provider" if (PreferredProviders.ContainsKey(formats[i]) == false) { if (dp is T) { result.Append(potentialFormat); result.Append("|" + formats[i]); } } } } } result.Append("|All Files (*.*) |*.*"); return result.ToString(); } private string GetReadFilter<T>(string description) where T : IDataProvider { return GetFilter<T>(description, d => d.DialogReadFilter); } private string GetWriteFilter<T>(string description) where T : IDataProvider { return GetFilter<T>(description, d => d.DialogWriteFilter); } #endregion #region Events /// <summary> /// Occurs after the directory providers have been loaded into the project. /// </summary> public event EventHandler<DataProviderEventArgs> DirectoryProvidersLoaded; /// <summary> /// Triggers the DirectoryProvidersLoaded event /// </summary> protected virtual void OnProvidersLoaded(IEnumerable<IDataProvider> list) { if (DirectoryProvidersLoaded != null) DirectoryProvidersLoaded(this, new DataProviderEventArgs(list)); } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.WebHooks.Properties; using Microsoft.AspNetCore.WebHooks.Utilities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.WebHooks.Filters { /// <summary> /// An <see cref="IAsyncResourceFilter"/> that verifies the Stripe signature header. Confirms the header exists, /// parses the header, reads Body bytes, and compares the hashes. /// </summary> public class StripeVerifySignatureFilter : WebHookVerifySignatureFilter, IAsyncResourceFilter { private static readonly char[] CommaSeparator = new[] { ',' }; private static readonly char[] EqualSeparator = new[] { '=' }; /// <summary> /// Instantiates a new <see cref="StripeVerifySignatureFilter"/> instance. /// </summary> /// <param name="configuration"> /// The <see cref="IConfiguration"/> used to initialize <see cref="WebHookSecurityFilter.Configuration"/>. /// </param> /// <param name="hostingEnvironment"> /// The <see cref="IHostingEnvironment" /> used to initialize /// <see cref="WebHookSecurityFilter.HostingEnvironment"/>. /// </param> /// <param name="loggerFactory"> /// The <see cref="ILoggerFactory"/> used to initialize <see cref="WebHookSecurityFilter.Logger"/>. /// </param> public StripeVerifySignatureFilter( IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) : base(configuration, hostingEnvironment, loggerFactory) { } /// <inheritdoc /> public override string ReceiverName => StripeConstants.ReceiverName; /// <inheritdoc /> public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (next == null) { throw new ArgumentNullException(nameof(next)); } // 1. Confirm this filter applies. var request = context.HttpContext.Request; if (!HttpMethods.IsPost(request.Method)) { await next(); return; } // 2. Confirm a secure connection. var errorResult = EnsureSecureConnection(ReceiverName, request); if (errorResult != null) { context.Result = errorResult; return; } // 3. Get the timestamp and expected signature(s) from the signature header. var header = GetRequestHeader(request, StripeConstants.SignatureHeaderName, out errorResult); if (errorResult != null) { context.Result = errorResult; return; } errorResult = ValidateHeader(header); if (errorResult != null) { context.Result = errorResult; return; } var timestamp = GetTimestamp(header); var signatures = GetSignatures(header); // 4. Get the configured secret key. var secretKey = GetSecretKey(ReceiverName, context.RouteData, StripeConstants.SecretKeyMinLength); if (secretKey == null) { context.Result = new NotFoundResult(); return; } var secret = Encoding.UTF8.GetBytes(secretKey); var prefix = Encoding.UTF8.GetBytes(timestamp + "."); // 5. Get the actual hash of the request body. var actualHash = await ComputeRequestBodySha256HashAsync(request, secret, prefix); // 6. Verify that the actual hash matches one of the expected hashes. var match = false; foreach (var signature in signatures) { // While this looks repetitious compared to hex-encoding actualHash (once), a single v1 entry in the // header is the normal case. Expect multiple signatures only when rolling secret keys. var expectedHash = FromHex(signature.Value, StripeConstants.SignatureHeaderName); if (expectedHash == null) { context.Result = CreateBadHexEncodingResult(StripeConstants.SignatureHeaderName); return; } if (SecretEqual(expectedHash, actualHash)) { match = true; break; } } if (!match) { // Log about the issue and short-circuit remainder of the pipeline. context.Result = CreateBadSignatureResult(StripeConstants.SignatureHeaderName); return; } // Success await next(); } // Header contains a comma-separated collection of key / value pairs. Get the value for the "t" key. private StringSegment GetTimestamp(string header) { var pairs = new TrimmingTokenizer(header, CommaSeparator); foreach (var pair in pairs) { var keyValuePair = new TrimmingTokenizer(pair, EqualSeparator, maxCount: 2); var enumerator = keyValuePair.GetEnumerator(); enumerator.MoveNext(); if (StringSegment.Equals(enumerator.Current, StripeConstants.TimestampKey, StringComparison.Ordinal)) { enumerator.MoveNext(); return enumerator.Current; } } return StringSegment.Empty; } // Header contains a comma-separated collection of key / value pairs. Get all values for the "v1" key. private IEnumerable<StringSegment> GetSignatures(string header) { var pairs = new TrimmingTokenizer(header, CommaSeparator); foreach (var pair in pairs) { var keyValuePair = new TrimmingTokenizer(pair, EqualSeparator, maxCount: 2); var enumerator = keyValuePair.GetEnumerator(); enumerator.MoveNext(); if (StringSegment.Equals(enumerator.Current, StripeConstants.SignatureKey, StringComparison.Ordinal)) { enumerator.MoveNext(); yield return enumerator.Current; } } } private IActionResult ValidateHeader(string header) { var hasTimestamp = false; var hasSignature = false; var pairs = new TrimmingTokenizer(header, CommaSeparator); foreach (var pair in pairs) { var keyValuePair = new TrimmingTokenizer(pair, EqualSeparator, maxCount: 2); if (keyValuePair.Count != 2) { // Header is not formatted correctly. Logger.LogWarning( 0, $"The '{StripeConstants.SignatureHeaderName}' header value is invalid. '{{InvalidPair}}' " + "should be a 'key=value' pair.", pair); var message = string.Format( CultureInfo.CurrentCulture, Resources.SignatureFilter_InvalidHeaderFormat, StripeConstants.SignatureHeaderName); return new BadRequestObjectResult(message); } var enumerator = keyValuePair.GetEnumerator(); enumerator.MoveNext(); var key = enumerator.Current; if (StringSegment.Equals(key, StripeConstants.SignatureKey, StringComparison.Ordinal)) { enumerator.MoveNext(); hasSignature = !StringSegment.IsNullOrEmpty(enumerator.Current); } else if (StringSegment.Equals(key, StripeConstants.TimestampKey, StringComparison.Ordinal)) { enumerator.MoveNext(); hasTimestamp = !StringSegment.IsNullOrEmpty(enumerator.Current); } } if (!hasSignature) { Logger.LogWarning( 1, $"The '{StripeConstants.SignatureHeaderName}' header value is invalid. Does not contain a " + $"timestamp ('{StripeConstants.SignatureKey}') value."); } if (!hasTimestamp) { Logger.LogWarning( 2, $"The '{StripeConstants.SignatureHeaderName}' header value is invalid. Does not contain a " + $"signature ('{StripeConstants.TimestampKey}') value."); } if (!hasSignature || !hasTimestamp) { var message = string.Format( CultureInfo.CurrentCulture, Resources.SignatureFilter_HeaderMissingValue, StripeConstants.SignatureHeaderName, StripeConstants.TimestampKey, StripeConstants.SignatureKey); return new BadRequestObjectResult(message); } // Success return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Security.Permissions; using System.Threading; using System.Text; using Microsoft.Win32; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics { internal static class SharedUtils { internal const int UnknownEnvironment = 0; internal const int W2kEnvironment = 1; internal const int NtEnvironment = 2; internal const int NonNtEnvironment = 3; public const int WAIT_OBJECT_0 = 0x00000000; public const int WAIT_ABANDONED = 0x00000080; private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } internal static Win32Exception CreateSafeWin32Exception() { return CreateSafeWin32Exception(0); } internal static Win32Exception CreateSafeWin32Exception(int error) { Win32Exception newException = null; try { if (error == 0) newException = new Win32Exception(); else newException = new Win32Exception(error); } finally { } return newException; } internal static void EnterMutex(string name, ref Mutex mutex) { string mutexName = "Global\\" + name; EnterMutexWithoutGlobal(mutexName, ref mutex); } internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex) { bool createdNew; Mutex tmpMutex = new Mutex(false, mutexName, out createdNew); SafeWaitForMutex(tmpMutex, ref mutex); } // We need to atomically attempt to acquire the mutex and record whether we took it (because we require thread affinity // while the mutex is held and the two states must be kept in lock step). We can get atomicity with a CER, but we don't want // to hold a CER over a call to WaitOne (this could cause deadlocks). The final solution is to provide a new API out of // mscorlib that performs the wait and lets us know if it succeeded. But at this late stage we don't want to expose a new // API out of mscorlib, so we'll build our own solution. // We'll P/Invoke out to the WaitForSingleObject inside a CER, but use a timeout to ensure we can't block a thread abort for // an unlimited time (we do this in an infinite loop so the semantic of acquiring the mutex is unchanged, the timeout is // just to allow us to poll for abort). A limitation of CERs in Whidbey (and part of the problem that put us in this // position in the first place) is that a CER root in a method will cause the entire method to delay thread aborts. So we // need to carefully partition the real CER part of out logic in a sub-method (and ensure the jit doesn't inline on us). private static bool SafeWaitForMutex(Mutex mutexIn, ref Mutex mutexOut) { Debug.Assert(mutexOut == null, "You must pass in a null ref Mutex"); // Wait as long as necessary for the mutex. while (true) { // Attempt to acquire the mutex but timeout quickly if we can't. if (!SafeWaitForMutexOnce(mutexIn, ref mutexOut)) return false; if (mutexOut != null) return true; // We come out here to the outer method every so often so we're not in a CER and a thread abort can interrupt us. // But the abort logic itself is poll based (in the this case) so we really need to check for a pending abort // explicitly else the two timing windows will virtually never line up and we'll still end up stalling the abort // attempt. Thread.Sleep checks for pending abort for us. Thread.Sleep(0); } } // The portion of SafeWaitForMutex that runs under a CER and thus must not block for a arbitrary period of time. // This method must not be inlined (to stop the CER accidently spilling into the calling method). [MethodImplAttribute(MethodImplOptions.NoInlining)] private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex mutexOut) { bool ret; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // Wait for the mutex for half a second (long enough to gain the mutex in most scenarios and short enough to avoid // impacting a thread abort for too long). // Holding a mutex requires us to keep thread affinity and announce ourselves as a critical region. Thread.BeginCriticalRegion(); Thread.BeginThreadAffinity(); int result = Interop.Kernel32.WaitForSingleObject(mutexIn.SafeWaitHandle, 500); switch (result) { case WAIT_OBJECT_0: case WAIT_ABANDONED: // Mutex was obtained, atomically record that fact. mutexOut = mutexIn; ret = true; break; case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT: // Couldn't get mutex yet, simply return and we'll try again later. ret = true; break; default: // Some sort of failure return immediately all the way to the caller of SafeWaitForMutex. ret = false; break; } // If we're not leaving with the Mutex we don't require thread affinity and we're not a critical region any more. if (mutexOut == null) { Thread.EndThreadAffinity(); Thread.EndCriticalRegion(); } } return ret; } // What if an app is locked back? Why would we use this? internal static string GetLatestBuildDllDirectory(string machineName) { string dllDir = ""; RegistryKey baseKey = null; RegistryKey complusReg = null; //This property is retrieved only when creationg a new category, // the calling code already demanded PerformanceCounterPermission. // Therefore the assert below is safe. //This property is retrieved only when creationg a new log, // the calling code already demanded EventLogPermission. // Therefore the assert below is safe. RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { if (machineName.Equals(".")) { return GetLocalBuildDirectory(); } else { baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName); } if (baseKey == null) throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, "HKEY_LOCAL_MACHINE", machineName)); complusReg = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework"); if (complusReg != null) { string installRoot = (string)complusReg.GetValue("InstallRoot"); if (installRoot != null && installRoot != string.Empty) { // the "policy" subkey contains a v{major}.{minor} subkey for each version installed. There are also // some extra subkeys like "standards" and "upgrades" we want to ignore. // first we figure out what version we are... string versionPrefix = "v" + Environment.Version.Major + "." + Environment.Version.Minor; RegistryKey policyKey = complusReg.OpenSubKey("policy"); // This is the full version string of the install on the remote machine we want to use (for example "v2.0.50727") string version = null; if (policyKey != null) { try { // First check to see if there is a version of the runtime with the same minor and major number: RegistryKey bestKey = policyKey.OpenSubKey(versionPrefix); if (bestKey != null) { try { version = versionPrefix + "." + GetLargestBuildNumberFromKey(bestKey); } finally { bestKey.Close(); } } else { // There isn't an exact match for our version, so we will look for the largest version // installed. string[] majorVersions = policyKey.GetSubKeyNames(); int[] largestVersion = new int[] { -1, -1, -1 }; for (int i = 0; i < majorVersions.Length; i++) { string majorVersion = majorVersions[i]; // If this looks like a key of the form v{something}.{something}, we should see if it's a usable build. if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains(".")) { int[] currentVersion = new int[] { -1, -1, -1 }; string[] splitVersion = majorVersion.Substring(1).Split('.'); if (splitVersion.Length != 2) { continue; } if (!Int32.TryParse(splitVersion[0], out currentVersion[0]) || !Int32.TryParse(splitVersion[1], out currentVersion[1])) { continue; } RegistryKey k = policyKey.OpenSubKey(majorVersion); if (k == null) { // We may be able to use another subkey continue; } try { currentVersion[2] = GetLargestBuildNumberFromKey(k); if (currentVersion[0] > largestVersion[0] || ((currentVersion[0] == largestVersion[0]) && (currentVersion[1] > largestVersion[1]))) { largestVersion = currentVersion; } } finally { k.Close(); } } } version = "v" + largestVersion[0] + "." + largestVersion[1] + "." + largestVersion[2]; } } finally { policyKey.Close(); } if (version != null && version != string.Empty) { StringBuilder installBuilder = new StringBuilder(); installBuilder.Append(installRoot); if (!installRoot.EndsWith("\\", StringComparison.Ordinal)) installBuilder.Append("\\"); installBuilder.Append(version); dllDir = installBuilder.ToString(); } } } } } catch { // ignore } finally { if (complusReg != null) complusReg.Close(); if (baseKey != null) baseKey.Close(); RegistryPermission.RevertAssert(); } return dllDir; } private static int GetLargestBuildNumberFromKey(RegistryKey rootKey) { int largestBuild = -1; string[] minorVersions = rootKey.GetValueNames(); for (int i = 0; i < minorVersions.Length; i++) { int o; if (Int32.TryParse(minorVersions[i], out o)) { largestBuild = (largestBuild > o) ? largestBuild : o; } } return largestBuild; } private static string GetLocalBuildDirectory() { return RuntimeEnvironment.GetRuntimeDirectory(); } } }
using System; using NSec.Experimental.Asn1; using Xunit; namespace NSec.Tests.Formatting { public static class Asn1ReaderTests { [Theory] [InlineData(new byte[] { 0x01, 0x01, 0x00 }, false)] [InlineData(new byte[] { 0x01, 0x01, 0xFF }, true)] public static void Bool(byte[] value, bool expected) { var reader = new Asn1Reader(value); Assert.Equal(expected, reader.Bool()); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x01, 0x00 })] [InlineData(new byte[] { 0x01, 0x01, 0x01 })] [InlineData(new byte[] { 0x01, 0x01, 0x80 })] [InlineData(new byte[] { 0x01, 0x01, 0xFE })] [InlineData(new byte[] { 0x01, 0x02, 0x00, 0x00 })] [InlineData(new byte[] { 0x01, 0x02, 0xFF, 0xFF })] public static void BoolInvalid(byte[] value) { var reader = new Asn1Reader(value); Assert.False(reader.Bool()); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x03, 0x01, 0x00 }, new byte[] { })] [InlineData(new byte[] { 0x03, 0x02, 0x00, 0x01 }, new byte[] { 0x01 })] [InlineData(new byte[] { 0x03, 0x09, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef })] public static void BitString(byte[] value, byte[] expected) { var reader = new Asn1Reader(value); Assert.Equal(expected, reader.BitString().ToArray()); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x03, 0x00 })] [InlineData(new byte[] { 0x03, 0x01 })] [InlineData(new byte[] { 0x03, 0x01, 0x08 })] [InlineData(new byte[] { 0x03, 0x01, 0x80 })] [InlineData(new byte[] { 0x03, 0x01, 0xFF })] public static void BitStringInvalid(byte[] value) { var reader = new Asn1Reader(value); Assert.Equal(Array.Empty<byte>(), reader.BitString().ToArray()); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x02, 0x01, 0x00 }, 0)] [InlineData(new byte[] { 0x02, 0x01, 0x7F }, 127)] [InlineData(new byte[] { 0x02, 0x02, 0x00, 0x80 }, 128)] [InlineData(new byte[] { 0x02, 0x02, 0x01, 0x00 }, 256)] [InlineData(new byte[] { 0x02, 0x02, 0x7F, 0xFF }, 32767)] [InlineData(new byte[] { 0x02, 0x03, 0x00, 0x80, 0x00 }, 32768)] [InlineData(new byte[] { 0x02, 0x01, 0xFF }, -1)] [InlineData(new byte[] { 0x02, 0x01, 0x80 }, -128)] [InlineData(new byte[] { 0x02, 0x02, 0xFF, 0x7F }, -129)] [InlineData(new byte[] { 0x02, 0x02, 0x80, 0x00 }, -32768)] [InlineData(new byte[] { 0x02, 0x04, 0x80, 0x00, 0x00, 0x00 }, int.MinValue)] public static void Integer32(byte[] value, int expected) { var reader = new Asn1Reader(value); Assert.Equal(expected, reader.Integer32()); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x02, 0x00 })] // contents octets shall consist of one or more octets [InlineData(new byte[] { 0x02, 0x02, 0x00, 0x7F })] // the bits of the first octet and bit 8 of the second octet shall not all be zero [InlineData(new byte[] { 0x02, 0x02, 0xFF, 0x80 })] // the bits of the first octet and bit 8 of the second octet shall not all be ones [InlineData(new byte[] { 0x02, 0x05, 0x01, 0x23, 0x45, 0x67, 0x89 })] public static void Integer32Invalid(byte[] value) { var reader = new Asn1Reader(value); Assert.Equal(0, reader.Integer32()); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x02, 0x01, 0x00 }, 0L)] [InlineData(new byte[] { 0x02, 0x01, 0x7F }, 127L)] [InlineData(new byte[] { 0x02, 0x02, 0x00, 0x80 }, 128L)] [InlineData(new byte[] { 0x02, 0x02, 0x01, 0x00 }, 256L)] [InlineData(new byte[] { 0x02, 0x02, 0x7F, 0xFF }, 32767L)] [InlineData(new byte[] { 0x02, 0x03, 0x00, 0x80, 0x00 }, 32768L)] [InlineData(new byte[] { 0x02, 0x01, 0xFF }, -1L)] [InlineData(new byte[] { 0x02, 0x01, 0x80 }, -128L)] [InlineData(new byte[] { 0x02, 0x02, 0xFF, 0x7F }, -129L)] [InlineData(new byte[] { 0x02, 0x02, 0x80, 0x00 }, -32768L)] [InlineData(new byte[] { 0x02, 0x04, 0x80, 0x00, 0x00, 0x00 }, int.MinValue)] [InlineData(new byte[] { 0x02, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, long.MinValue)] public static void Integer64(byte[] value, long expected) { var reader = new Asn1Reader(value); Assert.Equal(expected, reader.Integer64()); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x02, 0x00 })] // contents octets shall consist of one or more octets [InlineData(new byte[] { 0x02, 0x02, 0x00, 0x7F })] // the bits of the first octet and bit 8 of the second octet shall not all be zero [InlineData(new byte[] { 0x02, 0x02, 0xFF, 0x80 })] // the bits of the first octet and bit 8 of the second octet shall not all be ones [InlineData(new byte[] { 0x02, 0x09, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })] public static void Integer64Invalid(byte[] value) { var reader = new Asn1Reader(value); Assert.Equal(0, reader.Integer64()); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x04 })] [InlineData(new byte[] { 0x04, 0x01 })] [InlineData(new byte[] { 0x04, 0x80 })] [InlineData(new byte[] { 0x04, 0x81, 0x00 })] [InlineData(new byte[] { 0x04, 0x81, 0x01, 0x17 })] [InlineData(new byte[] { 0x04, 0x82, 0x00, 0x01, 0x17 })] [InlineData(new byte[] { 0x04, 0x84, 0x80, 0x00, 0x00, 0x00 })] [InlineData(new byte[] { 0x04, 0x84, 0xFF, 0xFF, 0xFF, 0xFF })] [InlineData(new byte[] { 0x04, 0xFF })] public static void LengthInvalid(byte[] value) { var reader = new Asn1Reader(value); Assert.Equal(Array.Empty<byte>(), reader.OctetString().ToArray()); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Fact] public static void Null() { var value = new byte[] { 0x05, 0x00 }; var reader = new Asn1Reader(value); reader.Null(); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x05, 0x01, 0xFF })] [InlineData(new byte[] { 0x05, 0x80 })] [InlineData(new byte[] { 0x05, 0x81, 0x00 })] [InlineData(new byte[] { 0x05, 0x81, 0x01, 0xFF })] public static void NullInvalid(byte[] value) { var reader = new Asn1Reader(value); reader.Null(); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x06, 0x06, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d }, new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d })] public static void ObjectIdentifier(byte[] value, byte[] expected) { var reader = new Asn1Reader(value); Assert.Equal(expected, reader.ObjectIdentifier().ToArray()); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x04, 0x00 }, new byte[] { })] [InlineData(new byte[] { 0x04, 0x01, 0x01 }, new byte[] { 0x01 })] [InlineData(new byte[] { 0x04, 0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef })] public static void OctetString(byte[] value, byte[] expected) { var reader = new Asn1Reader(value); Assert.Equal(expected, reader.OctetString().ToArray()); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x24, 0x80, 0x04, 0x02, 0x0A, 0x3B, 0x04, 0x04, 0x5F, 0x29, 0x1C, 0xD0, 0x00, 0x00 })] // The constructed form of encoding shall not be used [InlineData(new byte[] { 0x04, 0x80 })] [InlineData(new byte[] { 0x04, 0x81, 0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef })] // The length shall be encoded in the minimum number of octets [InlineData(new byte[] { 0x04, 0x82, 0x00, 0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef })] // The length shall be encoded in the minimum number of octets public static void OctetStringInvalid(byte[] value) { var reader = new Asn1Reader(value); Assert.Equal(Array.Empty<byte>(), reader.OctetString().ToArray()); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Fact] public static void SequenceStackOverflow() { Assert.Equal(7, Asn1Reader.MaxDepth); var value = new byte[] { 0x30, 0x14, 0x30, 0x12, 0x30, 0x10, 0x30, 0x0E, 0x30, 0x0C, 0x30, 0x0A, 0x30, 0x08, 0x30, 0x06, 0x30, 0x04, 0x30, 0x02, 0x30, 0x00 }; var reader = new Asn1Reader(value); reader.BeginSequence(); Assert.True(reader.Success); reader.BeginSequence(); Assert.True(reader.Success); reader.BeginSequence(); Assert.True(reader.Success); reader.BeginSequence(); Assert.True(reader.Success); reader.BeginSequence(); Assert.True(reader.Success); reader.BeginSequence(); Assert.True(reader.Success); try { reader.BeginSequence(); Assert.True(false); } catch (InvalidOperationException) { } // cannot use Assert.Throws } [Fact] public static void SequenceStackUnderflow() { var value = Array.Empty<byte>(); var reader = new Asn1Reader(value); try { reader.End(); Assert.True(false); } catch (InvalidOperationException) { } // cannot use Assert.Throws } [Fact] public static void SequenceGraceful() { var value = new byte[] { 0x30, 0x06, 0x30, 0x04, 0x30, 0x02, 0x30, 0x00 }; var reader = new Asn1Reader(value); reader.BeginSequence(); Assert.True(reader.Success); reader.BeginSequence(); Assert.True(reader.Success); Assert.Equal(0, reader.Integer32()); Assert.False(reader.Success); reader.End(); Assert.False(reader.Success); reader.End(); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Theory] [InlineData(1, new byte[] { 0x30, 0x00 })] [InlineData(2, new byte[] { 0x30, 0x02, 0x30, 0x00 })] [InlineData(3, new byte[] { 0x30, 0x04, 0x30, 0x02, 0x30, 0x00 })] [InlineData(4, new byte[] { 0x30, 0x06, 0x30, 0x04, 0x30, 0x02, 0x30, 0x00 })] public static void Sequence(int depth, byte[] value) { var reader = new Asn1Reader(value); for (var i = 0; i < depth; i++) { reader.BeginSequence(); Assert.True(reader.Success); } for (var i = 0; i < depth; i++) { reader.End(); Assert.True(reader.Success); } Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x30, 0x00 }, new int[] { })] [InlineData(new byte[] { 0x30, 0x03, 0x02, 0x01, 0x01 }, new int[] { 1 })] [InlineData(new byte[] { 0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02 }, new int[] { 1, 2 })] [InlineData(new byte[] { 0x30, 0x09, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x01, 0x03 }, new int[] { 1, 2, 3 })] public static void IntegerSequence(byte[] value, int[] expected) { var reader = new Asn1Reader(value); reader.BeginSequence(); for (var i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], reader.Integer32()); } reader.End(); Assert.True(reader.Success); Assert.True(reader.SuccessComplete); } [Theory] [InlineData(new byte[] { 0x30 })] [InlineData(new byte[] { 0x30, 0x01 })] [InlineData(new byte[] { 0x30, 0x80 })] [InlineData(new byte[] { 0x30, 0x81, 0x00 })] [InlineData(new byte[] { 0x30, 0x81, 0x01, 0xFF })] [InlineData(new byte[] { 0x30, 0x84, 0xFF, 0xFF, 0xFF, 0xFF })] [InlineData(new byte[] { 0x10, 0x00 })] public static void SequenceInvalid(byte[] value) { var reader = new Asn1Reader(value); reader.BeginSequence(); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Fact] public static void InnerLengthGreaterThanOuterLength() { var value = new byte[] { 0x30, 0x08, 0x04, 0x0A, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }; var reader = new Asn1Reader(value); reader.BeginSequence(); Assert.True(reader.Success); Assert.Equal(Array.Empty<byte>(), reader.OctetString().ToArray()); Assert.False(reader.Success); reader.End(); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } [Fact] public static void UnexpectedDataAfterEnd1() { var value = new byte[] { 0x30, 0x03, 0x02, 0x01, 0x17, 0x02, 0x01, 0x42 }; var reader = new Asn1Reader(value); reader.BeginSequence(); Assert.True(reader.Success); Assert.Equal(0x17, reader.Integer32()); Assert.True(reader.Success); reader.End(); Assert.True(reader.Success); Assert.False(reader.SuccessComplete); } [Fact] public static void UnexpectedDataAfterEnd2() { var value = new byte[] { 0x30, 0x06, 0x02, 0x01, 0x17, 0x02, 0x01, 0x42 }; var reader = new Asn1Reader(value); reader.BeginSequence(); Assert.True(reader.Success); Assert.Equal(0x17, reader.Integer32()); Assert.True(reader.Success); reader.End(); Assert.False(reader.Success); Assert.False(reader.SuccessComplete); } } }
//----------------------------------------------------------------------- // <copyright file="MethodWrapper.cs" company="Redpoint Software"> // The MIT License (MIT) // // Copyright (c) 2013 James Rhodes // // 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> //----------------------------------------------------------------------- namespace Dx.Process { using System; using System.Diagnostics; using System.Linq; using Dx.Runtime; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; /// <summary> /// Wraps a method for distributed behaviour. /// </summary> internal class MethodWrapper : IWrapper { /// <summary> /// The method to be wrapped. /// </summary> private readonly MethodDefinition m_Method; /// <summary> /// The type on which the method to be wrapped is defined. /// </summary> private readonly TypeDefinition m_Type; /// <summary> /// The module containing the method to be wrapped. /// </summary> private readonly ModuleDefinition m_Module; /// <summary> /// The trace source on which logging will be done. /// </summary> private readonly TraceSource m_TraceSource; /// <summary> /// Initializes a new instance of the <see cref="Process4.Task.Wrappers.MethodWrapper"/> class. /// </summary> /// <param name="method">The method to wrap.</param> public MethodWrapper(MethodDefinition method) { this.m_Method = method; this.m_Type = method.DeclaringType; this.m_Module = method.Module; this.m_TraceSource = new TraceSource("MethodWrapper"); } /// <summary> /// Wraps the method. /// </summary> public void Wrap(WrapContext context) { if (this.m_Method.CustomAttributes.Any(c => c.AttributeType.Name == "LocalAttribute")) return; this.m_TraceSource.TraceEvent(TraceEventType.Information, 0, "Modifying {0} for distributed processing", this.m_Method.Name); // Generate the direct invocation class. TypeDefinition idc = this.GenerateDirectInvokeClass(); // Get a list of existing instructions. Collection<Instruction> instructions = this.m_Method.Body.Instructions; // Get a reference to the context setting method. var assignNodeContext = new MethodReference("AssignNodeContext", this.m_Type.Module.Import(typeof(void)), this.m_Type.Module.Import(typeof(DpmConstructContext))); assignNodeContext.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(object)))); // Create a new Action delegate using those instructions. TypeReference mdr = this.m_Method.ReturnType; MethodDefinition md = new MethodDefinition(this.m_Method.Name + "__Distributed0", MethodAttributes.Private, mdr); md.Body = new MethodBody(md); md.Body.InitLocals = true; md.Body.Instructions.Clear(); foreach (Instruction ii in instructions) { if (ii.OpCode == OpCodes.Newobj) { md.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); md.Body.Instructions.Add(Instruction.Create(OpCodes.Call, assignNodeContext)); } md.Body.Instructions.Add(ii); } foreach (VariableDefinition l in this.m_Method.Body.Variables) { md.Body.Variables.Add(l); } foreach (ExceptionHandler ex in this.m_Method.Body.ExceptionHandlers) { md.Body.ExceptionHandlers.Add(ex); } foreach (ParameterDefinition p in this.m_Method.Parameters) { md.Parameters.Add(p); } foreach (GenericParameter gp in this.m_Method.GenericParameters) { GenericParameter gpn = new GenericParameter(gp.Name, md); gpn.Attributes = gp.Attributes; foreach (TypeReference tr in gp.Constraints) { gpn.Constraints.Add(tr); } md.GenericParameters.Add(gpn); } this.m_Type.Methods.Add(md); Utility.AddAttribute(md, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), this.m_Module); // Get the ILProcessor and create variables to store the delegate variable // and delegate constructor. ILProcessor il = this.m_Method.Body.GetILProcessor(); VariableDefinition vd; MethodReference ct; // Clear the existing instructions and local variables. this.m_Method.Body.ExceptionHandlers.Clear(); this.m_Method.Body.Instructions.Clear(); this.m_Method.Body.Variables.Clear(); // Generate the IL for the delegate definition and fill the vd and ct // variables. TypeDefinition dg = Utility.EmitDelegate(il, idc, md, this.m_Type, out vd, out ct); // Implement the Invoke method in the DirectInvoke class. this.ImplementDirectInvokeClass(idc, dg, md.Parameters, md.ReturnType); // Create the Process4.Providers.DpmEntrypoint::GetProperty method reference. MethodReference getproperty = new MethodReference("GetProperty", this.m_Type.Module.Import(typeof(object)), this.m_Type.Module.Import(typeof(DpmEntrypoint))); getproperty.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(Delegate)))); getproperty.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(object[])))); // Create the Process4.Providers.DpmEntrypoint::SetProperty method reference. MethodReference setproperty = new MethodReference("SetProperty", this.m_Type.Module.Import(typeof(object)), this.m_Type.Module.Import(typeof(DpmEntrypoint))); setproperty.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(Delegate)))); setproperty.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(object[])))); // Create the Process4.Providers.DpmEntrypoint::Invoke method reference. MethodReference invoke = new MethodReference("Invoke", this.m_Type.Module.Import(typeof(object)), this.m_Type.Module.Import(typeof(DpmEntrypoint))); invoke.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(Delegate)))); invoke.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(object[])))); // Generate the local variables like: // * 0 - MultitypeDelegate // * 1 - object[] // * 2 - {return type} (if not void) VariableDefinition v_0 = vd; VariableDefinition v_1 = new VariableDefinition(this.m_Type.Module.Import(typeof(object[]))); VariableDefinition v_2 = new VariableDefinition(md.ReturnType); // Add the variables to the local variable list (delegate is already added). this.m_Method.Body.Variables.Add(v_1); if (v_2.VariableType.Name.ToLower() != "void") { this.m_Method.Body.Variables.Add(v_2); } // Force local variables to be initalized. this.m_Method.Body.InitLocals = true; this.m_Method.Body.MaxStackSize = 10; // Create statement processor for method. StatementProcessor processor = new StatementProcessor(il); // Make a generic version of the delegate method. TypeDefinition btd = this.m_Type; MethodDefinition bmd = md; MethodReference bmr = btd.Module.Import(bmd); GenericInstanceType bti = null; if (this.m_Type.HasGenericParameters) { bti = (GenericInstanceType)Utility.MakeGenericType(this.m_Type, this.m_Type.GenericParameters.ToArray()); bmr = Utility.MakeGeneric(bmr, bti.GenericArguments.ToArray()); } if (this.m_Method.HasGenericParameters) { GenericInstanceMethod gim = new GenericInstanceMethod(bmr); foreach (GenericParameter gp in bmr.GenericParameters) { gim.GenericArguments.Add(gp); } bmr = gim; } foreach (var gp in this.m_Type.GenericParameters) { ((GenericInstanceType)ct.DeclaringType).GenericArguments.Add(gp); } foreach (var gp in this.m_Method.GenericParameters) { ((GenericInstanceType)ct.DeclaringType).GenericArguments.Add(gp); } // Initialize the delegate. processor.Add(new InitDelegateStatement(ct, bmr, v_0)); // Initialize the array. if (this.m_Method.IsSetter) { il.Append(Instruction.Create(OpCodes.Ldloc_0)); } processor.Add( new InitArrayStatement( this.m_Module.Import(typeof(object)), (sbyte)md.Parameters.Count, v_1, new Action<ILProcessor, int>((p, i) => { // Get a reference to the parameter being passed to the method. ParameterDefinition pd = this.m_Method.Parameters[i]; if (i > this.m_Method.Parameters.Count - 1) { return; } // Create IL to copy the value from the parameter directly // into the array, boxing the value if needed. p.Append(Instruction.Create(OpCodes.Ldloc, v_1)); p.Append(Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)i)); p.Append(Instruction.Create(OpCodes.Ldarg_S, pd)); if (pd.ParameterType.IsValueType || pd.ParameterType.IsGenericParameter) { p.Append(Instruction.Create(OpCodes.Box, pd.ParameterType)); } p.Append(Instruction.Create(OpCodes.Stelem_Ref)); }))); // Call the delegate. if (this.m_Method.IsSetter) { processor.Add(new CallStatement(setproperty, new VariableDefinition[] { v_1 }, this.m_Method.ReturnType, v_2)); } else if (this.m_Method.IsGetter) { processor.Add(new CallStatement(getproperty, new VariableDefinition[] { v_0, v_1 }, this.m_Method.ReturnType, v_2)); } else { processor.Add(new CallStatement(invoke, new VariableDefinition[] { v_0, v_1 }, this.m_Method.ReturnType, v_2)); } } /// <summary> /// Generates the direct invocation class which allows methods to be called /// without exceptions being wrapped in TargetInvocationException. /// </summary> /// <returns>The direct invocation class.</returns> private TypeDefinition GenerateDirectInvokeClass() { // Determine the generic appendix. var genericAppendix = string.Empty; if (this.m_Method.GenericParameters.Count > 0) { genericAppendix = "`" + this.m_Method.GenericParameters.Count; } // Create a new type. var idc = new TypeDefinition( string.Empty, this.m_Method.Name + "__InvokeDirect" + this.m_Type.NestedTypes.Count + genericAppendix, TypeAttributes.Public | TypeAttributes.NestedPublic | TypeAttributes.BeforeFieldInit); idc.BaseType = this.m_Module.Import(typeof(object)); idc.DeclaringType = this.m_Type; foreach (var gp in this.m_Type.GenericParameters) { var gpn = new GenericParameter(gp.Name, idc); gpn.Attributes = gp.Attributes; foreach (var tr in gp.Constraints) { if (tr is GenericInstanceType) { gpn.Constraints.Add(Utility.RewriteGenericReferencesToType(this.m_Type, tr as GenericInstanceType)); } else { gpn.Constraints.Add(tr); } } idc.GenericParameters.Add(gpn); } foreach (var gp in this.m_Method.GenericParameters) { var gpn = new GenericParameter(gp.Name, idc); gpn.Attributes = gp.Attributes; foreach (var tr in gp.Constraints) { if (tr is GenericInstanceType) { gpn.Constraints.Add(Utility.RewriteGenericReferencesToType(this.m_Type, tr as GenericInstanceType)); } else { gpn.Constraints.Add(tr); } } idc.GenericParameters.Add(gpn); } this.m_Type.NestedTypes.Add(idc); // Add the IDirectInvoke interface. idc.Interfaces.Add(this.m_Module.Import(typeof(IDirectInvoke))); // Create the System.Object::.ctor method reference. var objctor = new MethodReference(".ctor", this.m_Type.Module.Import(typeof(void)), this.m_Type.Module.Import(typeof(object))); objctor.HasThis = true; // Add the constructor. var ctorAttributes = MethodAttributes.Public; ctorAttributes |= MethodAttributes.CompilerControlled; ctorAttributes |= MethodAttributes.SpecialName; ctorAttributes |= MethodAttributes.HideBySig; ctorAttributes |= MethodAttributes.RTSpecialName; var ctor = new MethodDefinition( ".ctor", ctorAttributes, this.m_Module.Import(typeof(void))); var p = ctor.Body.GetILProcessor(); p.Append(Instruction.Create(OpCodes.Ldarg_0)); p.Append(Instruction.Create(OpCodes.Call, objctor)); p.Append(Instruction.Create(OpCodes.Ret)); idc.Methods.Add(ctor); return idc; } /// <summary> /// Implements the direct invocation class. /// </summary> /// <param name="idc">Idc sdf.</param> /// <param name="dg">Dg sdf .</param> /// <param name="ps">Pssd fsdf.</param> /// <param name="tret">Tret sdf.</param> private void ImplementDirectInvokeClass(TypeDefinition idc, TypeDefinition dg, Collection<ParameterDefinition> ps, TypeReference tret) { // Create the generic instance type. GenericInstanceType gdg = new GenericInstanceType(dg); int gi = 0; foreach (GenericParameter gp in idc.GenericParameters) { gdg.GenericParameters.Add(new GenericParameter(gp.Name, gdg)); gdg.GenericArguments.Add(gdg.GenericParameters[gi]); gi++; } TypeReference ret = tret; if (ret is GenericInstanceType) { ret = Utility.RewriteGenericReferencesToType(this.m_Type, ret as GenericInstanceType); } else if (ret is GenericParameter) { ret = new GenericParameter( (tret as GenericParameter).Type == GenericParameterType.Type ? (tret as GenericParameter).Position : (tret as GenericParameter).Position + this.m_Type.GenericParameters.Count, GenericParameterType.Type, idc.Module); } // Pick the normal delegate if there were no generic type parameters. TypeReference rdg = gdg.GenericArguments.Count > 0 ? gdg : (TypeReference)dg; // Add the parameters and variables. MethodDefinition invoke = new MethodDefinition( "Invoke", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot, this.m_Module.Import(typeof(object))); invoke.Parameters.Add(new ParameterDefinition("method", ParameterAttributes.None, this.m_Module.Import(typeof(System.Reflection.MethodInfo)))); invoke.Parameters.Add(new ParameterDefinition("instance", ParameterAttributes.None, this.m_Module.Import(typeof(object)))); invoke.Parameters.Add(new ParameterDefinition("parameters", ParameterAttributes.None, this.m_Module.Import(typeof(object[])))); invoke.Body.Variables.Add(new VariableDefinition("d", rdg)); invoke.Body.Variables.Add(new VariableDefinition("ret", this.m_Module.Import(typeof(object)))); // Get the ILProcessor and create variables to store the delegate variable. ILProcessor il = invoke.Body.GetILProcessor(); VariableDefinition v_0 = invoke.Body.Variables[0]; VariableDefinition v_1 = invoke.Body.Variables.Count == 1 ? null : invoke.Body.Variables[1]; // Create the System.Type::GetTypeFromHandle method reference. MethodReference gettypefromhandle = new MethodReference("GetTypeFromHandle", this.m_Type.Module.Import(typeof(Type)), this.m_Type.Module.Import(typeof(Type))); gettypefromhandle.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(RuntimeTypeHandle)))); // Create the System.Delegate::CreateDelegate method reference. MethodReference createdelegate = new MethodReference("CreateDelegate", this.m_Type.Module.Import(typeof(Delegate)), this.m_Type.Module.Import(typeof(Delegate))); createdelegate.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(Type)))); createdelegate.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(object)))); createdelegate.Parameters.Add(new ParameterDefinition(this.m_Type.Module.Import(typeof(System.Reflection.MethodInfo)))); // Create the dg::Invoke method reference. MethodReference invokedelegate = new MethodReference("Invoke", this.m_Module.Import(ret), rdg); foreach (ParameterDefinition pd in ps) { var propType = pd.ParameterType; if (pd.ParameterType is GenericParameter) { propType = new GenericParameter( (pd.ParameterType as GenericParameter).Type == GenericParameterType.Type ? (pd.ParameterType as GenericParameter).Position : (pd.ParameterType as GenericParameter).Position + this.m_Type.GenericParameters.Count, GenericParameterType.Type, this.m_Module); } invokedelegate.Parameters.Add(new ParameterDefinition( pd.Name, pd.Attributes, propType)); } invokedelegate.HasThis = true; // Force local variables to be initalized. invoke.Body.InitLocals = true; // Get a type instance reference from the delegate type. il.Append(Instruction.Create(OpCodes.Nop)); il.Append(Instruction.Create(OpCodes.Ldtoken, rdg)); il.Append(Instruction.Create(OpCodes.Call, gettypefromhandle)); // Get a delegate and then cast it. il.Append(Instruction.Create(OpCodes.Ldarg_2)); il.Append(Instruction.Create(OpCodes.Ldarg_1)); il.Append(Instruction.Create(OpCodes.Call, createdelegate)); il.Append(Instruction.Create(OpCodes.Castclass, rdg)); il.Append(Instruction.Create(OpCodes.Stloc, v_0)); // Load the delegate. il.Append(Instruction.Create(OpCodes.Ldloc, v_0)); // Load the arguments. int i = 0; foreach (ParameterDefinition pd in ps) { var propType = pd.ParameterType; if (pd.ParameterType is GenericParameter) { propType = new GenericParameter( (pd.ParameterType as GenericParameter).Type == GenericParameterType.Type ? (pd.ParameterType as GenericParameter).Position : (pd.ParameterType as GenericParameter).Position + this.m_Type.GenericParameters.Count, GenericParameterType.Type, this.m_Module); } il.Append(Instruction.Create(OpCodes.Ldarg_3)); il.Append(Instruction.Create(OpCodes.Ldc_I4, i)); il.Append(Instruction.Create(OpCodes.Ldelem_Ref)); if (propType.IsValueType || propType.IsGenericParameter) { il.Append(Instruction.Create(OpCodes.Unbox_Any, propType)); } else { il.Append(Instruction.Create(OpCodes.Castclass, propType)); } i += 1; } // Call the delegate's Invoke method. il.Append(Instruction.Create(OpCodes.Callvirt, invokedelegate)); if (ret.FullName == this.m_Module.Import(typeof(void)).FullName) { il.Append(Instruction.Create(OpCodes.Ldnull)); } else if (ret.IsValueType || ret.IsGenericParameter) { il.Append(Instruction.Create(OpCodes.Box, ret)); } var ii_stloc = Instruction.Create(OpCodes.Stloc, v_1); var ii_ldloc = Instruction.Create(OpCodes.Ldloc, v_1); il.Append(ii_stloc); il.Append(ii_ldloc); il.Append(Instruction.Create(OpCodes.Ret)); il.InsertAfter(ii_stloc, Instruction.Create(OpCodes.Br_S, ii_ldloc)); idc.Methods.Insert(0, invoke); } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.Security.Permissions; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.Samples.VisualStudio.IDE.EditorWithToolbox { /// <summary> /// Factory for creating our editors. /// </summary> [Guid(GuidStrings.GuidEditorFactory)] public class EditorFactory : IVsEditorFactory, IDisposable { #region Fields // private instance of the EditorFactory's OleServiceProvider private ServiceProvider vsServiceProvider; #endregion #region Constructors /// <summary> /// Explicitly defined default constructor. /// Initialize new instance of the EditorFactory object. /// </summary> public EditorFactory() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} constructor", typeof(EditorFactory).ToString())); } #endregion Constructors #region Methods #region IDisposable Pattern implementation /// <summary> /// Clean up any resources being used. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">This parameter determines whether the method has been called directly or indirectly by a user's code.</param> private void Dispose(bool disposing) { // If disposing equals true, dispose all managed and unmanaged resources if (disposing) { /// Since we create a ServiceProvider which implements IDisposable we /// also need to implement IDisposable to make sure that the ServiceProvider's /// Dispose method gets called. if (vsServiceProvider != null) { vsServiceProvider.Dispose(); vsServiceProvider = null; } } } #endregion #region IVsEditorFactory Members /// <summary> /// Used for initialization of the editor in the environment. /// </summary> /// <param name="psp">Pointer to the service provider. Can be used to obtain instances of other interfaces.</param> /// <returns>S_OK if the method succeeds.</returns> public int SetSite(IOleServiceProvider psp) { vsServiceProvider = new ServiceProvider(psp); return VSConstants.S_OK; } // This method is called by the Environment (inside IVsUIShellOpenDocument:: // OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a // PHYSICAL view. A LOGICAL view identifies the purpose of the view that is // desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a // view appropriate for text view manipulation as by navigating to a find // result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type // of view implementation that an IVsEditorFactory can create. // // NOTE: Physical views are identified by a string of your choice with the // one constraint that the default/primary physical view for an editor // *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL). // // NOTE: It is essential that the implementation of MapLogicalView properly // validates that the LogicalView desired is actually supported by the editor. // If an unsupported LogicalView is requested then E_NOTIMPL must be returned. // // NOTE: The special Logical Views supported by an Editor Factory must also // be registered in the local registry hive. LOGVIEWID_Primary is implicitly // supported by all editor types and does not need to be registered. // For example, an editor that supports a ViewCode/ViewDesigner scenario // might register something like the following: // HKLM\Software\Microsoft\VisualStudio\10.0\Editors\ // {...guidEditor...}\ // LogicalViews\ // {...LOGVIEWID_TextView...} = s '' // {...LOGVIEWID_Code...} = s '' // {...LOGVIEWID_Debugging...} = s '' // {...LOGVIEWID_Designer...} = s 'Form' // public int MapLogicalView(ref Guid rguidLogicalView, out string pbstrPhysicalView) { pbstrPhysicalView = null; // initialize out parameter // we support only a single physical view if (VSConstants.LOGVIEWID_Primary == rguidLogicalView) { // primary view uses NULL as pbstrPhysicalView return VSConstants.S_OK; } else { // you must return E_NOTIMPL for any unrecognized rguidLogicalView values return VSConstants.E_NOTIMPL; } } /// <summary> /// Releases all cached interface pointers and unregisters any event sinks /// </summary> /// <returns>S_OK if the method succeeds.</returns> public int Close() { return VSConstants.S_OK; } /// <summary> /// Used by the editor factory to create an editor instance. the environment first determines the /// editor factory with the highest priority for opening the file and then calls /// IVsEditorFactory.CreateEditorInstance. If the environment is unable to instantiate the document data /// in that editor, it will find the editor with the next highest priority and attempt to so that same /// thing. /// NOTE: The priority of our editor is 32 as mentioned in the attributes on the package class. /// /// Since our editor supports opening only a single view for an instance of the document data, if we /// are requested to open document data that is already instantiated in another editor, or even our /// editor, we return a value VS_E_INCOMPATIBLEDOCDATA. /// </summary> /// <param name="grfCreateDoc">Flags determining when to create the editor. Only open and silent flags /// are valid. /// </param> /// <param name="pszMkDocument">path to the file to be opened.</param> /// <param name="pszPhysicalView">name of the physical view.</param> /// <param name="pvHier">pointer to the IVsHierarchy interface.</param> /// <param name="itemid">Item identifier of this editor instance.</param> /// <param name="punkDocDataExisting">This parameter is used to determine if a document buffer /// (DocData object) has already been created. /// </param> /// <param name="ppunkDocView">Pointer to the IUnknown interface for the DocView object.</param> /// <param name="ppunkDocData">Pointer to the IUnknown interface for the DocData object.</param> /// <param name="pbstrEditorCaption">Caption mentioned by the editor for the doc window.</param> /// <param name="pguidCmdUI">the Command UI Guid. Any UI element that is visible in the editor has /// to use this GUID. /// </param> /// <param name="pgrfCDW">Flags for CreateDocumentWindow.</param> /// <returns>HRESULT result code. S_OK if the method succeeds.</returns> /// <remarks> /// Attribute usage according to FxCop rule regarding SecurityAction requirements (LinkDemand). /// This method do use SecurityAction.Demand action instead of LinkDemand because it overrides method without LinkDemand /// see "Demand vs. LinkDemand" article in MSDN for more details. /// </remarks> [EnvironmentPermission(SecurityAction.Demand, Unrestricted = true)] public int CreateEditorInstance( uint grfCreateDoc, string pszMkDocument, string pszPhysicalView, IVsHierarchy pvHier, uint itemid, IntPtr punkDocDataExisting, out IntPtr ppunkDocView, out IntPtr ppunkDocData, out string pbstrEditorCaption, out Guid pguidCmdUI, out int pgrfCDW) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} CreateEditorInstance()", ToString())); // Initialize to null ppunkDocView = IntPtr.Zero; ppunkDocData = IntPtr.Zero; pguidCmdUI = GuidList.guidEditorFactory; pgrfCDW = 0; pbstrEditorCaption = null; // Validate inputs if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) { return VSConstants.E_INVALIDARG; } if (punkDocDataExisting != IntPtr.Zero) { return VSConstants.VS_E_INCOMPATIBLEDOCDATA; } // Create the Document (editor) EditorPane newEditor = new EditorPane(); ppunkDocView = Marshal.GetIUnknownForObject(newEditor); ppunkDocData = Marshal.GetIUnknownForObject(newEditor); pbstrEditorCaption = ""; return VSConstants.S_OK; } #endregion #region Other methods /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType">An Type that specifies the type of service object to get.</param> /// <returns>A service object of type serviceType. -or- /// A a null reference if there is no service object of type serviceType.</returns> public object GetService(Type serviceType) { return vsServiceProvider.GetService(serviceType); } #endregion #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.CSharp.QuickInfo; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo { public class SyntacticQuickInfoSourceTests : AbstractQuickInfoSourceTests { [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Brackets_0() { await TestInMethodAndScriptAsync( @" switch (true) { }$$ ", @"switch (true) {"); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Brackets_1() { await TestInClassAsync("int Property { get; }$$ ", "int Property {"); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Brackets_2() { await TestInClassAsync("void M()\r\n{ }$$ ", "void M()\r\n{"); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Brackets_3() { await TestInMethodAndScriptAsync("var a = new int[] { }$$ ", "new int[] {"); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Brackets_4() { await TestInMethodAndScriptAsync( @" if (true) { }$$ ", @"if (true) {"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_0() { await TestInMethodAndScriptAsync( @"if (true) { { }$$ }", "{"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_1() { await TestInMethodAndScriptAsync( @"while (true) { // some // comment { }$$ }", @"// some // comment {"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_2() { await TestInMethodAndScriptAsync( @"do { /* comment */ { }$$ } while (true);", @"/* comment */ {"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_3() { await TestInMethodAndScriptAsync( @"if (true) { } else { { // some // comment }$$ }", @"{ // some // comment"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_4() { await TestInMethodAndScriptAsync( @"using (var x = new X()) { { /* comment */ }$$ }", @"{ /* comment */"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_5() { await TestInMethodAndScriptAsync( @"foreach (var x in xs) { // above { /* below */ }$$ }", @"// above {"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_6() { await TestInMethodAndScriptAsync( @"for (;;) { /*************/ // part 1 // part 2 { }$$ }", @"/*************/ // part 1 // part 2 {"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_7() { await TestInMethodAndScriptAsync( @"try { /*************/ // part 1 // part 2 { }$$ } catch { throw; }", @"/*************/ // part 1 // part 2 {"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_8() { await TestInMethodAndScriptAsync( @" { /*************/ // part 1 // part 2 }$$ ", @"{ /*************/ // part 1 // part 2"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_9() { await TestInClassAsync( @"int Property { set { { }$$ } }", "{"); } [WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ScopeBrackets_10() { await TestInMethodAndScriptAsync( @"switch (true) { default: // comment { }$$ break; }", @"// comment {"); } private IQuickInfoProvider CreateProvider(TestWorkspace workspace) { return new SyntacticQuickInfoProvider( workspace.GetService<IProjectionBufferFactoryService>(), workspace.GetService<IEditorOptionsFactoryService>(), workspace.GetService<ITextEditorFactoryService>(), workspace.GetService<IGlyphService>(), workspace.GetService<ClassificationTypeMap>()); } protected override async Task AssertNoContentAsync( TestWorkspace workspace, Document document, int position) { var provider = CreateProvider(workspace); Assert.Null(await provider.GetItemAsync(document, position, CancellationToken.None)); } protected override async Task AssertContentIsAsync( TestWorkspace workspace, Document document, int position, string expectedContent, string expectedDocumentationComment = null) { var provider = CreateProvider(workspace); var state = await provider.GetItemAsync(document, position, cancellationToken: CancellationToken.None); Assert.NotNull(state); var viewHostingControl = (ViewHostingControl)((ElisionBufferDeferredContent)state.Content).Create(); try { var actualContent = viewHostingControl.ToString(); Assert.Equal(expectedContent, actualContent); } finally { viewHostingControl.TextView_TestOnly.Close(); } } protected override Task TestInMethodAsync(string code, string expectedContent, string expectedDocumentationComment = null) { return TestInClassAsync( @"void M() {" + code + "}", expectedContent, expectedDocumentationComment); } protected override Task TestInClassAsync(string code, string expectedContent, string expectedDocumentationComment = null) { return TestAsync( @"class C {" + code + "}", expectedContent, expectedDocumentationComment); } protected override Task TestInScriptAsync(string code, string expectedContent, string expectedDocumentationComment = null) { return TestAsync(code, expectedContent, expectedContent, Options.Script); } protected override async Task TestAsync( string code, string expectedContent, string expectedDocumentationComment = null, CSharpParseOptions parseOptions = null) { using (var workspace = await TestWorkspace.CreateCSharpAsync(code, parseOptions)) { var testDocument = workspace.Documents.Single(); var position = testDocument.CursorPosition.Value; var document = workspace.CurrentSolution.Projects.First().Documents.First(); if (string.IsNullOrEmpty(expectedContent)) { await AssertNoContentAsync(workspace, document, position); } else { await AssertContentIsAsync(workspace, document, position, expectedContent, expectedDocumentationComment); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using SvnBridge.Utility; namespace SvnBridge.Net { public class ListenerResponseStream : Stream { protected bool flushed = false; protected bool headerWritten = false; protected int maxKeepAliveConnections; protected ListenerRequest request; protected ListenerResponse response; protected Stream stream; protected MemoryStream streamBuffer = new MemoryStream(); public ListenerResponseStream(ListenerRequest request, ListenerResponse response, Stream stream, int maxKeepAliveConnections) { this.request = request; this.response = response; this.stream = stream; this.maxKeepAliveConnections = maxKeepAliveConnections; streamBuffer = new MemoryStream(); } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override void Flush() { if (!flushed) { WriteHeaderIfNotAlreadyWritten(); if (response.SendChunked) { byte[] chunkFooter = Encoding.UTF8.GetBytes("0\r\n\r\n"); stream.Write(chunkFooter, 0, chunkFooter.Length); } else { byte[] buffer = streamBuffer.ToArray(); stream.Write(buffer, 0, buffer.Length); } stream.Flush(); flushed = true; } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { if (response.SendChunked) { WriteHeaderIfNotAlreadyWritten(); byte[] chunkHeader = Encoding.UTF8.GetBytes(string.Format("{0:x}", count) + "\r\n"); byte[] chunkFooter = Encoding.UTF8.GetBytes("\r\n"); stream.Write(chunkHeader, 0, chunkHeader.Length); stream.Write(buffer, offset, count); stream.Write(chunkFooter, 0, chunkFooter.Length); } else { streamBuffer.Write(buffer, offset, count); } } protected void WriteHeaderIfNotAlreadyWritten() { if (!headerWritten) { string statusCodeDescription; switch (response.StatusCode) { case 204: statusCodeDescription = "No Content"; break; case 207: statusCodeDescription = "Multi-Status"; break; case 301: statusCodeDescription = "Moved Permanently"; break; case 401: statusCodeDescription = "Authorization Required"; break; case 404: statusCodeDescription = "Not Found"; break; case 405: statusCodeDescription = "Method Not Allowed"; break; case 500: statusCodeDescription = "Internal Server Error"; break; case 501: statusCodeDescription = "Method Not Implemented"; break; default: statusCodeDescription = ((HttpStatusCode) response.StatusCode).ToString(); break; } StringBuilder buffer = new StringBuilder(); StringWriter writer = new StringWriter(buffer); writer.WriteLine("HTTP/1.1 {0} {1}", response.StatusCode, statusCodeDescription); writer.WriteLine("Date: {0}", Helper.FormatDateB(DateTime.Now)); writer.WriteLine("Server: Apache"); List<KeyValuePair<string, string>> headers = response.Headers; string xPadHeader = null; string connection = null; foreach (KeyValuePair<string, string> header in headers) { if (header.Key == "X-Pad") { xPadHeader = header.Value; continue; } else if (header.Key == "Connection") { connection = header.Value; continue; } else { writer.WriteLine("{0}: {1}", header.Key, header.Value); } } if (!response.SendChunked) { writer.WriteLine("Content-Length: {0}", streamBuffer.Length); } else { writer.WriteLine("Transfer-Encoding: chunked"); } if (connection != null) { writer.WriteLine("Connection: {0}", connection); } if (request.Headers["Connection"] != null) { string[] connectionHeaderParts = request.Headers["Connection"].Split(','); foreach (string directive in connectionHeaderParts) { if (directive.TrimStart() == "Keep-Alive") { writer.WriteLine("Keep-Alive: timeout=15, max={0}", maxKeepAliveConnections); writer.WriteLine("Connection: Keep-Alive"); } } } writer.WriteLine("Content-Type: {0}", response.ContentType); if (!String.IsNullOrEmpty(xPadHeader)) { writer.WriteLine("X-Pad: {0}", xPadHeader); } writer.WriteLine(""); byte[] bufferBytes = Encoding.UTF8.GetBytes(buffer.ToString()); stream.Write(bufferBytes, 0, bufferBytes.Length); headerWritten = true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections; using System.Collections.Generic; #if !FEATURE_PAL using Dia; using Dia.Util; #endif // !FEATURE_PAL using System.Globalization; /****************************************************************************** * *****************************************************************************/ public abstract class SymbolProvider { public enum SymType { GlobalData, GlobalFunction, }; public abstract UInt32 GetGlobalRVA(String symbolName, SymType symType); public abstract UInt32 GetVTableRVA(String symbolName, String keyBaseName); } #if !FEATURE_PAL public class PdbSymbolProvider : SymbolProvider { public PdbSymbolProvider(String symbolFilename, String dllFilename) { fPDB = new FileInfo(symbolFilename); df = new DiaFile(fPDB.FullName, dllFilename); } public UInt32 DebugTimestamp { get { return df.DebugTimestamp; } } public string LoadedPdbPath { get { return df.LoadedPdbPath; } } private UInt32 GetSymbolRva(DiaSymbol sy, String symbolName, String typeName) { if (sy == null) { // Ideally this would throw an exception and // cause the whole process to fail but // currently it's too complicated to get // all the ifdef'ing right for all the // mix of debug/checked/free multiplied by // x86/AMD64/IA64/etc. return UInt32.MaxValue; } if (sy.Address > UInt32.MaxValue) { throw new InvalidOperationException(typeName + " symbol " + symbolName + " overflows UInt32"); } return (UInt32)sy.Address; } private DiaSymbol GetValidPublicSymbolEntry(String name) { IDiaEnumSymbols e = df.FindPublicSymbols(name); if (e.count != 1) { return null; } else { IDiaSymbol s; UInt32 celt; e.Next(1, out s, out celt); return new DiaSymbol(s); } } public override UInt32 GetGlobalRVA(String symbolName, SymType symType) { DiaSymbol sy = df.GlobalSymbol.FindSymbol(symbolName); if (sy == null && symType == SymType.GlobalFunction) { // Try looking for the symbol in public symbols, // as assembly routines do not have normal // global symbol table entries. We don't know // how many parameters to use, so just guess // at a few sizes. for (int i = 0; i <= 16; i += 4) { // Non-fastcall. sy = GetValidPublicSymbolEntry("_" + symbolName + "@" + i); if (sy != null) { break; } // Fastcall. sy = GetValidPublicSymbolEntry("@" + symbolName + "@" + i); if (sy != null) { break; } } } return GetSymbolRva(sy, symbolName, "Symbol"); } public override UInt32 GetVTableRVA(String symbolName, String keyBaseName) { String mangledName; // Single-inheritance vtable symbols have different // mangling from multiple-inheritance so form the // proper name based on which case this is. mangledName = "??_7" + symbolName + "@@6B"; if (keyBaseName != null) { mangledName += keyBaseName + "@@@"; } else { mangledName += "@"; } return GetSymbolRva(GetValidPublicSymbolEntry(mangledName), symbolName, "VTable"); } FileInfo fPDB = null; DiaFile df = null; } #endif // !FEATURE_PAL public class Shell { const String dacSwitch = "/dac:"; const String pdbSwitch = "/pdb:"; const String mapSwitch = "/map:"; const String binSwitch = "/bin:"; const String dllSwitch = "/dll:"; const String ignoreErrorsSwitch = "/ignoreerrors"; public static void Help() { HelpHdr(); Console.WriteLine(); HelpBody(); } public static void HelpHdr() { String helpHdr = //////////// @"Microsoft (R) CLR External Data Access Data Table Generator Version 0.3 Copyright (C) Microsoft Corp. All rights reserved."; //////////// Console.WriteLine(helpHdr); } public static void HelpBody() { String helpMsg = //////////// @"Usage: DacTableGen /dac:<file> [/pdb:<file> /dll:<file>] [/map:<file>] /bin:<file> [/ignoreerrors] Required: /dac: The data access header file containing items to be added. /pdb: The PDB file from which to get details. /map: The MAP file from which to get details. In Windows, this file is created by providing /MAP in link.exe. In UNIX, this file is created by the nm utility. OBSOLETE - Use DacTableGen.pl instead for UNIX systems /dll: The DLL which matches the specified PDB or MAP file. /bin: The binary output file. /ignoreerrors: Turn errors into warnings. The produced binary may hit runtime failures "; //////////// Console.WriteLine(helpMsg); } public static bool MatchArg(String arg, String cmd) { if (arg.Length >= cmd.Length && arg.Substring(0, cmd.Length).ToLower(CultureInfo.InvariantCulture).Equals(cmd.ToLower(CultureInfo.InvariantCulture))) return true; return false; } public static int DoMain(String[] args) { String dacFile = null; String pdbFile = null; String mapFile = null; String binFile = null; String dllFile = null; for (int i = 0; i < args.Length; i++) { if (MatchArg(args[i], dacSwitch)) { dacFile = args[i].Substring(dacSwitch.Length); } else if (MatchArg(args[i], pdbSwitch)) { pdbFile = args[i].Substring(pdbSwitch.Length); } else if (MatchArg(args[i], mapSwitch)) { mapFile = args[i].Substring(mapSwitch.Length); } else if (MatchArg(args[i], binSwitch)) { binFile = args[i].Substring(binSwitch.Length); } else if (MatchArg(args[i], dllSwitch)) { dllFile = args[i].Substring(dllSwitch.Length); } else if (MatchArg(args[i], ignoreErrorsSwitch)) { s_ignoreErrors = true; } else { Help(); return 1; } } if (dacFile == null || (pdbFile == null && mapFile == null) || (dllFile == null && pdbFile != null) || binFile == null) { HelpHdr(); Console.WriteLine(); Console.WriteLine("Required option missing."); // Provide some extra help if just the new dllFile option is missing if ((dllFile == null) && (dacFile != null) && (binFile != null) && (pdbFile != null)) { Console.WriteLine("NOTE that /dll is a new required argument which must point to mscorwks.dll."); Console.WriteLine("Ideally all uses of DacTableGen.exe should use the build logic in ndp/clr/src/DacUpdateDll."); } Console.WriteLine(); HelpBody(); return 1; } // Validate the specified files exist string[] inputFiles = new string[] { dacFile, pdbFile, mapFile, dllFile }; foreach (string file in inputFiles) { if (file != null && !File.Exists(file)) { Console.WriteLine("ERROR, file does not exist: " + file); return 1; } } HelpHdr(); Console.WriteLine(); List<UInt32> rvaArray = new List<UInt32>(); UInt32 numGlobals; UInt32 debugTimestamp = 0; if (pdbFile != null) { #if FEATURE_PAL throw new InvalidOperationException("Not supported in Rotor."); #else PdbSymbolProvider pdbSymProvider = new PdbSymbolProvider(pdbFile, dllFile); // Read the mscorwks debug directory timestamp debugTimestamp = pdbSymProvider.DebugTimestamp; if (debugTimestamp == 0) { throw new System.ApplicationException("Didn't get debug directory timestamp from DIA"); } DateTime dt = new DateTime(1970, 01, 01, 0, 0, 0, DateTimeKind.Utc); dt = dt.AddSeconds(debugTimestamp).ToLocalTime(); // Output information about the PDB loaded Console.WriteLine("Processing DLL with PDB timestamp: {0}", dt.ToString("F")); Console.WriteLine("Loaded PDB file: " + pdbSymProvider.LoadedPdbPath); if (Path.GetFullPath(pdbSymProvider.LoadedPdbPath).ToLowerInvariant() != Path.GetFullPath(pdbFile).ToLowerInvariant()) { // DIA loaded a PDB oter than the one the user asked for. This could possibly happen if the PDB // also exists in a sub-directory that DIA automatically probes for ("retail" etc.). There doesn't // appear to be any mechanism for turning this sub-directory probing off, but all other searching mechanisms // should be turned off by the DiaLoadCallback. This could also happen if the user specified an incorrect // (but still existing) filename in a path containing the real PDB. Since DIA loaded it, it must match the DLL, // and so should only be an exact copy of the requested PDB (if the requested PDB actuall matches the DLL). So // go ahead and use it anyway with a warning. To be less confusing, we could update the command-line syntax // to take a PDB search path instead of a filename, but that inconsistent with the map path, and probably not // worth changing semantics for. In practice this warning will probably never be hit. Shell.Error("Loaded PDB path differs from requested path: " + pdbFile); } Console.WriteLine(); ScanDacFile(dacFile, pdbSymProvider, rvaArray, out numGlobals); if (mapFile != null) { List<UInt32> mapRvaArray = new List<UInt32>(); UInt32 mapNumGlobals; // check that both map file and pdb file produce same output to avoid breakages on Rotor ScanDacFile(dacFile, new MapSymbolProvider(mapFile), mapRvaArray, out mapNumGlobals); // Produce a nice message to include with any errors. For some reason, binplace will silently fail // when a PDB can't be updated due to file locking. This means that problems of this nature usually // occur when mscorwks.pdb was locked when mscorwks.dll was last rebuilt. string diagMsg = String.Format(". This is usually caused by mscorwks.pdb and mscorwks.map being out of sync. " + "Was {0} (last modified {1}) in-use and locked when {2} was built (last modified {3})? " + "Both should have been created when {4} was last rebuilt (last modified {5}).", pdbFile, File.GetLastWriteTime(pdbFile), mapFile, File.GetLastWriteTime(mapFile), dllFile, File.GetLastWriteTime(dllFile)); if (rvaArray.Count != mapRvaArray.Count) throw new InvalidOperationException("Number of RVAs differes between pdb file and map file: " + numGlobals + " " + mapNumGlobals + diagMsg); for (int i = 0; i < rvaArray.Count; i++) { if (rvaArray[i] != mapRvaArray[i] // it is ok if we find more stuff in the MAP file && rvaArray[i] != UInt32.MaxValue) { throw new InvalidOperationException("RVAs differ between pdb file and map file: " + ToHexNB(rvaArray[i]) + " " + ToHexNB(mapRvaArray[i]) + diagMsg); } } if (numGlobals != mapNumGlobals) throw new InvalidOperationException("Number of globals differes between pdb file and map file: " + numGlobals + " " + mapNumGlobals + diagMsg); } #endif } else { ScanDacFile(dacFile, new MapSymbolProvider(mapFile), rvaArray, out numGlobals); } if (s_errors && !s_ignoreErrors) { Console.Error.WriteLine( "DacTableGen : fatal error : Failing due to above validation errors. " + "Do you have an #ifdef (or name) mismatch between the symbol definition and the entry specified? " + "Or perhaps the symbol referenced was optimized away as unused? " + "If you're stuck, send e-mail to 'ClrDac'. Worst case, these errors can be temporarily ignored by passing the /ignoreerrors switch - but you may cause runtime failures instead."); return 1; } UInt32 numVptrs; numVptrs = (UInt32)rvaArray.Count - numGlobals; FileStream outFile = new FileStream(binFile, FileMode.Create, FileAccess.Write); BinaryWriter binWrite = new BinaryWriter(outFile); // Write header information binWrite.Write(numGlobals); binWrite.Write(numVptrs); binWrite.Write(debugTimestamp); binWrite.Write(0); // On Windows we only need a 4-byte timestamp, but on Mac we use binWrite.Write(0); // a 16-byte UUID. We need to be consistent here. binWrite.Write(0); // Write out the table of RVAs for (int i = 0; i < numGlobals + numVptrs; i++) { binWrite.Write(rvaArray[i]); } binWrite.Close(); return 0; } public static int Main(string[] args) { // Don't catch exceptions if a debugger is attached - makes debugging easier if (System.Diagnostics.Debugger.IsAttached) { return DoMain(args); } int exitCode; try { exitCode = DoMain(args); } catch(Exception e) { Console.WriteLine("BUILDMSG: " + e.ToString()); exitCode = 1; } return exitCode; } private static void ScanDacFile(String file, SymbolProvider sf, List<UInt32> rvaArray, out UInt32 numGlobals) { StreamReader strm = new StreamReader(file, System.Text.Encoding.ASCII); String line; Hashtable vtables = new Hashtable(); // hashtable to guarantee uniqueness of entries // // Scan through the data access header file looking // for the globals structure. // for (;;) { line = strm.ReadLine(); if (line == null) { throw new InvalidOperationException("Invalid dac header format"); } else if (line == "typedef struct _DacGlobals") { break; } } if (strm.ReadLine() != "{") { throw new InvalidOperationException("Invalid dac header format"); } // // All the globals come first so pick up each line that // begins with ULONG. // bool fFoundVptrs = false; numGlobals = 0; for (;;) { line = strm.ReadLine().Trim(); if ( line.Equals("union {") || line.Equals("struct {") || line.Equals("};") || line.StartsWith("#line ") || line.StartsWith("# ")) { // Ignore. } else if (line.StartsWith("ULONG ")) { UInt32 rva = 0; line = line.Remove(0, 6); line = line.TrimEnd(";".ToCharArray()); string vptrSuffixSingle = "__vtAddr"; string vptrSuffixMulti = "__mvtAddr"; string vptrSuffix = null; if (line.EndsWith(vptrSuffixSingle)) { vptrSuffix = vptrSuffixSingle; } else if (line.EndsWith(vptrSuffixMulti)) { vptrSuffix = vptrSuffixMulti; } if (vptrSuffix != null) { if (!fFoundVptrs) { numGlobals = (UInt32)rvaArray.Count; fFoundVptrs = true; } line = line.Remove(line.Length - vptrSuffix.Length, vptrSuffix.Length); string keyBaseName = null; string descTail = null; if (vptrSuffix == vptrSuffixMulti) { // line now has the form <class>__<base>, so // split off the base. int basePrefix = line.LastIndexOf("__"); if (basePrefix < 0) { throw new InvalidOperationException("VPTR_MULTI_CLASS has no keyBase."); } keyBaseName = line.Substring(basePrefix + 2); line = line.Remove(basePrefix); descTail = " for " + keyBaseName; } rva = sf.GetVTableRVA(line, keyBaseName); if (rva == UInt32.MaxValue) { Console.WriteLine(" " + ToHexNB(rva)); Shell.Error("Invalid vtable " + line + descTail); } else { String existing = (String)vtables[rva]; if (existing != null) { throw new InvalidOperationException(existing + " and " + line + " are at the same offsets." + " Add VPTR_UNIQUE(<a random unique number here>) to the offending classes to make their vtables unique."); } vtables[rva] = line; Console.WriteLine(" " + ToHexNB(rva) + ", // vtable " + line + descTail); } } else { SymbolProvider.SymType symType; if (fFoundVptrs) throw new InvalidOperationException("Invalid dac header format. Vtable pointers must be last."); if (line.StartsWith("dac__")) { // Global variables, use the prefix. line = line.Remove(0, 5); symType = SymbolProvider.SymType.GlobalData; } else if (line.StartsWith("fn__")) { // Global or static functions, use the prefix. line = line.Remove(0, 4); line = line.Replace("__", "::"); symType = SymbolProvider.SymType.GlobalFunction; } else { // Static member variable, use the full name with // namespace replacement. line = line.Replace("__", "::"); symType = SymbolProvider.SymType.GlobalData; } if (0 == rva) { rva = sf.GetGlobalRVA(line, symType); if (rva == UInt32.MaxValue) { Console.WriteLine(" " + ToHexNB(rva)); Shell.Error("Invalid symbol " + line); } else { Console.WriteLine(" " + ToHexNB(rva) + ", // " + line); } } } rvaArray.Add(rva); } else if (line == "") { // Skip blanks. } else { // We hit a non-global so we're done. if (!line.Equals("} DacGlobals;")) { throw new InvalidOperationException("Invalid dac header format at \"" + line + "\""); } break; } } if (!fFoundVptrs) throw new InvalidOperationException("Invalid dac header format. Vtable pointers not found."); } private static String ToHex(Object o) { if (o is UInt32 || o is Int32) return String.Format("0x{0:x8}", o); else if (o is UInt64 || o is Int64) return String.Format("0x{0:x16}", o); else return null; } private static String ToHexNB(Object o) { return String.Format("0x{0:x}", o); } public static void Error(string message) { Console.Error.WriteLine((s_ignoreErrors ? "WARNING: " : "ERROR: ") + message); s_errors = true; } // Try to tolerate errors (as we've always done in the past), which may result in failures at run-time instead. private static bool s_ignoreErrors = false; private static bool s_errors = false; }
using Microsoft.Kinect; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace KINECTmania.GUI { public static class Extensions { #region Camera public static ImageSource ToBitmap(this ColorFrame frame) { int width = frame.FrameDescription.Width; int height = frame.FrameDescription.Height; PixelFormat format = PixelFormats.Bgr32; byte[] pixels = new byte[width * height * ((format.BitsPerPixel + 7) / 8)]; if (frame.RawColorImageFormat == ColorImageFormat.Bgra) { frame.CopyRawFrameDataToArray(pixels); } else { frame.CopyConvertedFrameDataToArray(pixels, ColorImageFormat.Bgra); } int stride = width * format.BitsPerPixel / 8; return BitmapSource.Create(width, height, 96, 96, format, null, pixels, stride); } public static ImageSource ToBitmap(this DepthFrame frame) { int width = frame.FrameDescription.Width; int height = frame.FrameDescription.Height; PixelFormat format = PixelFormats.Bgr32; ushort minDepth = frame.DepthMinReliableDistance; ushort maxDepth = frame.DepthMaxReliableDistance; ushort[] pixelData = new ushort[width * height]; byte[] pixels = new byte[width * height * (format.BitsPerPixel + 7) / 8]; frame.CopyFrameDataToArray(pixelData); int colorIndex = 0; for (int depthIndex = 0; depthIndex < pixelData.Length; ++depthIndex) { ushort depth = pixelData[depthIndex]; byte intensity = (byte)(depth >= minDepth && depth <= maxDepth ? depth : 0); pixels[colorIndex++] = intensity; // Blue pixels[colorIndex++] = intensity; // Green pixels[colorIndex++] = intensity; // Red ++colorIndex; } int stride = width * format.BitsPerPixel / 8; return BitmapSource.Create(width, height, 96, 96, format, null, pixels, stride); } public static ImageSource ToBitmap(this InfraredFrame frame) { int width = frame.FrameDescription.Width; int height = frame.FrameDescription.Height; PixelFormat format = PixelFormats.Bgr32; ushort[] frameData = new ushort[width * height]; byte[] pixels = new byte[width * height * (format.BitsPerPixel + 7) / 8]; frame.CopyFrameDataToArray(frameData); int colorIndex = 0; for (int infraredIndex = 0; infraredIndex < frameData.Length; infraredIndex++) { ushort ir = frameData[infraredIndex]; byte intensity = (byte)(ir >> 7); pixels[colorIndex++] = (byte)(intensity / 1); // Blue pixels[colorIndex++] = (byte)(intensity / 1); // Green pixels[colorIndex++] = (byte)(intensity / 0.4); // Red colorIndex++; } int stride = width * format.BitsPerPixel / 8; return BitmapSource.Create(width, height, 96, 96, format, null, pixels, stride); } #endregion #region Body public static Joint ScaleTo(this Joint joint, double width, double height, float skeletonMaxX, float skeletonMaxY) { joint.Position = new CameraSpacePoint { X = Scale(width, skeletonMaxX, joint.Position.X), Y = Scale(height, skeletonMaxY, -joint.Position.Y), Z = joint.Position.Z }; return joint; } public static Joint ScaleTo(this Joint joint, double width, double height) { return ScaleTo(joint, width, height, 1.0f, 1.0f); } private static float Scale(double maxPixel, double maxSkeleton, float position) { float value = (float)((((maxPixel / maxSkeleton) / 2) * position) + (maxPixel / 2)); if (value > maxPixel) { return (float)maxPixel; } if (value < 0) { return 0; } return value; } #endregion #region Drawing public static void DrawSkeleton(this Canvas canvas, Body body) { if (body == null) return; foreach (Joint joint in body.Joints.Values) { canvas.DrawPoint(joint); } canvas.DrawLine(body.Joints[JointType.Head], body.Joints[JointType.Neck]); canvas.DrawLine(body.Joints[JointType.Neck], body.Joints[JointType.SpineShoulder]); canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.ShoulderLeft]); canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.ShoulderRight]); canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.SpineMid]); canvas.DrawLine(body.Joints[JointType.ShoulderLeft], body.Joints[JointType.ElbowLeft]); canvas.DrawLine(body.Joints[JointType.ShoulderRight], body.Joints[JointType.ElbowRight]); canvas.DrawLine(body.Joints[JointType.ElbowLeft], body.Joints[JointType.WristLeft]); canvas.DrawLine(body.Joints[JointType.ElbowRight], body.Joints[JointType.WristRight]); canvas.DrawLine(body.Joints[JointType.WristLeft], body.Joints[JointType.HandLeft]); canvas.DrawLine(body.Joints[JointType.WristRight], body.Joints[JointType.HandRight]); canvas.DrawLine(body.Joints[JointType.HandLeft], body.Joints[JointType.HandTipLeft]); canvas.DrawLine(body.Joints[JointType.HandRight], body.Joints[JointType.HandTipRight]); canvas.DrawLine(body.Joints[JointType.HandTipLeft], body.Joints[JointType.ThumbLeft]); canvas.DrawLine(body.Joints[JointType.HandTipRight], body.Joints[JointType.ThumbRight]); canvas.DrawLine(body.Joints[JointType.SpineMid], body.Joints[JointType.SpineBase]); canvas.DrawLine(body.Joints[JointType.SpineBase], body.Joints[JointType.HipLeft]); canvas.DrawLine(body.Joints[JointType.SpineBase], body.Joints[JointType.HipRight]); canvas.DrawLine(body.Joints[JointType.HipLeft], body.Joints[JointType.KneeLeft]); canvas.DrawLine(body.Joints[JointType.HipRight], body.Joints[JointType.KneeRight]); canvas.DrawLine(body.Joints[JointType.KneeLeft], body.Joints[JointType.AnkleLeft]); canvas.DrawLine(body.Joints[JointType.KneeRight], body.Joints[JointType.AnkleRight]); canvas.DrawLine(body.Joints[JointType.AnkleLeft], body.Joints[JointType.FootLeft]); canvas.DrawLine(body.Joints[JointType.AnkleRight], body.Joints[JointType.FootRight]); } public static void DrawPoint(this Canvas canvas, Joint joint) { if (joint.TrackingState == TrackingState.NotTracked) return; joint = joint.ScaleTo(canvas.ActualWidth, canvas.ActualHeight); Ellipse ellipse = new Ellipse { Width = 20, Height = 20, Fill = new SolidColorBrush(Colors.LightBlue) }; Canvas.SetLeft(ellipse, joint.Position.X - ellipse.Width / 2); Canvas.SetTop(ellipse, joint.Position.Y - ellipse.Height / 2); canvas.Children.Add(ellipse); } public static void DrawLine(this Canvas canvas, Joint first, Joint second) { if (first.TrackingState == TrackingState.NotTracked || second.TrackingState == TrackingState.NotTracked) return; first = first.ScaleTo(canvas.ActualWidth, canvas.ActualHeight); second = second.ScaleTo(canvas.ActualWidth, canvas.ActualHeight); Line line = new Line { X1 = first.Position.X, Y1 = first.Position.Y, X2 = second.Position.X, Y2 = second.Position.Y, StrokeThickness = 8, Stroke = new SolidColorBrush(Colors.LightBlue) }; canvas.Children.Add(line); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using Orleans.CodeGeneration; using Orleans.Runtime; namespace Orleans.Serialization { /// <summary> /// Writer for Orleans binary token streams /// </summary> public class BinaryTokenStreamWriter { private readonly ByteArrayBuilder ab; private static readonly Dictionary<RuntimeTypeHandle, SerializationTokenType> typeTokens; private static readonly Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>> writers; static BinaryTokenStreamWriter() { typeTokens = new Dictionary<RuntimeTypeHandle, SerializationTokenType>(); typeTokens[typeof(bool).TypeHandle] = SerializationTokenType.Boolean; typeTokens[typeof(int).TypeHandle] = SerializationTokenType.Int; typeTokens[typeof(uint).TypeHandle] = SerializationTokenType.Uint; typeTokens[typeof(short).TypeHandle] = SerializationTokenType.Short; typeTokens[typeof(ushort).TypeHandle] = SerializationTokenType.Ushort; typeTokens[typeof(long).TypeHandle] = SerializationTokenType.Long; typeTokens[typeof(ulong).TypeHandle] = SerializationTokenType.Ulong; typeTokens[typeof(byte).TypeHandle] = SerializationTokenType.Byte; typeTokens[typeof(sbyte).TypeHandle] = SerializationTokenType.Sbyte; typeTokens[typeof(float).TypeHandle] = SerializationTokenType.Float; typeTokens[typeof(double).TypeHandle] = SerializationTokenType.Double; typeTokens[typeof(decimal).TypeHandle] = SerializationTokenType.Decimal; typeTokens[typeof(string).TypeHandle] = SerializationTokenType.String; typeTokens[typeof(char).TypeHandle] = SerializationTokenType.Character; typeTokens[typeof(Guid).TypeHandle] = SerializationTokenType.Guid; typeTokens[typeof(DateTime).TypeHandle] = SerializationTokenType.Date; typeTokens[typeof(TimeSpan).TypeHandle] = SerializationTokenType.TimeSpan; typeTokens[typeof(GrainId).TypeHandle] = SerializationTokenType.GrainId; typeTokens[typeof(ActivationId).TypeHandle] = SerializationTokenType.ActivationId; typeTokens[typeof(SiloAddress).TypeHandle] = SerializationTokenType.SiloAddress; typeTokens[typeof(ActivationAddress).TypeHandle] = SerializationTokenType.ActivationAddress; typeTokens[typeof(IPAddress).TypeHandle] = SerializationTokenType.IpAddress; typeTokens[typeof(IPEndPoint).TypeHandle] = SerializationTokenType.IpEndPoint; typeTokens[typeof(CorrelationId).TypeHandle] = SerializationTokenType.CorrelationId; typeTokens[typeof(InvokeMethodRequest).TypeHandle] = SerializationTokenType.Request; typeTokens[typeof(Response).TypeHandle] = SerializationTokenType.Response; typeTokens[typeof(Dictionary<string, object>).TypeHandle] = SerializationTokenType.StringObjDict; typeTokens[typeof(Object).TypeHandle] = SerializationTokenType.Object; typeTokens[typeof(List<>).TypeHandle] = SerializationTokenType.List; typeTokens[typeof(SortedList<,>).TypeHandle] = SerializationTokenType.SortedList; typeTokens[typeof(Dictionary<,>).TypeHandle] = SerializationTokenType.Dictionary; typeTokens[typeof(HashSet<>).TypeHandle] = SerializationTokenType.Set; typeTokens[typeof(SortedSet<>).TypeHandle] = SerializationTokenType.SortedSet; typeTokens[typeof(KeyValuePair<,>).TypeHandle] = SerializationTokenType.KeyValuePair; typeTokens[typeof(LinkedList<>).TypeHandle] = SerializationTokenType.LinkedList; typeTokens[typeof(Stack<>).TypeHandle] = SerializationTokenType.Stack; typeTokens[typeof(Queue<>).TypeHandle] = SerializationTokenType.Queue; typeTokens[typeof(Tuple<>).TypeHandle] = SerializationTokenType.Tuple + 1; typeTokens[typeof(Tuple<,>).TypeHandle] = SerializationTokenType.Tuple + 2; typeTokens[typeof(Tuple<,,>).TypeHandle] = SerializationTokenType.Tuple + 3; typeTokens[typeof(Tuple<,,,>).TypeHandle] = SerializationTokenType.Tuple + 4; typeTokens[typeof(Tuple<,,,,>).TypeHandle] = SerializationTokenType.Tuple + 5; typeTokens[typeof(Tuple<,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 6; typeTokens[typeof(Tuple<,,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 7; writers = new Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>>(); writers[typeof(bool).TypeHandle] = (stream, obj) => stream.Write((bool) obj); writers[typeof(int).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Int); stream.Write((int) obj); }; writers[typeof(uint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Uint); stream.Write((uint) obj); }; writers[typeof(short).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Short); stream.Write((short) obj); }; writers[typeof(ushort).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ushort); stream.Write((ushort) obj); }; writers[typeof(long).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Long); stream.Write((long) obj); }; writers[typeof(ulong).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ulong); stream.Write((ulong) obj); }; writers[typeof(byte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Byte); stream.Write((byte) obj); }; writers[typeof(sbyte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Sbyte); stream.Write((sbyte) obj); }; writers[typeof(float).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Float); stream.Write((float) obj); }; writers[typeof(double).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Double); stream.Write((double) obj); }; writers[typeof(decimal).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Decimal); stream.Write((decimal)obj); }; writers[typeof(string).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.String); stream.Write((string)obj); }; writers[typeof(char).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Character); stream.Write((char) obj); }; writers[typeof(Guid).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Guid); stream.Write((Guid) obj); }; writers[typeof(DateTime).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Date); stream.Write((DateTime) obj); }; writers[typeof(TimeSpan).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.TimeSpan); stream.Write((TimeSpan) obj); }; writers[typeof(GrainId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.GrainId); stream.Write((GrainId) obj); }; writers[typeof(ActivationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationId); stream.Write((ActivationId) obj); }; writers[typeof(SiloAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.SiloAddress); stream.Write((SiloAddress) obj); }; writers[typeof(ActivationAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationAddress); stream.Write((ActivationAddress) obj); }; writers[typeof(IPAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpAddress); stream.Write((IPAddress) obj); }; writers[typeof(IPEndPoint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpEndPoint); stream.Write((IPEndPoint) obj); }; writers[typeof(CorrelationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.CorrelationId); stream.Write((CorrelationId) obj); }; } /// <summary> Default constructor. </summary> public BinaryTokenStreamWriter() { ab = new ByteArrayBuilder(); Trace("Starting new binary token stream"); } /// <summary> Return the output stream as a set of <c>ArraySegment</c>. </summary> /// <returns>Data from this stream, converted to output type.</returns> public IList<ArraySegment<byte>> ToBytes() { return ab.ToBytes(); } /// <summary> Return the output stream as a <c>byte[]</c>. </summary> /// <returns>Data from this stream, converted to output type.</returns> public byte[] ToByteArray() { return ab.ToByteArray(); } /// <summary> Release any serialization buffers being used by this stream. </summary> public void ReleaseBuffers() { ab.ReleaseBuffers(); } /// <summary> Current write position in the stream. </summary> public int CurrentOffset { get { return ab.Length; } } // Numbers /// <summary> Write an <c>Int32</c> value to the stream. </summary> public void Write(int i) { Trace("--Wrote integer {0}", i); ab.Append(i); } /// <summary> Write an <c>Int16</c> value to the stream. </summary> public void Write(short s) { Trace("--Wrote short {0}", s); ab.Append(s); } /// <summary> Write an <c>Int64</c> value to the stream. </summary> public void Write(long l) { Trace("--Wrote long {0}", l); ab.Append(l); } /// <summary> Write a <c>sbyte</c> value to the stream. </summary> public void Write(sbyte b) { Trace("--Wrote sbyte {0}", b); ab.Append(b); } /// <summary> Write a <c>UInt32</c> value to the stream. </summary> public void Write(uint u) { Trace("--Wrote uint {0}", u); ab.Append(u); } /// <summary> Write a <c>UInt16</c> value to the stream. </summary> public void Write(ushort u) { Trace("--Wrote ushort {0}", u); ab.Append(u); } /// <summary> Write a <c>UInt64</c> value to the stream. </summary> public void Write(ulong u) { Trace("--Wrote ulong {0}", u); ab.Append(u); } /// <summary> Write a <c>byte</c> value to the stream. </summary> public void Write(byte b) { Trace("--Wrote byte {0}", b); ab.Append(b); } /// <summary> Write a <c>float</c> value to the stream. </summary> public void Write(float f) { Trace("--Wrote float {0}", f); ab.Append(f); } /// <summary> Write a <c>double</c> value to the stream. </summary> public void Write(double d) { Trace("--Wrote double {0}", d); ab.Append(d); } /// <summary> Write a <c>decimal</c> value to the stream. </summary> public void Write(decimal d) { Trace("--Wrote decimal {0}", d); ab.Append(Decimal.GetBits(d)); } // Text /// <summary> Write a <c>string</c> value to the stream. </summary> public void Write(string s) { Trace("--Wrote string '{0}'", s); if (null == s) { ab.Append(-1); } else { var bytes = Encoding.UTF8.GetBytes(s); ab.Append(bytes.Length); ab.Append(bytes); } } /// <summary> Write a <c>char</c> value to the stream. </summary> public void Write(char c) { Trace("--Wrote char {0}", c); ab.Append(Convert.ToInt16(c)); } // Other primitives /// <summary> Write a <c>bool</c> value to the stream. </summary> public void Write(bool b) { Trace("--Wrote Boolean {0}", b); ab.Append((byte)(b ? SerializationTokenType.True : SerializationTokenType.False)); } /// <summary> Write a <c>null</c> value to the stream. </summary> public void WriteNull() { Trace("--Wrote null"); ab.Append((byte)SerializationTokenType.Null); } internal void Write(SerializationTokenType t) { Trace("--Wrote token {0}", t); ab.Append((byte)t); } // Types /// <summary> Write a type header for the specified Type to the stream. </summary> /// <param name="t">Type to write header for.</param> /// <param name="expected">Currently expected Type for this stream.</param> public void WriteTypeHeader(Type t, Type expected = null) { Trace("-Writing type header for type {0}, expected {1}", t, expected); if (t == expected) { ab.Append((byte)SerializationTokenType.ExpectedType); return; } ab.Append((byte) SerializationTokenType.SpecifiedType); if (t.IsArray) { ab.Append((byte)(SerializationTokenType.Array + (byte)t.GetArrayRank())); WriteTypeHeader(t.GetElementType()); return; } SerializationTokenType token; if (typeTokens.TryGetValue(t.TypeHandle, out token)) { ab.Append((byte) token); return; } if (t.GetTypeInfo().IsGenericType) { if (typeTokens.TryGetValue(t.GetGenericTypeDefinition().TypeHandle, out token)) { ab.Append((byte)token); foreach (var tp in t.GetGenericArguments()) { WriteTypeHeader(tp); } return; } } ab.Append((byte)SerializationTokenType.NamedType); var typeKey = t.OrleansTypeKey(); ab.Append(typeKey.Length); ab.Append(typeKey); } // Primitive arrays /// <summary> Write a <c>byte[]</c> value to the stream. </summary> public void Write(byte[] b) { Trace("--Wrote byte array of length {0}", b.Length); ab.Append(b); } /// <summary> Write the specified number of bytes to the stream, starting at the specified offset in the input <c>byte[]</c>. </summary> /// <param name="b">The input data to be written.</param> /// <param name="offset">The offset into the inout byte[] to start writing bytes from.</param> /// <param name="count">The number of bytes to be written.</param> public void Write(byte[] b, int offset, int count) { if (count <= 0) { return; } Trace("--Wrote byte array of length {0}", count); if ((offset == 0) && (count == b.Length)) { Write(b); } else { var temp = new byte[count]; Buffer.BlockCopy(b, offset, temp, 0, count); Write(temp); } } /// <summary> Write a <c>Int16[]</c> value to the stream. </summary> public void Write(short[] i) { Trace("--Wrote short array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>Int32[]</c> value to the stream. </summary> public void Write(int[] i) { Trace("--Wrote short array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>Int64[]</c> value to the stream. </summary> public void Write(long[] l) { Trace("--Wrote long array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>UInt16[]</c> value to the stream. </summary> public void Write(ushort[] i) { Trace("--Wrote ushort array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>UInt32[]</c> value to the stream. </summary> public void Write(uint[] i) { Trace("--Wrote uint array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>UInt64[]</c> value to the stream. </summary> public void Write(ulong[] l) { Trace("--Wrote ulong array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>sbyte[]</c> value to the stream. </summary> public void Write(sbyte[] l) { Trace("--Wrote sbyte array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>char[]</c> value to the stream. </summary> public void Write(char[] l) { Trace("--Wrote char array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>bool[]</c> value to the stream. </summary> public void Write(bool[] l) { Trace("--Wrote bool array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>double[]</c> value to the stream. </summary> public void Write(double[] d) { Trace("--Wrote double array of length {0}", d.Length); ab.Append(d); } /// <summary> Write a <c>float[]</c> value to the stream. </summary> public void Write(float[] f) { Trace("--Wrote float array of length {0}", f.Length); ab.Append(f); } // Other simple types /// <summary> Write a <c>CorrelationId</c> value to the stream. </summary> internal void Write(CorrelationId id) { Write(id.ToByteArray()); } /// <summary> Write a <c>IPEndPoint</c> value to the stream. </summary> public void Write(IPEndPoint ep) { Write(ep.Address); Write(ep.Port); } /// <summary> Write a <c>IPAddress</c> value to the stream. </summary> public void Write(IPAddress ip) { if (ip.AddressFamily == AddressFamily.InterNetwork) { for (var i = 0; i < 12; i++) { Write((byte)0); } Write(ip.GetAddressBytes()); // IPv4 -- 4 bytes } else { Write(ip.GetAddressBytes()); // IPv6 -- 16 bytes } } /// <summary> Write a <c>ActivationAddress</c> value to the stream. </summary> internal void Write(ActivationAddress addr) { Write(addr.Silo ?? SiloAddress.Zero); // GrainId must not be null Write(addr.Grain); Write(addr.Activation ?? ActivationId.Zero); Write((byte) addr.Status); } /// <summary> Write a <c>SiloAddress</c> value to the stream. </summary> public void Write(SiloAddress addr) { Write(addr.Endpoint); Write(addr.Generation); } internal void Write(UniqueKey key) { Write(key.N0); Write(key.N1); Write(key.TypeCodeData); Write(key.KeyExt); } /// <summary> Write a <c>ActivationId</c> value to the stream. </summary> internal void Write(ActivationId id) { Write(id.Key); } /// <summary> Write a <c>GrainId</c> value to the stream. </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] internal void Write(GrainId id) { Write(id.Key); } /// <summary> Write a <c>TimeSpan</c> value to the stream. </summary> public void Write(TimeSpan ts) { Write(ts.Ticks); } /// <summary> Write a <c>DataTime</c> value to the stream. </summary> public void Write(DateTime dt) { Write(dt.ToBinary()); } /// <summary> Write a <c>Guid</c> value to the stream. </summary> public void Write(Guid id) { Write(id.ToByteArray()); } /// <summary> /// Try to write a simple type (non-array) value to the stream. /// </summary> /// <param name="obj">Input object to be written to the output stream.</param> /// <returns>Returns <c>true</c> if the value was successfully written to the output stream.</returns> public bool TryWriteSimpleObject(object obj) { if (obj == null) { WriteNull(); return true; } Action<BinaryTokenStreamWriter, object> writer; if (writers.TryGetValue(obj.GetType().TypeHandle, out writer)) { writer(this, obj); return true; } return false; } // General containers /// <summary> /// Write header for an <c>Array</c> to the output stream. /// </summary> /// <param name="a">Data object for which header should be written.</param> /// <param name="expected">The most recent Expected Type currently active for this stream.</param> internal void WriteArrayHeader(Array a, Type expected = null) { WriteTypeHeader(a.GetType(), expected); for (var i = 0; i < a.Rank; i++) { ab.Append(a.GetLength(i)); } } // Back-references internal void WriteReference(int offset) { Trace("Writing a reference to the object at offset {0}", offset); ab.Append((byte) SerializationTokenType.Reference); ab.Append(offset); } private StreamWriter trace; [Conditional("TRACE_SERIALIZATION")] private void Trace(string format, params object[] args) { if (trace == null) { var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks); Console.WriteLine("Opening trace file at '{0}'", path); trace = File.CreateText(path); } trace.Write(format, args); trace.WriteLine(" at offset {0}", CurrentOffset); trace.Flush(); } } }
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 VwAspnetRole class. /// </summary> [Serializable] public partial class VwAspnetRoleCollection : ReadOnlyList<VwAspnetRole, VwAspnetRoleCollection> { public VwAspnetRoleCollection() {} } /// <summary> /// This is Read-only wrapper class for the vw_aspnet_Roles view. /// </summary> [Serializable] public partial class VwAspnetRole : ReadOnlyRecord<VwAspnetRole>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor 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("vw_aspnet_Roles", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarApplicationId = new TableSchema.TableColumn(schema); colvarApplicationId.ColumnName = "ApplicationId"; colvarApplicationId.DataType = DbType.Guid; colvarApplicationId.MaxLength = 0; colvarApplicationId.AutoIncrement = false; colvarApplicationId.IsNullable = false; colvarApplicationId.IsPrimaryKey = false; colvarApplicationId.IsForeignKey = false; colvarApplicationId.IsReadOnly = false; schema.Columns.Add(colvarApplicationId); TableSchema.TableColumn colvarRoleId = new TableSchema.TableColumn(schema); colvarRoleId.ColumnName = "RoleId"; colvarRoleId.DataType = DbType.Guid; colvarRoleId.MaxLength = 0; colvarRoleId.AutoIncrement = false; colvarRoleId.IsNullable = false; colvarRoleId.IsPrimaryKey = false; colvarRoleId.IsForeignKey = false; colvarRoleId.IsReadOnly = false; schema.Columns.Add(colvarRoleId); TableSchema.TableColumn colvarRoleName = new TableSchema.TableColumn(schema); colvarRoleName.ColumnName = "RoleName"; colvarRoleName.DataType = DbType.String; colvarRoleName.MaxLength = 256; colvarRoleName.AutoIncrement = false; colvarRoleName.IsNullable = false; colvarRoleName.IsPrimaryKey = false; colvarRoleName.IsForeignKey = false; colvarRoleName.IsReadOnly = false; schema.Columns.Add(colvarRoleName); TableSchema.TableColumn colvarLoweredRoleName = new TableSchema.TableColumn(schema); colvarLoweredRoleName.ColumnName = "LoweredRoleName"; colvarLoweredRoleName.DataType = DbType.String; colvarLoweredRoleName.MaxLength = 256; colvarLoweredRoleName.AutoIncrement = false; colvarLoweredRoleName.IsNullable = false; colvarLoweredRoleName.IsPrimaryKey = false; colvarLoweredRoleName.IsForeignKey = false; colvarLoweredRoleName.IsReadOnly = false; schema.Columns.Add(colvarLoweredRoleName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.String; colvarDescription.MaxLength = 256; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; schema.Columns.Add(colvarDescription); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("vw_aspnet_Roles",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VwAspnetRole() { SetSQLProps(); SetDefaults(); MarkNew(); } public VwAspnetRole(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VwAspnetRole(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VwAspnetRole(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("ApplicationId")] [Bindable(true)] public Guid ApplicationId { get { return GetColumnValue<Guid>("ApplicationId"); } set { SetColumnValue("ApplicationId", value); } } [XmlAttribute("RoleId")] [Bindable(true)] public Guid RoleId { get { return GetColumnValue<Guid>("RoleId"); } set { SetColumnValue("RoleId", value); } } [XmlAttribute("RoleName")] [Bindable(true)] public string RoleName { get { return GetColumnValue<string>("RoleName"); } set { SetColumnValue("RoleName", value); } } [XmlAttribute("LoweredRoleName")] [Bindable(true)] public string LoweredRoleName { get { return GetColumnValue<string>("LoweredRoleName"); } set { SetColumnValue("LoweredRoleName", value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>("Description"); } set { SetColumnValue("Description", value); } } #endregion #region Columns Struct public struct Columns { public static string ApplicationId = @"ApplicationId"; public static string RoleId = @"RoleId"; public static string RoleName = @"RoleName"; public static string LoweredRoleName = @"LoweredRoleName"; public static string Description = @"Description"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections.Generic; using Lucene.Net.Index; using Lucene.Net.Queries; using Lucene.Net.Queries.Function; using Lucene.Net.Search; using Lucene.Net.Tests.Queries.Function; using NUnit.Framework; namespace Lucene.Net.Tests.Queries { /// <summary> /// Test CustomScoreQuery search. /// </summary> public class TestCustomScoreQuery : FunctionTestSetup { [SetUp] public override void SetUp() { base.SetUp(); CreateIndex(true); } /// <summary> /// Test that CustomScoreQuery of Type.BYTE returns the expected scores. /// </summary> [Test] public virtual void TestCustomScoreByte() { // INT field values are small enough to be parsed as byte DoTestCustomScore(BYTE_VALUESOURCE, 1.0); DoTestCustomScore(BYTE_VALUESOURCE, 2.0); } /// <summary> /// Test that CustomScoreQuery of Type.SHORT returns the expected scores. /// </summary> [Test] public virtual void TestCustomScoreShort() { // INT field values are small enough to be parsed as short DoTestCustomScore(SHORT_VALUESOURCE, 1.0); DoTestCustomScore(SHORT_VALUESOURCE, 3.0); } /// <summary> /// Test that CustomScoreQuery of Type.INT returns the expected scores. /// </summary> [Test] public virtual void TestCustomScoreInt() { DoTestCustomScore(INT_VALUESOURCE, 1.0); DoTestCustomScore(INT_VALUESOURCE, 4.0); } /// <summary> /// Test that CustomScoreQuery of Type.FLOAT returns the expected scores. /// </summary> [Test] public virtual void TestCustomScoreFloat() { // INT field can be parsed as float DoTestCustomScore(INT_AS_FLOAT_VALUESOURCE, 1.0); DoTestCustomScore(INT_AS_FLOAT_VALUESOURCE, 5.0); // same values, but in float format DoTestCustomScore(FLOAT_VALUESOURCE, 1.0); DoTestCustomScore(FLOAT_VALUESOURCE, 6.0); } // must have static class otherwise serialization tests fail private class CustomAddQuery : CustomScoreQuery { // constructor internal CustomAddQuery(Query q, FunctionQuery qValSrc) : base(q, qValSrc) { } public override string Name => "customAdd"; protected override CustomScoreProvider GetCustomScoreProvider(AtomicReaderContext context) { return new CustomScoreProviderAnonymousInnerClassHelper(this, context); } private class CustomScoreProviderAnonymousInnerClassHelper : CustomScoreProvider { private readonly CustomAddQuery outerInstance; public CustomScoreProviderAnonymousInnerClassHelper(CustomAddQuery outerInstance, AtomicReaderContext context) : base(context) { this.outerInstance = outerInstance; } public override float CustomScore(int doc, float subQueryScore, float valSrcScore) { return subQueryScore + valSrcScore; } public override Explanation CustomExplain(int doc, Explanation subQueryExpl, Explanation valSrcExpl) { float valSrcScore = valSrcExpl == null ? 0 : valSrcExpl.Value; Explanation exp = new Explanation(valSrcScore + subQueryExpl.Value, "custom score: sum of:"); exp.AddDetail(subQueryExpl); if (valSrcExpl != null) { exp.AddDetail(valSrcExpl); } return exp; } } } // must have static class otherwise serialization tests fail private class CustomMulAddQuery : CustomScoreQuery { // constructor internal CustomMulAddQuery(Query q, FunctionQuery qValSrc1, FunctionQuery qValSrc2) : base(q, qValSrc1, qValSrc2) { } public override string Name => "customMulAdd"; protected override CustomScoreProvider GetCustomScoreProvider(AtomicReaderContext context) { return new CustomScoreProviderAnonymousInnerClassHelper(this, context); } private class CustomScoreProviderAnonymousInnerClassHelper : CustomScoreProvider { private readonly CustomMulAddQuery outerInstance; public CustomScoreProviderAnonymousInnerClassHelper(CustomMulAddQuery outerInstance, AtomicReaderContext context) : base(context) { this.outerInstance = outerInstance; } public override float CustomScore(int doc, float subQueryScore, float[] valSrcScores) { if (valSrcScores.Length == 0) { return subQueryScore; } if (valSrcScores.Length == 1) { return subQueryScore + valSrcScores[0]; // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS } return (subQueryScore + valSrcScores[0]) * valSrcScores[1]; // we know there are two } public override Explanation CustomExplain(int doc, Explanation subQueryExpl, Explanation[] valSrcExpls) { if (valSrcExpls.Length == 0) { return subQueryExpl; } Explanation exp = new Explanation(valSrcExpls[0].Value + subQueryExpl.Value, "sum of:"); exp.AddDetail(subQueryExpl); exp.AddDetail(valSrcExpls[0]); if (valSrcExpls.Length == 1) { exp.Description = "CustomMulAdd, sum of:"; return exp; } Explanation exp2 = new Explanation(valSrcExpls[1].Value * exp.Value, "custom score: product of:"); exp2.AddDetail(valSrcExpls[1]); exp2.AddDetail(exp); return exp2; } } } private sealed class CustomExternalQuery : CustomScoreQuery { private readonly TestCustomScoreQuery outerInstance; protected override CustomScoreProvider GetCustomScoreProvider(AtomicReaderContext context) { FieldCache.Int32s values = FieldCache.DEFAULT.GetInt32s(context.AtomicReader, INT_FIELD, false); return new CustomScoreProviderAnonymousInnerClassHelper(this, context, values); } private class CustomScoreProviderAnonymousInnerClassHelper : CustomScoreProvider { private readonly CustomExternalQuery outerInstance; private FieldCache.Int32s values; public CustomScoreProviderAnonymousInnerClassHelper(CustomExternalQuery outerInstance, AtomicReaderContext context, FieldCache.Int32s values) : base(context) { this.outerInstance = outerInstance; this.values = values; } public override float CustomScore(int doc, float subScore, float valSrcScore) { assertTrue(doc <= m_context.AtomicReader.MaxDoc); return values.Get(doc); } } public CustomExternalQuery(TestCustomScoreQuery outerInstance, Query q) : base(q) { this.outerInstance = outerInstance; } } [Test] public virtual void TestCustomExternalQuery() { BooleanQuery q1 = new BooleanQuery(); q1.Add(new TermQuery(new Term(TEXT_FIELD, "first")), Occur.SHOULD); q1.Add(new TermQuery(new Term(TEXT_FIELD, "aid")), Occur.SHOULD); q1.Add(new TermQuery(new Term(TEXT_FIELD, "text")), Occur.SHOULD); Query q = new CustomExternalQuery(this, q1); Log(q); IndexReader r = DirectoryReader.Open(dir); IndexSearcher s = NewSearcher(r); TopDocs hits = s.Search(q, 1000); assertEquals(N_DOCS, hits.TotalHits); for (int i = 0; i < N_DOCS; i++) { int doc = hits.ScoreDocs[i].Doc; float score = hits.ScoreDocs[i].Score; assertEquals("doc=" + doc, (float)1 + (4 * doc) % N_DOCS, score, 0.0001); } r.Dispose(); } [Test] public virtual void TestRewrite() { IndexReader r = DirectoryReader.Open(dir); IndexSearcher s = NewSearcher(r); Query q = new TermQuery(new Term(TEXT_FIELD, "first")); CustomScoreQuery original = new CustomScoreQuery(q); CustomScoreQuery rewritten = (CustomScoreQuery)original.Rewrite(s.IndexReader); assertTrue("rewritten query should be identical, as TermQuery does not rewrite", original == rewritten); assertTrue("no hits for query", s.Search(rewritten, 1).TotalHits > 0); assertEquals(s.Search(q, 1).TotalHits, s.Search(rewritten, 1).TotalHits); q = new TermRangeQuery(TEXT_FIELD, null, null, true, true); // everything original = new CustomScoreQuery(q); rewritten = (CustomScoreQuery)original.Rewrite(s.IndexReader); assertTrue("rewritten query should not be identical, as TermRangeQuery rewrites", original != rewritten); assertTrue("no hits for query", s.Search(rewritten, 1).TotalHits > 0); assertEquals(s.Search(q, 1).TotalHits, s.Search(original, 1).TotalHits); assertEquals(s.Search(q, 1).TotalHits, s.Search(rewritten, 1).TotalHits); r.Dispose(); } private void DoTestCustomScore(ValueSource valueSource, double dboost) { float boost = (float)dboost; FunctionQuery functionQuery = new FunctionQuery(valueSource); IndexReader r = DirectoryReader.Open(dir); IndexSearcher s = NewSearcher(r); // regular (boolean) query. BooleanQuery q1 = new BooleanQuery(); q1.Add(new TermQuery(new Term(TEXT_FIELD, "first")), Occur.SHOULD); q1.Add(new TermQuery(new Term(TEXT_FIELD, "aid")), Occur.SHOULD); q1.Add(new TermQuery(new Term(TEXT_FIELD, "text")), Occur.SHOULD); Log(q1); // custom query, that should score the same as q1. BooleanQuery q2CustomNeutral = new BooleanQuery(true); Query q2CustomNeutralInner = new CustomScoreQuery(q1); q2CustomNeutral.Add(q2CustomNeutralInner, Occur.SHOULD); // a little tricky: we split the boost across an outer BQ and CustomScoreQuery // this ensures boosting is correct across all these functions (see LUCENE-4935) q2CustomNeutral.Boost = (float)Math.Sqrt(dboost); q2CustomNeutralInner.Boost = (float)Math.Sqrt(dboost); Log(q2CustomNeutral); // custom query, that should (by default) multiply the scores of q1 by that of the field CustomScoreQuery q3CustomMul = new CustomScoreQuery(q1, functionQuery); q3CustomMul.IsStrict = true; q3CustomMul.Boost = boost; Log(q3CustomMul); // custom query, that should add the scores of q1 to that of the field CustomScoreQuery q4CustomAdd = new CustomAddQuery(q1, functionQuery); q4CustomAdd.IsStrict = true; q4CustomAdd.Boost = boost; Log(q4CustomAdd); // custom query, that multiplies and adds the field score to that of q1 CustomScoreQuery q5CustomMulAdd = new CustomMulAddQuery(q1, functionQuery, functionQuery); q5CustomMulAdd.IsStrict = true; q5CustomMulAdd.Boost = boost; Log(q5CustomMulAdd); // do al the searches TopDocs td1 = s.Search(q1, null, 1000); TopDocs td2CustomNeutral = s.Search(q2CustomNeutral, null, 1000); TopDocs td3CustomMul = s.Search(q3CustomMul, null, 1000); TopDocs td4CustomAdd = s.Search(q4CustomAdd, null, 1000); TopDocs td5CustomMulAdd = s.Search(q5CustomMulAdd, null, 1000); // put results in map so we can verify the scores although they have changed IDictionary<int, float> h1 = TopDocsToMap(td1); IDictionary<int, float> h2CustomNeutral = TopDocsToMap(td2CustomNeutral); IDictionary<int, float> h3CustomMul = TopDocsToMap(td3CustomMul); IDictionary<int, float> h4CustomAdd = TopDocsToMap(td4CustomAdd); IDictionary<int, float> h5CustomMulAdd = TopDocsToMap(td5CustomMulAdd); VerifyResults(boost, s, h1, h2CustomNeutral, h3CustomMul, h4CustomAdd, h5CustomMulAdd, q1, q2CustomNeutral, q3CustomMul, q4CustomAdd, q5CustomMulAdd); r.Dispose(); } // verify results are as expected. private void VerifyResults(float boost, IndexSearcher s, IDictionary<int, float> h1, IDictionary<int, float> h2customNeutral, IDictionary<int, float> h3CustomMul, IDictionary<int, float> h4CustomAdd, IDictionary<int, float> h5CustomMulAdd, Query q1, Query q2, Query q3, Query q4, Query q5) { // verify numbers of matches Log("#hits = " + h1.Count); assertEquals("queries should have same #hits", h1.Count, h2customNeutral.Count); assertEquals("queries should have same #hits", h1.Count, h3CustomMul.Count); assertEquals("queries should have same #hits", h1.Count, h4CustomAdd.Count); assertEquals("queries should have same #hits", h1.Count, h5CustomMulAdd.Count); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, q1, s, Rarely()); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, q2, s, Rarely()); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, q3, s, Rarely()); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, q4, s, Rarely()); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, q5, s, Rarely()); // verify scores ratios foreach (int doc in h1.Keys) { Log("doc = " + doc); float fieldScore = ExpectedFieldScore(s.IndexReader.Document(doc).Get(ID_FIELD)); Log("fieldScore = " + fieldScore); assertTrue("fieldScore should not be 0", fieldScore > 0); float score1 = h1[doc]; LogResult("score1=", s, q1, doc, score1); float score2 = h2customNeutral[doc]; LogResult("score2=", s, q2, doc, score2); assertEquals("same score (just boosted) for neutral", boost * score1, score2, CheckHits.ExplainToleranceDelta(boost * score1, score2)); float score3 = h3CustomMul[doc]; LogResult("score3=", s, q3, doc, score3); assertEquals("new score for custom mul", boost * fieldScore * score1, score3, CheckHits.ExplainToleranceDelta(boost * fieldScore * score1, score3)); float score4 = h4CustomAdd[doc]; LogResult("score4=", s, q4, doc, score4); assertEquals("new score for custom add", boost * (fieldScore + score1), score4, CheckHits.ExplainToleranceDelta(boost * (fieldScore + score1), score4)); float score5 = h5CustomMulAdd[doc]; LogResult("score5=", s, q5, doc, score5); assertEquals("new score for custom mul add", boost * fieldScore * (score1 + fieldScore), score5, CheckHits.ExplainToleranceDelta(boost * fieldScore * (score1 + fieldScore), score5)); } } private void LogResult(string msg, IndexSearcher s, Query q, int doc, float? score1) { Log(msg + " " + score1); Log("Explain by: " + q); Log(s.Explain(q, doc)); } /// <summary> /// Since custom scoring modified the order of docs, map results /// by doc ids so that we can later compare/verify them. /// </summary> /// <param name="td"></param> /// <returns></returns> private IDictionary<int, float> TopDocsToMap(TopDocs td) { var h = new Dictionary<int, float>(); for (int i = 0; i < td.TotalHits; i++) { h[td.ScoreDocs[i].Doc] = td.ScoreDocs[i].Score; } return h; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Events.Edir.EventData.GeneralDSEventData.cs // // Author: // Anil Bhatia (banil@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System.IO; using System.Text; using Novell.Directory.Ldap.Asn1; namespace Novell.Directory.Ldap.Events.Edir.EventData { /// <summary> /// The class represents the data for General DS Events. /// </summary> public class GeneralDSEventData : BaseEdirEventData { protected int ds_time; public int DSTime { get { return ds_time; } } protected int milli_seconds; public int MilliSeconds { get { return milli_seconds; } } protected int nVerb; public int Verb { get { return nVerb; } } protected int current_process; public int CurrentProcess { get { return current_process; } } protected string strPerpetratorDN; public string PerpetratorDN { get { return strPerpetratorDN; } } protected int[] integer_values; public int[] IntegerValues { get { return integer_values; } } protected string[] string_values; public string[] StringValues { get { return string_values; } } public GeneralDSEventData(EdirEventDataType eventDataType, Asn1Object message) : base(eventDataType, message) { int[] length = new int[1]; ds_time = getTaggedIntValue( (Asn1Tagged) decoder.decode(decodedData, length), GeneralEventField.EVT_TAG_GEN_DSTIME); milli_seconds = getTaggedIntValue( (Asn1Tagged) decoder.decode(decodedData, length), GeneralEventField.EVT_TAG_GEN_MILLISEC); nVerb = getTaggedIntValue( (Asn1Tagged) decoder.decode(decodedData, length), GeneralEventField.EVT_TAG_GEN_VERB); current_process = getTaggedIntValue( (Asn1Tagged) decoder.decode(decodedData, length), GeneralEventField.EVT_TAG_GEN_CURRPROC); strPerpetratorDN = getTaggedStringValue( (Asn1Tagged) decoder.decode(decodedData, length), GeneralEventField.EVT_TAG_GEN_PERP); Asn1Tagged temptaggedvalue = ((Asn1Tagged) decoder.decode(decodedData, length)); if (temptaggedvalue.getIdentifier().Tag == (int) GeneralEventField.EVT_TAG_GEN_INTEGERS) { //Integer List. Asn1Sequence inteseq = getTaggedSequence(temptaggedvalue, GeneralEventField.EVT_TAG_GEN_INTEGERS); Asn1Object[] intobject = inteseq.toArray(); integer_values = new int[intobject.Length]; for (int i = 0; i < intobject.Length; i++) { integer_values[i] = ((Asn1Integer) intobject[i]).intValue(); } //second decoding for Strings. temptaggedvalue = ((Asn1Tagged) decoder.decode(decodedData, length)); } else { integer_values = null; } if ((temptaggedvalue.getIdentifier().Tag == (int) GeneralEventField.EVT_TAG_GEN_STRINGS) && (temptaggedvalue.getIdentifier().Constructed)) { //String values. Asn1Sequence inteseq = getTaggedSequence(temptaggedvalue, GeneralEventField.EVT_TAG_GEN_STRINGS); Asn1Object[] stringobject = inteseq.toArray(); string_values = new string[stringobject.Length]; for (int i = 0; i < stringobject.Length; i++) { string_values[i] = ((Asn1OctetString) stringobject[i]).stringValue(); } } else { string_values = null; } DataInitDone(); } protected int getTaggedIntValue(Asn1Tagged tagvalue, GeneralEventField tagid) { Asn1Object obj = tagvalue.taggedValue(); if ((int)tagid != tagvalue.getIdentifier().Tag) { throw new IOException("Unknown Tagged Data"); } byte[] dbytes = SupportClass.ToByteArray(((Asn1OctetString) obj).byteValue()); MemoryStream data = new MemoryStream(dbytes); LBERDecoder dec = new LBERDecoder(); int length = dbytes.Length; return (int)(dec.decodeNumeric(data, length)); } protected string getTaggedStringValue(Asn1Tagged tagvalue, GeneralEventField tagid) { Asn1Object obj = tagvalue.taggedValue(); if ((int)tagid != tagvalue.getIdentifier().Tag) { throw new IOException("Unknown Tagged Data"); } byte[] dbytes = SupportClass.ToByteArray(((Asn1OctetString) obj).byteValue()); MemoryStream data = new MemoryStream(dbytes); LBERDecoder dec = new LBERDecoder(); int length = dbytes.Length; return (string) dec.decodeCharacterString(data, length); } protected Asn1Sequence getTaggedSequence(Asn1Tagged tagvalue, GeneralEventField tagid) { Asn1Object obj = tagvalue.taggedValue(); if ((int)tagid != tagvalue.getIdentifier().Tag) { throw new IOException("Unknown Tagged Data"); } byte[] dbytes = SupportClass.ToByteArray(((Asn1OctetString) obj).byteValue()); MemoryStream data = new MemoryStream(dbytes); LBERDecoder dec = new LBERDecoder(); int length = dbytes.Length; return new Asn1Sequence(dec, data, length); } /// <summary> /// Returns a string representation of the object. /// </summary> public override string ToString() { StringBuilder buf = new StringBuilder(); buf.Append("[GeneralDSEventData"); buf.AppendFormat("(DSTime={0})", ds_time); buf.AppendFormat("(MilliSeconds={0})", milli_seconds); buf.AppendFormat("(verb={0})",nVerb); buf.AppendFormat("(currentProcess={0})", current_process); buf.AppendFormat("(PerpetartorDN={0})", strPerpetratorDN); buf.AppendFormat("(Integer Values={0})", integer_values); buf.AppendFormat("(String Values={0})", string_values); buf.Append("]"); return buf.ToString(); } } }
using System; using System.Collections.Generic; using System.Device.Location; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; using Windows.Devices.Geolocation; using ASPC2014.Windows.Phone.App.Helpers; using ASPC2014.Windows.Phone.App.Services; using ASPC2014.Windows.Phone.App.Services.Contracts; using Cirrious.CrossCore; using Cirrious.MvvmCross.Plugins.Messenger; using Cirrious.MvvmCross.WindowsPhone.Views; using Microsoft.Phone.Maps.Controls; using PortableClassLibrary.Messages; using PortableClassLibrary.Services; using PortableClassLibrary.Services.Contracts; namespace ASPC2014.Windows.Phone.App.Views { public partial class FirstView : MvxPhonePage { public static string Coordinates { get; private set; } private static Dictionary<int, Point> CoordinatesDictionary { get; set; } public GeoCoordinateCollection GeoCoordinateCollection { get; set; } private static int Counter { get; set; } private string Results { get; set; } public IMvxMessenger MvxMessenger { get; private set; } public IArmaService ArmaService { get; set; } public IAzureCloudService AzureCloudService { get; set; } public IRasPiService RasPiService { get; set; } public FirstView() { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); InitializeComponent(); GetCurrentLocationAndDrawPointAndAddToMap(); //SetLemnosLocationOnMap(); //TODO: Used for Arma 3 Map.Tap += MapTap; ResultTextBox.IsEnabled = false; ArmaCoordinatesTextBox.IsEnabled = false; RasPiResultTextBox.IsEnabled = false; SolveButton.Foreground = new SolidColorBrush(Colors.Gray); CoordinatesDictionary = new Dictionary<int, Point>(); MvxMessenger = Mvx.Resolve<IMvxMessenger>(); GeoCoordinateCollection = new GeoCoordinateCollection(); ArmaService = new ArmaService(); AzureCloudService = new AzureCloudService(); RasPiService = new RasPiService(); } private void MapTap(object sender, GestureEventArgs gestureEventArgs) { ResetTheMapIfGotResults(); var coordinate = GetPointFrom(gestureEventArgs); DrawAndAddToMap(coordinate); if (CoordinatesDictionary.Count >= 2) { SolveButton.Foreground = new SolidColorBrush(Colors.White); } } private async void GetCurrentLocationAndDrawPointAndAddToMap() { var geolocator = new Geolocator(); try { var geoCoordinate = await SetCurrentLocationOnMap(geolocator); //MarkOnMap(geoCoordinate, Colors.Blue); } catch (UnauthorizedAccessException e) { } } private void MarkOnMap(GeoCoordinate geoCoordinate, Color color) { var ellipse = new Ellipse { Fill = new SolidColorBrush(color), Height = 10, Width = 10, Opacity = 50 }; var mapOverlay = new MapOverlay { Content = ellipse, PositionOrigin = new Point(0.5, 0.5), GeoCoordinate = geoCoordinate }; var mapLayer = new MapLayer { mapOverlay }; Map.Layers.Add(mapLayer); } private async Task<GeoCoordinate> SetCurrentLocationOnMap(Geolocator myGeolocator) { var myGeoposition = await myGeolocator.GetGeopositionAsync(); var myGeopositionCoordinate = myGeoposition.Coordinate; var myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate(myGeopositionCoordinate); Map.Center = myGeoCoordinate; Map.ZoomLevel = 15; return myGeoCoordinate; } private GeoCoordinate SetLemnosLocationOnMap() { var lemnosGeoCoordinate = new GeoCoordinate(39.878880, 25.231705); Map.Center = lemnosGeoCoordinate; Map.ZoomLevel = 13; return lemnosGeoCoordinate; } private void SolveButtonClick(object sender, RoutedEventArgs e) { if (CoordinatesDictionary.Count < 2) return; var coordinatesMessage = new CoordinatesMessage(this) { Coordinates = Coordinates }; MvxMessenger.Publish(coordinatesMessage); } private void TextBoxResultsOnTextChanged(object sender, TextChangedEventArgs e) { Results = ((TextBox)sender).Text; var pathList = GetPath(Results); DrawPathAndAddToGeoCoordinateCollectionAndAddToMap(pathList); BeginGetRequestForConvertingLatLongToArmaCoordinates(); BeginGetRequestForFlyingDrone(pathList); } private void BeginGetRequestForConvertingLatLongToArmaCoordinates() { var latLongList = GeoCoordinateCollection.Select(geoCoordinate => geoCoordinate.Latitude + "," + geoCoordinate.Longitude).ToList(); AzureCloudService.BeginGetRequestForConverting(latLongList); } private void BeginGetRequestForFlyingDrone(IEnumerable<string> pathList) { var xyPathList = pathList.Select(point => CoordinatesDictionary[Convert.ToInt32(point, CultureInfo.InvariantCulture)]).Select(point => String.Join(",", point.X, point.Y)).ToList(); RasPiService.BeginGetRequestForFlyingDrone(xyPathList, AzureCloudService.GetFirstViewModel()); } private void TextBoxArmaCoordinatesOnTextChanged(object sender, TextChangedEventArgs e) { var armaCoordinates = ((TextBox)sender).Text.Split('\n'); var armaCommand = BuildArmaCommand(armaCoordinates); ArmaService.StartTcpListenerAndSendCommandToArma(armaCommand); } private void DrawPathAndAddToGeoCoordinateCollectionAndAddToMap(IEnumerable<string> pathList) { var mapPolyline = new MapPolyline(); GeoCoordinateCollection = new GeoCoordinateCollection(); foreach (var point in pathList.Select(point => CoordinatesDictionary[Convert.ToInt32(point, CultureInfo.InvariantCulture)])) { GeoCoordinateCollection.Add(Map.ConvertViewportPointToGeoCoordinate(point)); } mapPolyline.Path = GeoCoordinateCollection; mapPolyline.StrokeColor = Colors.Red; mapPolyline.StrokeThickness = 2; Map.MapElements.Add(mapPolyline); } private Point GetPointFrom(GestureEventArgs e) { var coordinate = e.GetPosition(Map); CoordinatesDictionary.Add(Counter, coordinate); Coordinates += coordinate + " "; Counter++; return coordinate; } private static string BuildArmaCommand(string[] armaCoordinates) { var armaCommand = ""; for (var i = 0; i < armaCoordinates.Length; i++) { armaCommand += "group testuav addWaypoint " + "[[" + armaCoordinates[i] + ",50]," + i + "] setWayPointType \"MOVE\" setWaypointSpeed \"FULL\";"; } return armaCommand; } private void DrawAndAddToMap(Point coordinate) { var geoCoordinate = Map.ConvertViewportPointToGeoCoordinate(coordinate); MarkOnMap(geoCoordinate, Colors.Red); } private IEnumerable<string> GetPath(string results) { var path = results.Split('\n').Last().Replace("(", "").Replace(")", "").Replace("Path: ", ""); var pathList = path.Split(','); return pathList; } private void ResetMap() { RemoveCoordinatesFromMapAndResetStaticFields(); GetCurrentLocationAndDrawPointAndAddToMap(); //SetLemnosLocationOnMap(); //TODO: Used for Arma 3 } private void ResetTheMapIfGotResults() { if (!string.IsNullOrEmpty(Results)) { ResetMap(); } } private void RemoveCoordinatesFromMapAndResetStaticFields() { Results = string.Empty; Coordinates = string.Empty; Counter = 0; SolveButton.Foreground = new SolidColorBrush(Colors.Gray); CoordinatesDictionary.Clear(); Map.Layers.Clear(); Map.MapElements.Clear(); } } }
////////////////////////////////////////////////////////////////////////// // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch // them to disk. // // This software is licensed under the MIT license. See license.txt for // details. // // Copyright (c) The Watcher // Partial Rights Reserved. // ////////////////////////////////////////////////////////////////////////// // This file is part of the RiP Ripper project base. using System; using System.Collections; using System.IO; using System.Net; using System.Threading; namespace Ripper { using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images hosted on DumbARump.com /// </summary> public class DumbARump : ServiceTemplate { public DumbARump(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable) { } protected override bool DoDownload() { var strImgURL = this.ImageLinkURL; if (this.EventTable.ContainsKey(strImgURL)) { return true; } var strFilePath = string.Empty; strFilePath = strImgURL.Substring(strImgURL.IndexOf("?id=") + 4); try { if (!Directory.Exists(this.SavePath)) Directory.CreateDirectory(this.SavePath); } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; return false; } strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath)); var CCObj = new CacheObject(); CCObj.IsDownloaded = false; CCObj.FilePath = strFilePath; CCObj.Url = strImgURL; try { this.EventTable.Add(strImgURL, CCObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (this.EventTable.ContainsKey(strImgURL)) { return false; } else { this.EventTable.Add(strImgURL, CCObj); } } var strIVPage = this.GetImageHostPage(ref strImgURL); if (strIVPage.Length < 10) { return false; } var strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1); var iStartIMG = 0; var iStartSRC = 0; var iEndSRC = 0; iStartIMG = strIVPage.IndexOf("<a href=\"random.php\"><img "); if (iStartIMG < 0) { return false; } iStartSRC = strIVPage.IndexOf("src=\"", iStartIMG); if (iStartSRC < 0) { return false; } iStartSRC += 5; iEndSRC = strIVPage.IndexOf("\" border=\"0\"", iStartSRC); if (iEndSRC < 0) { return false; } strNewURL = strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC); ////////////////////////////////////////////////////////////////////////// HttpWebRequest lHttpWebRequest; HttpWebResponse lHttpWebResponse; Stream lHttpWebResponseStream; // FileStream lFileStream = new FileStream(strFilePath, FileMode.Create); // int bytesRead; try { lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL); lHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"; lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5"); lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate"); lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); lHttpWebRequest.Referer = strImgURL; lHttpWebRequest.Accept = "image/png,*/*;q=0.5"; lHttpWebRequest.KeepAlive = true; lHttpWebResponse = (HttpWebResponse)lHttpWebRequest.GetResponse(); lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream(); if (lHttpWebResponse.ContentType.IndexOf("image") < 0) { // if (lFileStream != null) // lFileStream.Close(); return false; } if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg") strFilePath += ".jpg"; else if (lHttpWebResponse.ContentType.ToLower() == "image/gif") strFilePath += ".gif"; else if (lHttpWebResponse.ContentType.ToLower() == "image/png") strFilePath += ".png"; var NewAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != NewAlteredPath) { strFilePath = NewAlteredPath; ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; } lHttpWebResponseStream.Close(); var client = new WebClient(); client.Headers.Add("Accept-Language: en-us,en;q=0.5"); client.Headers.Add("Accept-Encoding: gzip,deflate"); client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); client.Headers.Add("Referer: " + strImgURL); client.Headers.Add( "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return true; } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return true; } catch (WebException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return false; } ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true; // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath; CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; return true; } ////////////////////////////////////////////////////////////////////////// } }
using Autofac; using Autofac.Core; using Autofac.Integration.WebApi; using AutoMapper; using Common.Logging; using ReMi.Api.Insfrastructure; using ReMi.Api.Insfrastructure.Commands; using ReMi.Api.Insfrastructure.Notifications; using ReMi.Api.Insfrastructure.Notifications.Filters; using ReMi.Api.Insfrastructure.Queries; using ReMi.Api.Insfrastructure.Security; using ReMi.BusinessLogic.Api; using ReMi.CommandHandlers.ExecPoll; using ReMi.Common.Utils; using ReMi.Common.Utils.Repository; using ReMi.Common.WebApi; using ReMi.Common.WebApi.Notifications; using ReMi.Common.WebApi.Tracking; using ReMi.Contracts.Cqrs; using ReMi.Contracts.Cqrs.Commands; using ReMi.Contracts.Cqrs.Events; using ReMi.Contracts.Cqrs.Queries; using ReMi.DataAccess; using ReMi.DataAccess.Helpers; using ReMi.EventHandlers; using ReMi.Plugin.Common.PluginsConfiguration; using ReMi.Plugin.Composites.Services; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Hosting; using System.Web.Http; using System.Web.Http.Dependencies; namespace ReMi.Api { public static class DependencyResolverConfig { private const string RemiKey = "C5BC8B6B-28F0-4444-A04F-D86D11EAB9D8"; private static readonly ILog Logger = LogManager.GetCurrentClassLogger(); public static void Configure(HttpConfiguration configuration) { configuration.DependencyResolver = new AutofacWebApiDependencyResolver(RegisterDependencies(new ContainerBuilder(), configuration)); } private static IContainer RegisterDependencies(ContainerBuilder builder, HttpConfiguration configuration) { // Register the Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()) .PropertiesAutowired() .InstancePerDependency(); // Register other dependencies. var assemblies = RemiAssembliesHelper.GetReMiAssemblies(); RegisterCqrs(builder, assemblies); RegisterBusinessLogic(builder, assemblies); RegisterDataAccess(builder, assemblies); RegisterMappingEngine(builder, assemblies); RegisterEvents(builder, assemblies); RegisterNotifications(builder, assemblies); RegisterOther(builder); RegisterPlugins(builder); builder.RegisterWebApiFilterProvider(configuration); const string containerKey = "Container"; var tempDic = new Dictionary<string, IContainer> { { containerKey, null } }; builder.Register(x => tempDic[containerKey]).As<IContainer>().SingleInstance(); tempDic[containerKey] = builder.Build(); return tempDic[containerKey]; } private static void RegisterCqrs(ContainerBuilder builder, Assembly[] assemblies) { builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof(IValidateRequest<>)) .InstancePerDependency() .PropertiesAutowired(); builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof(IHandleQuery<,>)) .InstancePerDependency().PropertiesAutowired(); builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof(IHandleCommand<>)) .InstancePerDependency().PropertiesAutowired(); builder.RegisterGeneric(typeof(QueryActionImplementation<,>)) .As(typeof(IImplementQueryAction<,>)) .PropertiesAutowired() .InstancePerDependency(); builder.RegisterGeneric(typeof(CommandProcessorGeneric<>)) .As(typeof(ICommandProcessorGeneric<>)) .PropertiesAutowired() .InstancePerDependency(); builder.RegisterType(typeof(CommandTrackerHandler)) .As(typeof(ICommandTracker)) .InstancePerDependency(); builder.RegisterType(typeof(CommandProcessor)) .As(typeof(ICommandProcessor)) .InstancePerLifetimeScope() .PropertiesAutowired(); builder.Register(c => new CommandDispatcher()) .As(typeof(ICommandDispatcher)) .SingleInstance() .PropertiesAutowired(); builder.RegisterAssemblyTypes(assemblies) .As(typeof(ICommand)) .InstancePerLifetimeScope(); builder.RegisterType(typeof(AuthorizationManager)) .As(typeof(IAuthorizationManager)) .PropertiesAutowired() .InstancePerLifetimeScope(); builder.RegisterType(typeof(PrincipalSetter)) .As(typeof(IPrincipalSetter)) .InstancePerLifetimeScope(); builder.RegisterType(typeof(PermissionChecker)) .As(typeof(IPermissionChecker)) .InstancePerLifetimeScope() .PropertiesAutowired(); } private static void RegisterEvents(ContainerBuilder builder, Assembly[] assemblies) { builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof(IHandleEvent<>)) .InstancePerDependency() .PropertiesAutowired(); builder.Register(c => new EventPublisher(c.Resolve<IDependencyResolver>())) .As<IPublishEvent>() .SingleInstance() .PropertiesAutowired(); builder.RegisterType(typeof(EventTrackerHandler)) .As(typeof(IEventTracker)) .InstancePerDependency(); } private static void RegisterBusinessLogic(ContainerBuilder builder, Assembly[] assemblies) { builder.RegisterAssemblyTypes(assemblies) .Where(t => !string.IsNullOrWhiteSpace(t.Namespace) && t.Namespace.StartsWith("ReMi.BusinessLogic")) .AsImplementedInterfaces() .InstancePerDependency() .PropertiesAutowired(); builder.Register<IApiDescriptionBuilder>( c => new ApiDescriptionBuilder( assemblies.SelectMany(a => a.GetTypes().Where(t => typeof(ApiController).IsAssignableFrom(t)).Select(x => x)), assemblies.SelectMany(a => a.GetTypes().Where(t => typeof(ICommand).IsAssignableFrom(t) && t.IsClass).Select(x => x)) )) .PropertiesAutowired() .InstancePerDependency(); } private static void RegisterDataAccess(ContainerBuilder builder, Assembly[] assemblies) { builder.RegisterType<EntityFrameworkUnitOfWork<ReleaseContext>>() .As<IUnitOfWork>() .Named<IUnitOfWork>(RemiKey) .InstancePerDependency() .PropertiesAutowired(); builder.RegisterGeneric(typeof(EntityFrameworkRepository<>)) .As(typeof(IRepository<>)) .Named(RemiKey, typeof(IRepository<>)) .InstancePerDependency() .PropertiesAutowired() .WithParameter(new ResolvedParameter( (p, c) => p.ParameterType.Name == typeof(IUnitOfWork).Name, (p, c) => c.ResolveNamed<IUnitOfWork>(RemiKey))); builder.RegisterType(typeof(DatabaseAdapter)) .As(typeof(IDatabaseAdapter)) .InstancePerDependency() .PropertiesAutowired() .WithProperty(new ResolvedParameter( (p, c) => p.ParameterType.Name == typeof(IUnitOfWork).Name, (p, c) => c.ResolveNamed<IUnitOfWork>(RemiKey))); var repositoryPropertyResolver = Enumerable.Repeat(new ResolvedParameter( (p, c) => p.ParameterType.Name == typeof (IRepository<>).Name, (p, c) => c.ResolveNamed(RemiKey, p.ParameterType)), 20); builder.RegisterAssemblyTypes(assemblies) .Where(t => !string.IsNullOrWhiteSpace(t.Namespace) && t.Namespace.StartsWith("ReMi.DataAccess.BusinessEntityGateways")) .AsImplementedInterfaces() .InstancePerDependency() .PropertiesAutowired() .WithProperties(repositoryPropertyResolver); } private static void RegisterMappingEngine(ContainerBuilder builder, Assembly[] assemblies) { builder.Register(c => Mapper.Engine).As<IMappingEngine>(); builder.RegisterAssemblyTypes(assemblies) .AssignableTo<Profile>() .PropertiesAutowired() .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof(ITypeConverter<,>)) .InstancePerDependency() .PropertiesAutowired(); } private static void RegisterNotifications(ContainerBuilder builder, Assembly[] assemblies) { builder.Register(c => new SubscriptionManager()).As<ISubscriptionManager>() .PropertiesAutowired() .InstancePerDependency(); builder.Register(c => new NotificationsHub(c.Resolve<ISerialization>(), c.Resolve<ISubscriptionManager>())) .As<IFrontendNotificator>() .PropertiesAutowired() .InstancePerDependency(); builder.Register(c => new NotificationFilterApplying()) .As<INotificationFilterApplying>() .SingleInstance() .PropertiesAutowired(); builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof(INotificationFilterApplication<>)) .PropertiesAutowired() .InstancePerDependency(); } private static void RegisterOther(ContainerBuilder builder) { builder.Register(c => new Serialization()).As<ISerialization>().InstancePerLifetimeScope(); builder.Register(c => GlobalConfiguration.Configuration.DependencyResolver).As<IDependencyResolver>().SingleInstance(); builder.Register(c => new FileStorage(HostingEnvironment.MapPath("~"))).As<IFileStorage>().SingleInstance(); builder.Register(c => new FileStorage(HostingEnvironment.MapPath("~/App_Data"))).As<IAppDataFileStorage>().SingleInstance(); builder.Register(c => new ApplicationSettings()).As<IApplicationSettings>() .SingleInstance() .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies); builder.Register(c => new ClientRequestInfoRetriever()).As<IClientRequestInfoRetriever>().SingleInstance(); } private static void RegisterPlugins(ContainerBuilder builder) { Logger.Info("Registering Plugin Dependencies"); builder.RegisterType<CheckQaStatusComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); builder.RegisterType<ReleaseContentComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); builder.RegisterType<DeploymentToolComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); builder.RegisterType<SourceControlComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); builder.RegisterType<AuthenticationServiceComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); builder.RegisterType<EmailServiceComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); builder.RegisterType<HelpDeskServiceComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); builder.RegisterType<CacheServiceComposite>() .AsImplementedInterfaces() .PropertiesAutowired() .SingleInstance(); var pluginConfiguration = new PluginConfiguration(); builder.Register<IPluginConfiguration>(x => pluginConfiguration) .SingleInstance(); foreach (var pluginInitializer in pluginConfiguration.PluginInitializers) { pluginInitializer.InitializeDependencies(builder); } } } }
// 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 gcoc = Google.Cloud.OsLogin.Common; 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.OsLogin.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedOsLoginServiceClientTest { [xunit::FactAttribute] public void DeletePosixAccountRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeletePosixAccount(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePosixAccountRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePosixAccountAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePosixAccountAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePosixAccount() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeletePosixAccount(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePosixAccountAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePosixAccountAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePosixAccountAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePosixAccountResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeletePosixAccount(request.PosixAccountName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePosixAccountResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePosixAccountAsync(request.PosixAccountName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePosixAccountAsync(request.PosixAccountName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeleteSshPublicKey(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSshPublicKeyAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSshPublicKey() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeleteSshPublicKey(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSshPublicKeyAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSshPublicKeyAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSshPublicKeyResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeleteSshPublicKey(request.SshPublicKeyName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSshPublicKeyResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetLoginProfileRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), ProjectId = "project_id43ad98b0", SystemId = "system_id43548ac1", }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile response = client.GetLoginProfile(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetLoginProfileRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), ProjectId = "project_id43ad98b0", SystemId = "system_id43548ac1", }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetLoginProfile() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile response = client.GetLoginProfile(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetLoginProfileAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetLoginProfileResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile response = client.GetLoginProfile(request.UserName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetLoginProfileResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.UserName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.UserName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.GetSshPublicKey(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSshPublicKey() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.GetSshPublicKey(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSshPublicKeyAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSshPublicKeyResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.GetSshPublicKey(request.SshPublicKeyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSshPublicKeyResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey1() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey1Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey1ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey1ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey2() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey, request.ProjectId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey2Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey2ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey, request.ProjectId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey2ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey1() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey1Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey1ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey1ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey2() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey2Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey2ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey2ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
//------------------------------------------------------------------------------ // <copyright file="XmlPatch.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.IO; using System.Xml; using System.Text; using System.Diagnostics; using Microsoft.XmlDiffPatch; namespace Microsoft.XmlDiffPatch { ////////////////////////////////////////////////////////////////// // XmlPatch // /// <include file='doc\XmlPatch.uex' path='docs/doc[@for="XmlPatch"]/*' /> /// <summary> /// XML Patch modifies XML documents or nodes according to the XDL diffgram created by XML Diff. /// </summary> public class XmlPatch { // Fields XmlNode _sourceRootNode; bool _ignoreChildOrder; // Constructor public XmlPatch() { } // Methods /// <include file='doc\XmlPatch.uex' path='docs/doc[@for="XmlPatch.Patch1"]/*' /> /// <summary> /// Reads the XDL diffgram from the diffgramFileName and modifies the original XML document /// sourceDoc according to the changes described in the diffgram. /// </summary> /// <param name="sourceDoc">The original xml document</param> /// <param name="diffgramFileName">XmlReader for the XDL diffgram.</param> public void Patch( XmlDocument sourceDoc, XmlReader diffgram ) { if ( sourceDoc == null ) throw new ArgumentNullException( "sourceDoc" ); if ( diffgram == null ) throw new ArgumentNullException( "diffgram" ); XmlNode sourceNode = sourceDoc; Patch( ref sourceNode, diffgram ); Debug.Assert( sourceNode == sourceDoc ); } /// <include file='doc\XmlPatch.uex' path='docs/doc[@for="XmlPatch.Patch3"]/*' /> /// <summary> /// Reads the XDL diffgram from the diffgramFileName and modifies the original XML document /// sourceDoc according to the changes described in the diffgram. /// </summary> /// <param name="sourceDoc">The original xml document</param> /// <param name="diffgramFileName">XmlReader for the XDL diffgram.</param> public void Patch( string sourceFile, Stream outputStream, XmlReader diffgram ) { if ( sourceFile == null ) throw new ArgumentNullException( "sourceFile" ); if ( outputStream == null ) throw new ArgumentNullException( "outputStream" ); if ( diffgram == null ) throw new ArgumentException( "diffgram" ); XmlDocument diffDoc = new XmlDocument(); diffDoc.Load( diffgram ); // patch fragment if ( diffDoc.DocumentElement.GetAttribute( "fragments" ) == "yes" ) { NameTable nt = new NameTable(); XmlTextReader tr = new XmlTextReader( new FileStream( sourceFile, FileMode.Open, FileAccess.Read ), XmlNodeType.Element, new XmlParserContext( nt, new XmlNamespaceManager( nt ), string.Empty, XmlSpace.Default ) ); Patch( tr, outputStream, diffDoc ); } // patch document else { Patch ( new XmlTextReader( sourceFile ), outputStream, diffDoc ); } } /// <include file='doc\XmlPatch.uex' path='docs/doc[@for="XmlPatch.Patch3"]/*' /> /// <summary> /// Reads the XDL diffgram from the diffgramFileName and modifies the original XML document /// sourceDoc according to the changes described in the diffgram. /// </summary> /// <param name="sourceDoc">The original xml document</param> /// <param name="diffgramFileName">XmlReader for the XDL diffgram.</param> public void Patch( XmlReader sourceReader, Stream outputStream, XmlReader diffgram ) { if ( sourceReader == null ) throw new ArgumentNullException( "sourceReader" ); if ( outputStream == null ) throw new ArgumentNullException( "outputStream" ); if ( diffgram == null ) throw new ArgumentException( "diffgram" ); XmlDocument diffDoc = new XmlDocument(); diffDoc.Load( diffgram ); Patch( sourceReader, outputStream, diffDoc ); } private void Patch( XmlReader sourceReader, Stream outputStream, XmlDocument diffDoc ) { bool bFragments = diffDoc.DocumentElement.GetAttribute( "fragments" ) == "yes"; Encoding enc = null; if ( bFragments ) { // load fragment XmlDocument tmpDoc = new XmlDocument(); XmlDocumentFragment frag = tmpDoc.CreateDocumentFragment(); XmlNode node; while ( ( node = tmpDoc.ReadNode( sourceReader ) ) != null ) { switch ( node.NodeType ) { case XmlNodeType.Whitespace: break; case XmlNodeType.XmlDeclaration: frag.InnerXml = node.OuterXml; break; default: frag.AppendChild( node ); break; } if ( enc == null ) { if ( sourceReader is XmlTextReader ) { enc = ((XmlTextReader)sourceReader).Encoding; } else if ( sourceReader is XmlValidatingReader ) { enc = ((XmlValidatingReader)sourceReader).Encoding; } else { enc = Encoding.Unicode; } } } // patch XmlNode sourceNode = frag; Patch( ref sourceNode, diffDoc ); Debug.Assert( sourceNode == frag ); // save if ( frag.FirstChild != null && frag.FirstChild.NodeType == XmlNodeType.XmlDeclaration ) { enc = Encoding.GetEncoding( ((XmlDeclaration)sourceNode.FirstChild).Encoding ); } XmlTextWriter tw = new XmlTextWriter( outputStream, enc ); frag.WriteTo( tw ); tw.Flush(); } else { // load document XmlDocument sourceDoc = new XmlDocument(); sourceDoc.XmlResolver = null; sourceDoc.Load( sourceReader ); // patch XmlNode sourceNode = sourceDoc; Patch( ref sourceNode, diffDoc ); Debug.Assert( sourceNode == sourceDoc ); // save sourceDoc.Save( outputStream ); } } /// <include file='doc\XmlPatch.uex' path='docs/doc[@for="XmlPatch.Patch2"]/*' /> /// <summary> /// Reads the XDL diffgram from the diffgramFileName and modifies the original XML document /// sourceDoc according to the changes described in the diffgram. /// </summary> /// <param name="sourceDoc">The original xml node</param> /// <param name="diffgramFileName">XmlReader for the XDL diffgram.</param> public void Patch( ref XmlNode sourceNode, XmlReader diffgram ) { if ( sourceNode == null ) throw new ArgumentNullException( "sourceNode" ); if ( diffgram == null ) throw new ArgumentNullException( "diffgram" ); XmlDocument diffDoc = new XmlDocument(); diffDoc.Load( diffgram ); Patch( ref sourceNode, diffDoc ); } private void Patch( ref XmlNode sourceNode, XmlDocument diffDoc ) { XmlElement diffgramEl = diffDoc.DocumentElement; if ( diffgramEl.LocalName != "xmldiff" || diffgramEl.NamespaceURI != XmlDiff.NamespaceUri ) XmlPatchError.Error( XmlPatchError.ExpectingDiffgramElement ); XmlNamedNodeMap diffgramAttributes = diffgramEl.Attributes; XmlAttribute srcDocAttr = (XmlAttribute)diffgramAttributes.GetNamedItem( "srcDocHash" ); if ( srcDocAttr == null ) XmlPatchError.Error( XmlPatchError.MissingSrcDocAttribute ); ulong hashValue = 0; try { hashValue = ulong.Parse( srcDocAttr.Value ); } catch { XmlPatchError.Error( XmlPatchError.InvalidSrcDocAttribute ); } XmlAttribute optionsAttr = (XmlAttribute) diffgramAttributes.GetNamedItem( "options" ); if ( optionsAttr == null ) XmlPatchError.Error( XmlPatchError.MissingOptionsAttribute ); // parse options XmlDiffOptions xmlDiffOptions = XmlDiffOptions.None; try { xmlDiffOptions = XmlDiff.ParseOptions( optionsAttr.Value ); } catch { XmlPatchError.Error( XmlPatchError.InvalidOptionsAttribute ); } _ignoreChildOrder = ( (int)xmlDiffOptions & (int)XmlDiffOptions.IgnoreChildOrder ) != 0; // Calculate the hash value of source document and check if it agrees with // of srcDocHash attribute value. if ( !XmlDiff.VerifySource( sourceNode, hashValue, xmlDiffOptions ) ) XmlPatchError.Error( XmlPatchError.SrcDocMismatch ); // Translate diffgram & Apply patch if ( sourceNode.NodeType == XmlNodeType.Document ) { Patch patch = CreatePatch( sourceNode, diffgramEl ); // create temporary root element and move all document children under it XmlDocument sourceDoc = (XmlDocument)sourceNode; XmlElement tempRoot = sourceDoc.CreateElement( "tempRoot" ); XmlNode child = sourceDoc.FirstChild; while ( child != null ) { XmlNode tmpChild = child.NextSibling; if ( child.NodeType != XmlNodeType.XmlDeclaration && child.NodeType != XmlNodeType.DocumentType ) { sourceDoc.RemoveChild( child ); tempRoot.AppendChild( child ); } child = tmpChild; } sourceDoc.AppendChild( tempRoot ); // Apply patch XmlNode temp = null; patch.Apply( tempRoot, ref temp ); // remove the temporary root element if ( sourceNode.NodeType == XmlNodeType.Document ) { sourceDoc.RemoveChild( tempRoot ); Debug.Assert( tempRoot.Attributes.Count == 0 ); while ( ( child = tempRoot.FirstChild ) != null ) { tempRoot.RemoveChild( child ); sourceDoc.AppendChild( child ); } } } else if ( sourceNode.NodeType == XmlNodeType.DocumentFragment ) { Patch patch = CreatePatch( sourceNode, diffgramEl ); XmlNode temp = null; patch.Apply( sourceNode, ref temp ); } else { // create fragment with sourceNode as its only child XmlDocumentFragment fragment = sourceNode.OwnerDocument.CreateDocumentFragment(); XmlNode previousSourceParent = sourceNode.ParentNode; XmlNode previousSourceSibbling = sourceNode.PreviousSibling; if ( previousSourceParent != null ) { previousSourceParent.RemoveChild( sourceNode ); } if ( sourceNode.NodeType != XmlNodeType.XmlDeclaration ) { fragment.AppendChild( sourceNode ); } else { fragment.InnerXml = sourceNode.OuterXml; } Patch patch = CreatePatch( fragment, diffgramEl ); XmlNode temp = null; patch.Apply( fragment, ref temp ); XmlNodeList childNodes = fragment.ChildNodes; if ( childNodes.Count != 1 ) { XmlPatchError.Error( XmlPatchError.InternalErrorMoreThanOneNodeLeft, childNodes.Count.ToString() ); } sourceNode = childNodes.Item(0); fragment.RemoveAll(); if ( previousSourceParent != null ) { previousSourceParent.InsertAfter( sourceNode, previousSourceSibbling ); } } } private Patch CreatePatch( XmlNode sourceNode, XmlElement diffgramElement ) { Debug.Assert( sourceNode.NodeType == XmlNodeType.Document || sourceNode.NodeType == XmlNodeType.DocumentFragment ); Patch patch = new Patch( sourceNode ); _sourceRootNode = sourceNode; // create patch for <xmldiff> node children CreatePatchForChildren( sourceNode, diffgramElement, patch ); return patch; } private void CreatePatchForChildren( XmlNode sourceParent, XmlElement diffgramParent, XmlPatchParentOperation patchParent ) { Debug.Assert( sourceParent != null ); Debug.Assert( diffgramParent != null ); Debug.Assert( patchParent != null ); XmlPatchOperation lastPatchOp = null; XmlNode node = diffgramParent.FirstChild; while ( node != null ) { if ( node.NodeType != XmlNodeType.Element ) { node = node.NextSibling; continue; } XmlElement diffOp = (XmlElement)node; XmlNodeList matchNodes = null; string matchAttr = diffOp.GetAttribute( "match" ); if ( matchAttr != string.Empty ) { matchNodes = PathDescriptorParser.SelectNodes( _sourceRootNode, sourceParent, matchAttr ); if ( matchNodes.Count == 0 ) XmlPatchError.Error( XmlPatchError.NoMatchingNode, matchAttr ); } XmlPatchOperation patchOp = null; switch ( diffOp.LocalName ) { case "node": { Debug.Assert( matchAttr != string.Empty ); if ( matchNodes.Count != 1 ) XmlPatchError.Error( XmlPatchError.MoreThanOneNodeMatched, matchAttr ); XmlNode matchNode = matchNodes.Item( 0 ); if ( _sourceRootNode.NodeType != XmlNodeType.Document || ( matchNode.NodeType != XmlNodeType.XmlDeclaration && matchNode.NodeType != XmlNodeType.DocumentType ) ) { patchOp = new PatchSetPosition( matchNode ); CreatePatchForChildren( matchNode, diffOp, (XmlPatchParentOperation) patchOp ); } break; } case "add": { // copy node/subtree if ( matchAttr != string.Empty ) { bool bSubtree = diffOp.GetAttribute( "subtree" ) != "no"; patchOp = new PatchCopy( matchNodes, bSubtree ); if ( !bSubtree ) CreatePatchForChildren( sourceParent, diffOp, (XmlPatchParentOperation) patchOp ); } else { string type = diffOp.GetAttribute( "type" ); // add single node if ( type != string.Empty ) { XmlNodeType nodeType = (XmlNodeType) int.Parse( type ); bool bElement = (nodeType == XmlNodeType.Element); if ( nodeType != XmlNodeType.DocumentType ) { patchOp = new PatchAddNode( nodeType, diffOp.GetAttribute( "name" ), diffOp.GetAttribute( "ns" ), diffOp.GetAttribute( "prefix" ), bElement ? string.Empty : diffOp.InnerText, _ignoreChildOrder ); if ( bElement ) CreatePatchForChildren( sourceParent, diffOp, (XmlPatchParentOperation) patchOp ); } else { patchOp = new PatchAddNode( nodeType, diffOp.GetAttribute( "name" ), diffOp.GetAttribute( "systemId" ), diffOp.GetAttribute( "publicId" ), diffOp.InnerText, _ignoreChildOrder ); } } // add blob else { Debug.Assert( diffOp.ChildNodes.Count > 0 ); patchOp = new PatchAddXmlFragment( diffOp.ChildNodes ); } } break; } case "remove": { Debug.Assert( matchAttr != string.Empty ); bool bSubtree = diffOp.GetAttribute( "subtree" ) != "no"; patchOp = new PatchRemove( matchNodes, bSubtree ); if ( !bSubtree ) { Debug.Assert( matchNodes.Count == 1 ); CreatePatchForChildren( matchNodes.Item(0), diffOp, (XmlPatchParentOperation) patchOp ); } break; } case "change": { Debug.Assert( matchAttr != string.Empty ); if ( matchNodes.Count != 1 ) XmlPatchError.Error( XmlPatchError.MoreThanOneNodeMatched, matchAttr ); XmlNode matchNode = matchNodes.Item( 0 ); if ( matchNode.NodeType != XmlNodeType.DocumentType ) { patchOp = new PatchChange( matchNode, diffOp.HasAttribute( "name" ) ? diffOp.GetAttribute( "name" ) : null, diffOp.HasAttribute( "ns" ) ? diffOp.GetAttribute( "ns" ) : null, diffOp.HasAttribute( "prefix" ) ? diffOp.GetAttribute( "prefix" ) : null, (matchNode.NodeType == XmlNodeType.Element) ? null : diffOp ); } else { patchOp = new PatchChange( matchNode, diffOp.HasAttribute( "name" ) ? diffOp.GetAttribute( "name" ) : null, diffOp.HasAttribute( "systemId" ) ? diffOp.GetAttribute( "systemId" ) : null, diffOp.HasAttribute( "publicId" ) ? diffOp.GetAttribute( "publicId" ) : null, diffOp.IsEmpty ? null : diffOp ); } if ( matchNode.NodeType == XmlNodeType.Element ) CreatePatchForChildren( matchNode, diffOp, (XmlPatchParentOperation) patchOp ); break; } case "descriptor": return; default: Debug.Assert( false, "Invalid element in the XDL diffgram ." ); break; } if ( patchOp != null ) { patchParent.InsertChildAfter( lastPatchOp, patchOp ); lastPatchOp = patchOp; } node = node.NextSibling; } } } }
// <copyright file="SafariDriverServer.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Permissions; using System.Text; using System.Threading; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Safari.Internal; namespace OpenQA.Selenium.Safari { /// <summary> /// Provides the WebSockets server for communicating with the Safari extension. /// </summary> public class SafariDriverServer : ICommandServer { private WebSocketServer webSocketServer; private Queue<SafariDriverConnection> connections = new Queue<SafariDriverConnection>(); private Uri serverUri; private string temporaryDirectoryPath; private string safariExecutableLocation; private Process safariProcess; private SafariDriverConnection connection; /// <summary> /// Initializes a new instance of the <see cref="SafariDriverServer"/> class using the specified options. /// </summary> /// <param name="options">The <see cref="SafariOptions"/> defining the browser settings.</param> public SafariDriverServer(SafariOptions options) { int webSocketPort = options.Port; if (webSocketPort == 0) { webSocketPort = PortUtilities.FindFreePort(); } this.webSocketServer = new WebSocketServer(webSocketPort, "ws://localhost/wd"); this.webSocketServer.Opened += new EventHandler<ConnectionEventArgs>(this.ServerOpenedEventHandler); this.webSocketServer.Closed += new EventHandler<ConnectionEventArgs>(this.ServerClosedEventHandler); this.webSocketServer.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ServerStandardHttpRequestReceivedEventHandler); this.serverUri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/", webSocketPort.ToString(CultureInfo.InvariantCulture))); if (string.IsNullOrEmpty(options.SafariLocation)) { this.safariExecutableLocation = GetDefaultSafariLocation(); } else { this.safariExecutableLocation = options.SafariLocation; } } /// <summary> /// Starts the server. /// </summary> public void Start() { this.webSocketServer.Start(); string connectFileName = this.PrepareConnectFile(); this.LaunchSafariProcess(connectFileName); this.connection = this.WaitForConnection(TimeSpan.FromSeconds(45)); this.DeleteConnectFile(); if (this.connection == null) { throw new WebDriverException("Did not receive a connection from the Safari extension. Please verify that it is properly installed and is the proper version."); } } /// <summary> /// Sends a command to the server. /// </summary> /// <param name="commandToSend">The <see cref="Command"/> to send.</param> /// <returns>The command <see cref="Response"/>.</returns> public Response SendCommand(Command commandToSend) { return this.connection.Send(commandToSend); } /// <summary> /// Waits for a connection to be established with the server by the Safari browser extension. /// </summary> /// <param name="timeout">A <see cref="TimeSpan"/> containing the amount of time to wait for the connection.</param> /// <returns>A <see cref="SafariDriverConnection"/> representing the connection to the browser.</returns> public SafariDriverConnection WaitForConnection(TimeSpan timeout) { SafariDriverConnection foundConnection = null; DateTime end = DateTime.Now.Add(timeout); while (this.connections.Count == 0 && DateTime.Now < end) { Thread.Sleep(250); } if (this.connections.Count > 0) { foundConnection = this.connections.Dequeue(); } return foundConnection; } /// <summary> /// Releases all resources used by the <see cref="SafariDriverServer"/>. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the <see cref="SafariDriverServer"/> and optionally /// releases the managed resources. /// </summary> /// <param name="disposing"><see langword="true"/> to release managed and resources; /// <see langword="false"/> to only release unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { this.webSocketServer.Dispose(); if (this.safariProcess != null) { this.CloseSafariProcess(); this.safariProcess.Dispose(); } } } private static string GetDefaultSafariLocation() { string safariPath = string.Empty; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Safari remains a 32-bit application. Use a hack to look for it // in the 32-bit program files directory. If a 64-bit version of // Safari for Windows is released, this needs to be revisited. string programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (Directory.Exists(programFilesDirectory + " (x86)")) { programFilesDirectory += " (x86)"; } safariPath = Path.Combine(programFilesDirectory, Path.Combine("Safari", "safari.exe")); } else { safariPath = "/Applications/Safari.app/Contents/MacOS/Safari"; } return safariPath; } [SecurityPermission(SecurityAction.Demand)] private void LaunchSafariProcess(string initialPage) { this.safariProcess = new Process(); this.safariProcess.StartInfo.FileName = this.safariExecutableLocation; this.safariProcess.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", initialPage); this.safariProcess.Start(); } [SecurityPermission(SecurityAction.Demand)] private void CloseSafariProcess() { if (this.safariProcess != null && !this.safariProcess.HasExited) { this.safariProcess.Kill(); while (!this.safariProcess.HasExited) { Thread.Sleep(250); } } } private string PrepareConnectFile() { string directoryName = FileUtilities.GenerateRandomTempDirectoryName("SafariDriverConnect.{0}"); this.temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), directoryName); string tempFileName = Path.Combine(this.temporaryDirectoryPath, "connect.html"); string contents = string.Format(CultureInfo.InvariantCulture, "<!DOCTYPE html><script>window.location = '{0}';</script>", this.serverUri.ToString()); Directory.CreateDirectory(this.temporaryDirectoryPath); using (FileStream stream = File.Create(tempFileName)) { stream.Write(Encoding.UTF8.GetBytes(contents), 0, Encoding.UTF8.GetByteCount(contents)); } return tempFileName; } private void DeleteConnectFile() { Directory.Delete(this.temporaryDirectoryPath, true); } private void ServerOpenedEventHandler(object sender, ConnectionEventArgs e) { this.connections.Enqueue(new SafariDriverConnection(e.Connection)); } private void ServerClosedEventHandler(object sender, ConnectionEventArgs e) { } private void ServerStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e) { const string PageSource = @"<!DOCTYPE html> <script> window.onload = function() {{ window.postMessage({{ 'type': 'connect', 'origin': 'webdriver', 'url': 'ws://localhost:{0}/wd' }}, '*'); }}; </script>"; string redirectPage = string.Format(CultureInfo.InvariantCulture, PageSource, this.webSocketServer.Port.ToString(CultureInfo.InvariantCulture)); StringBuilder builder = new StringBuilder(); builder.AppendLine("HTTP/1.1 200"); builder.AppendLine("Content-Length: " + redirectPage.Length.ToString(CultureInfo.InvariantCulture)); builder.AppendLine("Connection:close"); builder.AppendLine(); builder.AppendLine(redirectPage); e.Connection.SendRaw(builder.ToString()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Linq; using System.Data.Common; using System.Linq.Expressions; using System.IO; using System.Linq; using System.Text; using System.Transactions; using System.Reflection; using System.Diagnostics.CodeAnalysis; namespace System.Data.Linq.Provider { /// <summary> /// A data provider implements this interface to hook into the LINQ to SQL framework. /// </summary> internal interface IProvider : IDisposable { /// <summary> /// Initializes the database provider with the data services object and connection. /// </summary> /// <param name="dataServices"></param> /// <param name="connection">A connection string, connection object or transaction object /// used to seed the provider with database connection information.</param> void Initialize(IDataServices dataServices, object connection); /// <summary> /// The text writer used by the provider to output information such as query and commands /// being executed. /// </summary> TextWriter Log { get; set; } /// <summary> /// The connection object used by the provider when executing queries and commands. /// </summary> DbConnection Connection { get; } /// <summary> /// The transaction object used by the provider when executing queries and commands. /// </summary> DbTransaction Transaction { get; set; } /// <summary> /// The command timeout setting to use for command execution. /// </summary> int CommandTimeout { get; set; } /// <summary> /// Clears the connection of any current activity. /// </summary> void ClearConnection(); /// <summary> /// Creates a new database instance (catalog or file) at the location specified by the connection /// using the metadata encoded within the entities or mapping file. /// </summary> void CreateDatabase(); /// <summary> /// Deletes the database instance at the location specified by the connection. /// </summary> void DeleteDatabase(); /// <summary> /// Returns true if the database specified by the connection object exists. /// </summary> /// <returns></returns> bool DatabaseExists(); /// <summary> /// Executes the query specified as a LINQ expression tree. /// </summary> /// <param name="query"></param> /// <returns>A result object from which you can obtain the return value and output parameters.</returns> IExecuteResult Execute(Expression query); /// <summary> /// Compiles the query specified as a LINQ expression tree. /// </summary> /// <param name="query"></param> /// <returns>A compiled query instance.</returns> ICompiledQuery Compile(Expression query); /// <summary> /// Translates a DbDataReader into a sequence of objects (entity or projection) by mapping /// columns of the data reader to object members by name. /// </summary> /// <param name="elementType">The type of the resulting objects.</param> /// <param name="reader"></param> /// <returns></returns> IEnumerable Translate(Type elementType, DbDataReader reader); /// <summary> /// Translates an IDataReader containing multiple result sets into sequences of objects /// (entity or projection) by mapping columns of the data reader to object members by name. /// </summary> /// <param name="reader"></param> /// <returns></returns> IMultipleResults Translate(DbDataReader reader); /// <summary> /// Returns the query text in the database server's native query language /// that would need to be executed to perform the specified query. /// </summary> /// <param name="query">The query</param> /// <returns></returns> string GetQueryText(Expression query); /// <summary> /// Return an IDbCommand object representing the translation of specified query. /// </summary> /// <param name="query"></param> /// <returns></returns> DbCommand GetCommand(Expression query); } /// <summary> /// A compiled query. /// </summary> internal interface ICompiledQuery { /// <summary> /// Executes the compiled query using the specified provider and a set of arguments. /// </summary> /// <param name="provider">The provider that will execute the compiled query.</param> /// <param name="arguments">Argument values to supply to the parameters of the compiled query, /// when the query is specified as a LambdaExpression.</param> /// <returns></returns> IExecuteResult Execute(IProvider provider, object[] arguments); } internal static class DataManipulation { /// <summary> /// The method signature used to encode an Insert command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="item"></param> /// <param name="resultSelector"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "resultSelector", Justification = "[....]: The method is being used to represent a method signature")] public static TResult Insert<TEntity, TResult>(TEntity item, Func<TEntity, TResult> resultSelector) { throw new NotImplementedException(); } /// <summary> /// The method signature used to encode an Insert command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="item"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] public static int Insert<TEntity>(TEntity item) { throw new NotImplementedException(); } /// <summary> /// The method signature used to encode an Update command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="item"></param> /// <param name="check"></param> /// <param name="resultSelector"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "check", Justification = "[....]: The method is being used to represent a method signature")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "resultSelector", Justification = "[....]: The method is being used to represent a method signature")] public static TResult Update<TEntity, TResult>(TEntity item, Func<TEntity, bool> check, Func<TEntity, TResult> resultSelector) { throw new NotImplementedException(); } /// <summary> /// The method signature used to encode an Update command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="item"></param> /// <param name="resultSelector"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "resultSelector", Justification = "[....]: The method is being used to represent a method signature")] public static TResult Update<TEntity, TResult>(TEntity item, Func<TEntity, TResult> resultSelector) { throw new NotImplementedException(); } /// <summary> /// The method signature used to encode an Update command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="item"></param> /// <param name="check"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "check", Justification = "[....]: The method is being used to represent a method signature")] public static int Update<TEntity>(TEntity item, Func<TEntity, bool> check) { throw new NotImplementedException(); } /// <summary> /// The method signature used to encode an Update command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="item"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] public static int Update<TEntity>(TEntity item) { throw new NotImplementedException(); } /// <summary> /// The method signature used to encode a Delete command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="item"></param> /// <param name="check"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "check", Justification = "[....]: The method is being used to represent a method signature")] public static int Delete<TEntity>(TEntity item, Func<TEntity, bool> check) { throw new NotImplementedException(); } /// <summary> /// The method signature used to encode a Delete command. /// The method will throw a NotImplementedException if called directly. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="item"></param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "item", Justification = "[....]: The method is being used to represent a method signature")] public static int Delete<TEntity>(TEntity item) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_CTYPES using System; using System.Collections.Generic; using System.ComponentModel; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; [assembly: PythonModule("_ctypes", typeof(IronPython.Modules.CTypes))] namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { private static readonly object _lock = new object(); // lock for creating dynamic module for unsafe code private static readonly object _pointerTypeCacheKey = new object(); // key for system state for the pointer type cache private static readonly object _conversion_mode = new object(); // key for system state current conversion mode private static Dictionary<object, RefCountInfo> _refCountTable; // dictionary used to maintain a ref count on objects private static ModuleBuilder _dynamicModule; // the dynamic module we generate unsafe code into private static Dictionary<int, Type> _nativeTypes = new Dictionary<int, Type>(); // native types of the specified size for marshalling private static StringAtDelegate _stringAt = StringAt, _wstringAt = WStringAt; // delegates for wchar/char functions we hand addresses out to (just keeping it alive) private static CastDelegate _cast = Cast; // delegate for cast function whose address we hand out (just keeping it alive) public const string __version__ = "1.1.0"; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr CastDelegate(IntPtr data, IntPtr obj, IntPtr type); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr StringAtDelegate(IntPtr addr, int length); [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException("ArgumentError", dict, "ArgumentError", "_ctypes"); // TODO: Provide an implementation which is coordinated with our _refCountTable context.SystemState.__dict__["getrefcount"] = null; PythonDictionary pointerTypeCache = new PythonDictionary(); dict["_pointer_type_cache"] = pointerTypeCache; context.SetModuleState(_pointerTypeCacheKey, pointerTypeCache); if (Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE) { context.EnsureModuleException( "COMError", PythonExceptions.Exception, typeof(_COMError), dict, "COMError", "_ctypes", "Raised when a COM method call failed.", msg => new COMException(msg) ); context.SetModuleState(_conversion_mode, PythonTuple.MakeTuple("mbcs", "ignore")); } else { context.SetModuleState(_conversion_mode, PythonTuple.MakeTuple("ascii", "strict")); } } #region Public Functions /// <summary> /// Gets a function which casts the specified memory. Because this is used only /// w/ Python API we use a delegate as the return type instead of an actual address. /// </summary> public static object _cast_addr { get { return Marshal.GetFunctionPointerForDelegate(_cast).ToPython(); } } /// <summary> /// Implementation of our cast function. data is marshalled as a void* /// so it ends up as an address. obj and type are marshalled as an object /// so we need to unmarshal them. /// </summary> private static IntPtr Cast(IntPtr data, IntPtr obj, IntPtr type) { GCHandle objHandle = GCHandle.FromIntPtr(obj); GCHandle typeHandle = GCHandle.FromIntPtr(type); try { CData cdata = objHandle.Target as CData; PythonType pt = (PythonType)typeHandle.Target; CData res = (CData)pt.CreateInstance(pt.Context.SharedContext); if (IsPointer(pt)) { res._memHolder = new MemoryHolder(IntPtr.Size); if (IsPointer(DynamicHelpers.GetPythonType(cdata))) { res._memHolder.WriteIntPtr(0, cdata._memHolder.ReadIntPtr(0)); } else { res._memHolder.WriteIntPtr(0, data); } if (cdata != null) { res._memHolder.Objects = cdata._memHolder.Objects; res._memHolder.AddObject(IdDispenser.GetId(cdata), cdata); } } else { if (cdata != null) { res._memHolder = new MemoryHolder(data, ((INativeType)pt).Size, cdata._memHolder); } else { res._memHolder = new MemoryHolder(data, ((INativeType)pt).Size); } } return GCHandle.ToIntPtr(GCHandle.Alloc(res)); } finally { typeHandle.Free(); objHandle.Free(); } } private static bool IsPointer(PythonType pt) { SimpleType simpleType; return pt is PointerType || ((simpleType = pt as SimpleType) != null && (simpleType._type == SimpleTypeKind.Pointer || simpleType._type == SimpleTypeKind.CharPointer || simpleType._type == SimpleTypeKind.WCharPointer)); } public static object _memmove_addr { get { return NativeFunctions.GetMemMoveAddress().ToPython(); } } public static object _memset_addr { get { return NativeFunctions.GetMemSetAddress().ToPython(); } } public static object _string_at_addr { get { return Marshal.GetFunctionPointerForDelegate(_stringAt).ToPython(); } } public static object _wstring_at_addr { get { return Marshal.GetFunctionPointerForDelegate(_wstringAt).ToPython(); } } public static int CopyComPointer(object src, object dest) { throw new NotImplementedException("CopyComPointer"); } public static string FormatError() { return FormatError(get_last_error()); } public static string FormatError(int errorCode) { return new Win32Exception(errorCode).Message; } [PythonHidden(PlatformsAttribute.PlatformFamily.Unix)] public static void FreeLibrary(int handle) { FreeLibrary(new IntPtr(handle)); } [PythonHidden(PlatformsAttribute.PlatformFamily.Unix)] public static void FreeLibrary(BigInteger handle) { FreeLibrary(new IntPtr((long)handle)); } [PythonHidden(PlatformsAttribute.PlatformFamily.Unix)] public static void FreeLibrary(IntPtr handle) { NativeFunctions.FreeLibrary(handle); } [PythonHidden(PlatformsAttribute.PlatformFamily.Unix)] public static object LoadLibrary(string library, [DefaultParameterValue(0)]int mode) { IntPtr res = NativeFunctions.LoadDLL(library, mode); if (res == IntPtr.Zero) { throw PythonOps.OSError($"cannot load library {library}"); } return res.ToPython(); } // Provided for Posix compat. public static object dlopen(string library, [DefaultParameterValue(0)]int mode) { return LoadLibrary(library, mode); } /// <summary> /// Returns a new type which represents a pointer given the existing type. /// </summary> public static PythonType POINTER(CodeContext/*!*/ context, PythonType type) { PythonContext pc = context.LanguageContext; PythonDictionary dict = (PythonDictionary)pc.GetModuleState(_pointerTypeCacheKey); lock (dict) { if (!dict.TryGetValue(type, out object res)) { string name; if (type == null) { name = "c_void_p"; } else { name = "LP_" + type.Name; } dict[type] = res = MakePointer(context, name, PythonOps.MakeDictFromItems(new object[] { type, "_type_" })); } return res as PythonType; } } private static PointerType MakePointer(CodeContext context, string name, PythonDictionary dict) { return new PointerType(context, name, PythonTuple.MakeTuple(_Pointer), dict ); } public static PythonType POINTER(CodeContext/*!*/ context, [NotNull]string name) { PythonType res = MakePointer(context, name, new PythonDictionary()); PythonContext pc = context.LanguageContext; PythonDictionary dict = (PythonDictionary)pc.GetModuleState(_pointerTypeCacheKey); lock (dict) { dict[Builtin.id(res)] = res; } return res; } /// <summary> /// Converts an address acquired from PyObj_FromPtr or that has been /// marshaled as type 'O' back into an object. /// </summary> public static object PyObj_FromPtr(IntPtr address) { GCHandle handle = GCHandle.FromIntPtr(address); object res = handle.Target; handle.Free(); return res; } /// <summary> /// Converts an object into an opaque address which can be handed out to /// managed code. /// </summary> public static IntPtr PyObj_ToPtr(object obj) { return GCHandle.ToIntPtr(GCHandle.Alloc(obj)); } /// <summary> /// Decreases the ref count on an object which has been increased with /// Py_INCREF. /// </summary> public static void Py_DECREF(object key) { EnsureRefCountTable(); lock (_refCountTable) { if (!_refCountTable.TryGetValue(key, out RefCountInfo info)) { // dec without an inc throw new InvalidOperationException(); } info.RefCount--; if (info.RefCount == 0) { info.Handle.Free(); _refCountTable.Remove(key); } } } /// <summary> /// Increases the ref count on an object ensuring that it will not be collected. /// </summary> public static void Py_INCREF(object key) { EnsureRefCountTable(); lock (_refCountTable) { if (!_refCountTable.TryGetValue(key, out RefCountInfo info)) { _refCountTable[key] = info = new RefCountInfo(); // TODO: this only works w/ blittable types, what to do for others? info.Handle = GCHandle.Alloc(key, GCHandleType.Pinned); } info.RefCount++; } } // for testing purposes only public static PythonTuple _buffer_info(CData data) { return data.GetBufferInfo(); } public static void _check_HRESULT(int hresult) { if (hresult < 0) { throw PythonOps.WindowsError("ctypes function returned failed HRESULT: {0}", PythonOps.Hex((BigInteger)(uint)hresult)); } } public static void _unpickle() { } /// <summary> /// returns address of C instance internal buffer. /// /// It is the callers responsibility to ensure that the provided instance will /// stay alive if memory in the resulting address is to be used later. /// </summary> public static object addressof(CData data) { return data._memHolder.UnsafeAddress.ToPython(); } /// <summary> /// Gets the required alignment of the given type. /// </summary> public static int alignment(PythonType type) { if (!(type is INativeType nativeType)) { throw PythonOps.TypeError("this type has no size"); } return nativeType.Alignment; } /// <summary> /// Gets the required alignment of an object. /// </summary> public static int alignment(object o) { return alignment(DynamicHelpers.GetPythonType(o)); } public static object byref(CData instance, int offset = 0) { if (offset != 0) { // new in 2.6 throw new NotImplementedException("byref w/ arg"); } return new NativeArgument(instance, "P"); } public static object call_cdeclfunction(CodeContext context, int address, PythonTuple args) { return call_cdeclfunction(context, new IntPtr(address), args); } public static object call_cdeclfunction(CodeContext context, BigInteger address, PythonTuple args) { return call_cdeclfunction(context, new IntPtr((long)address), args); } public static object call_cdeclfunction(CodeContext context, IntPtr address, PythonTuple args) { CFuncPtrType funcType = GetFunctionType(context, FUNCFLAG_CDECL); _CFuncPtr func = (_CFuncPtr)funcType.CreateInstance(context, address); return PythonOps.CallWithArgsTuple(func, new object[0], args); } public static void call_commethod() { } public static object call_function(CodeContext context, int address, PythonTuple args) { return call_function(context, new IntPtr(address), args); } public static object call_function(CodeContext context, BigInteger address, PythonTuple args) { return call_function(context, new IntPtr((long)address), args); } public static object call_function(CodeContext context, IntPtr address, PythonTuple args) { CFuncPtrType funcType = GetFunctionType(context, FUNCFLAG_STDCALL); _CFuncPtr func = (_CFuncPtr)funcType.CreateInstance(context, address); return PythonOps.CallWithArgsTuple(func, new object[0], args); } private static CFuncPtrType GetFunctionType(CodeContext context, int flags) { // Ideally we should cache these... SimpleType resType = new SimpleType( context, "int", PythonTuple.MakeTuple(DynamicHelpers.GetPythonTypeFromType(typeof(SimpleCData))), PythonOps.MakeHomogeneousDictFromItems(new object[] { "i", "_type_" })); CFuncPtrType funcType = new CFuncPtrType( context, "func", PythonTuple.MakeTuple(DynamicHelpers.GetPythonTypeFromType(typeof(_CFuncPtr))), PythonOps.MakeHomogeneousDictFromItems(new object[] { FUNCFLAG_STDCALL, "_flags_", resType, "_restype_" })); return funcType; } public static int get_errno() { return 0; } public static int get_last_error() { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { return NativeFunctions.GetLastError(); } throw PythonOps.NameError("get_last_error"); } /// <summary> /// Returns a pointer instance for the given CData /// </summary> public static Pointer pointer(CodeContext/*!*/ context, CData data) { PythonType ptrType = POINTER(context, DynamicHelpers.GetPythonType(data)); return (Pointer)ptrType.CreateInstance(context, data); } public static void resize(CData obj, int newSize) { if (newSize < obj.NativeType.Size) { throw PythonOps.ValueError("minimum size is {0}", newSize); } MemoryHolder newMem = new MemoryHolder(newSize); obj._memHolder.CopyTo(newMem, 0, Math.Min(obj._memHolder.Size, newSize)); obj._memHolder = newMem; } public static PythonTuple/*!*/ set_conversion_mode(CodeContext/*!*/ context, string encoding, string errors) { // TODO: Need an atomic update for module state PythonContext pc = context.LanguageContext; PythonTuple prev = (PythonTuple)pc.GetModuleState(_conversion_mode); pc.SetModuleState(_conversion_mode, PythonTuple.MakeTuple(encoding, errors)); return prev; } public static void set_errno() { // we can't support this without a native library } [PythonHidden(PlatformsAttribute.PlatformFamily.Unix)] public static int set_last_error(int errorCode) { int old_errno = NativeFunctions.GetLastError(); NativeFunctions.SetLastError(errorCode); return old_errno; } public static int @sizeof(PythonType/*!*/ type) { if (!(type is INativeType simpleType)) { throw PythonOps.TypeError("this type has no size"); } return simpleType.Size; } public static int @sizeof(object/*!*/ instance) { if (instance is CData cdata && cdata._memHolder != null) { return cdata._memHolder.Size; } return @sizeof(DynamicHelpers.GetPythonType(instance)); } #endregion #region Public Constants public const int FUNCFLAG_STDCALL = 0; public const int FUNCFLAG_CDECL = 1; public const int FUNCFLAG_HRESULT = 2; public const int FUNCFLAG_PYTHONAPI = 4; public const int FUNCFLAG_USE_ERRNO = 8; public const int FUNCFLAG_USE_LASTERROR = 16; public const int RTLD_GLOBAL = 0; public const int RTLD_LOCAL = 0; #endregion #region Implementation Details /// <summary> /// Gets the ModuleBuilder used to generate our unsafe call stubs into. /// </summary> private static ModuleBuilder DynamicModule { get { if (_dynamicModule == null) { lock (_lock) { if (_dynamicModule == null) { var attributes = new[] { new CustomAttributeBuilder(typeof(UnverifiableCodeAttribute).GetConstructor(ReflectionUtils.EmptyTypes), new object[0]), #if !NETCOREAPP && !NETSTANDARD //PermissionSet(SecurityAction.Demand, Unrestricted = true) new CustomAttributeBuilder(typeof(PermissionSetAttribute).GetConstructor(new Type[] { typeof(SecurityAction) }), new object[]{ SecurityAction.Demand }, new PropertyInfo[] { typeof(PermissionSetAttribute).GetProperty(nameof(PermissionSetAttribute.Unrestricted)) }, new object[] { true } ) #endif }; string name = typeof(CTypes).Namespace + ".DynamicAssembly"; var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Run, attributes); #if !NETCOREAPP && !NETSTANDARD assembly.DefineVersionInfoResource(); #endif _dynamicModule = assembly.DefineDynamicModule(name); } } } return _dynamicModule; } } /// <summary> /// Given a specific size returns a .NET type of the equivalent size that /// we can use when marshalling these values across calls. /// </summary> private static Type/*!*/ GetMarshalTypeFromSize(int size) { lock (_nativeTypes) { if (!_nativeTypes.TryGetValue(size, out Type res)) { int sizeRemaining = size; TypeBuilder tb = DynamicModule.DefineType("interop_type_size_" + size, TypeAttributes.Public | TypeAttributes.SequentialLayout | TypeAttributes.Sealed | TypeAttributes.Serializable, typeof(ValueType), size); while (sizeRemaining > 8) { tb.DefineField("field" + sizeRemaining, typeof(long), FieldAttributes.Private); sizeRemaining -= 8; } while (sizeRemaining > 4) { tb.DefineField("field" + sizeRemaining, typeof(int), FieldAttributes.Private); sizeRemaining -= 4; } while (sizeRemaining > 0) { tb.DefineField("field" + sizeRemaining, typeof(byte), FieldAttributes.Private); sizeRemaining--; } _nativeTypes[size] = res = tb.CreateTypeInfo(); } return res; } } /// <summary> /// Shared helper between struct and union for getting field info and validating it. /// </summary> private static void GetFieldInfo(INativeType type, object o, out string fieldName, out INativeType cdata, out int? bitCount) { PythonTuple pt = o as PythonTuple; if (pt.Count != 2 && pt.Count != 3) { throw PythonOps.AttributeError("'_fields_' must be a sequence of pairs"); } fieldName = pt[0] as string; if (fieldName == null) { throw PythonOps.TypeError("first item in _fields_ tuple must be a string, got", PythonTypeOps.GetName(pt[0])); } cdata = pt[1] as INativeType; if (cdata == null) { throw PythonOps.TypeError("second item in _fields_ tuple must be a C type, got {0}", PythonTypeOps.GetName(pt[0])); } else if (cdata == type) { throw StructureCannotContainSelf(); } if (cdata is StructType st) { st.EnsureFinal(); } if (pt.Count != 3) { bitCount = null; } else { bitCount = CheckBits(cdata, pt); } } /// <summary> /// Verifies that the provided bit field settings are valid for this type. /// </summary> private static int CheckBits(INativeType cdata, PythonTuple pt) { int bitCount = Converter.ConvertToInt32(pt[2]); if (!(cdata is SimpleType simpType)) { throw PythonOps.TypeError("bit fields not allowed for type {0}", ((PythonType)cdata).Name); } switch (simpType._type) { case SimpleTypeKind.Object: case SimpleTypeKind.Pointer: case SimpleTypeKind.Single: case SimpleTypeKind.Double: case SimpleTypeKind.Char: case SimpleTypeKind.CharPointer: case SimpleTypeKind.WChar: case SimpleTypeKind.WCharPointer: throw PythonOps.TypeError("bit fields not allowed for type {0}", ((PythonType)cdata).Name); } if (bitCount <= 0 || bitCount > cdata.Size * 8) { throw PythonOps.ValueError("number of bits invalid for bit field"); } return bitCount; } /// <summary> /// Shared helper to get the _fields_ list for struct/union and validate it. /// </summary> private static IList<object>/*!*/ GetFieldsList(object fields) { if (!(fields is IList<object> list)) { throw PythonOps.TypeError("class must be a sequence of pairs"); } return list; } private static Exception StructureCannotContainSelf() { return PythonOps.AttributeError("Structure or union cannot contain itself"); } /// <summary> /// Helper function for translating from memset to NT's FillMemory API. /// </summary> private static IntPtr StringAt(IntPtr src, int len) { string res; if (len == -1) { res = MemoryHolder.ReadAnsiString(src, 0); } else { res = MemoryHolder.ReadAnsiString(src, 0, len); } return GCHandle.ToIntPtr(GCHandle.Alloc(res)); } /// <summary> /// Helper function for translating from memset to NT's FillMemory API. /// </summary> private static IntPtr WStringAt(IntPtr src, int len) { string res; if (len == -1) { res = Marshal.PtrToStringUni(src); } else { res = Marshal.PtrToStringUni(src, len); } return GCHandle.ToIntPtr(GCHandle.Alloc(res)); } private static IntPtr GetHandleFromObject(object dll, string errorMsg) { IntPtr intPtrHandle; object dllHandle = PythonOps.GetBoundAttr(DefaultContext.Default, dll, "_handle"); if (!Converter.TryConvertToBigInteger(dllHandle, out BigInteger intHandle)) { throw PythonOps.TypeError(errorMsg); } intPtrHandle = new IntPtr((long)intHandle); return intPtrHandle; } private static void ValidateArraySizes(ArrayModule.array array, int offset, int size) { ValidateArraySizes(array.__len__() * array.itemsize, offset, size); } private static void ValidateArraySizes(Bytes bytes, int offset, int size) { ValidateArraySizes(bytes.Count, offset, size); } private static void ValidateArraySizes(string data, int offset, int size) { ValidateArraySizes(data.Length, offset, size); } private static void ValidateArraySizes(int arraySize, int offset, int size) { if (offset < 0) { throw PythonOps.ValueError("offset cannot be negative"); } else if (arraySize < size + offset) { throw PythonOps.ValueError($"Buffer size too small ({arraySize} instead of at least {size} bytes)"); } } private static void ValidateArraySizes(BigInteger arraySize, int offset, int size) { if (offset < 0) { throw PythonOps.ValueError("offset cannot be negative"); } else if (arraySize < size + offset) { throw PythonOps.ValueError($"Buffer size too small ({arraySize} instead of at least {size} bytes)"); } } // TODO: Move these to an Ops class public static object GetCharArrayValue(_Array arr) { return arr.NativeType.GetValue(arr._memHolder, arr, 0, false); } public static void SetCharArrayValue(_Array arr, object value) { if (value is PythonBuffer buf && buf._object is string) { value = buf.ToString(); } arr.NativeType.SetValue(arr._memHolder, 0, value); } public static void DeleteCharArrayValue(_Array arr) { throw PythonOps.TypeError("cannot delete char array value"); } public static object GetWCharArrayValue(_Array arr) { return arr.NativeType.GetValue(arr._memHolder, arr, 0, false); } public static void SetWCharArrayValue(_Array arr, object value) { arr.NativeType.SetValue(arr._memHolder, 0, value); } public static object DeleteWCharArrayValue(_Array arr) { throw PythonOps.TypeError("cannot delete wchar array value"); } public static object GetWCharArrayRaw(_Array arr) { return ((ArrayType)arr.NativeType).GetRawValue(arr._memHolder, 0); } public static void SetWCharArrayRaw(_Array arr, object value) { PythonBuffer buf = value as PythonBuffer; if (buf != null && (buf._object is string || buf._object is Bytes)) { value = buf.ToString(); } MemoryView view = value as MemoryView; if ((object)view != null) { string strVal = view.tobytes().ToString(); if (strVal.Length > arr.__len__()) { throw PythonOps.ValueError("string too long"); } value = strVal; } arr.NativeType.SetValue(arr._memHolder, 0, value); } public static object DeleteWCharArrayRaw(_Array arr) { throw PythonOps.AttributeError("cannot delete wchar array raw"); } class RefCountInfo { public int RefCount; public GCHandle Handle; } /// <summary> /// Emits the marshalling code to create a CData object for reverse marshalling. /// </summary> private static void EmitCDataCreation(INativeType type, ILGenerator method, List<object> constantPool, int constantPoolArgument) { LocalBuilder locVal = method.DeclareLocal(type.GetNativeType()); method.Emit(OpCodes.Stloc, locVal); method.Emit(OpCodes.Ldloca, locVal); constantPool.Add(type); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CreateCData")); } private static void EnsureRefCountTable() { if (_refCountTable == null) { Interlocked.CompareExchange(ref _refCountTable, new Dictionary<object, RefCountInfo>(), null); } } #endregion [PythonHidden, PythonType("COMError"), DynamicBaseType] public class _COMError : PythonExceptions.BaseException { public _COMError(PythonType cls) : base(cls) { } public override void __init__(params object[] args) { base.__init__(args); if (args.Length < 3) { throw PythonOps.TypeError($"COMError() takes exactly 4 arguments({args.Length} given)"); } hresult = args[0]; text = args[1]; details = args[2]; } public object hresult { get; set; } public object text { get; set; } public object details { get; set; } } } } #endif
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL 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. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Collections; using System.Collections.Specialized; using System.Threading; using fyiReporting.RDL; namespace fyiReporting.RDL { ///<summary> /// A report expression: includes original source, parsed expression and type information. ///</summary> [Serializable] internal class DynamicExpression: IExpr { string _Source; // source of expression IExpr _Expr; // expression after parse TypeCode _Type; ReportLink _rl; internal DynamicExpression(Report rpt, ReportLink p, string expr, Row row) { _Source=expr; _Expr = null; _rl = p; _Type = DoParse(rpt); } internal TypeCode DoParse(Report rpt) { // optimization: avoid expression overhead if this isn't really an expression if (_Source == null) { _Expr = new Constant(""); return _Expr.GetTypeCode(); } else if (_Source == string.Empty || // empty expression _Source[0] != '=') // if 1st char not '=' { _Expr = new Constant(_Source); // this is a constant value return _Expr.GetTypeCode(); } Parser p = new Parser(new System.Collections.Generic.List<ICacheData>()); // find the fields that are part of the DataRegion (if there is one) IDictionary fields=null; ReportLink dr = _rl.Parent; Grouping grp= null; // remember if in a table group or detail group or list group Matrix m=null; while (dr != null) { if (dr is Grouping) p.NoAggregateFunctions = true; else if (dr is TableGroup) grp = ((TableGroup) dr).Grouping; else if (dr is Matrix) { m = (Matrix) dr; // if matrix we need to pass special break; } else if (dr is Details) { grp = ((Details) dr).Grouping; } else if (dr is List) { grp = ((List) dr).Grouping; break; } else if (dr is DataRegion || dr is DataSetDefn) break; dr = dr.Parent; } if (dr != null) { if (dr is DataSetDefn) { DataSetDefn d = (DataSetDefn) dr; if (d.Fields != null) fields = d.Fields.Items; } else // must be a DataRegion { DataRegion d = (DataRegion) dr; if (d.DataSetDefn != null && d.DataSetDefn.Fields != null) fields = d.DataSetDefn.Fields.Items; } } NameLookup lu = new NameLookup(fields, rpt.ReportDefinition.LUReportParameters, rpt.ReportDefinition.LUReportItems, rpt.ReportDefinition.LUGlobals, rpt.ReportDefinition.LUUser, rpt.ReportDefinition.LUAggrScope, grp, m, rpt.ReportDefinition.CodeModules, rpt.ReportDefinition.Classes, rpt.ReportDefinition.DataSetsDefn, rpt.ReportDefinition.CodeType); try { _Expr = p.Parse(lu, _Source); } catch (Exception e) { _Expr = new ConstantError(e.Message); // Invalid expression rpt.rl.LogError(8, ErrorText(e.Message)); } // Optimize removing any expression that always result in a constant try { _Expr = _Expr.ConstantOptimization(); } catch(Exception ex) { rpt.rl.LogError(4, "Expression:" + _Source + "\r\nConstant Optimization exception:\r\n" + ex.Message + "\r\nStack trace:\r\n" + ex.StackTrace ); } return _Expr.GetTypeCode(); } private string ErrorText(string msg) { ReportLink rl = _rl.Parent; while (rl != null) { if (rl is ReportItem) break; rl = rl.Parent; } string prefix="Expression"; if (rl != null) { ReportItem ri = rl as ReportItem; if (ri.Name != null) prefix = ri.Name.Nm + " expression"; } return prefix + " '" + _Source + "' failed to parse: " + msg; } private void ReportError(Report rpt, int severity, string err) { rpt.rl.LogError(severity, err); } internal string Source { get { return _Source; } } internal IExpr Expr { get { return _Expr; } } internal TypeCode Type { get { return _Type; } } #region IExpr Members public System.TypeCode GetTypeCode() { return _Expr.GetTypeCode(); } public bool IsConstant() { return _Expr.IsConstant(); } public IExpr ConstantOptimization() { return this; } public object Evaluate(Report rpt, Row row) { try { return _Expr.Evaluate(rpt, row); } catch (Exception e) { string err; if (e.InnerException != null) err = String.Format("Exception evaluating {0}. {1}. {2}", _Source, e.Message, e.InnerException.Message); else err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return null; } } public string EvaluateString(Report rpt, Row row) { try { return _Expr.EvaluateString(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return null; } } public double EvaluateDouble(Report rpt, Row row) { try { return _Expr.EvaluateDouble(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return double.NaN; } } public decimal EvaluateDecimal(Report rpt, Row row) { try { return _Expr.EvaluateDecimal(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return decimal.MinValue; } } public int EvaluateInt32(Report rpt, Row row) { try { return _Expr.EvaluateInt32(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return int.MinValue; } } public DateTime EvaluateDateTime(Report rpt, Row row) { try { return _Expr.EvaluateDateTime(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return DateTime.MinValue; } } public bool EvaluateBoolean(Report rpt, Row row) { try { return _Expr.EvaluateBoolean(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return false; } } #endregion } }
using Microsoft.EntityFrameworkCore; using Neo.Cryptography; using Neo.IO; using Neo.SmartContract; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security; using System.Security.Cryptography; namespace Neo.Wallets.SQLite { public class UserWallet : Wallet { private readonly object db_lock = new object(); private readonly string path; private readonly byte[] iv; private readonly byte[] masterKey; private readonly Dictionary<UInt160, UserWalletAccount> accounts; public override string Name => Path.GetFileNameWithoutExtension(path); public override Version Version { get { byte[] buffer = LoadStoredData("Version"); if (buffer == null || buffer.Length < 16) return new Version(0, 0); int major = buffer.ToInt32(0); int minor = buffer.ToInt32(4); int build = buffer.ToInt32(8); int revision = buffer.ToInt32(12); return new Version(major, minor, build, revision); } } private UserWallet(string path, byte[] passwordKey, bool create) { this.path = path; if (create) { this.iv = new byte[16]; this.masterKey = new byte[32]; this.accounts = new Dictionary<UInt160, UserWalletAccount>(); using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(iv); rng.GetBytes(masterKey); } Version version = Assembly.GetExecutingAssembly().GetName().Version; BuildDatabase(); SaveStoredData("PasswordHash", passwordKey.Sha256()); SaveStoredData("IV", iv); SaveStoredData("MasterKey", masterKey.AesEncrypt(passwordKey, iv)); SaveStoredData("Version", new[] { version.Major, version.Minor, version.Build, version.Revision }.Select(p => BitConverter.GetBytes(p)).SelectMany(p => p).ToArray()); } else { byte[] passwordHash = LoadStoredData("PasswordHash"); if (passwordHash != null && !passwordHash.SequenceEqual(passwordKey.Sha256())) throw new CryptographicException(); this.iv = LoadStoredData("IV"); this.masterKey = LoadStoredData("MasterKey").AesDecrypt(passwordKey, iv); this.accounts = LoadAccounts(); } } private void AddAccount(UserWalletAccount account, bool is_import) { lock (accounts) { if (accounts.TryGetValue(account.ScriptHash, out UserWalletAccount account_old)) { if (account.Contract == null) { account.Contract = account_old.Contract; } } accounts[account.ScriptHash] = account; } lock (db_lock) using (WalletDataContext ctx = new WalletDataContext(path)) { if (account.HasKey) { byte[] decryptedPrivateKey = new byte[96]; Buffer.BlockCopy(account.Key.PublicKey.EncodePoint(false), 1, decryptedPrivateKey, 0, 64); Buffer.BlockCopy(account.Key.PrivateKey, 0, decryptedPrivateKey, 64, 32); byte[] encryptedPrivateKey = EncryptPrivateKey(decryptedPrivateKey); Array.Clear(decryptedPrivateKey, 0, decryptedPrivateKey.Length); Account db_account = ctx.Accounts.FirstOrDefault(p => p.PublicKeyHash == account.Key.PublicKeyHash.ToArray()); if (db_account == null) { db_account = ctx.Accounts.Add(new Account { PrivateKeyEncrypted = encryptedPrivateKey, PublicKeyHash = account.Key.PublicKeyHash.ToArray() }).Entity; } else { db_account.PrivateKeyEncrypted = encryptedPrivateKey; } } if (account.Contract != null) { Contract db_contract = ctx.Contracts.FirstOrDefault(p => p.ScriptHash == account.Contract.ScriptHash.ToArray()); if (db_contract != null) { db_contract.PublicKeyHash = account.Key.PublicKeyHash.ToArray(); } else { ctx.Contracts.Add(new Contract { RawData = ((VerificationContract)account.Contract).ToArray(), ScriptHash = account.Contract.ScriptHash.ToArray(), PublicKeyHash = account.Key.PublicKeyHash.ToArray() }); } } //add address { Address db_address = ctx.Addresses.FirstOrDefault(p => p.ScriptHash == account.ScriptHash.ToArray()); if (db_address == null) { ctx.Addresses.Add(new Address { ScriptHash = account.ScriptHash.ToArray() }); } } ctx.SaveChanges(); } } private void BuildDatabase() { using (WalletDataContext ctx = new WalletDataContext(path)) { ctx.Database.EnsureDeleted(); ctx.Database.EnsureCreated(); } } public bool ChangePassword(string password_old, string password_new) { if (!VerifyPassword(password_old)) return false; byte[] passwordKey = password_new.ToAesKey(); try { SaveStoredData("PasswordHash", passwordKey.Sha256()); SaveStoredData("MasterKey", masterKey.AesEncrypt(passwordKey, iv)); return true; } finally { Array.Clear(passwordKey, 0, passwordKey.Length); } } public override bool Contains(UInt160 scriptHash) { lock (accounts) { return accounts.ContainsKey(scriptHash); } } public static UserWallet Create(string path, string password) { return new UserWallet(path, password.ToAesKey(), true); } public static UserWallet Create(string path, SecureString password) { return new UserWallet(path, password.ToAesKey(), true); } public override WalletAccount CreateAccount(byte[] privateKey) { KeyPair key = new KeyPair(privateKey); VerificationContract contract = new VerificationContract { Script = SmartContract.Contract.CreateSignatureRedeemScript(key.PublicKey), ParameterList = new[] { ContractParameterType.Signature } }; UserWalletAccount account = new UserWalletAccount(contract.ScriptHash) { Key = key, Contract = contract }; AddAccount(account, false); return account; } public override WalletAccount CreateAccount(SmartContract.Contract contract, KeyPair key = null) { VerificationContract verification_contract = contract as VerificationContract; if (verification_contract == null) { verification_contract = new VerificationContract { Script = contract.Script, ParameterList = contract.ParameterList }; } UserWalletAccount account = new UserWalletAccount(verification_contract.ScriptHash) { Key = key, Contract = verification_contract }; AddAccount(account, false); return account; } public override WalletAccount CreateAccount(UInt160 scriptHash) { UserWalletAccount account = new UserWalletAccount(scriptHash); AddAccount(account, true); return account; } private byte[] DecryptPrivateKey(byte[] encryptedPrivateKey) { if (encryptedPrivateKey == null) throw new ArgumentNullException(nameof(encryptedPrivateKey)); if (encryptedPrivateKey.Length != 96) throw new ArgumentException(); return encryptedPrivateKey.AesDecrypt(masterKey, iv); } public override bool DeleteAccount(UInt160 scriptHash) { UserWalletAccount account; lock (accounts) { if (accounts.TryGetValue(scriptHash, out account)) accounts.Remove(scriptHash); } if (account != null) { lock (db_lock) using (WalletDataContext ctx = new WalletDataContext(path)) { if (account.HasKey) { Account db_account = ctx.Accounts.First(p => p.PublicKeyHash == account.Key.PublicKeyHash.ToArray()); ctx.Accounts.Remove(db_account); } if (account.Contract != null) { Contract db_contract = ctx.Contracts.First(p => p.ScriptHash == scriptHash.ToArray()); ctx.Contracts.Remove(db_contract); } //delete address { Address db_address = ctx.Addresses.First(p => p.ScriptHash == scriptHash.ToArray()); ctx.Addresses.Remove(db_address); } ctx.SaveChanges(); } return true; } return false; } private byte[] EncryptPrivateKey(byte[] decryptedPrivateKey) { return decryptedPrivateKey.AesEncrypt(masterKey, iv); } public override WalletAccount GetAccount(UInt160 scriptHash) { lock (accounts) { accounts.TryGetValue(scriptHash, out UserWalletAccount account); return account; } } public override IEnumerable<WalletAccount> GetAccounts() { lock (accounts) { foreach (UserWalletAccount account in accounts.Values) yield return account; } } private Dictionary<UInt160, UserWalletAccount> LoadAccounts() { using (WalletDataContext ctx = new WalletDataContext(path)) { Dictionary<UInt160, UserWalletAccount> accounts = ctx.Addresses.Select(p => p.ScriptHash).AsEnumerable().Select(p => new UserWalletAccount(new UInt160(p))).ToDictionary(p => p.ScriptHash); foreach (Contract db_contract in ctx.Contracts.Include(p => p.Account)) { VerificationContract contract = db_contract.RawData.AsSerializable<VerificationContract>(); UserWalletAccount account = accounts[contract.ScriptHash]; account.Contract = contract; account.Key = new KeyPair(DecryptPrivateKey(db_contract.Account.PrivateKeyEncrypted)); } return accounts; } } private byte[] LoadStoredData(string name) { using (WalletDataContext ctx = new WalletDataContext(path)) { return ctx.Keys.FirstOrDefault(p => p.Name == name)?.Value; } } public static UserWallet Open(string path, string password) { return new UserWallet(path, password.ToAesKey(), false); } public static UserWallet Open(string path, SecureString password) { return new UserWallet(path, password.ToAesKey(), false); } private void SaveStoredData(string name, byte[] value) { lock (db_lock) using (WalletDataContext ctx = new WalletDataContext(path)) { SaveStoredData(ctx, name, value); ctx.SaveChanges(); } } private static void SaveStoredData(WalletDataContext ctx, string name, byte[] value) { Key key = ctx.Keys.FirstOrDefault(p => p.Name == name); if (key == null) { ctx.Keys.Add(new Key { Name = name, Value = value }); } else { key.Value = value; } } public override bool VerifyPassword(string password) { return password.ToAesKey().Sha256().SequenceEqual(LoadStoredData("PasswordHash")); } } }
// 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.Linq; using System.Reflection; using Xunit; namespace System.Tests { public static partial class AttributeTests { [Fact] public static void DefaultEquality() { var a1 = new ParentAttribute { Prop = 1 }; var a2 = new ParentAttribute { Prop = 42 }; var a3 = new ParentAttribute { Prop = 1 }; var d1 = new ChildAttribute { Prop = 1 }; var d2 = new ChildAttribute { Prop = 42 }; var d3 = new ChildAttribute { Prop = 1 }; var s1 = new GrandchildAttribute { Prop = 1 }; var s2 = new GrandchildAttribute { Prop = 42 }; var s3 = new GrandchildAttribute { Prop = 1 }; var f1 = new ChildAttributeWithField { Prop = 1 }; var f2 = new ChildAttributeWithField { Prop = 42 }; var f3 = new ChildAttributeWithField { Prop = 1 }; Assert.NotEqual(a1, a2); Assert.NotEqual(a2, a3); Assert.Equal(a1, a3); // The implementation of Attribute.Equals uses reflection to // enumerate fields. On .NET core, we add `BindingFlags.DeclaredOnly` // to fix a bug where an instance of a subclass of an attribute can // be equal to an instance of the parent class. // See https://github.com/dotnet/coreclr/pull/6240 Assert.Equal(PlatformDetection.IsFullFramework, d1.Equals(d2)); Assert.Equal(PlatformDetection.IsFullFramework, d2.Equals(d3)); Assert.Equal(d1, d3); Assert.Equal(PlatformDetection.IsFullFramework, s1.Equals(s2)); Assert.Equal(PlatformDetection.IsFullFramework, s2.Equals(s3)); Assert.Equal(s1, s3); Assert.Equal(PlatformDetection.IsFullFramework, f1.Equals(f2)); Assert.Equal(PlatformDetection.IsFullFramework, f2.Equals(f3)); Assert.Equal(f1, f3); Assert.NotEqual(d1, a1); Assert.NotEqual(d2, a2); Assert.NotEqual(d3, a3); Assert.NotEqual(d1, a3); Assert.NotEqual(d3, a1); Assert.NotEqual(d1, s1); Assert.NotEqual(d2, s2); Assert.NotEqual(d3, s3); Assert.NotEqual(d1, s3); Assert.NotEqual(d3, s1); Assert.NotEqual(f1, a1); Assert.NotEqual(f2, a2); Assert.NotEqual(f3, a3); Assert.NotEqual(f1, a3); Assert.NotEqual(f3, a1); } [Fact] public static void DefaultHashCode() { var a1 = new ParentAttribute { Prop = 1 }; var a2 = new ParentAttribute { Prop = 42 }; var a3 = new ParentAttribute { Prop = 1 }; var d1 = new ChildAttribute { Prop = 1 }; var d2 = new ChildAttribute { Prop = 42 }; var d3 = new ChildAttribute { Prop = 1 }; var s1 = new GrandchildAttribute { Prop = 1 }; var s2 = new GrandchildAttribute { Prop = 42 }; var s3 = new GrandchildAttribute { Prop = 1 }; var f1 = new ChildAttributeWithField { Prop = 1 }; var f2 = new ChildAttributeWithField { Prop = 42 }; var f3 = new ChildAttributeWithField { Prop = 1 }; Assert.NotEqual(a1.GetHashCode(), 0); Assert.NotEqual(a2.GetHashCode(), 0); Assert.NotEqual(a3.GetHashCode(), 0); Assert.NotEqual(d1.GetHashCode(), 0); Assert.NotEqual(d2.GetHashCode(), 0); Assert.NotEqual(d3.GetHashCode(), 0); Assert.NotEqual(s1.GetHashCode(), 0); Assert.NotEqual(s2.GetHashCode(), 0); Assert.NotEqual(s3.GetHashCode(), 0); Assert.Equal(f1.GetHashCode(), 0); Assert.Equal(f2.GetHashCode(), 0); Assert.Equal(f3.GetHashCode(), 0); Assert.NotEqual(a1.GetHashCode(), a2.GetHashCode()); Assert.NotEqual(a2.GetHashCode(), a3.GetHashCode()); Assert.Equal(a1.GetHashCode(), a3.GetHashCode()); // The implementation of Attribute.GetHashCode uses reflection to // enumerate fields. On .NET core, we add `BindingFlags.DeclaredOnly` // to fix a bug where the hash code of a a subclass of an attribute can // be equal to an instance of the parent class. // See https://github.com/dotnet/coreclr/pull/6240 Assert.Equal(PlatformDetection.IsFullFramework, s1.GetHashCode().Equals(s2.GetHashCode())); Assert.Equal(PlatformDetection.IsFullFramework, s2.GetHashCode().Equals(s3.GetHashCode())); Assert.Equal(s1.GetHashCode(), s3.GetHashCode()); Assert.Equal(PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(d2.GetHashCode())); Assert.Equal(PlatformDetection.IsFullFramework, d2.GetHashCode().Equals(d3.GetHashCode())); Assert.Equal(d1.GetHashCode(), d3.GetHashCode()); Assert.Equal(f1.GetHashCode(), f2.GetHashCode()); Assert.Equal(f2.GetHashCode(), f3.GetHashCode()); Assert.Equal(f1.GetHashCode(), f3.GetHashCode()); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(a1.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d2.GetHashCode().Equals(a2.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(a3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(a3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(a1.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(s1.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d2.GetHashCode().Equals(s2.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(s3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d1.GetHashCode().Equals(s3.GetHashCode())); Assert.Equal(!PlatformDetection.IsFullFramework, d3.GetHashCode().Equals(s1.GetHashCode())); Assert.NotEqual(f1.GetHashCode(), a1.GetHashCode()); Assert.NotEqual(f2.GetHashCode(), a2.GetHashCode()); Assert.NotEqual(f3.GetHashCode(), a3.GetHashCode()); Assert.NotEqual(f1.GetHashCode(), a3.GetHashCode()); Assert.NotEqual(f3.GetHashCode(), a1.GetHashCode()); } class ParentAttribute : Attribute { public int Prop {get;set;} } class ChildAttribute : ParentAttribute { } class GrandchildAttribute : ChildAttribute { } class ChildAttributeWithField : ParentAttribute { public int Field = 0; } [Fact] [StringValue("\uDFFF")] public static void StringArgument_InvalidCodeUnits_FallbackUsed() { MethodInfo thisMethod = typeof(AttributeTests).GetTypeInfo().GetDeclaredMethod("StringArgument_InvalidCodeUnits_FallbackUsed"); Assert.NotNull(thisMethod); CustomAttributeData cad = thisMethod.CustomAttributes.Where(ca => ca.AttributeType == typeof(StringValueAttribute)).FirstOrDefault(); Assert.NotNull(cad); string stringArg = cad.ConstructorArguments[0].Value as string; Assert.NotNull(stringArg); Assert.Equal("\uFFFD\uFFFD", stringArg); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new StringValueAttribute("hello"), new StringValueAttribute("hello"), true, true }; yield return new object[] { new StringValueAttribute("hello"), new StringValueAttribute("foo"), false, false }; yield return new object[] { new StringValueIntValueAttribute("hello", 1), new StringValueIntValueAttribute("hello", 1), true, true }; yield return new object[] { new StringValueIntValueAttribute("hello", 1), new StringValueIntValueAttribute("hello", 2), false, true }; // GetHashCode() ignores the int value yield return new object[] { new EmptyAttribute(), new EmptyAttribute(), true, true }; yield return new object[] { new StringValueAttribute("hello"), new StringValueIntValueAttribute("hello", 1), false, true }; // GetHashCode() ignores the int value yield return new object[] { new StringValueAttribute("hello"), "hello", false, false }; yield return new object[] { new StringValueAttribute("hello"), null, false, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void Equals(Attribute attr1, object obj, bool expected, bool hashEqualityExpected) { Assert.Equal(expected, attr1.Equals(obj)); Attribute attr2 = obj as Attribute; if (attr2 != null) { Assert.Equal(hashEqualityExpected, attr1.GetHashCode() == attr2.GetHashCode()); } } [AttributeUsage(AttributeTargets.Method)] private sealed class StringValueAttribute : Attribute { public string StringValue; public StringValueAttribute(string stringValue) { StringValue = stringValue; } } private sealed class StringValueIntValueAttribute : Attribute { public string StringValue; private int IntValue; public StringValueIntValueAttribute(string stringValue, int intValue) { StringValue = stringValue; IntValue = intValue; } } [AttributeUsage(AttributeTargets.Method)] private sealed class EmptyAttribute : Attribute { } [Fact] public static void ValidateDefaults() { StringValueAttribute sav = new StringValueAttribute("test"); Assert.Equal(false, sav.IsDefaultAttribute()); Assert.Equal(sav.GetType(), sav.TypeId); Assert.Equal(true, sav.Match(sav)); } } }
//------------------------------------------------------------------------------ // <copyright file="GenericWebPart.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls.WebParts { using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Util; /// <devdoc> /// A WebPart that can wrap any other generic server control, and provide it /// with "WebPart-ness." /// 1. Implements several properties if not set on the WebPart by looking for an /// attribute on the contained control. /// 2. Implement IWebEditable to allow the PropertyGridEditorPart to tunnel-in /// and browse the contained control. /// </devdoc> [ ToolboxItem(false) ] public class GenericWebPart : WebPart { internal const string IDPrefix = "gwp"; private Control _childControl; private IWebPart _childIWebPart; private string _subtitle; /// <devdoc> /// Intializes an instance of GenericWebPart with the control it is to wrap. /// </devdoc> protected internal GenericWebPart(Control control) { if (control == null) { throw new ArgumentNullException("control"); } if (control is WebPart) { throw new ArgumentException(SR.GetString(SR.GenericWebPart_CannotWrapWebPart), "control"); } if (control is BasePartialCachingControl) { throw new ArgumentException(SR.GetString(SR.GenericWebPart_CannotWrapOutputCachedControl), "control"); } if (String.IsNullOrEmpty(control.ID)) { throw new ArgumentException(SR.GetString(SR.GenericWebPart_NoID, control.GetType().FullName)); } ID = IDPrefix + control.ID; _childControl = control; _childIWebPart = _childControl as IWebPart; CopyChildAttributes(); } public override string CatalogIconImageUrl { get { if (_childIWebPart != null) { return _childIWebPart.CatalogIconImageUrl; } else { return base.CatalogIconImageUrl; } } set { if (_childIWebPart != null) { _childIWebPart.CatalogIconImageUrl = value; } else { base.CatalogIconImageUrl = value; } } } public Control ChildControl { get { Debug.Assert(_childControl != null, "ChildControl cannot be null."); return _childControl; } } public override string Description { get { if (_childIWebPart != null) { return _childIWebPart.Description; } else { return base.Description; } } set { if (_childIWebPart != null) { _childIWebPart.Description = value; } else { base.Description = value; } } } public override Unit Height { get { WebControl c = ChildControl as WebControl; if (c != null) { return c.Height; } else { return base.Height; } } set { WebControl c = ChildControl as WebControl; if (c != null) { c.Height = value; } else { base.Height = value; } } } // Seal the ID property so we can set it in the constructor without an FxCop violation. public sealed override string ID { get { return base.ID; } set { base.ID = value; } } public override string Subtitle { get { if (_childIWebPart != null) { return _childIWebPart.Subtitle; } else { return (_subtitle != null ? _subtitle : String.Empty); } } } public override string Title { get { if (_childIWebPart != null) { return _childIWebPart.Title; } else { return base.Title; } } set { if (_childIWebPart != null) { _childIWebPart.Title = value; } else { base.Title = value; } } } public override string TitleIconImageUrl { get { if (_childIWebPart != null) { return _childIWebPart.TitleIconImageUrl; } else { return base.TitleIconImageUrl; } } set { if (_childIWebPart != null) { _childIWebPart.TitleIconImageUrl = value; } else { base.TitleIconImageUrl = value; } } } public override string TitleUrl { get { if (_childIWebPart != null) { return _childIWebPart.TitleUrl; } else { return base.TitleUrl; } } set { if (_childIWebPart != null) { _childIWebPart.TitleUrl = value; } else { base.TitleUrl = value; } } } public override WebPartVerbCollection Verbs { get { if (ChildControl != null) { IWebActionable webActionableChildControl = ChildControl as IWebActionable; if (webActionableChildControl != null) { return new WebPartVerbCollection(base.Verbs, webActionableChildControl.Verbs); } } return base.Verbs; } } public override object WebBrowsableObject { get { IWebEditable webEditableChildControl = ChildControl as IWebEditable; if (webEditableChildControl != null) { return webEditableChildControl.WebBrowsableObject; } else { return ChildControl; } } } public override Unit Width { get { WebControl c = ChildControl as WebControl; if (c != null) { return c.Width; } else { return base.Width; } } set { WebControl c = ChildControl as WebControl; if (c != null) { c.Width = value; } else { base.Width = value; } } } private void CopyChildAttributes() { // Copy the attribute values from the ChildControl to the GenericWebPart properties. IAttributeAccessor childAttributeAccessor = ChildControl as IAttributeAccessor; if (childAttributeAccessor != null) { base.AuthorizationFilter = childAttributeAccessor.GetAttribute("AuthorizationFilter"); base.CatalogIconImageUrl = childAttributeAccessor.GetAttribute("CatalogIconImageUrl"); base.Description = childAttributeAccessor.GetAttribute("Description"); string exportMode = childAttributeAccessor.GetAttribute("ExportMode"); if (exportMode != null) { base.ExportMode = (WebPartExportMode)(Util.GetEnumAttribute( "ExportMode", exportMode, typeof(WebPartExportMode))); } // Don't need to check base.Subtitle, since we always want to use the Subtitle on the // ChildControl if it is present. Also, the property is not settable on WebPart, so we // know that base.Subtitle will always be String.Empty. _subtitle = childAttributeAccessor.GetAttribute("Subtitle"); base.Title = childAttributeAccessor.GetAttribute("Title"); base.TitleIconImageUrl = childAttributeAccessor.GetAttribute("TitleIconImageUrl"); base.TitleUrl = childAttributeAccessor.GetAttribute("TitleUrl"); } // Remove all the attributes from the ChildControl, whether or not they were copied // to the GenericWebPart property. We want to remove the attributes so they are not // rendered on the ChildControl. (VSWhidbey 313674) WebControl childWebControl = ChildControl as WebControl; if (childWebControl != null) { // If the ChildControl is a WebControl, we want to completely remove the attributes. childWebControl.Attributes.Remove("AuthorizationFilter"); childWebControl.Attributes.Remove("CatalogIconImageUrl"); childWebControl.Attributes.Remove("Description"); childWebControl.Attributes.Remove("ExportMode"); childWebControl.Attributes.Remove("Subtitle"); childWebControl.Attributes.Remove("Title"); childWebControl.Attributes.Remove("TitleIconImageUrl"); childWebControl.Attributes.Remove("TitleUrl"); } else if (childAttributeAccessor != null) { // If the ChildControl is not a WebControl, we cannot remove the attributes, so we set // them to null instead. childAttributeAccessor.SetAttribute("AuthorizationFilter", null); childAttributeAccessor.SetAttribute("CatalogIconImageUrl", null); childAttributeAccessor.SetAttribute("Description", null); childAttributeAccessor.SetAttribute("ExportMode", null); childAttributeAccessor.SetAttribute("Subtitle", null); childAttributeAccessor.SetAttribute("Title", null); childAttributeAccessor.SetAttribute("TitleIconImageUrl", null); childAttributeAccessor.SetAttribute("TitleUrl", null); } } protected internal override void CreateChildControls() { ((GenericWebPartControlCollection)Controls).AddGenericControl(ChildControl); } protected override ControlCollection CreateControlCollection() { return new GenericWebPartControlCollection(this); } public override EditorPartCollection CreateEditorParts() { IWebEditable webEditableChildControl = ChildControl as IWebEditable; if (webEditableChildControl != null) { return new EditorPartCollection(base.CreateEditorParts(), webEditableChildControl.CreateEditorParts()); } else { return base.CreateEditorParts(); } } protected internal override void Render(HtmlTextWriter writer) { // Copied from CompositeControl.Render() if (DesignMode) { EnsureChildControls(); } RenderContents(writer); } private sealed class GenericWebPartControlCollection : ControlCollection { public GenericWebPartControlCollection(GenericWebPart owner) : base(owner) { SetCollectionReadOnly(SR.GenericWebPart_CannotModify); } /// <devdoc> /// Allows adding the generic control to be wrapped. /// </devdoc> public void AddGenericControl(Control control) { string originalError = SetCollectionReadOnly(null); // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { Clear(); Add(control); } finally { SetCollectionReadOnly(originalError); } } catch { throw; } } } } }
using System.Diagnostics; using va_list = System.Object; namespace System.Data.SQLite { public partial class Sqlite3 { /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#if !_OS_COMMON_H_ //#define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #if MEMORY_DEBUG //# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif #if SQLITE_DEBUG || TRACE static bool sqlite3OsTrace = false; //#define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X static void OSTRACE( string X, params va_list[] ap ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, ap ); } #else //#define OSTRACE(X) static void OSTRACE(string X, params object[] ap) { } #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #if SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ //#include "hwtime.h" static sqlite_u3264 g_start; static sqlite_u3264 g_elapsed; //#define TIMER_START g_start=sqlite3Hwtime() //#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start //#define TIMER_ELAPSED g_elapsed #else const int TIMER_START = 0; //#define TIMER_START const int TIMER_END = 0; //#define TIMER_END const int TIMER_ELAPSED = 0; //#define TIMER_ELAPSED ((sqlite_u3264)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if SQLITE_TEST #if !TCLSH static int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ static int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ static int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ static int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ static int sqlite3_io_error_benign = 0; /* True if errors are benign */ static int sqlite3_diskfull_pending = 0; static int sqlite3_diskfull = 0; #else static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_hit = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_hit" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_hardhit = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_hardhit" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_pending = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_pending" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_persist = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_persist" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_benign = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_benign" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_diskfull_pending = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_diskfull_pending" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_diskfull = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_diskfull" ); #endif static void SimulateIOErrorBenign( int X ) { #if !TCLSH sqlite3_io_error_benign = ( X ); #else sqlite3_io_error_benign.iValue = ( X ); #endif } //#define SimulateIOError(CODE) \ // if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ // || sqlite3_io_error_pending-- == 1 ) \ // { local_ioerr(); CODE; } static bool SimulateIOError() { #if !TCLSH if ( ( sqlite3_io_error_persist != 0 && sqlite3_io_error_hit != 0 ) || sqlite3_io_error_pending-- == 1 ) #else if ( ( sqlite3_io_error_persist.iValue != 0 && sqlite3_io_error_hit.iValue != 0 ) || sqlite3_io_error_pending.iValue-- == 1 ) #endif { local_ioerr(); return true; } return false; } static void local_ioerr() { #if TRACE IOTRACE( "IOERR\n" ); #endif #if !TCLSH sqlite3_io_error_hit++; if ( sqlite3_io_error_benign == 0 ) sqlite3_io_error_hardhit++; #else sqlite3_io_error_hit.iValue++; if ( sqlite3_io_error_benign.iValue == 0 ) sqlite3_io_error_hardhit.iValue++; #endif } //#define SimulateDiskfullError(CODE) \ // if( sqlite3_diskfull_pending ){ \ // if( sqlite3_diskfull_pending == 1 ){ \ // local_ioerr(); \ // sqlite3_diskfull = 1; \ // sqlite3_io_error_hit = 1; \ // CODE; \ // }else{ \ // sqlite3_diskfull_pending--; \ // } \ // } static bool SimulateDiskfullError() { #if !TCLSH if ( sqlite3_diskfull_pending != 0 ) { if ( sqlite3_diskfull_pending == 1 ) { #else if ( sqlite3_diskfull_pending.iValue != 0 ) { if ( sqlite3_diskfull_pending.iValue == 1 ) { #endif local_ioerr(); #if !TCLSH sqlite3_diskfull = 1; sqlite3_io_error_hit = 1; #else sqlite3_diskfull.iValue = 1; sqlite3_io_error_hit.iValue = 1; #endif return true; } else { #if !TCLSH sqlite3_diskfull_pending--; #else sqlite3_diskfull_pending.iValue--; #endif } } return false; } #else static bool SimulateIOError() { return false; } //#define SimulateIOErrorBenign(X) static void SimulateIOErrorBenign(int x) { } //#define SimulateIOError(A) //#define SimulateDiskfullError(A) #endif /* ** When testing, keep a count of the number of open files. */ #if SQLITE_TEST #if !TCLSH static int sqlite3_open_file_count = 0; #else static tcl.lang.Var.SQLITE3_GETSET sqlite3_open_file_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_open_file_count" ); #endif static void OpenCounter( int X ) { #if !TCLSH sqlite3_open_file_count += ( X ); #else sqlite3_open_file_count.iValue += ( X ); #endif } #else //#define OpenCounter(X) #endif //#endif //* !_OS_COMMON_H_) */ } }
using Gaming.Game; using Gaming.Graphics; using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.VectorMath; using System; namespace RockBlaster { public class TimedInterpolator { private static System.Diagnostics.Stopwatch runningTime = new System.Diagnostics.Stopwatch(); public enum Repeate { NONE, LOOP, PINGPONG }; public enum InterpolationType { LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT }; private double timeStartedAt; private double numSeconds; private double startValue; private double endValue; private double distance; private Repeate repeateType = Repeate.NONE; private InterpolationType interpolationType = InterpolationType.LINEAR; private bool haveStarted = false; private bool done = false; public TimedInterpolator() { if (!runningTime.IsRunning) { runningTime.Start(); } } public TimedInterpolator(double in_numSeconds, double in_startValue, double in_endValue, Repeate in_repeateType, InterpolationType in_interpolationType) : this() { numSeconds = in_numSeconds; startValue = in_startValue; endValue = in_endValue; distance = endValue - startValue; repeateType = in_repeateType; interpolationType = in_interpolationType; } public void Reset() { done = false; haveStarted = false; } public double GetInterpolatedValue(double compleatedRatio0To1) { switch (interpolationType) { case InterpolationType.LINEAR: return startValue + distance * compleatedRatio0To1; case InterpolationType.EASE_IN: return distance * Math.Pow(compleatedRatio0To1, 3) + startValue; case InterpolationType.EASE_OUT: return distance * (Math.Pow(compleatedRatio0To1 - 1, 3) + 1) + startValue; case InterpolationType.EASE_IN_OUT: if (compleatedRatio0To1 < .5) { return distance / 2 * Math.Pow(compleatedRatio0To1 * 2, 3) + startValue; } else { return distance / 2 * (Math.Pow(compleatedRatio0To1 * 2 - 2, 3) + 2) + startValue; } default: throw new NotImplementedException(); } } public double Read() { if (done) { return endValue; } if (!haveStarted) { timeStartedAt = runningTime.Elapsed.TotalSeconds; haveStarted = true; } double timePassed = runningTime.Elapsed.TotalSeconds - timeStartedAt; double compleatedRatio = timePassed / numSeconds; switch (repeateType) { case Repeate.NONE: if (compleatedRatio > 1) { done = true; return endValue; } return GetInterpolatedValue(compleatedRatio); case Repeate.LOOP: { int compleatedRatioInt = (int)compleatedRatio; compleatedRatio = compleatedRatio - compleatedRatioInt; return GetInterpolatedValue(compleatedRatio); } case Repeate.PINGPONG: { int compleatedRatioInt = (int)compleatedRatio; compleatedRatio = compleatedRatio - compleatedRatioInt; if ((compleatedRatioInt & 1) == 1) { return GetInterpolatedValue(1 - compleatedRatio); } else { return GetInterpolatedValue(compleatedRatio); } } default: throw new NotImplementedException(); } } }; /// <summary> /// Description of MainMenu. /// </summary> public class MainMenu : GuiWidget { public delegate void StartGameEventHandler(GuiWidget button); public event StartGameEventHandler StartGame; public delegate void ShowCreditsEventHandler(GuiWidget button); public event ShowCreditsEventHandler ShowCredits; public delegate void ExitGameEventHandler(GuiWidget button); public event ExitGameEventHandler ExitGame; private TimedInterpolator shipRatio = new TimedInterpolator(1, 1.0 / 8.0, 3.0 / 8.0, TimedInterpolator.Repeate.PINGPONG, TimedInterpolator.InterpolationType.EASE_IN_OUT); private TimedInterpolator planetRatio = new TimedInterpolator(.5, 0, 1, TimedInterpolator.Repeate.LOOP, TimedInterpolator.InterpolationType.LINEAR); public MainMenu(RectangleDouble bounds) { BoundsRelativeToParent = bounds; GameImageSequence startButtonSequence = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "MainMenuStartButton"); Button StartGameButton = new Button(400, 310, new ButtonViewThreeImage(startButtonSequence.GetImageByIndex(0), startButtonSequence.GetImageByIndex(1), startButtonSequence.GetImageByIndex(2))); AddChild(StartGameButton); StartGameButton.Click += new EventHandler(OnStartGameButton); GameImageSequence creditsButtonSequence = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "MainMenuCreditsButton"); Button creditsGameButton = new Button(400, 230, new ButtonViewThreeImage(creditsButtonSequence.GetImageByIndex(0), creditsButtonSequence.GetImageByIndex(1), creditsButtonSequence.GetImageByIndex(2))); AddChild(creditsGameButton); creditsGameButton.Click += new EventHandler(OnShowCreditsButton); GameImageSequence exitButtonSequence = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "MainMenuExitButton"); Button exitGameButton = new Button(400, 170, new ButtonViewThreeImage(exitButtonSequence.GetImageByIndex(0), exitButtonSequence.GetImageByIndex(1), exitButtonSequence.GetImageByIndex(2))); AddChild(exitGameButton); exitGameButton.Click += new EventHandler(OnExitGameButton); } public override void OnDraw(Graphics2D graphics2D) { GameImageSequence menuBackground = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "MainMenuBackground"); graphics2D.Render(menuBackground.GetImageByIndex(0), 0, 0); GameImageSequence planetOnMenu = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "PlanetOnMenu"); graphics2D.Render(planetOnMenu.GetImageByRatio(planetRatio.Read()), 620, 360); GameImageSequence shipOnMenu = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "Player1Ship"); int numFrames = shipOnMenu.NumFrames; double animationRatio0to1 = shipRatio.Read(); double curFrameDouble = (numFrames - 1) * animationRatio0to1; int curFrameInt = shipOnMenu.GetFrameIndexByRatio(animationRatio0to1); double curFrameRemainder = curFrameDouble - curFrameInt; double anglePerFrame = MathHelper.Tau / numFrames; double angleForThisFrame = curFrameRemainder * anglePerFrame; graphics2D.Render(shipOnMenu.GetImageByIndex(curFrameInt), 177, 156, angleForThisFrame, 1, 1); base.OnDraw(graphics2D); } private void OnStartGameButton(object sender, EventArgs mouseEvent) { if (StartGame != null) { StartGame(this); } } private void OnShowCreditsButton(object sender, EventArgs mouseEent) { if (ShowCredits != null) { ShowCredits(this); } } private void OnExitGameButton(object sender, EventArgs mouseEvent) { if (ExitGame != null) { ExitGame(this); } } } }
using System; using System.IO; using System.Reflection; using System.Diagnostics; using System.Threading; using System.Globalization; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace Protobuild { using System.Collections.Generic; using System.IO.Compression; /// <summary> /// The main entry point for Protobuild. This class resides in a library, not an executable, so /// another assembly such as Protobuild or Protobuild.Debug needs to invoke the main method on this /// class. /// </summary> public static class MainClass { /// <summary> /// The entry point for Protobuild. /// </summary> /// <param name="args">The arguments passed in on the command line.</param> public static void Main(string workingDirectory, string[] args) { // Ensure we always use the invariant culture in Protobuild. Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // Set our SSL trust policy. Because Mono doesn't ship with root certificates // on most Linux distributions, we have to be a little more insecure here than // I'd like. For protobuild.org we always verify that the root of the certificate // chain matches what we expect (so people can't forge a certificate from a // *different CA*), but for other domains we just have to implicitly trust them // on Linux since we have no root store. if (Path.DirectorySeparatorChar == '/' && !Directory.Exists("/Library")) { ServicePointManager.ServerCertificateValidationCallback = SSLValidationForLinux; } var kernel = new LightweightKernel(); kernel.BindCore(); kernel.BindBuildResources(); kernel.BindGeneration(); kernel.BindJSIL(); kernel.BindTargets(); kernel.BindFileFilter(); kernel.BindPackages(); kernel.BindAutomatedBuild(); var featureManager = kernel.Get<IFeatureManager>(); featureManager.LoadFeaturesFromDirectory(workingDirectory); var commandMappings = new Dictionary<string, ICommand> { { "sync", kernel.Get<SyncCommand>() }, { "resync", kernel.Get<ResyncCommand>() }, { "generate", kernel.Get<GenerateCommand>() }, { "build", kernel.Get<BuildCommand>() }, { "build-target", kernel.Get<BuildTargetCommand>() }, { "build-property", kernel.Get<BuildPropertyCommand>() }, { "build-process-arch", kernel.Get<BuildProcessArchCommand>() }, { "clean", kernel.Get<CleanCommand>() }, { "automated-build", kernel.Get<AutomatedBuildCommand>() }, { "extract-xslt", kernel.Get<ExtractXSLTCommand>() }, { "enable", kernel.Get<EnableServiceCommand>() }, { "disable", kernel.Get<DisableServiceCommand>() }, { "debug-service-resolution", kernel.Get<DebugServiceResolutionCommand>() }, { "debug-project-generation", kernel.Get<DebugProjectGenerationCommand>() }, { "simulate-host-platform", kernel.Get<SimulateHostPlatformCommand>() }, { "spec", kernel.Get<ServiceSpecificationCommand>() }, { "query-features", kernel.Get<QueryFeaturesCommand>() }, { "features", kernel.Get<FeaturesCommand>() }, { "add", kernel.Get<AddPackageCommand>() }, { "remove", kernel.Get<RemovePackageCommand>() }, { "list", kernel.Get<ListPackagesCommand>() }, { "install", kernel.Get<InstallPackageCommand>() }, { "upgrade", kernel.Get<UpgradePackageCommand>() }, { "upgrade-all", kernel.Get<UpgradeAllPackagesCommand>() }, { "pack", kernel.Get<PackPackageCommand>() }, { "format", kernel.Get<FormatPackageCommand>() }, { "push", kernel.Get<PushPackageCommand>() }, { "ignore-on-existing", kernel.Get<IgnoreOnExistingPackageCommand>() }, { "repush", kernel.Get<RepushPackageCommand>() }, { "resolve", kernel.Get<ResolveCommand>() }, { "no-resolve", kernel.Get<NoResolveCommand>() }, { "safe-resolve", kernel.Get<SafeResolveCommand>() }, { "parallel", kernel.Get<ParallelCommand>() }, { "no-parallel", kernel.Get<NoParallelCommand>() }, { "redirect", kernel.Get<RedirectPackageCommand>() }, { "swap-to-source", kernel.Get<SwapToSourceCommand>() }, { "swap-to-binary", kernel.Get<SwapToBinaryCommand>() }, { "start", kernel.Get<StartCommand>() }, { "no-generate", kernel.Get<NoGenerateCommand>() }, { "no-host-generate", kernel.Get<NoHostGenerateCommand>() }, { "execute", kernel.Get<ExecuteCommand>() }, { "execute-configuration", kernel.Get<ExecuteConfigurationCommand>() }, { "package-id", kernel.Get<PackageIdCommand>() }, { "package-git-repo", kernel.Get<PackageGitRepoCommand>() }, { "package-git-commit", kernel.Get<PackageGitCommitCommand>() }, { "package-type", kernel.Get<PackageTypeCommand>() }, }; var execution = new Execution(); execution.WorkingDirectory = workingDirectory; execution.CommandToExecute = kernel.Get<DefaultCommand>(); var options = new Options(); foreach (var kv in commandMappings) { var key = kv.Key; var value = kv.Value; Action<string[]> handle = x => { if (value.IsRecognised()) { value.Encounter(execution, x); } else if (value.IsIgnored()) { } else { throw new InvalidOperationException("Unknown argument '" + key + "'"); } }; if (value.GetArgCount() == 0) { options[key] = handle; } else { options[key + "@" + value.GetArgCount()] = handle; } } Action<string[]> helpAction = x => { PrintHelp(commandMappings); ExecEnvironment.Exit(0); }; options["help"] = helpAction; options["?"] = helpAction; if (ExecEnvironment.DoNotWrapExecutionInTry) { options.Parse(args); } else { try { options.Parse(args); } catch (InvalidOperationException ex) { RedirectableConsole.WriteLine(ex.Message); PrintHelp(commandMappings); ExecEnvironment.Exit(1); } } featureManager.ValidateEnabledFeatures(); if (ExecEnvironment.DoNotWrapExecutionInTry) { var exitCode = execution.CommandToExecute.Execute(execution); ExecEnvironment.Exit(exitCode); } else { try { var exitCode = execution.CommandToExecute.Execute(execution); ExecEnvironment.Exit(exitCode); } catch (ExecEnvironment.SelfInvokeExitException) { throw; } catch (Exception ex) { RedirectableConsole.WriteLine(ex); ExecEnvironment.Exit(1); } } } private static bool SSLValidationForLinux(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors) { // If the Mono root CA store is initialized properly, then use that. if (sslpolicyerrors == SslPolicyErrors.None) { // Good certificate. return true; } // I'm not sure of the stability of the certificate thumbprint for protobuild.org // itself, so instead just verify that it is Let's Encrypt that's providing the // certificate. if (sender is HttpWebRequest && (sender as HttpWebRequest).Host == "protobuild.org") { if (chain.ChainElements.Count > 2 && chain.ChainElements[1].Certificate.Thumbprint == "3EAE91937EC85D74483FF4B77B07B43E2AF36BF4") { // This is the Let's Encrypt certificate authority. We can implicitly trust this without warning. return true; } else { // The thumbprint differs! Show a danger message to the user, but continue anyway // because if the thumbprint does legitimately change, we have no way of backporting // a new certificate thumbprint without issuing a new version of Protobuild. var givenThumbprint = chain.ChainElements.Count >= 2 ? chain.ChainElements[1].Certificate.Thumbprint : "<no thumbprint available>"; RedirectableConsole.ErrorWriteLine( "DANGER: The thumbprint of the issuer's SSL certificate for protobuild.org \"" + givenThumbprint + "\" does not match the expected thumbprint value \"" + chain.ChainElements[1].Certificate.Thumbprint + "\". It's possible that Let's Encrypt " + "changed their certificate thumbprint, or someone is performing a MITM " + "attack on your connection. Unfortunately Mono does not ship out-of-the-box " + "with appropriate root CA certificates on Linux, so we have no method of verifying " + "that the proposed thumbprint is correct. You should verify that the given " + "thumbprint is correct either through your web browser (by visiting protobuild.org " + "and checking the certificate chain), or by performing the same operation on " + "Mac OS or Windows. If the operation succeeds, or the thumbprint matches, please " + "file an issue at https://github.com/hach-que/Protobuild/issues/new so we can " + "update the embedded thumbprint. We will now continue the operation regardless " + "as we can't update the thumbprint in previous versions if it has changed."); return true; } } RedirectableConsole.WriteLine( "WARNING: Implicitly trusting SSL certificate " + certificate.GetCertHashString() + " " + "for " + certificate.Subject + " issued by " + certificate.Issuer + " on Linux, due " + "to inconsistent root CA store policies of Mono."); return true; } private static void PrintHelp(Dictionary<string, ICommand> commandMappings) { RedirectableConsole.WriteLine("Protobuild.exe [options]"); RedirectableConsole.WriteLine(); RedirectableConsole.WriteLine("By default Protobuild resynchronises or generates projects for"); RedirectableConsole.WriteLine("the current platform, depending on the module configuration."); RedirectableConsole.WriteLine(); foreach (var kv in commandMappings) { if (kv.Value.IsInternal() || !kv.Value.IsRecognised() || kv.Value.IsIgnored()) { continue; } var description = kv.Value.GetDescription(); description = description.Replace("\n", " "); description = description.Replace("\r", ""); var lines = new List<string>(); var wordBuffer = string.Empty; var lineBuffer = string.Empty; var count = 0; var last = false; for (var i = 0; i < description.Length || wordBuffer.Length > 0; i++) { if (i < description.Length) { if (description[i] == ' ') { if (wordBuffer.Length > 0) { lineBuffer += wordBuffer + " "; } wordBuffer = string.Empty; } else { wordBuffer += description[i]; count++; } } else { lineBuffer += wordBuffer + " "; count++; last = true; } if (count >= 74) { lines.Add(lineBuffer); lineBuffer = string.Empty; count = 0; } if (last) { break; } } if (count > 0) { lines.Add(lineBuffer); lineBuffer = string.Empty; } var argDesc = string.Empty; foreach (var arg in kv.Value.GetArgNames()) { if (arg.EndsWith("?")) { argDesc += " [" + arg.TrimEnd('?') + "]"; } else { argDesc += " " + arg; } } RedirectableConsole.WriteLine(" -" + kv.Key + argDesc); RedirectableConsole.WriteLine(); foreach (var line in lines) { RedirectableConsole.WriteLine(" " + line); } RedirectableConsole.WriteLine(); } } } }
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Represents an Azure Batch JobManager task. /// </summary> public partial class JobManagerTask : ITransportObjectProvider<Models.JobManagerTask>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<bool?> AllowLowPriorityNodeProperty; public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty; public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty; public readonly PropertyAccessor<string> CommandLineProperty; public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty; public readonly PropertyAccessor<TaskContainerSettings> ContainerSettingsProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<bool?> KillJobOnCompletionProperty; public readonly PropertyAccessor<IList<OutputFile>> OutputFilesProperty; public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty; public readonly PropertyAccessor<bool?> RunExclusiveProperty; public readonly PropertyAccessor<UserIdentity> UserIdentityProperty; public PropertyContainer() : base(BindingState.Unbound) { this.AllowLowPriorityNodeProperty = this.CreatePropertyAccessor<bool?>(nameof(AllowLowPriorityNode), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>(nameof(AuthenticationTokenSettings), BindingAccess.Read | BindingAccess.Write); this.CommandLineProperty = this.CreatePropertyAccessor<string>(nameof(CommandLine), BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write); this.ContainerSettingsProperty = this.CreatePropertyAccessor<TaskContainerSettings>(nameof(ContainerSettings), BindingAccess.Read | BindingAccess.Write); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write); this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write); this.KillJobOnCompletionProperty = this.CreatePropertyAccessor<bool?>(nameof(KillJobOnCompletion), BindingAccess.Read | BindingAccess.Write); this.OutputFilesProperty = this.CreatePropertyAccessor<IList<OutputFile>>(nameof(OutputFiles), BindingAccess.Read | BindingAccess.Write); this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>(nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write); this.RunExclusiveProperty = this.CreatePropertyAccessor<bool?>(nameof(RunExclusive), BindingAccess.Read | BindingAccess.Write); this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>(nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.JobManagerTask protocolObject) : base(BindingState.Bound) { this.AllowLowPriorityNodeProperty = this.CreatePropertyAccessor( protocolObject.AllowLowPriorityNode, nameof(AllowLowPriorityNode), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor( ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences), nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o)), nameof(AuthenticationTokenSettings), BindingAccess.Read | BindingAccess.Write); this.CommandLineProperty = this.CreatePropertyAccessor( protocolObject.CommandLine, nameof(CommandLine), BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)), nameof(Constraints), BindingAccess.Read | BindingAccess.Write); this.ContainerSettingsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerSettings, o => new TaskContainerSettings(o).Freeze()), nameof(ContainerSettings), BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.EnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings), nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, nameof(Id), BindingAccess.Read | BindingAccess.Write); this.KillJobOnCompletionProperty = this.CreatePropertyAccessor( protocolObject.KillJobOnCompletion, nameof(KillJobOnCompletion), BindingAccess.Read | BindingAccess.Write); this.OutputFilesProperty = this.CreatePropertyAccessor( OutputFile.ConvertFromProtocolCollection(protocolObject.OutputFiles), nameof(OutputFiles), BindingAccess.Read | BindingAccess.Write); this.ResourceFilesProperty = this.CreatePropertyAccessor( ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles), nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write); this.RunExclusiveProperty = this.CreatePropertyAccessor( protocolObject.RunExclusive, nameof(RunExclusive), BindingAccess.Read | BindingAccess.Write); this.UserIdentityProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o)), nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="JobManagerTask"/> class. /// </summary> /// <param name='id'>The id of the task.</param> /// <param name='commandLine'>The command line of the task.</param> public JobManagerTask( string id, string commandLine) { this.propertyContainer = new PropertyContainer(); this.Id = id; this.CommandLine = commandLine; } internal JobManagerTask(Models.JobManagerTask protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region JobManagerTask /// <summary> /// Gets or sets whether the Job Manager task may run on a low-priority compute node. If omitted, the default is /// false. /// </summary> public bool? AllowLowPriorityNode { get { return this.propertyContainer.AllowLowPriorityNodeProperty.Value; } set { this.propertyContainer.AllowLowPriorityNodeProperty.Value = value; } } /// <summary> /// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running /// the command line. /// </summary> public IList<ApplicationPackageReference> ApplicationPackageReferences { get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; } set { this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the settings for an authentication token that the task can use to perform Batch service operations. /// </summary> /// <remarks> /// If this property is set, the Batch service provides the task with an authentication token which can be used to /// authenticate Batch service operations without requiring an account access key. The token is provided via the /// AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token /// depend on the settings. For example, a task can request job permissions in order to add other tasks to the job, /// or check the status of the job or of other tasks. /// </remarks> public AuthenticationTokenSettings AuthenticationTokenSettings { get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; } set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; } } /// <summary> /// Gets or sets the command line of the task. /// </summary> /// <remarks> /// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment /// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command /// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. /// </remarks> public string CommandLine { get { return this.propertyContainer.CommandLineProperty.Value; } set { this.propertyContainer.CommandLineProperty.Value = value; } } /// <summary> /// Gets or sets the execution constraints for this JobManager task. /// </summary> public TaskConstraints Constraints { get { return this.propertyContainer.ConstraintsProperty.Value; } set { this.propertyContainer.ConstraintsProperty.Value = value; } } /// <summary> /// Gets or sets the settings for the container under which the task runs. /// </summary> /// <remarks> /// If the pool that will run this task has <see cref="VirtualMachineConfiguration.ContainerConfiguration"/> set, /// this must be set as well. If the pool that will run this task doesn't have <see cref="VirtualMachineConfiguration.ContainerConfiguration"/> /// set, this must not be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR /// (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables /// are mapped into the container, and the task command line is executed in the container. /// </remarks> public TaskContainerSettings ContainerSettings { get { return this.propertyContainer.ContainerSettingsProperty.Value; } set { this.propertyContainer.ContainerSettingsProperty.Value = value; } } /// <summary> /// Gets or sets the display name of the JobManager task. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets or sets a set of environment settings for the JobManager task. /// </summary> public IList<EnvironmentSetting> EnvironmentSettings { get { return this.propertyContainer.EnvironmentSettingsProperty.Value; } set { this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the id of the task. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets a value that indicates whether to terminate all tasks in the job and complete the job when the job /// manager task completes. /// </summary> public bool? KillJobOnCompletion { get { return this.propertyContainer.KillJobOnCompletionProperty.Value; } set { this.propertyContainer.KillJobOnCompletionProperty.Value = value; } } /// <summary> /// Gets or sets a list of files that the Batch service will upload from the compute node after running the command /// line. /// </summary> public IList<OutputFile> OutputFiles { get { return this.propertyContainer.OutputFilesProperty.Value; } set { this.propertyContainer.OutputFilesProperty.Value = ConcurrentChangeTrackedModifiableList<OutputFile>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets a list of files that the Batch service will download to the compute node before running the command /// line. /// </summary> public IList<ResourceFile> ResourceFiles { get { return this.propertyContainer.ResourceFilesProperty.Value; } set { this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets whether the Job Manager task requires exclusive use of the compute node where it runs. /// </summary> public bool? RunExclusive { get { return this.propertyContainer.RunExclusiveProperty.Value; } set { this.propertyContainer.RunExclusiveProperty.Value = value; } } /// <summary> /// Gets or sets the user identity under which the task runs. /// </summary> /// <remarks> /// If omitted, the task runs as a non-administrative user unique to the task. /// </remarks> public UserIdentity UserIdentity { get { return this.propertyContainer.UserIdentityProperty.Value; } set { this.propertyContainer.UserIdentityProperty.Value = value; } } #endregion // JobManagerTask #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.JobManagerTask ITransportObjectProvider<Models.JobManagerTask>.GetTransportObject() { Models.JobManagerTask result = new Models.JobManagerTask() { AllowLowPriorityNode = this.AllowLowPriorityNode, ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences), AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()), CommandLine = this.CommandLine, Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()), ContainerSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerSettings, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings), Id = this.Id, KillJobOnCompletion = this.KillJobOnCompletion, OutputFiles = UtilitiesInternal.ConvertToProtocolCollection(this.OutputFiles), ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles), RunExclusive = this.RunExclusive, UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()), }; return result; } #endregion // Internal/private methods } }
namespace nHydrate.DslPackage.Forms { partial class ImportDatabaseForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImportDatabaseForm)); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.wizard1 = new nHydrate.Wizard.Wizard(); this.pageConnection = new nHydrate.Wizard.WizardPage(); this.grpConnectionStringPostgres = new System.Windows.Forms.GroupBox(); this.lblConnectionString = new System.Windows.Forms.Label(); this.txtConnectionStringPostgres = new nHydrate.DslPackage.Forms.CueTextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.optDatabaseTypePostgres = new System.Windows.Forms.RadioButton(); this.optDatabaseTypeSQL = new System.Windows.Forms.RadioButton(); this.cmdTestConnection = new System.Windows.Forms.Button(); this.DatabaseConnectionControl1 = new nHydrate.DslPackage.Forms.DatabaseConnectionControl(); this.pageSummary = new nHydrate.Wizard.WizardPage(); this.txtSummary = new FastColoredTextBoxNS.FastColoredTextBox(); this.pageEntities = new nHydrate.Wizard.WizardPage(); this.panel2 = new System.Windows.Forms.Panel(); this.chkIgnoreRelations = new System.Windows.Forms.CheckBox(); this.chkInheritance = new System.Windows.Forms.CheckBox(); this.chkSettingPK = new System.Windows.Forms.CheckBox(); this.pnlMain = new System.Windows.Forms.Panel(); this.cmdViewDiff = new System.Windows.Forms.Button(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tvwAdd = new System.Windows.Forms.TreeView(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.tvwRefresh = new System.Windows.Forms.TreeView(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.tvwDelete = new System.Windows.Forms.TreeView(); this.wizard1.SuspendLayout(); this.pageConnection.SuspendLayout(); this.grpConnectionStringPostgres.SuspendLayout(); this.panel1.SuspendLayout(); this.pageSummary.SuspendLayout(); this.pageEntities.SuspendLayout(); this.panel2.SuspendLayout(); this.pnlMain.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.SuspendLayout(); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "import_table_header.png"); this.imageList1.Images.SetKeyName(1, "import_view_header.png"); this.imageList1.Images.SetKeyName(2, "import_storedprocedure_header.png"); this.imageList1.Images.SetKeyName(3, "import_table.png"); this.imageList1.Images.SetKeyName(4, "import_view.png"); this.imageList1.Images.SetKeyName(5, "import_storedprocedure.png"); // // wizard1 // this.wizard1.ButtonFlatStyle = System.Windows.Forms.FlatStyle.Standard; this.wizard1.Controls.Add(this.pageEntities); this.wizard1.Controls.Add(this.pageConnection); this.wizard1.Controls.Add(this.pageSummary); this.wizard1.HeaderImage = ((System.Drawing.Image)(resources.GetObject("wizard1.HeaderImage"))); this.wizard1.Location = new System.Drawing.Point(0, 0); this.wizard1.Name = "wizard1"; this.wizard1.Size = new System.Drawing.Size(653, 543); this.wizard1.TabIndex = 74; this.wizard1.WizardPages.AddRange(new nHydrate.Wizard.WizardPage[] { this.pageConnection, this.pageEntities, this.pageSummary}); // // pageConnection // this.pageConnection.Controls.Add(this.grpConnectionStringPostgres); this.pageConnection.Controls.Add(this.panel1); this.pageConnection.Controls.Add(this.cmdTestConnection); this.pageConnection.Controls.Add(this.DatabaseConnectionControl1); this.pageConnection.Description = "Specify your database connection information."; this.pageConnection.Location = new System.Drawing.Point(0, 0); this.pageConnection.Name = "pageConnection"; this.pageConnection.Size = new System.Drawing.Size(653, 495); this.pageConnection.TabIndex = 7; this.pageConnection.Title = "Database Connection"; // // grpConnectionStringPostgres // this.grpConnectionStringPostgres.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpConnectionStringPostgres.Controls.Add(this.lblConnectionString); this.grpConnectionStringPostgres.Controls.Add(this.txtConnectionStringPostgres); this.grpConnectionStringPostgres.Location = new System.Drawing.Point(12, 396); this.grpConnectionStringPostgres.Name = "grpConnectionStringPostgres"; this.grpConnectionStringPostgres.Size = new System.Drawing.Size(619, 57); this.grpConnectionStringPostgres.TabIndex = 82; this.grpConnectionStringPostgres.TabStop = false; this.grpConnectionStringPostgres.Visible = false; // // lblConnectionString // this.lblConnectionString.AutoSize = true; this.lblConnectionString.Location = new System.Drawing.Point(19, 27); this.lblConnectionString.Name = "lblConnectionString"; this.lblConnectionString.Size = new System.Drawing.Size(112, 13); this.lblConnectionString.TabIndex = 5; this.lblConnectionString.Text = "Database connection:"; // // txtConnectionStringPostgres // this.txtConnectionStringPostgres.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtConnectionStringPostgres.Cue = "<Enter Connectionstring>"; this.txtConnectionStringPostgres.Location = new System.Drawing.Point(136, 24); this.txtConnectionStringPostgres.Name = "txtConnectionStringPostgres"; this.txtConnectionStringPostgres.Size = new System.Drawing.Size(469, 20); this.txtConnectionStringPostgres.TabIndex = 8; // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.Controls.Add(this.optDatabaseTypePostgres); this.panel1.Controls.Add(this.optDatabaseTypeSQL); this.panel1.Location = new System.Drawing.Point(12, 67); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(619, 52); this.panel1.TabIndex = 81; // // optDatabaseTypePostgres // this.optDatabaseTypePostgres.AutoSize = true; this.optDatabaseTypePostgres.Location = new System.Drawing.Point(157, 13); this.optDatabaseTypePostgres.Name = "optDatabaseTypePostgres"; this.optDatabaseTypePostgres.Size = new System.Drawing.Size(66, 17); this.optDatabaseTypePostgres.TabIndex = 0; this.optDatabaseTypePostgres.Text = "Postgres"; this.optDatabaseTypePostgres.UseVisualStyleBackColor = true; // // optDatabaseTypeSQL // this.optDatabaseTypeSQL.AutoSize = true; this.optDatabaseTypeSQL.Checked = true; this.optDatabaseTypeSQL.Location = new System.Drawing.Point(17, 13); this.optDatabaseTypeSQL.Name = "optDatabaseTypeSQL"; this.optDatabaseTypeSQL.Size = new System.Drawing.Size(80, 17); this.optDatabaseTypeSQL.TabIndex = 0; this.optDatabaseTypeSQL.TabStop = true; this.optDatabaseTypeSQL.Text = "SQL Server"; this.optDatabaseTypeSQL.UseVisualStyleBackColor = true; // // cmdTestConnection // this.cmdTestConnection.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cmdTestConnection.Location = new System.Drawing.Point(501, 459); this.cmdTestConnection.Name = "cmdTestConnection"; this.cmdTestConnection.Size = new System.Drawing.Size(130, 23); this.cmdTestConnection.TabIndex = 80; this.cmdTestConnection.Text = "Test Connection"; this.cmdTestConnection.UseVisualStyleBackColor = true; // // DatabaseConnectionControl1 // this.DatabaseConnectionControl1.AutoSize = true; this.DatabaseConnectionControl1.FileName = ""; this.DatabaseConnectionControl1.Location = new System.Drawing.Point(12, 125); this.DatabaseConnectionControl1.Name = "DatabaseConnectionControl1"; this.DatabaseConnectionControl1.Size = new System.Drawing.Size(619, 269); this.DatabaseConnectionControl1.TabIndex = 76; // // pageSummary // this.pageSummary.Controls.Add(this.txtSummary); this.pageSummary.Description = "This is a summary of the import. Please verify this information and press \'Finish" + "\' to import the new objects."; this.pageSummary.Location = new System.Drawing.Point(0, 0); this.pageSummary.Name = "pageSummary"; this.pageSummary.Size = new System.Drawing.Size(653, 495); this.pageSummary.TabIndex = 9; this.pageSummary.Title = "Summary"; // // txtSummary // this.txtSummary.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.txtSummary.AutoScrollMinSize = new System.Drawing.Size(2, 14); this.txtSummary.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSummary.CommentPrefix = "--"; this.txtSummary.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSummary.Font = new System.Drawing.Font("Courier New", 9.75F); this.txtSummary.LeftBracket = '('; this.txtSummary.Location = new System.Drawing.Point(12, 76); this.txtSummary.Name = "txtSummary"; this.txtSummary.ReadOnly = true; this.txtSummary.RightBracket = ')'; this.txtSummary.ShowLineNumbers = false; this.txtSummary.Size = new System.Drawing.Size(629, 404); this.txtSummary.TabIndex = 2; // // pageEntities // this.pageEntities.Controls.Add(this.panel2); this.pageEntities.Controls.Add(this.pnlMain); this.pageEntities.Description = "Choose the objects to import."; this.pageEntities.Location = new System.Drawing.Point(0, 0); this.pageEntities.Name = "pageEntities"; this.pageEntities.Size = new System.Drawing.Size(653, 495); this.pageEntities.TabIndex = 8; this.pageEntities.Title = "Choose Objects"; // // panel2 // this.panel2.Controls.Add(this.chkIgnoreRelations); this.panel2.Controls.Add(this.chkInheritance); this.panel2.Controls.Add(this.chkSettingPK); this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel2.Location = new System.Drawing.Point(0, 441); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(653, 54); this.panel2.TabIndex = 75; // // chkIgnoreRelations // this.chkIgnoreRelations.AutoSize = true; this.chkIgnoreRelations.Location = new System.Drawing.Point(151, 31); this.chkIgnoreRelations.Name = "chkIgnoreRelations"; this.chkIgnoreRelations.Size = new System.Drawing.Size(103, 17); this.chkIgnoreRelations.TabIndex = 73; this.chkIgnoreRelations.Text = "Ignore Relations"; this.chkIgnoreRelations.UseVisualStyleBackColor = true; // // chkInheritance // this.chkInheritance.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.chkInheritance.AutoSize = true; this.chkInheritance.Location = new System.Drawing.Point(151, 8); this.chkInheritance.Name = "chkInheritance"; this.chkInheritance.Size = new System.Drawing.Size(119, 17); this.chkInheritance.TabIndex = 72; this.chkInheritance.Text = "Assume Inheritance"; this.chkInheritance.UseVisualStyleBackColor = true; // // chkSettingPK // this.chkSettingPK.AutoSize = true; this.chkSettingPK.Checked = true; this.chkSettingPK.CheckState = System.Windows.Forms.CheckState.Checked; this.chkSettingPK.Location = new System.Drawing.Point(8, 8); this.chkSettingPK.Name = "chkSettingPK"; this.chkSettingPK.Size = new System.Drawing.Size(124, 17); this.chkSettingPK.TabIndex = 70; this.chkSettingPK.Text = "Override Primary Key"; this.chkSettingPK.UseVisualStyleBackColor = true; // // pnlMain // this.pnlMain.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.pnlMain.Controls.Add(this.cmdViewDiff); this.pnlMain.Controls.Add(this.tabControl1); this.pnlMain.Location = new System.Drawing.Point(0, 78); this.pnlMain.Margin = new System.Windows.Forms.Padding(0); this.pnlMain.Name = "pnlMain"; this.pnlMain.Padding = new System.Windows.Forms.Padding(10); this.pnlMain.Size = new System.Drawing.Size(653, 363); this.pnlMain.TabIndex = 73; // // cmdViewDiff // this.cmdViewDiff.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdViewDiff.Enabled = false; this.cmdViewDiff.Location = new System.Drawing.Point(500, 345); this.cmdViewDiff.Name = "cmdViewDiff"; this.cmdViewDiff.Size = new System.Drawing.Size(140, 23); this.cmdViewDiff.TabIndex = 73; this.cmdViewDiff.Text = "View Differences"; this.cmdViewDiff.UseVisualStyleBackColor = true; this.cmdViewDiff.Click += new System.EventHandler(this.cmdViewDiff_Click); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Top; this.tabControl1.Location = new System.Drawing.Point(10, 10); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(633, 329); this.tabControl1.TabIndex = 70; this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged); // // tabPage1 // this.tabPage1.Controls.Add(this.tvwAdd); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(625, 303); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Add"; this.tabPage1.UseVisualStyleBackColor = true; // // tvwAdd // this.tvwAdd.CheckBoxes = true; this.tvwAdd.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwAdd.HideSelection = false; this.tvwAdd.Location = new System.Drawing.Point(3, 3); this.tvwAdd.Name = "tvwAdd"; this.tvwAdd.Size = new System.Drawing.Size(619, 297); this.tvwAdd.TabIndex = 68; // // tabPage2 // this.tabPage2.Controls.Add(this.tvwRefresh); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(625, 303); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Refresh"; this.tabPage2.UseVisualStyleBackColor = true; // // tvwRefresh // this.tvwRefresh.CheckBoxes = true; this.tvwRefresh.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwRefresh.HideSelection = false; this.tvwRefresh.Location = new System.Drawing.Point(3, 3); this.tvwRefresh.Name = "tvwRefresh"; this.tvwRefresh.Size = new System.Drawing.Size(619, 297); this.tvwRefresh.TabIndex = 69; // // tabPage3 // this.tabPage3.Controls.Add(this.tvwDelete); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(625, 303); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Delete"; this.tabPage3.UseVisualStyleBackColor = true; // // tvwDelete // this.tvwDelete.CheckBoxes = true; this.tvwDelete.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwDelete.HideSelection = false; this.tvwDelete.Location = new System.Drawing.Point(3, 3); this.tvwDelete.Name = "tvwDelete"; this.tvwDelete.Size = new System.Drawing.Size(619, 297); this.tvwDelete.TabIndex = 69; // // ImportDatabaseForm // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(653, 543); this.Controls.Add(this.wizard1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(659, 582); this.Name = "ImportDatabaseForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Import Model Wizard"; this.wizard1.ResumeLayout(false); this.wizard1.PerformLayout(); this.pageConnection.ResumeLayout(false); this.pageConnection.PerformLayout(); this.grpConnectionStringPostgres.ResumeLayout(false); this.grpConnectionStringPostgres.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.pageSummary.ResumeLayout(false); this.pageEntities.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.pnlMain.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ImageList imageList1; private nHydrate.Wizard.Wizard wizard1; private nHydrate.Wizard.WizardPage pageConnection; private nHydrate.Wizard.WizardPage pageEntities; private System.Windows.Forms.Panel pnlMain; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TreeView tvwAdd; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TreeView tvwRefresh; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.TreeView tvwDelete; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.CheckBox chkSettingPK; private nHydrate.DslPackage.Forms.DatabaseConnectionControl DatabaseConnectionControl1; private System.Windows.Forms.Button cmdTestConnection; private System.Windows.Forms.CheckBox chkInheritance; private System.Windows.Forms.CheckBox chkIgnoreRelations; private System.Windows.Forms.Button cmdViewDiff; private Wizard.WizardPage pageSummary; private FastColoredTextBoxNS.FastColoredTextBox txtSummary; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.RadioButton optDatabaseTypePostgres; private System.Windows.Forms.RadioButton optDatabaseTypeSQL; private System.Windows.Forms.GroupBox grpConnectionStringPostgres; private System.Windows.Forms.Label lblConnectionString; private nHydrate.DslPackage.Forms.CueTextBox txtConnectionStringPostgres; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.AspNetCore.Testing; using Xunit; using static Microsoft.AspNetCore.Routing.Patterns.RoutePatternFactory; namespace Microsoft.AspNetCore.Routing.Patterns { public class RoutePatternParameterParserTest { [Fact] public void Parse_SingleLiteral() { // Arrange var template = "cool"; var expected = Pattern( template, Segment(LiteralPart("cool"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_SingleParameter() { // Arrange var template = "{p}"; var expected = Pattern(template, Segment(ParameterPart("p"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_OptionalParameter() { // Arrange var template = "{p?}"; var expected = Pattern(template, Segment(ParameterPart("p", null, RoutePatternParameterKind.Optional))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_MultipleLiterals() { // Arrange var template = "cool/awesome/super"; var expected = Pattern( template, Segment(LiteralPart("cool")), Segment(LiteralPart("awesome")), Segment(LiteralPart("super"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_MultipleParameters() { // Arrange var template = "{p1}/{p2}/{*p3}"; var expected = Pattern( template, Segment(ParameterPart("p1")), Segment(ParameterPart("p2")), Segment(ParameterPart("p3", null, RoutePatternParameterKind.CatchAll))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_LP() { // Arrange var template = "cool-{p1}"; var expected = Pattern( template, Segment( LiteralPart("cool-"), ParameterPart("p1"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_PL() { // Arrange var template = "{p1}-cool"; var expected = Pattern( template, Segment( ParameterPart("p1"), LiteralPart("-cool"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_PLP() { // Arrange var template = "{p1}-cool-{p2}"; var expected = Pattern( template, Segment( ParameterPart("p1"), LiteralPart("-cool-"), ParameterPart("p2"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_LPL() { // Arrange var template = "cool-{p1}-awesome"; var expected = Pattern( template, Segment( LiteralPart("cool-"), ParameterPart("p1"), LiteralPart("-awesome"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_OptionalParameterFollowingPeriod() { // Arrange var template = "{p1}.{p2?}"; var expected = Pattern( template, Segment( ParameterPart("p1"), SeparatorPart("."), ParameterPart("p2", null, RoutePatternParameterKind.Optional))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_ParametersFollowingPeriod() { // Arrange var template = "{p1}.{p2}"; var expected = Pattern( template, Segment( ParameterPart("p1"), LiteralPart("."), ParameterPart("p2"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_OptionalParameterFollowingPeriod_ThreeParameters() { // Arrange var template = "{p1}.{p2}.{p3?}"; var expected = Pattern( template, Segment( ParameterPart("p1"), LiteralPart("."), ParameterPart("p2"), SeparatorPart("."), ParameterPart("p3", null, RoutePatternParameterKind.Optional))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_ThreeParametersSeparatedByPeriod() { // Arrange var template = "{p1}.{p2}.{p3}"; var expected = Pattern( template, Segment( ParameterPart("p1"), LiteralPart("."), ParameterPart("p2"), LiteralPart("."), ParameterPart("p3"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_OptionalParameterFollowingPeriod_MiddleSegment() { // Arrange var template = "{p1}.{p2?}/{p3}"; var expected = Pattern( template, Segment( ParameterPart("p1"), SeparatorPart("."), ParameterPart("p2", null, RoutePatternParameterKind.Optional)), Segment( ParameterPart("p3"))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_OptionalParameterFollowingPeriod_LastSegment() { // Arrange var template = "{p1}/{p2}.{p3?}"; var expected = Pattern( template, Segment( ParameterPart("p1")), Segment( ParameterPart("p2"), SeparatorPart("."), ParameterPart("p3", null, RoutePatternParameterKind.Optional))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Fact] public void Parse_ComplexSegment_OptionalParameterFollowingPeriod_PeriodAfterSlash() { // Arrange var template = "{p2}/.{p3?}"; var expected = Pattern( template, Segment(ParameterPart("p2")), Segment( SeparatorPart("."), ParameterPart("p3", null, RoutePatternParameterKind.Optional))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Theory] [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}}$)}", @"regex(^\d{3}-\d{3}-\d{4}$)")] // ssn [InlineData(@"{p1:regex(^\d{{1,2}}\/\d{{1,2}}\/\d{{4}}$)}", @"regex(^\d{1,2}\/\d{1,2}\/\d{4}$)")] // date [InlineData(@"{p1:regex(^\w+\@\w+\.\w+)}", @"regex(^\w+\@\w+\.\w+)")] // email [InlineData(@"{p1:regex(([}}])\w+)}", @"regex(([}])\w+)")] // Not balanced } [InlineData(@"{p1:regex(([{{(])\w+)}", @"regex(([{(])\w+)")] // Not balanced { public void Parse_RegularExpressions(string template, string constraint) { // Arrange var expected = Pattern( template, Segment( ParameterPart( "p1", null, RoutePatternParameterKind.Standard, Constraint(constraint)))); // Act var actual = RoutePatternParser.Parse(template); // Assert Assert.Equal<RoutePattern>(expected, actual, new RoutePatternEqualityComparer()); } [Theory] [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}}}$)}")] // extra } [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}}$)}}")] // extra } at the end [InlineData(@"{{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}}$)}")] // extra { at the beginning [InlineData(@"{p1:regex(([}])\w+}")] // Not escaped } [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}$)}")] // Not escaped } [InlineData(@"{p1:regex(abc)")] public void Parse_RegularExpressions_Invalid(string template) { // Act and Assert ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse(template), "There is an incomplete parameter in the route template. Check that each '{' character has a matching " + "'}' character."); } [Theory] [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{{4}}$)}")] // extra { [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{4}}$)}")] // Not escaped { public void Parse_RegularExpressions_Unescaped(string template) { // Act and Assert ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse(template), "In a route parameter, '{' and '}' must be escaped with '{{' and '}}'."); } [Theory] [InlineData("{p1}.{p2?}.{p3}", "p2", ".")] [InlineData("{p1?}{p2}", "p1", "{p2}")] [InlineData("{p1?}{p2?}", "p1", "{p2?}")] [InlineData("{p1}.{p2?})", "p2", ")")] [InlineData("{foorb?}-bar-{z}", "foorb", "-bar-")] public void Parse_ComplexSegment_OptionalParameter_NotTheLastPart( string template, string parameter, string invalid) { // Act and Assert ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse(template), "An optional parameter must be at the end of the segment. In the segment '" + template + "', optional parameter '" + parameter + "' is followed by '" + invalid + "'."); } [Theory] [InlineData("{p1}-{p2?}", "-")] [InlineData("{p1}..{p2?}", "..")] [InlineData("..{p2?}", "..")] [InlineData("{p1}.abc.{p2?}", ".abc.")] [InlineData("{p1}{p2?}", "{p1}")] public void Parse_ComplexSegment_OptionalParametersSeparatedByPeriod_Invalid(string template, string parameter) { // Act and Assert ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse(template), "In the segment '" + template + "', the optional parameter 'p2' is preceded by an invalid " + "segment '" + parameter + "'. Only a period (.) can precede an optional parameter."); } [Fact] public void InvalidTemplate_WithRepeatedParameter() { var ex = ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{Controller}.mvc/{id}/{controller}"), "The route parameter name 'controller' appears more than one time in the route template."); } [Theory] [InlineData("123{a}abc{")] [InlineData("123{a}abc}")] [InlineData("xyz}123{a}abc}")] [InlineData("{{p1}")] [InlineData("{p1}}")] [InlineData("p1}}p2{")] public void InvalidTemplate_WithMismatchedBraces(string template) { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse(template), @"There is an incomplete parameter in the route template. Check that each '{' character has a " + "matching '}' character."); } [Fact] public void InvalidTemplate_CannotHaveCatchAllInMultiSegment() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("123{a}abc{*moo}"), "A path segment that contains more than one section, such as a literal section or a parameter, " + "cannot contain a catch-all parameter."); } [Fact] public void InvalidTemplate_CannotHaveMoreThanOneCatchAll() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{*p1}/{*p2}"), "A catch-all parameter can only appear as the last segment of the route template."); } [Fact] public void InvalidTemplate_CannotHaveMoreThanOneCatchAllInMultiSegment() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{*p1}abc{*p2}"), "A path segment that contains more than one section, such as a literal section or a parameter, " + "cannot contain a catch-all parameter."); } [Fact] public void InvalidTemplate_CannotHaveCatchAllWithNoName() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("foo/{*}"), "The route parameter name '' is invalid. Route parameter names must be non-empty and cannot" + " contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional," + " and can occur only at the end of the parameter. The '*' character marks a parameter as catch-all," + " and can occur only at the start of the parameter."); } [Theory] [InlineData("{a*}", "a*")] [InlineData("{*a*}", "a*")] [InlineData("{*a*:int}", "a*")] [InlineData("{*a*=5}", "a*")] [InlineData("{*a*b=5}", "a*b")] [InlineData("{p1?}.{p2/}/{p3}", "p2/")] [InlineData("{p{{}", "p{")] [InlineData("{p}}}", "p}")] [InlineData("{p/}", "p/")] public void ParseRouteParameter_ThrowsIf_ParameterContainsSpecialCharacters( string template, string parameterName) { // Arrange var expectedMessage = "The route parameter name '" + parameterName + "' is invalid. Route parameter " + "names must be non-empty and cannot contain these characters: '{', '}', '/'. The '?' character " + "marks a parameter as optional, and can occur only at the end of the parameter. The '*' character " + "marks a parameter as catch-all, and can occur only at the start of the parameter."; // Act & Assert ExceptionAssert.Throws<RoutePatternException>(() => RoutePatternParser.Parse(template), expectedMessage); } [Fact] public void InvalidTemplate_CannotHaveConsecutiveOpenBrace() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("foo/{{p1}"), "There is an incomplete parameter in the route template. Check that each '{' character has a " + "matching '}' character."); } [Fact] public void InvalidTemplate_CannotHaveConsecutiveCloseBrace() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("foo/{p1}}"), "There is an incomplete parameter in the route template. Check that each '{' character has a " + "matching '}' character."); } [Fact] public void InvalidTemplate_SameParameterTwiceThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{aaa}/{AAA}"), "The route parameter name 'AAA' appears more than one time in the route template."); } [Fact] public void InvalidTemplate_SameParameterTwiceAndOneCatchAllThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{aaa}/{*AAA}"), "The route parameter name 'AAA' appears more than one time in the route template."); } [Fact] public void InvalidTemplate_InvalidParameterNameWithCloseBracketThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{a}/{aa}a}/{z}"), "There is an incomplete parameter in the route template. Check that each '{' character has a " + "matching '}' character."); } [Fact] public void InvalidTemplate_InvalidParameterNameWithOpenBracketThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{a}/{a{aa}/{z}"), "In a route parameter, '{' and '}' must be escaped with '{{' and '}}'."); } [Fact] public void InvalidTemplate_InvalidParameterNameWithEmptyNameThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{a}/{}/{z}"), "The route parameter name '' is invalid. Route parameter names must be non-empty and cannot" + " contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional, and" + " can occur only at the end of the parameter. The '*' character marks a parameter as catch-all," + " and can occur only at the start of the parameter."); } [Fact] public void InvalidTemplate_InvalidParameterNameWithQuestionThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{Controller}.mvc/{?}"), "The route parameter name '' is invalid. Route parameter names must be non-empty and cannot" + " contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional, and" + " can occur only at the end of the parameter. The '*' character marks a parameter as catch-all," + " and can occur only at the start of the parameter."); } [Fact] public void InvalidTemplate_ConsecutiveSeparatorsSlashSlashThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{a}//{z}"), "The route template separator character '/' cannot appear consecutively. It must be separated by " + "either a parameter or a literal value."); } [Fact] public void InvalidTemplate_WithCatchAllNotAtTheEndThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("foo/{p1}/{*p2}/{p3}"), "A catch-all parameter can only appear as the last segment of the route template."); } [Fact] public void InvalidTemplate_RepeatedParametersThrows() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("foo/aa{p1}{p2}"), "A path segment cannot contain two consecutive parameters. They must be separated by a '/' or by " + "a literal string."); } [Theory] [InlineData("/foo")] [InlineData("~/foo")] public void ValidTemplate_CanStartWithSlashOrTildeSlash(string routePattern) { // Arrange & Act var pattern = RoutePatternParser.Parse(routePattern); // Assert Assert.Equal(routePattern, pattern.RawText); } [Fact] public void InvalidTemplate_CannotStartWithTilde() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("~foo"), "The route template cannot start with a '~' character unless followed by a '/'."); } [Fact] public void InvalidTemplate_CannotContainQuestionMark() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("foor?bar"), "The literal section 'foor?bar' is invalid. Literal sections cannot contain the '?' character."); } [Fact] public void InvalidTemplate_ParameterCannotContainQuestionMark_UnlessAtEnd() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{foor?b}"), "The route parameter name 'foor?b' is invalid. Route parameter names must be non-empty and cannot" + " contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional, and" + " can occur only at the end of the parameter. The '*' character marks a parameter as catch-all," + " and can occur only at the start of the parameter."); } [Fact] public void InvalidTemplate_CatchAllMarkedOptional() { ExceptionAssert.Throws<RoutePatternException>( () => RoutePatternParser.Parse("{a}/{*b?}"), "A catch-all parameter cannot be marked optional."); } private class RoutePatternEqualityComparer : IEqualityComparer<RoutePattern>, IEqualityComparer<RoutePatternParameterPolicyReference> { public bool Equals(RoutePattern x, RoutePattern y) { if (x == null && y == null) { return true; } else if (x == null || y == null) { return false; } else { if (!string.Equals(x.RawText, y.RawText, StringComparison.Ordinal)) { return false; } if (x.PathSegments.Count != y.PathSegments.Count) { return false; } for (var i = 0; i < x.PathSegments.Count; i++) { if (x.PathSegments[i].Parts.Count != y.PathSegments[i].Parts.Count) { return false; } for (int j = 0; j < x.PathSegments[i].Parts.Count; j++) { if (!Equals(x.PathSegments[i].Parts[j], y.PathSegments[i].Parts[j])) { return false; } } } if (x.Parameters.Count != y.Parameters.Count) { return false; } for (var i = 0; i < x.Parameters.Count; i++) { if (!Equals(x.Parameters[i], y.Parameters[i])) { return false; } } return true; } } private bool Equals(RoutePatternPart x, RoutePatternPart y) { if (x.GetType() != y.GetType()) { return false; } if (x.IsLiteral && y.IsLiteral) { return Equals((RoutePatternLiteralPart)x, (RoutePatternLiteralPart)y); } else if (x.IsParameter && y.IsParameter) { return Equals((RoutePatternParameterPart)x, (RoutePatternParameterPart)y); } else if (x.IsSeparator && y.IsSeparator) { return Equals((RoutePatternSeparatorPart)x, (RoutePatternSeparatorPart)y); } Debug.Fail("This should not be reachable. Do you need to update the comparison logic?"); return false; } private bool Equals(RoutePatternLiteralPart x, RoutePatternLiteralPart y) { return x.Content == y.Content; } private bool Equals(RoutePatternParameterPart x, RoutePatternParameterPart y) { return x.Name == y.Name && x.Default == y.Default && x.ParameterKind == y.ParameterKind && Enumerable.SequenceEqual(x.ParameterPolicies, y.ParameterPolicies, this); } public bool Equals(RoutePatternParameterPolicyReference x, RoutePatternParameterPolicyReference y) { return x.Content == y.Content && x.ParameterPolicy == y.ParameterPolicy; } private bool Equals(RoutePatternSeparatorPart x, RoutePatternSeparatorPart y) { return x.Content == y.Content; } public int GetHashCode(RoutePattern obj) { throw new NotImplementedException(); } public int GetHashCode(RoutePatternParameterPolicyReference obj) { throw new NotImplementedException(); } } } }
using Lucene.Net.Diagnostics; using System.Collections.Generic; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Base class for <see cref="Scorer"/>s that score disjunctions. /// Currently this just provides helper methods to manage the heap. /// </summary> internal abstract class DisjunctionScorer : Scorer { protected readonly Scorer[] m_subScorers; /// <summary> /// The document number of the current match. </summary> protected int m_doc = -1; protected int m_numScorers; protected DisjunctionScorer(Weight weight, Scorer[] subScorers) : base(weight) { this.m_subScorers = subScorers; this.m_numScorers = subScorers.Length; Heapify(); } /// <summary> /// Organize subScorers into a min heap with scorers generating the earliest document on top. /// </summary> protected void Heapify() { for (int i = (m_numScorers >> 1) - 1; i >= 0; i--) { HeapAdjust(i); } } /// <summary> /// The subtree of subScorers at root is a min heap except possibly for its root element. /// Bubble the root down as required to make the subtree a heap. /// </summary> protected void HeapAdjust(int root) { Scorer scorer = m_subScorers[root]; int doc = scorer.DocID; int i = root; while (i <= (m_numScorers >> 1) - 1) { int lchild = (i << 1) + 1; Scorer lscorer = m_subScorers[lchild]; int ldoc = lscorer.DocID; int rdoc = int.MaxValue, rchild = (i << 1) + 2; Scorer rscorer = null; if (rchild < m_numScorers) { rscorer = m_subScorers[rchild]; rdoc = rscorer.DocID; } if (ldoc < doc) { if (rdoc < ldoc) { m_subScorers[i] = rscorer; m_subScorers[rchild] = scorer; i = rchild; } else { m_subScorers[i] = lscorer; m_subScorers[lchild] = scorer; i = lchild; } } else if (rdoc < doc) { m_subScorers[i] = rscorer; m_subScorers[rchild] = scorer; i = rchild; } else { return; } } } /// <summary> /// Remove the root <see cref="Scorer"/> from subScorers and re-establish it as a heap /// </summary> protected void HeapRemoveRoot() { if (m_numScorers == 1) { m_subScorers[0] = null; m_numScorers = 0; } else { m_subScorers[0] = m_subScorers[m_numScorers - 1]; m_subScorers[m_numScorers - 1] = null; --m_numScorers; HeapAdjust(0); } } public override sealed ICollection<ChildScorer> GetChildren() { List<ChildScorer> children = new List<ChildScorer>(m_numScorers); for (int i = 0; i < m_numScorers; i++) { children.Add(new ChildScorer(m_subScorers[i], "SHOULD")); } return children; } public override long GetCost() { long sum = 0; for (int i = 0; i < m_numScorers; i++) { sum += m_subScorers[i].GetCost(); } return sum; } public override int DocID => m_doc; public override int NextDoc() { if (Debugging.AssertsEnabled) Debugging.Assert(m_doc != NO_MORE_DOCS); while (true) { if (m_subScorers[0].NextDoc() != NO_MORE_DOCS) { HeapAdjust(0); } else { HeapRemoveRoot(); if (m_numScorers == 0) { return m_doc = NO_MORE_DOCS; } } if (m_subScorers[0].DocID != m_doc) { AfterNext(); return m_doc; } } } public override int Advance(int target) { if (Debugging.AssertsEnabled) Debugging.Assert(m_doc != NO_MORE_DOCS); while (true) { if (m_subScorers[0].Advance(target) != NO_MORE_DOCS) { HeapAdjust(0); } else { HeapRemoveRoot(); if (m_numScorers == 0) { return m_doc = NO_MORE_DOCS; } } if (m_subScorers[0].DocID >= target) { AfterNext(); return m_doc; } } } /// <summary> /// Called after <see cref="NextDoc()"/> or <see cref="Advance(int)"/> land on a new document. /// <para/> /// <c>subScorers[0]</c> will be positioned to the new docid, /// which could be <c>NO_MORE_DOCS</c> (subclass must handle this). /// <para/> /// Implementations should assign <c>doc</c> appropriately, and do any /// other work necessary to implement <see cref="Scorer.GetScore()"/> and <see cref="Index.DocsEnum.Freq"/> /// </summary> // TODO: make this less horrible protected abstract void AfterNext(); } }
namespace NServiceBus.ObjectBuilder.SimpleInjector { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using NServiceBus.SimpleInjector; using global::SimpleInjector; using Janitor; using System.Threading; using global::SimpleInjector.Lifestyles; class SimpleInjectorObjectBuilder : Common.IContainer { [SkipWeaving] Container container; readonly bool externalContainer = false; bool isBuilt = false; Dictionary<Type, IEnumerable<Registration>> collectionRegistrations = new Dictionary<Type, IEnumerable<Registration>>(); public SimpleInjectorObjectBuilder(Container parentContainer) { container = parentContainer; externalContainer = true; AsyncScopedLifestyle.BeginScope(container); } public SimpleInjectorObjectBuilder() { container = new Container(); container.AllowToResolveArraysAndLists(); container.Options.AllowOverridingRegistrations = true; container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.Options.AutoWirePropertiesImplicitly(); // Without this the InstancePerCall component cannot be registered because it is an IDisposable container.Options.EnableAutoVerification = false; AsyncScopedLifestyle.BeginScope(container); } public void Dispose() { //Injected at compile time } void DisposeManaged() { var scope = Lifestyle.Scoped.GetCurrentScope(container); var scopeTemp = Interlocked.Exchange(ref scope, null); if (scopeTemp != null) { scopeTemp.Dispose(); } if (!externalContainer) { var temp = Interlocked.Exchange(ref container, null); if (temp != null) { temp.Dispose(); } } } public Common.IContainer BuildChildContainer() { return new SimpleInjectorObjectBuilder(container); } public object Build(Type typeToBuild) { isBuilt = true; if (!HasComponent(typeToBuild)) { throw new ActivationException("The requested type is not registered yet"); } collectionRegistrations = null; return container.GetInstance(typeToBuild); } public IEnumerable<object> BuildAll(Type typeToBuild) { isBuilt = true; if (HasComponent(typeToBuild)) { collectionRegistrations = null; try { return container.GetAllInstances(typeToBuild); } catch (Exception) { // Urgh! return new[] { container.GetInstance(typeToBuild) }; } } return new object[] { }; } public void Configure(Type component, DependencyLifecycle dependencyLifecycle) { if (isBuilt) { container = container.Clone(); } var registration = GetRegistrationFromDependencyLifecycle(dependencyLifecycle, component); foreach (var implementedInterface in component.GetInterfaces()) { if (HasComponent(implementedInterface)) { var existingRegistration = GetExistingCollectionRegistrationsFor(implementedInterface); RegisterCollection(implementedInterface, existingRegistration.Union(new[] { registration })); } else { container.AddRegistration(implementedInterface, registration); } } if (HasComponent(component)) { var existingRegistration = GetExistingRegistrationsFor(component); var first = existingRegistration.First(); if (!AreRegistrationsEqual(first, registration)) { container.Collection.Register(component, existingRegistration.Union(new[] { registration })); } } else { container.AddRegistration(component, registration); } } public void Configure<T>(Func<T> componentFactory, DependencyLifecycle dependencyLifecycle) { if (isBuilt) { container = container.Clone(); } var funcType = typeof(T); var registration = GetRegistrationFromDependencyLifecycle(dependencyLifecycle, funcType, () => componentFactory()); foreach (var implementedInterface in funcType.GetInterfaces()) { if (HasComponent(implementedInterface)) { var existingRegistration = GetExistingCollectionRegistrationsFor(implementedInterface); RegisterCollection(implementedInterface, existingRegistration.Union(new[] { registration })); } else { AddRegistration(componentFactory, dependencyLifecycle, funcType, registration, implementedInterface); } } AddRegistration(componentFactory, dependencyLifecycle, funcType, registration); } private void AddRegistration<T>(Func<T> componentFactory, DependencyLifecycle dependencyLifecycle, Type funcType, Registration registration) { try { container.AddRegistration(funcType, registration); } catch (ArgumentException) { container = container.Clone(); registration = GetRegistrationFromDependencyLifecycle(dependencyLifecycle, funcType, () => componentFactory()); container.AddRegistration(funcType, registration); } } private void AddRegistration<T>(Func<T> componentFactory, DependencyLifecycle dependencyLifecycle, Type funcType, Registration registration, Type implementedInterface) { try { container.AddRegistration(implementedInterface, registration); } catch (InvalidOperationException) { container = container.Clone(); registration = GetRegistrationFromDependencyLifecycle(dependencyLifecycle, funcType, () => componentFactory()); container.AddRegistration(implementedInterface, registration); } } void RegisterCollection(Type implementedInterface, IEnumerable<Registration> registrations) { if (isBuilt) { container = container.Clone(); } container.Collection.Register(implementedInterface, registrations); collectionRegistrations[implementedInterface] = registrations; } IEnumerable<Registration> GetExistingCollectionRegistrationsFor(Type implementedInterface) { if (collectionRegistrations.ContainsKey(implementedInterface)) { return collectionRegistrations[implementedInterface]; } return GetExistingRegistrationsFor(implementedInterface); } IEnumerable<Registration> GetExistingRegistrationsFor(Type implementedInterface) { return container.GetCurrentRegistrations().Where(r => r.ServiceType == implementedInterface).Select(r => r.Registration); } IEnumerable<Registration> GetExistingRegistrationsFor<TType>() { return GetExistingRegistrationsFor(typeof(TType)); } public void RegisterSingleton(Type lookupType, object instance) { if (isBuilt) { container = container.Clone(); } var registration = GetRegistrationFromDependencyLifecycle(DependencyLifecycle.SingleInstance, lookupType, instance); foreach (var implementedInterface in lookupType.GetInterfaces()) { if (HasComponent(implementedInterface)) { var existingRegistrations = GetExistingRegistrationsFor(implementedInterface); container.Collection.Register(implementedInterface, existingRegistrations.Union(new[] { registration })); } else { container.AddRegistration(implementedInterface, registration); } } container.Register(lookupType, () => instance, registration.Lifestyle); // urgh } public bool HasComponent(Type componentType) { return GetExistingRegistrationsFor(componentType).Any(); } public void Release(object instance) { } Lifestyle GetLifestyleFromDependencyLifecycle(DependencyLifecycle dependencyLifecycle) { switch (dependencyLifecycle) { case DependencyLifecycle.SingleInstance: return Lifestyle.Singleton; case DependencyLifecycle.InstancePerUnitOfWork: return Lifestyle.Scoped; case DependencyLifecycle.InstancePerCall: default: return Lifestyle.Transient; } } Registration GetRegistrationFromDependencyLifecycle(DependencyLifecycle dependencyLifecycle, Type component) { return GetLifestyleFromDependencyLifecycle(dependencyLifecycle).CreateRegistration(component, container); } Registration GetRegistrationFromDependencyLifecycle(DependencyLifecycle dependencyLifecycle, Type component, Func<object> creator) { return GetLifestyleFromDependencyLifecycle(dependencyLifecycle).CreateRegistration(component, creator, container); } Registration GetRegistrationFromDependencyLifecycle(DependencyLifecycle dependencyLifecycle, Type component, object instance) { return GetRegistrationFromDependencyLifecycle(dependencyLifecycle, component, () => instance); } bool AreRegistrationsEqual(Registration registration, Registration otherRegistration) { return registration.Lifestyle == otherRegistration.Lifestyle && registration.ImplementationType == registration.ImplementationType; } static void SetPropertyValue(object instance, string propertyName, object value) { instance.GetType() .GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance) .SetValue(instance, value, null); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.NetworkInformation { public enum DuplicateAddressDetectionState { Deprecated = 3, Duplicate = 2, Invalid = 0, Preferred = 4, Tentative = 1, } public abstract partial class GatewayIPAddressInformation { protected GatewayIPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } } public partial class GatewayIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.IEnumerable { protected internal GatewayIPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.GatewayIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.GatewayIPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.GatewayIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.GatewayIPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.GatewayIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.GatewayIPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public abstract partial class IcmpV4Statistics { protected IcmpV4Statistics() { } public abstract long AddressMaskRepliesReceived { get; } public abstract long AddressMaskRepliesSent { get; } public abstract long AddressMaskRequestsReceived { get; } public abstract long AddressMaskRequestsSent { get; } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long SourceQuenchesReceived { get; } public abstract long SourceQuenchesSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } public abstract long TimestampRepliesReceived { get; } public abstract long TimestampRepliesSent { get; } public abstract long TimestampRequestsReceived { get; } public abstract long TimestampRequestsSent { get; } } public abstract partial class IcmpV6Statistics { protected IcmpV6Statistics() { } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MembershipQueriesReceived { get; } public abstract long MembershipQueriesSent { get; } public abstract long MembershipReductionsReceived { get; } public abstract long MembershipReductionsSent { get; } public abstract long MembershipReportsReceived { get; } public abstract long MembershipReportsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long NeighborAdvertisementsReceived { get; } public abstract long NeighborAdvertisementsSent { get; } public abstract long NeighborSolicitsReceived { get; } public abstract long NeighborSolicitsSent { get; } public abstract long PacketTooBigMessagesReceived { get; } public abstract long PacketTooBigMessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long RouterAdvertisementsReceived { get; } public abstract long RouterAdvertisementsSent { get; } public abstract long RouterSolicitsReceived { get; } public abstract long RouterSolicitsSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } } public abstract partial class IPAddressInformation { protected IPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } public abstract bool IsDnsEligible { get; } public abstract bool IsTransient { get; } } public partial class IPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.IEnumerable { internal IPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.IPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.IPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.IPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.IPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.IPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public abstract partial class IPGlobalProperties { protected IPGlobalProperties() { } public abstract string DhcpScopeName { get; } public abstract string DomainName { get; } public abstract string HostName { get; } public abstract bool IsWinsProxy { get; } public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; } public abstract System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections(); public abstract System.Net.IPEndPoint[] GetActiveTcpListeners(); public abstract System.Net.IPEndPoint[] GetActiveUdpListeners(); public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics(); public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics(); public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { return default(System.Net.NetworkInformation.IPGlobalProperties); } public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics(); public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics(); public virtual System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection> GetUnicastAddressesAsync() { return default(System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection>); } } public abstract partial class IPGlobalStatistics { protected IPGlobalStatistics() { } public abstract int DefaultTtl { get; } public abstract bool ForwardingEnabled { get; } public abstract int NumberOfInterfaces { get; } public abstract int NumberOfIPAddresses { get; } public abstract int NumberOfRoutes { get; } public abstract long OutputPacketRequests { get; } public abstract long OutputPacketRoutingDiscards { get; } public abstract long OutputPacketsDiscarded { get; } public abstract long OutputPacketsWithNoRoute { get; } public abstract long PacketFragmentFailures { get; } public abstract long PacketReassembliesRequired { get; } public abstract long PacketReassemblyFailures { get; } public abstract long PacketReassemblyTimeout { get; } public abstract long PacketsFragmented { get; } public abstract long PacketsReassembled { get; } public abstract long ReceivedPackets { get; } public abstract long ReceivedPacketsDelivered { get; } public abstract long ReceivedPacketsDiscarded { get; } public abstract long ReceivedPacketsForwarded { get; } public abstract long ReceivedPacketsWithAddressErrors { get; } public abstract long ReceivedPacketsWithHeadersErrors { get; } public abstract long ReceivedPacketsWithUnknownProtocol { get; } } public abstract partial class IPInterfaceProperties { protected IPInterfaceProperties() { } public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; } public abstract string DnsSuffix { get; } public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; } public abstract bool IsDnsEnabled { get; } public abstract bool IsDynamicDnsEnabled { get; } public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; } public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; } public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties(); public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties(); } public abstract partial class IPInterfaceStatistics { protected IPInterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv4InterfaceProperties { protected IPv4InterfaceProperties() { } public abstract int Index { get; } public abstract bool IsAutomaticPrivateAddressingActive { get; } public abstract bool IsAutomaticPrivateAddressingEnabled { get; } public abstract bool IsDhcpEnabled { get; } public abstract bool IsForwardingEnabled { get; } public abstract int Mtu { get; } public abstract bool UsesWins { get; } } public abstract partial class IPv6InterfaceProperties { protected IPv6InterfaceProperties() { } public abstract int Index { get; } public abstract int Mtu { get; } public virtual long GetScopeId(System.Net.NetworkInformation.ScopeLevel scopeLevel) { return default(long); } } public abstract partial class MulticastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected MulticastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class MulticastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.IEnumerable { protected internal MulticastIPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.MulticastIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.MulticastIPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.MulticastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.MulticastIPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.MulticastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.MulticastIPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public enum NetBiosNodeType { Broadcast = 1, Hybrid = 8, Mixed = 4, Peer2Peer = 2, Unknown = 0, } public delegate void NetworkAddressChangedEventHandler(object sender, System.EventArgs e); public static partial class NetworkChange { public static event System.Net.NetworkInformation.NetworkAddressChangedEventHandler NetworkAddressChanged { add { } remove { } } } public partial class NetworkInformationException : System.Exception { public NetworkInformationException() { } public NetworkInformationException(int errorCode) { } } public abstract partial class NetworkInterface { protected NetworkInterface() { } public virtual string Description { get { return default(string); } } public virtual string Id { get { return default(string); } } public static int IPv6LoopbackInterfaceIndex { get { return default(int); } } public virtual bool IsReceiveOnly { get { return default(bool); } } public static int LoopbackInterfaceIndex { get { return default(int); } } public virtual string Name { get { return default(string); } } public virtual System.Net.NetworkInformation.NetworkInterfaceType NetworkInterfaceType { get { return default(System.Net.NetworkInformation.NetworkInterfaceType); } } public virtual System.Net.NetworkInformation.OperationalStatus OperationalStatus { get { return default(System.Net.NetworkInformation.OperationalStatus); } } public virtual long Speed { get { return default(long); } } public virtual bool SupportsMulticast { get { return default(bool); } } public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { return default(System.Net.NetworkInformation.NetworkInterface[]); } public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { return default(System.Net.NetworkInformation.IPInterfaceProperties); } public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { return default(System.Net.NetworkInformation.IPInterfaceStatistics); } public static bool GetIsNetworkAvailable() { return default(bool); } public virtual System.Net.NetworkInformation.PhysicalAddress GetPhysicalAddress() { return default(System.Net.NetworkInformation.PhysicalAddress); } public virtual bool Supports(System.Net.NetworkInformation.NetworkInterfaceComponent networkInterfaceComponent) { return default(bool); } } public enum NetworkInterfaceComponent { IPv4 = 0, IPv6 = 1, } public enum NetworkInterfaceType { AsymmetricDsl = 94, Atm = 37, BasicIsdn = 20, Ethernet = 6, Ethernet3Megabit = 26, FastEthernetFx = 69, FastEthernetT = 62, Fddi = 15, GenericModem = 48, GigabitEthernet = 117, HighPerformanceSerialBus = 144, IPOverAtm = 114, Isdn = 63, Loopback = 24, MultiRateSymmetricDsl = 143, Ppp = 23, PrimaryIsdn = 21, RateAdaptDsl = 95, Slip = 28, SymmetricDsl = 96, TokenRing = 9, Tunnel = 131, Unknown = 1, VeryHighSpeedDsl = 97, Wireless80211 = 71, Wman = 237, Wwanpp = 243, Wwanpp2 = 244, } public enum OperationalStatus { Dormant = 5, Down = 2, LowerLayerDown = 7, NotPresent = 6, Testing = 3, Unknown = 4, Up = 1, } public partial class PhysicalAddress { public static readonly System.Net.NetworkInformation.PhysicalAddress None; public PhysicalAddress(byte[] address) { } public override bool Equals(object comparand) { return default(bool); } public byte[] GetAddressBytes() { return default(byte[]); } public override int GetHashCode() { return default(int); } public static System.Net.NetworkInformation.PhysicalAddress Parse(string address) { return default(System.Net.NetworkInformation.PhysicalAddress); } public override string ToString() { return default(string); } } public enum PrefixOrigin { Dhcp = 3, Manual = 1, Other = 0, RouterAdvertisement = 4, WellKnown = 2, } public enum ScopeLevel { Admin = 4, Global = 14, Interface = 1, Link = 2, None = 0, Organization = 8, Site = 5, Subnet = 3, } public enum SuffixOrigin { LinkLayerAddress = 4, Manual = 1, OriginDhcp = 3, Other = 0, Random = 5, WellKnown = 2, } public abstract partial class TcpConnectionInformation { protected TcpConnectionInformation() { } public abstract System.Net.IPEndPoint LocalEndPoint { get; } public abstract System.Net.IPEndPoint RemoteEndPoint { get; } public abstract System.Net.NetworkInformation.TcpState State { get; } } public enum TcpState { Closed = 1, CloseWait = 8, Closing = 9, DeleteTcb = 12, Established = 5, FinWait1 = 6, FinWait2 = 7, LastAck = 10, Listen = 2, SynReceived = 4, SynSent = 3, TimeWait = 11, Unknown = 0, } public abstract partial class TcpStatistics { protected TcpStatistics() { } public abstract long ConnectionsAccepted { get; } public abstract long ConnectionsInitiated { get; } public abstract long CumulativeConnections { get; } public abstract long CurrentConnections { get; } public abstract long ErrorsReceived { get; } public abstract long FailedConnectionAttempts { get; } public abstract long MaximumConnections { get; } public abstract long MaximumTransmissionTimeout { get; } public abstract long MinimumTransmissionTimeout { get; } public abstract long ResetConnections { get; } public abstract long ResetsSent { get; } public abstract long SegmentsReceived { get; } public abstract long SegmentsResent { get; } public abstract long SegmentsSent { get; } } public abstract partial class UdpStatistics { protected UdpStatistics() { } public abstract long DatagramsReceived { get; } public abstract long DatagramsSent { get; } public abstract long IncomingDatagramsDiscarded { get; } public abstract long IncomingDatagramsWithErrors { get; } public abstract int UdpListeners { get; } } public abstract partial class UnicastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected UnicastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.IPAddress IPv4Mask { get; } public virtual int PrefixLength { get { return default(int); } } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class UnicastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.IEnumerable { protected internal UnicastIPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.UnicastIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.UnicastIPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.UnicastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.UnicastIPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.UnicastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.UnicastIPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using System.Text; using FluentAssertions; using Microsoft.DotNet.Tools.Test.Utilities; using Microsoft.Extensions.DependencyModel.Tests; using Microsoft.Extensions.EnvironmentAbstractions; using Xunit; namespace Microsoft.DotNet.Tools.Tests.Utilities.Tests { public class MockFileSystemTests { [Theory] [InlineData(false)] [InlineData(true)] public void DirectoryExistsShouldCountTheSameNameFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nestedFilePath = Path.Combine(directory, "filename"); fileSystem.File.CreateEmptyFile(nestedFilePath); fileSystem.Directory.Exists(nestedFilePath).Should().BeFalse(); } [WindowsOnlyTheory] [InlineData(false)] [InlineData(true)] public void DifferentDirectorySeparatorShouldBeSameFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nestedFilePath = $"{directory}\\filename"; fileSystem.File.CreateEmptyFile(nestedFilePath); fileSystem.File.Exists($"{directory}/filename").Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenDirectoryExistsShouldCreateEmptyFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nestedFilePath = Path.Combine(directory, "filename"); fileSystem.File.CreateEmptyFile(nestedFilePath); fileSystem.File.Exists(nestedFilePath).Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenDirectoryDoesNotExistsCreateEmptyFileShouldThrow(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nestedFilePath = Path.Combine(directory, "nonExits", "filename"); Action a = () => fileSystem.File.CreateEmptyFile(nestedFilePath); a.ShouldThrow<DirectoryNotFoundException>().And.Message.Should() .Contain("Could not find a part of the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void DirectoryExistsWithRelativePathShouldCountTheSameNameFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.GetCurrentDirectory(); fileSystem.File.CreateEmptyFile("file"); fileSystem.File.Exists(Path.Combine(directory, "file")).Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public void WithRelativePathShouldCreateDirectory(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.GetCurrentDirectory(); fileSystem.Directory.CreateDirectory("dir"); fileSystem.Directory.Exists(Path.Combine(directory, "dir")).Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public void ShouldCreateDirectory(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; fileSystem.Directory.Exists(directory).Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public void CreateDirectoryWhenExistsShouldNotThrow(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; Action a = () => fileSystem.Directory.CreateDirectory(directory); a.ShouldNotThrow(); } [Theory] [InlineData(false)] [InlineData(true)] public void CreateDirectoryWhenExistsSameNameFileShouldThrow(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string path = Path.Combine(directory, "sub"); fileSystem.File.CreateEmptyFile(path); Action a = () => fileSystem.Directory.CreateDirectory(path); a.ShouldThrow<IOException>(); } [WindowsOnlyTheory] [InlineData(false)] [InlineData(true)] public void DirectoryDoesNotExistShouldThrow(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nestedFilePath = Path.Combine(directory, "subfolder", "filename"); Action a = () => fileSystem.File.CreateEmptyFile(nestedFilePath); a.ShouldThrow<DirectoryNotFoundException>(); } [Theory] [InlineData(false)] [InlineData(true)] public void FileReadAllTextWhenExists(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; const string content = "content"; string path = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.WriteAllText(path, content); fileSystem.File.ReadAllText(path).Should().Be(content); } [Theory] [InlineData(false)] [InlineData(true)] public void FileThrowsWhenTryToReadNonExistFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string path = Path.Combine(directory, Path.GetRandomFileName()); Action a = () => fileSystem.File.ReadAllText(path); a.ShouldThrow<FileNotFoundException>().And.Message.Should().Contain("Could not find file"); } [Theory] [InlineData(false)] [InlineData(true)] public void FileThrowsWhenTryToReadADictionary(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = Path.Combine( fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(directory); Action a = () => fileSystem.File.ReadAllText(directory); a.ShouldThrow<UnauthorizedAccessException>().And.Message.Should().Contain("Access to the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void FileOpenReadWhenExists(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; const string content = "content"; string path = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.WriteAllText(path, content); string fullString = ""; using (Stream fs = fileSystem.File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { fullString += temp.GetString(b); } } fullString.Should().StartWith(content); } [Theory] [InlineData(false)] [InlineData(true)] public void MoveFileWhenBothSourceAndDestinationExist(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string sourceFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(sourceFile); string destinationFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.Move(sourceFile, destinationFile); fileSystem.File.Exists(sourceFile).Should().BeFalse(); fileSystem.File.Exists(destinationFile).Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public void MoveFileThrowsWhenSourceDoesNotExist(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string sourceFile = Path.Combine(directory, Path.GetRandomFileName()); string destinationFile = Path.Combine(directory, Path.GetRandomFileName()); Action a = () => fileSystem.File.Move(sourceFile, destinationFile); a.ShouldThrow<FileNotFoundException>().And.Message.Should().Contain("Could not find file"); } [Theory] [InlineData(false)] [InlineData(true)] public void MoveFileThrowsWhenSourceIsADirectory(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string badSourceFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(badSourceFile); string destinationFile = Path.Combine(directory, Path.GetRandomFileName()); Action a = () => fileSystem.File.Move(badSourceFile, destinationFile); a.ShouldThrow<FileNotFoundException>().And.Message.Should().Contain("Could not find file"); } [Theory] [InlineData(false)] [InlineData(true)] public void MoveFileThrowsWhenDestinationDirectoryDoesNotExist(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string sourceFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(sourceFile); string destinationFile = Path.Combine(directory, Path.GetRandomFileName(), Path.GetRandomFileName()); Action a = () => fileSystem.File.Move(sourceFile, destinationFile); a.ShouldThrow<DirectoryNotFoundException>() .And.Message.Should().Contain("Could not find a part of the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void CopyFileWhenBothSourceAndDestinationDirectoryExist(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string sourceFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.WriteAllText(sourceFile, "content"); string destinationFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.Copy(sourceFile, destinationFile); fileSystem.File.ReadAllText(sourceFile).Should().Be(fileSystem.File.ReadAllText(destinationFile)); } [Theory] [InlineData(false)] [InlineData(true)] public void CopyFileThrowsWhenSourceDoesNotExist(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string sourceFile = Path.Combine(directory, Path.GetRandomFileName()); string destinationFile = Path.Combine(directory, Path.GetRandomFileName()); Action a = () => fileSystem.File.Copy(sourceFile, destinationFile); a.ShouldThrow<FileNotFoundException>().And.Message.Should().Contain("Could not find file"); } [Theory] [InlineData(false)] [InlineData(true)] public void CopyFileThrowsWhenSourceIsADirectory(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string badSourceFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(badSourceFile); string destinationFile = Path.Combine(directory, Path.GetRandomFileName()); Action a = () => fileSystem.File.Copy(badSourceFile, destinationFile); a.ShouldThrow<UnauthorizedAccessException>().And.Message.Should().Contain("Access to the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void CopyFileThrowsWhenDestinationDirectoryDoesNotExist(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string sourceFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(sourceFile); string destinationFile = Path.Combine(directory, Path.GetRandomFileName(), Path.GetRandomFileName()); Action a = () => fileSystem.File.Copy(sourceFile, destinationFile); a.ShouldThrow<DirectoryNotFoundException>() .And.Message.Should().Contain("Could not find a part of the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void CopyFileThrowsWhenDestinationExists(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string sourceFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(sourceFile); string destinationFile = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(destinationFile); Action a = () => fileSystem.File.Copy(sourceFile, destinationFile); a.ShouldThrow<IOException>() .And.Message.Should().Contain("already exists"); } [Theory] [InlineData(false)] [InlineData(true)] public void DeleteFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string file = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(file); fileSystem.File.Delete(file); fileSystem.File.Exists(file).Should().BeFalse(); } [Theory] [InlineData(false)] [InlineData(true)] public void DeleteFileShouldNotThrowWhenFileDoesNotExists(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string file = Path.Combine(directory, Path.GetRandomFileName()); Action a = () => fileSystem.File.Delete(file); a.ShouldNotThrow(); } // https://github.com/dotnet/corefx/issues/32110 // It behaves differently on Windows Vs Non Windows // Use Windows behavior since it is more strict [WindowsOnlyTheory] [InlineData(false)] [InlineData(true)] public void DeleteFileShouldNotThrowWhenDirectoryDoesNotExists(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string file = Path.Combine(directory, Path.GetRandomFileName(), Path.GetRandomFileName()); Action a = () => fileSystem.File.Delete(file); a.ShouldThrow<DirectoryNotFoundException>().And.Message.Should().Contain("Could not find a part of the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void EnumerateAllFilesThrowsWhenDirectoryDoesNotExists(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nonExistDirectory = Path.Combine(directory, Path.GetRandomFileName(), Path.GetRandomFileName()); Action a = () => fileSystem.Directory.EnumerateFiles(nonExistDirectory); a.ShouldThrow<DirectoryNotFoundException>().And.Message.Should() .Contain("Could not find a part of the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void EnumerateAllFilesThrowsWhenPathIsAFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string wrongFilePath = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(wrongFilePath); Action a = () => fileSystem.Directory.EnumerateFiles(wrongFilePath).ToArray(); // On Windows: The parameter is incorrect // On Linux: Not a directory // But the message is not important a.ShouldThrow<IOException>(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenEmptyEnumerateAllFiles(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string emptyDirectory = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(emptyDirectory); fileSystem.Directory.EnumerateFiles(emptyDirectory).Should().BeEmpty(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenFilesExistEnumerateAllFiles(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testDirectory = Path.Combine(tempDirectory, Path.GetRandomFileName()); string file1 = Path.Combine(testDirectory, Path.GetRandomFileName()); string file2 = Path.Combine(testDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testDirectory); fileSystem.File.CreateEmptyFile(file1); fileSystem.File.CreateEmptyFile(file2); fileSystem.Directory.EnumerateFiles(testDirectory).Should().Contain(file1); fileSystem.Directory.EnumerateFiles(testDirectory).Should().Contain(file2); } [Theory] [InlineData(false)] [InlineData(true)] public void EnumerateFileSystemEntriesThrowsWhenDirectoryDoesNotExists(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nonExistDirectory = Path.Combine(directory, Path.GetRandomFileName(), Path.GetRandomFileName()); Action a = () => fileSystem.Directory.EnumerateFileSystemEntries(nonExistDirectory); a.ShouldThrow<DirectoryNotFoundException>().And.Message.Should() .Contain("Could not find a part of the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void EnumerateFileSystemEntriesThrowsWhenPathIsAFile(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string directory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string wrongFilePath = Path.Combine(directory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(wrongFilePath); Action a = () => fileSystem.Directory.EnumerateFileSystemEntries(wrongFilePath).ToArray(); // On Windows: The parameter is incorrect // On Linux: Not a directory // But the message is not important a.ShouldThrow<IOException>(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenEmptyEnumerateFileSystemEntries(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string emptyDirectory = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(emptyDirectory); fileSystem.Directory.EnumerateFileSystemEntries(emptyDirectory).Should().BeEmpty(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenFilesExistEnumerateFileSystemEntries(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testDirectory = Path.Combine(tempDirectory, Path.GetRandomFileName()); string file1 = Path.Combine(testDirectory, Path.GetRandomFileName()); string file2 = Path.Combine(testDirectory, Path.GetRandomFileName()); string nestedDirectoryPath = Path.Combine(testDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testDirectory); fileSystem.File.CreateEmptyFile(file1); fileSystem.File.CreateEmptyFile(file2); fileSystem.Directory.CreateDirectory(nestedDirectoryPath); fileSystem.Directory.EnumerateFileSystemEntries(testDirectory).Should().Contain(file1); fileSystem.Directory.EnumerateFileSystemEntries(testDirectory).Should().Contain(file2); fileSystem.Directory.EnumerateFileSystemEntries(testDirectory).Should().Contain(nestedDirectoryPath); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, true)] [InlineData(true, false)] public void WhenDirectoryExistsItDeleteDirectory(bool testMockBehaviorIsInSync, bool recursive) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testDirectory = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testDirectory); fileSystem.Directory.Delete(testDirectory, recursive); fileSystem.Directory.Exists(testDirectory).Should().BeFalse(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, true)] [InlineData(true, false)] public void WhenDirectoryDoesNotExistsDirectoryDeleteThrows(bool testMockBehaviorIsInSync, bool recursive) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string nonExistsTestDirectory = Path.Combine(tempDirectory, Path.GetRandomFileName()); Action action = () => fileSystem.Directory.Delete(nonExistsTestDirectory, recursive); action.ShouldThrow<DirectoryNotFoundException>().And.Message.Should() .Contain("Could not find a part of the path"); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, true)] [InlineData(true, false)] public void WhenDirectoryPathIsAFileDirectoryDeleteThrows(bool testMockBehaviorIsInSync, bool recursive) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string actuallyAFilePath = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(actuallyAFilePath); Action action = () => fileSystem.Directory.Delete(actuallyAFilePath, recursive); action.ShouldThrow<IOException>(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenDirectoryPathHasAFileAndNonRecursiveDirectoryDeleteThrows(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); string testDirectoryFilePath = Path.Combine(testDirectoryPath, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testDirectoryPath); fileSystem.File.CreateEmptyFile(testDirectoryFilePath); Action action = () => fileSystem.Directory.Delete(testDirectoryPath, false); // On Windows: The directory is not empty // On Linux: Directory not empty // But the message is not important action.ShouldThrow<IOException>().And.Message.Should().Contain("not empty"); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenDirectoryPathHasAFileAndRecursiveItDeletes(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); string testDirectoryFilePath = Path.Combine(testDirectoryPath, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testDirectoryPath); fileSystem.File.CreateEmptyFile(testDirectoryFilePath); fileSystem.Directory.Delete(testDirectoryPath, true); fileSystem.Directory.Exists(testDirectoryPath).Should().BeFalse(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenItMovesDirectory(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testSourceDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); string nestedFilePath = Path.GetRandomFileName(); string testDirectoryFilePath = Path.Combine(testSourceDirectoryPath, nestedFilePath); fileSystem.Directory.CreateDirectory(testSourceDirectoryPath); fileSystem.File.CreateEmptyFile(testDirectoryFilePath); string testDestinationDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.Move(testSourceDirectoryPath, testDestinationDirectoryPath); fileSystem.Directory.Exists(testSourceDirectoryPath).Should().BeFalse(); fileSystem.Directory.Exists(testDirectoryFilePath).Should().BeFalse(); fileSystem.Directory.Exists(testDestinationDirectoryPath).Should().BeTrue(); fileSystem.File.Exists(Path.Combine(testDestinationDirectoryPath, nestedFilePath)).Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenSourcePathDoesNotExistsDirectoryMoveThrows(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testSourceDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); string testDestinationDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); Action a = () => fileSystem.Directory.Move(testSourceDirectoryPath, testDestinationDirectoryPath); a.ShouldThrow<DirectoryNotFoundException>().And.Message.Should() .Contain("Could not find a part of the path"); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenDestinationDirectoryPathExistsDirectoryMoveThrows(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testSourceDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testSourceDirectoryPath); string testDestinationDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testDestinationDirectoryPath); Action a = () => fileSystem.Directory.Move(testSourceDirectoryPath, testDestinationDirectoryPath); a.ShouldThrow<IOException>(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenDestinationDirectoryPathIsAFileDirectoryMoveThrows(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testSourceDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testSourceDirectoryPath); string testDestinationDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.File.CreateEmptyFile(testDestinationDirectoryPath); Action a = () => fileSystem.Directory.Move(testSourceDirectoryPath, testDestinationDirectoryPath); a.ShouldThrow<IOException>(); } [Theory] [InlineData(false)] [InlineData(true)] public void WhenSourceAndDestinationPathIsTheSameDirectoryMoveThrows(bool testMockBehaviorIsInSync) { IFileSystem fileSystem = SetupSubjectFileSystem(testMockBehaviorIsInSync); string tempDirectory = fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; string testSourceDirectoryPath = Path.Combine(tempDirectory, Path.GetRandomFileName()); fileSystem.Directory.CreateDirectory(testSourceDirectoryPath); Action a = () => fileSystem.Directory.Move(testSourceDirectoryPath, testSourceDirectoryPath); a.ShouldThrow<IOException>().And.Message.Should().Contain("Source and destination path must be different"); } private static IFileSystem SetupSubjectFileSystem(bool testMockBehaviorIsInSync) { IFileSystem fileSystem; if (testMockBehaviorIsInSync) { FileSystemMockBuilder temporaryFolder = new FileSystemMockBuilder { TemporaryFolder = Path.GetTempPath() }; fileSystem = temporaryFolder.Build(); } else { fileSystem = new FileSystemWrapper(); } return fileSystem; } } }
// 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.Threading; using System.Threading.Tasks; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class CommandCancelTest { // Shrink the packet size - this should make timeouts more likely private static readonly string s_connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { PacketSize = 512 }).ConnectionString; [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void PlainCancelTest() { PlainCancel(s_connStr); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void PlainMARSCancelTest() { PlainCancel((new SqlConnectionStringBuilder(s_connStr) { MultipleActiveResultSets = true }).ConnectionString); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void PlainCancelTestAsync() { PlainCancelAsync(s_connStr); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void PlainMARSCancelTestAsync() { PlainCancelAsync((new SqlConnectionStringBuilder(s_connStr) { MultipleActiveResultSets = true }).ConnectionString); } private static void PlainCancel(string connString) { using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand cmd = new SqlCommand("select * from dbo.Orders; waitfor delay '00:00:10'; select * from dbo.Orders", conn)) { conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { cmd.Cancel(); DataTestUtility.AssertThrowsWrapper<SqlException>( () => { do { while (reader.Read()) { } } while (reader.NextResult()); }, "A severe error occurred on the current command. The results, if any, should be discarded."); } } } private static void PlainCancelAsync(string connString) { using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand cmd = new SqlCommand("select * from dbo.Orders; waitfor delay '00:00:10'; select * from dbo.Orders", conn)) { conn.Open(); Task<SqlDataReader> readerTask = cmd.ExecuteReaderAsync(); DataTestUtility.AssertThrowsWrapper<SqlException>( () => { readerTask.Wait(2000); SqlDataReader reader = readerTask.Result; cmd.Cancel(); do { while (reader.Read()) { } } while (reader.NextResult()); }, "A severe error occurred on the current command. The results, if any, should be discarded."); } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MultiThreadedCancel_NonAsync() { MultiThreadedCancel(s_connStr, false); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MultiThreadedCancel_Async() { MultiThreadedCancel(s_connStr, true); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TimeoutCancel() { TimeoutCancel(s_connStr); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void CancelAndDisposePreparedCommand() { CancelAndDisposePreparedCommand(s_connStr); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TimeOutDuringRead() { TimeOutDuringRead(s_connStr); } private static void MultiThreadedCancel(string constr, bool async) { using (SqlConnection con = new SqlConnection(constr)) { con.Open(); var command = con.CreateCommand(); command.CommandText = "select * from orders; waitfor delay '00:00:08'; select * from customers"; Barrier threadsReady = new Barrier(2); object state = new Tuple<bool, SqlCommand, Barrier>(async, command, threadsReady); Task[] tasks = new Task[2]; tasks[0] = new Task(ExecuteCommandCancelExpected, state); tasks[1] = new Task(CancelSharedCommand, state); tasks[0].Start(); tasks[1].Start(); Task.WaitAll(tasks, 15 * 1000); CommandCancelTest.VerifyConnection(command); } } private static void TimeoutCancel(string constr) { using (SqlConnection con = new SqlConnection(constr)) { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandTimeout = 1; cmd.CommandText = "WAITFOR DELAY '00:00:30';select * from Customers"; string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout; DataTestUtility.ExpectFailure<SqlException>(() => cmd.ExecuteReader(), new string[] { errorMessage }); VerifyConnection(cmd); } } //InvalidOperationException from connection.Dispose if that connection has prepared command cancelled during reading of data private static void CancelAndDisposePreparedCommand(string constr) { int expectedValue = 1; using (var connection = new SqlConnection(constr)) { try { // Generate a query with a large number of results. using (var command = new SqlCommand("select @P from sysobjects a cross join sysobjects b cross join sysobjects c cross join sysobjects d cross join sysobjects e cross join sysobjects f", connection)) { command.Parameters.Add(new SqlParameter("@P", SqlDbType.Int) { Value = expectedValue }); connection.Open(); // Prepare the query. // Currently this does nothing until command.ExecuteReader is called. // Ideally this should call sp_prepare up-front. command.Prepare(); using (var reader = command.ExecuteReader(CommandBehavior.SingleResult)) { if (reader.Read()) { int actualValue = reader.GetInt32(0); Assert.True(actualValue == expectedValue, string.Format("Got incorrect value. Expected: {0}, Actual: {1}", expectedValue, actualValue)); } // Abandon reading the results. command.Cancel(); } } } finally { connection.Dispose(); // before the fix, InvalidOperationException happened here } } } private static void VerifyConnection(SqlCommand cmd) { Assert.True(cmd.Connection.State == ConnectionState.Open, "FAILURE: - unexpected non-open state after Execute!"); cmd.CommandText = "select 'ABC'"; // Verify Connection string value = (string)cmd.ExecuteScalar(); Assert.True(value == "ABC", "FAILURE: upon validation execute on connection: '" + value + "'"); } private static void ExecuteCommandCancelExpected(object state) { var stateTuple = (Tuple<bool, SqlCommand, Barrier>)state; bool async = stateTuple.Item1; SqlCommand command = stateTuple.Item2; Barrier threadsReady = stateTuple.Item3; string errorMessage = SystemDataResourceManager.Instance.SQL_OperationCancelled; string errorMessageSevereFailure = SystemDataResourceManager.Instance.SQL_SevereError; DataTestUtility.ExpectFailure<SqlException>(() => { threadsReady.SignalAndWait(); using (SqlDataReader r = command.ExecuteReader()) { do { while (r.Read()) { } } while (r.NextResult()); } }, new string[] { errorMessage, errorMessageSevereFailure }); } private static void CancelSharedCommand(object state) { var stateTuple = (Tuple<bool, SqlCommand, Barrier>)state; // sleep 1 seconds before cancel to ensure ExecuteReader starts and ensure it does not end before Cancel is called (command is running WAITFOR 8 seconds) stateTuple.Item3.SignalAndWait(); Thread.Sleep(TimeSpan.FromSeconds(1)); stateTuple.Item2.Cancel(); } private static void TimeOutDuringRead(string constr) { // Create the proxy ProxyServer proxy = ProxyServer.CreateAndStartProxy(constr, out constr); proxy.SimulatedPacketDelay = 100; proxy.SimulatedOutDelay = true; try { using (SqlConnection conn = new SqlConnection(constr)) { // Start the command conn.Open(); SqlCommand cmd = new SqlCommand("SELECT @p", conn); cmd.Parameters.AddWithValue("p", new byte[20000]); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); // Tweak the timeout to 1ms, stop the proxy from proxying and then try GetValue (which should timeout) reader.SetDefaultTimeout(1); proxy.PauseCopying(); string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout; Exception exception = Assert.Throws<SqlException>(() => reader.GetValue(0)); Assert.Contains(errorMessage, exception.Message); // Return everything to normal and close proxy.ResumeCopying(); reader.SetDefaultTimeout(30000); reader.Dispose(); } proxy.Stop(); } catch { // In case of error, stop the proxy and dump its logs (hopefully this will help with debugging proxy.Stop(); Console.WriteLine(proxy.GetServerEventLog()); Assert.True(false, "Error while reading through proxy"); throw; } } } }
// 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; using Microsoft.Win32.SafeHandles; using System; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Principal; using System.Diagnostics.Contracts; namespace System.Security.AccessControl { internal static class Win32 { internal const System.Int32 TRUE = 1; // // Wrapper around advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW // internal static int ConvertSdToSddl( byte[] binaryForm, int requestedRevision, SecurityInfos si, out string resultSddl) { int errorCode; IntPtr ByteArray; uint ByteArraySize = 0; if (TRUE != Interop.mincore.ConvertSdToStringSd(binaryForm, (uint)requestedRevision, (uint)si, out ByteArray, ref ByteArraySize)) { errorCode = Marshal.GetLastWin32Error(); goto Error; } // // Extract data from the returned pointer // resultSddl = Marshal.PtrToStringUni(ByteArray); // // Now is a good time to get rid of the returned pointer // Interop.mincore_obsolete.LocalFree(ByteArray); return 0; Error: resultSddl = null; if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } return errorCode; } // // Wrapper around advapi32.GetSecurityInfo // internal static int GetSecurityInfo( ResourceType resourceType, string name, SafeHandle handle, AccessControlSections accessControlSections, out RawSecurityDescriptor resultSd ) { resultSd = null; int errorCode; IntPtr SidOwner, SidGroup, Dacl, Sacl, ByteArray; SecurityInfos SecurityInfos = 0; Privilege privilege = null; if ((accessControlSections & AccessControlSections.Owner) != 0) { SecurityInfos |= SecurityInfos.Owner; } if ((accessControlSections & AccessControlSections.Group) != 0) { SecurityInfos |= SecurityInfos.Group; } if ((accessControlSections & AccessControlSections.Access) != 0) { SecurityInfos |= SecurityInfos.DiscretionaryAcl; } if ((accessControlSections & AccessControlSections.Audit) != 0) { SecurityInfos |= SecurityInfos.SystemAcl; privilege = new Privilege(Privilege.Security); } try { if (privilege != null) { try { privilege.Enable(); } catch (PrivilegeNotHeldException) { // we will ignore this exception and press on just in case this is a remote resource } } if (name != null) { errorCode = (int)Interop.mincore.GetSecurityInfoByName(name, (uint)resourceType, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray); } else if (handle != null) { if (handle.IsInvalid) { throw new ArgumentException( SR.Argument_InvalidSafeHandle, "handle"); } else { errorCode = (int)Interop.mincore.GetSecurityInfoByHandle(handle, (uint)resourceType, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray); } } else { // both are null, shouldn't happen // Changing from SystemException to ArgumentException as this code path is indicative of a null name argument // as well as an accessControlSections argument with an audit flag throw new ArgumentException(); } if (errorCode == Interop.mincore.Errors.ERROR_SUCCESS && IntPtr.Zero.Equals(ByteArray)) { // // This means that the object doesn't have a security descriptor. And thus we throw // a specific exception for the caller to catch and handle properly. // throw new InvalidOperationException(SR.InvalidOperation_NoSecurityDescriptor); } else if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED || errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD) { throw new PrivilegeNotHeldException(Privilege.Security); } else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED || errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS) { throw new UnauthorizedAccessException(); } if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS) { goto Error; } } catch { // protection against exception filter-based luring attacks if (privilege != null) { privilege.Revert(); } throw; } finally { if (privilege != null) { privilege.Revert(); } } // // Extract data from the returned pointer // uint Length = Interop.mincore.GetSecurityDescriptorLength(ByteArray); byte[] BinaryForm = new byte[Length]; Marshal.Copy(ByteArray, BinaryForm, 0, (int)Length); Interop.mincore_obsolete.LocalFree(ByteArray); resultSd = new RawSecurityDescriptor(BinaryForm, 0); return Interop.mincore.Errors.ERROR_SUCCESS; Error: if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } return errorCode; } // // Wrapper around advapi32.SetNamedSecurityInfoW and advapi32.SetSecurityInfo // internal static int SetSecurityInfo( ResourceType type, string name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl) { int errorCode; int Length; byte[] OwnerBinary = null, GroupBinary = null, SaclBinary = null, DaclBinary = null; Privilege securityPrivilege = null; if (owner != null) { Length = owner.BinaryLength; OwnerBinary = new byte[Length]; owner.GetBinaryForm(OwnerBinary, 0); } if (group != null) { Length = group.BinaryLength; GroupBinary = new byte[Length]; group.GetBinaryForm(GroupBinary, 0); } if (dacl != null) { Length = dacl.BinaryLength; DaclBinary = new byte[Length]; dacl.GetBinaryForm(DaclBinary, 0); } if (sacl != null) { Length = sacl.BinaryLength; SaclBinary = new byte[Length]; sacl.GetBinaryForm(SaclBinary, 0); } if ((securityInformation & SecurityInfos.SystemAcl) != 0) { // // Enable security privilege if trying to set a SACL. // Note: even setting it by handle needs this privilege enabled! // securityPrivilege = new Privilege(Privilege.Security); } try { if (securityPrivilege != null) { try { securityPrivilege.Enable(); } catch (PrivilegeNotHeldException) { // we will ignore this exception and press on just in case this is a remote resource } } if (name != null) { errorCode = (int)Interop.mincore.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary); } else if (handle != null) { if (handle.IsInvalid) { throw new ArgumentException( SR.Argument_InvalidSafeHandle, "handle"); } else { errorCode = (int)Interop.mincore.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary); } } else { // both are null, shouldn't happen Contract.Assert(false, "Internal error: both name and handle are null"); throw new ArgumentException(); } if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED || errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD) { throw new PrivilegeNotHeldException(Privilege.Security); } else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED || errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS) { throw new UnauthorizedAccessException(); } else if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS) { goto Error; } } catch { // protection against exception filter-based luring attacks if (securityPrivilege != null) { securityPrivilege.Revert(); } throw; } finally { if (securityPrivilege != null) { securityPrivilege.Revert(); } } return 0; Error: if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } return errorCode; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractUInt32129() { var test = new SimpleUnaryOpTest__ExtractUInt32129(); try { if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } } catch (PlatformNotSupportedException) { test.Succeeded = true; } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ExtractUInt32129 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int RetElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector128<UInt32> _clsVar; private Vector128<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static SimpleUnaryOpTest__ExtractUInt32129() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ExtractUInt32129() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Extract( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Extract( Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Extract( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (UInt32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (UInt32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (UInt32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Extract( _clsVar, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr); var result = Sse41.Extract(firstOp, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ExtractUInt32129(); var result = Sse41.Extract(test._fld, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Extract(_fld, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { if ((result[0] != firstOp[1])) { Succeeded = false; } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<UInt32>(Vector128<UInt32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Collections.ObjectModel; using Gallio.Common.Collections; using Gallio.Common.Markup.Tags; namespace Gallio.Common.Markup { /// <summary> /// A structured text object contains attachments and formatted text with rich /// presentation elements. /// </summary> /// <remarks> /// <para> /// Structured text is emitted by a <see cref="StructuredTextWriter" />. /// </para> /// </remarks> /// <seealso cref="StructuredTextWriter"/> [Serializable] public sealed class StructuredText : IEquatable<StructuredText>, IMarkupStreamWritable { private readonly BodyTag bodyTag; private readonly IList<Attachment> attachments; /// <summary> /// Creates a simple structured text object over a plain text string. /// </summary> /// <param name="text">The text string.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="text"/> is null.</exception> public StructuredText(string text) { if (text == null) throw new ArgumentNullException("text"); bodyTag = new BodyTag(); bodyTag.Contents.Add(new TextTag(text)); attachments = EmptyArray<Attachment>.Instance; } /// <summary> /// Creates a structured text object that wraps the body tag of a structured markup document stream /// and no attachments. /// </summary> /// <param name="bodyTag">The body tag to wrap.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="bodyTag"/> is null.</exception> public StructuredText(BodyTag bodyTag) : this(bodyTag, EmptyArray<Attachment>.Instance) { } /// <summary> /// Creates a structured text object that wraps the body tag of a structured markup document stream /// and a list of attachments. /// </summary> /// <param name="bodyTag">The body tag to wrap.</param> /// <param name="attachments">The list of attachments.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="bodyTag"/>, /// or <paramref name="attachments"/> is null.</exception> public StructuredText(BodyTag bodyTag, IList<Attachment> attachments) { if (bodyTag == null) throw new ArgumentNullException("bodyTag"); if (attachments == null) throw new ArgumentNullException("attachments"); this.bodyTag = bodyTag; this.attachments = attachments; } /// <summary> /// Gets a copy of the body tag that describes the structured text. /// </summary> public BodyTag BodyTag { get { return bodyTag.Clone(); } } /// <summary> /// Gets the immutable list of attachments belonging to the structured text. /// </summary> public IList<Attachment> Attachments { get { return new ReadOnlyCollection<Attachment>(attachments); } } /// <summary> /// Returns the total length of all <see cref="TextTag" />s that appear within /// the structured text body. /// </summary> /// <returns>The total text length.</returns> public int GetTextLength() { TextLengthVisitor visitor = new TextLengthVisitor(); bodyTag.Accept(visitor); return visitor.Length; } /// <summary> /// Writes the structured text to a markup stream writer. /// </summary> /// <param name="writer">The writer.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="writer"/> is null.</exception> public void WriteTo(MarkupStreamWriter writer) { WritePreambleTo(writer); bodyTag.WriteTo(writer); } /// <summary> /// Writes the structured text to a markup stream writer and truncates its text /// to a particular maximum length, omitting all subsequent contents. /// </summary> /// <param name="writer">The writer.</param> /// <param name="maxLength">The maximum length of text to write.</param> /// <returns>True if truncation occurred.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="writer"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="maxLength"/> is negative.</exception> public bool TruncatedWriteTo(MarkupStreamWriter writer, int maxLength) { if (maxLength < 0) throw new ArgumentOutOfRangeException("maxLength", "Max length must not be negative."); WritePreambleTo(writer); TruncateTextVisitor visitor = new TruncateTextVisitor(writer, maxLength); bodyTag.Accept(visitor); return visitor.Truncating; } private void WritePreambleTo(MarkupStreamWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); foreach (Attachment attachment in attachments) writer.Container.Attach(attachment); } /// <summary> /// Formats the structured text to a string, discarding unrepresentable formatting details. /// </summary> /// <returns>The structured text as a string.</returns> public override string ToString() { return bodyTag.ToString(); } /// <inheritdoc /> public bool Equals(StructuredText other) { return other != null && GenericCollectionUtils.ElementsEqual(attachments, other.attachments) && bodyTag.Equals(other.bodyTag); } /// <inheritdoc /> public override bool Equals(object obj) { return Equals(obj as StructuredText); } /// <inheritdoc /> public override int GetHashCode() { return attachments.Count ^ bodyTag.GetHashCode(); } /// <summary> /// Returns true if two structured text objects are equal. /// </summary> /// <param name="a">The first structured text object to compare.</param> /// <param name="b">The second structured text object to compare.</param> /// <returns>True if the structured text objects are equal.</returns> public static bool operator ==(StructuredText a, StructuredText b) { return ReferenceEquals(a, b) || ! ReferenceEquals(a, null) && a.Equals(b); } /// <summary> /// Returns true if two structured text objects are not equal. /// </summary> /// <param name="a">The first structured text object to compare.</param> /// <param name="b">The second structured text object to compare.</param> /// <returns>True if the structured text objects are not equal.</returns> public static bool operator !=(StructuredText a, StructuredText b) { return !(a == b); } private sealed class TextLengthVisitor : BaseTagVisitor { public int Length { get; private set;} public override void VisitTextTag(TextTag tag) { Length += tag.Text.Length; } } private sealed class TruncateTextVisitor : BaseTagVisitor { private readonly MarkupStreamWriter writer; private readonly int maxLength; private int length; public TruncateTextVisitor(MarkupStreamWriter writer, int maxLength) { this.writer = writer; this.maxLength = maxLength; } public bool Truncating { get { return length > maxLength; } } public override void VisitSectionTag(SectionTag tag) { if (!Truncating) { using (writer.BeginSection(tag.Name)) tag.AcceptContents(this); } } public override void VisitMarkerTag(MarkerTag tag) { if (!Truncating) { using (writer.BeginMarker(tag.Marker)) tag.AcceptContents(this); } } public override void VisitEmbedTag(EmbedTag tag) { if (!Truncating) { writer.EmbedExisting(tag.AttachmentName); } } public override void VisitTextTag(TextTag tag) { if (! Truncating) { length += tag.Text.Length; if (length > maxLength) writer.Write(tag.Text.Substring(0, tag.Text.Length - length + maxLength)); else writer.Write(tag.Text); } } } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] partial class AllReadyContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<DateTimeOffset?>("EndDateTime"); b.Property<int?>("EventId"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<int?>("OrganizationId"); b.Property<DateTimeOffset?>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<int?>("OrganizationId"); b.Property<string>("PasswordHash"); b.Property<string>("PendingNewEmail"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<string>("TimeZoneId") .IsRequired(); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("ExternalUrl"); b.Property<string>("ExternalUrlText"); b.Property<bool>("Featured"); b.Property<string>("FullDescription"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<bool>("Locked"); b.Property<int>("ManagingOrganizationId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.Property<string>("TimeZoneId") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("OrganizationId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ClosestLocation", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<double>("Distance"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<int>("EventType"); b.Property<string>("ImageUrl"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<int?>("EventId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.Property<int>("EventId"); b.Property<int>("SkillId"); b.HasKey("EventId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("Date"); b.Property<int>("EventId"); b.Property<string>("Name"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.Property<int>("ItineraryId"); b.Property<Guid>("RequestId"); b.HasKey("ItineraryId", "RequestId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("PrivacyPolicy"); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.Property<int>("OrganizationId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("OrganizationId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b => { b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.HasKey("Latitude", "Longitude"); }); modelBuilder.Entity("AllReady.Models.Request", b => { b.Property<Guid>("RequestId") .ValueGeneratedOnAdd(); b.Property<string>("Address"); b.Property<string>("City"); b.Property<string>("Email"); b.Property<int?>("EventId"); b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.Property<string>("Name"); b.Property<string>("Phone"); b.Property<string>("ProviderData"); b.Property<string>("ProviderId"); b.Property<string>("State"); b.Property<int>("Status"); b.Property<string>("Zip"); b.HasKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OwningOrganizationId"); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<int?>("ItineraryId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("ManagingOrganizationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.Request") .WithMany() .HasForeignKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Request", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OwningOrganizationId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
//------------------------------------------------------------------------------ // <copyright file="ClientProxyGenerator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Script.Services { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Web; using System.Web.Script.Serialization; internal abstract class ClientProxyGenerator { private static string DebugXmlComments = @"/// <param name=""succeededCallback"" type=""Function"" optional=""true"" mayBeNull=""true""></param> /// <param name=""failedCallback"" type=""Function"" optional=""true"" mayBeNull=""true""></param> /// <param name=""userContext"" optional=""true"" mayBeNull=""true""></param> "; private Hashtable _registeredNamespaces = new Hashtable(); private Hashtable _ensuredObjectParts = new Hashtable(); protected StringBuilder _builder; protected bool _debugMode; // comments are the same in the instance methods as they are in the static methods // this cache is used when calculating comments for instance methods, then re-used when // writing out static methods. private Dictionary<string, string> _docCommentCache; internal string GetClientProxyScript(WebServiceData webServiceData) { if (webServiceData.MethodDatas.Count == 0) return null; _builder = new StringBuilder(); if (_debugMode) { _docCommentCache = new Dictionary<string, string>(); } // Constructor GenerateConstructor(webServiceData); // Prototype functions GeneratePrototype(webServiceData); GenerateRegisterClass(webServiceData); GenerateStaticInstance(webServiceData); GenerateStaticMethods(webServiceData); // Generate some client proxy to make some types instantiatable on the client GenerateClientTypeProxies(webServiceData); GenerateEnumTypeProxies(webServiceData.EnumTypes); return _builder.ToString(); } protected void GenerateRegisterClass(WebServiceData webServiceData) { // Generate registerClass: Foo.NS.WebService.registerClass('Foo.NS.WebService', Sys.Net.WebServiceProxy); string typeName = GetProxyTypeName(webServiceData); _builder.Append(typeName).Append(".registerClass('").Append(typeName).Append("',Sys.Net.WebServiceProxy);\r\n"); } protected virtual void GenerateConstructor(WebServiceData webServiceData) { GenerateTypeDeclaration(webServiceData, false); _builder.Append("function() {\r\n"); _builder.Append(GetProxyTypeName(webServiceData)).Append(".initializeBase(this);\r\n"); GenerateFields(); _builder.Append("}\r\n"); } protected virtual void GeneratePrototype(WebServiceData webServiceData) { GenerateTypeDeclaration(webServiceData, true); _builder.Append("{\r\n"); // private method to return the path to be used , returns _path from current instance if set, otherwise returns _path from static instance. _builder.Append("_get_path:function() {\r\n var p = this.get_path();\r\n if (p) return p;\r\n else return "); _builder.Append(GetProxyTypeName(webServiceData)).Append("._staticInstance.get_path();},\r\n"); bool first = true; foreach (WebServiceMethodData methodData in webServiceData.MethodDatas) { if (!first) { _builder.Append(",\r\n"); } first = false; GenerateWebMethodProxy(methodData); } _builder.Append("}\r\n"); } protected virtual void GenerateTypeDeclaration(WebServiceData webServiceData, bool genClass) { AppendClientTypeDeclaration(webServiceData.TypeData.TypeNamespace, webServiceData.TypeData.TypeName, genClass, true); } protected void GenerateFields() { _builder.Append("this._timeout = 0;\r\n"); _builder.Append("this._userContext = null;\r\n"); _builder.Append("this._succeeded = null;\r\n"); _builder.Append("this._failed = null;\r\n"); } protected virtual void GenerateMethods() { } protected void GenerateStaticMethods(WebServiceData webServiceData) { string className = GetProxyTypeName(webServiceData); // Now generate static methods NS.Service.MyMethod = function() foreach (WebServiceMethodData methodData in webServiceData.MethodDatas) { string methodName = methodData.MethodName; _builder.Append(className).Append('.').Append(methodName).Append("= function("); StringBuilder argBuilder = new StringBuilder(); bool first = true; foreach (WebServiceParameterData paramData in methodData.ParameterDatas) { if (!first) argBuilder.Append(','); else first = false; argBuilder.Append(paramData.ParameterName); } if (!first) argBuilder.Append(','); argBuilder.Append("onSuccess,onFailed,userContext"); _builder.Append(argBuilder.ToString()).Append(") {"); if (_debugMode) { // doc comments should have been computed already _builder.Append("\r\n"); _builder.Append(_docCommentCache[methodName]); } _builder.Append(className).Append("._staticInstance.").Append(methodName).Append('('); _builder.Append(argBuilder.ToString()).Append("); }\r\n"); } } protected abstract string GetProxyPath(); protected virtual string GetJsonpCallbackParameterName() { return null; } protected virtual bool GetSupportsJsonp() { return false; } protected void GenerateStaticInstance(WebServiceData data) { string typeName = GetProxyTypeName(data); _builder.Append(typeName).Append("._staticInstance = new ").Append(typeName).Append("();\r\n"); // Generate the static properties if (_debugMode) { _builder.Append(typeName).Append(".set_path = function(value) {\r\n"); _builder.Append(typeName).Append("._staticInstance.set_path(value); }\r\n"); _builder.Append(typeName).Append(".get_path = function() { \r\n/// <value type=\"String\" mayBeNull=\"true\">The service url.</value>\r\nreturn "); _builder.Append(typeName).Append("._staticInstance.get_path();}\r\n"); _builder.Append(typeName).Append(".set_timeout = function(value) {\r\n"); _builder.Append(typeName).Append("._staticInstance.set_timeout(value); }\r\n"); _builder.Append(typeName).Append(".get_timeout = function() { \r\n/// <value type=\"Number\">The service timeout.</value>\r\nreturn "); _builder.Append(typeName).Append("._staticInstance.get_timeout(); }\r\n"); _builder.Append(typeName).Append(".set_defaultUserContext = function(value) { \r\n"); _builder.Append(typeName).Append("._staticInstance.set_defaultUserContext(value); }\r\n"); _builder.Append(typeName).Append(".get_defaultUserContext = function() { \r\n/// <value mayBeNull=\"true\">The service default user context.</value>\r\nreturn "); _builder.Append(typeName).Append("._staticInstance.get_defaultUserContext(); }\r\n"); _builder.Append(typeName).Append(".set_defaultSucceededCallback = function(value) { \r\n "); _builder.Append(typeName).Append("._staticInstance.set_defaultSucceededCallback(value); }\r\n"); _builder.Append(typeName).Append(".get_defaultSucceededCallback = function() { \r\n/// <value type=\"Function\" mayBeNull=\"true\">The service default succeeded callback.</value>\r\nreturn "); _builder.Append(typeName).Append("._staticInstance.get_defaultSucceededCallback(); }\r\n"); _builder.Append(typeName).Append(".set_defaultFailedCallback = function(value) { \r\n"); _builder.Append(typeName).Append("._staticInstance.set_defaultFailedCallback(value); }\r\n"); _builder.Append(typeName).Append(".get_defaultFailedCallback = function() { \r\n/// <value type=\"Function\" mayBeNull=\"true\">The service default failed callback.</value>\r\nreturn "); _builder.Append(typeName).Append("._staticInstance.get_defaultFailedCallback(); }\r\n"); _builder.Append(typeName).Append(".set_enableJsonp = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_enableJsonp(value); }\r\n"); _builder.Append(typeName).Append(".get_enableJsonp = function() { \r\n/// <value type=\"Boolean\">Specifies whether the service supports JSONP for cross domain calling.</value>\r\nreturn "); _builder.Append(typeName).Append("._staticInstance.get_enableJsonp(); }\r\n"); _builder.Append(typeName).Append(".set_jsonpCallbackParameter = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_jsonpCallbackParameter(value); }\r\n"); _builder.Append(typeName).Append(".get_jsonpCallbackParameter = function() { \r\n/// <value type=\"String\">Specifies the parameter name that contains the callback function name for a JSONP request.</value>\r\nreturn "); _builder.Append(typeName).Append("._staticInstance.get_jsonpCallbackParameter(); }\r\n"); } else { _builder.Append(typeName).Append(".set_path = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_path(value); }\r\n"); _builder.Append(typeName).Append(".get_path = function() { return "); _builder.Append(typeName).Append("._staticInstance.get_path(); }\r\n"); _builder.Append(typeName).Append(".set_timeout = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_timeout(value); }\r\n"); _builder.Append(typeName).Append(".get_timeout = function() { return "); _builder.Append(typeName).Append("._staticInstance.get_timeout(); }\r\n"); _builder.Append(typeName).Append(".set_defaultUserContext = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_defaultUserContext(value); }\r\n"); _builder.Append(typeName).Append(".get_defaultUserContext = function() { return "); _builder.Append(typeName).Append("._staticInstance.get_defaultUserContext(); }\r\n"); _builder.Append(typeName).Append(".set_defaultSucceededCallback = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_defaultSucceededCallback(value); }\r\n"); _builder.Append(typeName).Append(".get_defaultSucceededCallback = function() { return "); _builder.Append(typeName).Append("._staticInstance.get_defaultSucceededCallback(); }\r\n"); _builder.Append(typeName).Append(".set_defaultFailedCallback = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_defaultFailedCallback(value); }\r\n"); _builder.Append(typeName).Append(".get_defaultFailedCallback = function() { return "); _builder.Append(typeName).Append("._staticInstance.get_defaultFailedCallback(); }\r\n"); _builder.Append(typeName).Append(".set_enableJsonp = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_enableJsonp(value); }\r\n"); _builder.Append(typeName).Append(".get_enableJsonp = function() { return "); _builder.Append(typeName).Append("._staticInstance.get_enableJsonp(); }\r\n"); _builder.Append(typeName).Append(".set_jsonpCallbackParameter = function(value) { "); _builder.Append(typeName).Append("._staticInstance.set_jsonpCallbackParameter(value); }\r\n"); _builder.Append(typeName).Append(".get_jsonpCallbackParameter = function() { return "); _builder.Append(typeName).Append("._staticInstance.get_jsonpCallbackParameter(); }\r\n"); } // the path has to be the full absolete path if this is a JSONP enabled service. But it is the responsibility // of the caller to GetClientProxyScript to pass the full path if appropriate since determining it may be // dependant on the specific technology. string proxyPath = GetProxyPath(); if (!String.IsNullOrEmpty(proxyPath) && (proxyPath.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || proxyPath.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) { // DevDiv 91322: avoid url encoding the domain portion of an IDN url // find the first "/" after the scheme, and only encode after that. int domainStart = proxyPath.IndexOf("://", StringComparison.OrdinalIgnoreCase) + "://".Length; int domainEnd = proxyPath.IndexOf("/", domainStart, StringComparison.OrdinalIgnoreCase); // if no slash after :// was found, it could be a domain only url, http://[some service].com, don't encode any of it if (domainEnd != -1) { proxyPath = proxyPath.Substring(0, domainEnd) + HttpUtility.UrlPathEncode(proxyPath.Substring(domainEnd)); } } else { // it doesn't appear to be an absolute url, at least not an http or https one. All relative paths // and other oddities are safely encoded with UrlPathEncode. proxyPath = HttpUtility.UrlPathEncode(proxyPath); } _builder.Append(typeName).Append(".set_path(\"").Append(proxyPath).Append("\");\r\n"); if (GetSupportsJsonp()) { _builder.Append(typeName).Append(".set_enableJsonp(true);\r\n"); string jsonpParameterName = GetJsonpCallbackParameterName(); if (!String.IsNullOrEmpty(jsonpParameterName) && !jsonpParameterName.Equals("callback", StringComparison.Ordinal)) { _builder.Append(typeName).Append(".set_jsonpCallbackParameter(").Append(JavaScriptSerializer.SerializeInternal(jsonpParameterName)).Append(");\r\n"); } } } private void BuildArgsDictionary(WebServiceMethodData methodData, StringBuilder args, StringBuilder argsDict, StringBuilder docComments) { argsDict.Append('{'); foreach (WebServiceParameterData paramData in methodData.ParameterDatas) { string name = paramData.ParameterName; if (docComments != null) { // looks like: /// <param name="foo" type="ClientType">Namespace.ServerType</param> // client type may not match server type for built in js types like date, number, etc. // client type may be omitted for type Object. docComments.Append("/// <param name=\"").Append(name).Append("\""); Type serverType = ServicesUtilities.UnwrapNullableType(paramData.ParameterType); string clientType = GetClientTypeNamespace(ServicesUtilities.GetClientTypeFromServerType(methodData.Owner, serverType)); if (!String.IsNullOrEmpty(clientType)) { docComments.Append(" type=\"").Append(clientType).Append("\""); } docComments.Append(">").Append(serverType.FullName).Append("</param>\r\n"); } if (args.Length > 0) { args.Append(','); argsDict.Append(','); } args.Append(name); argsDict.Append(name).Append(':').Append(name); } if (docComments != null) { // append the built-in comments that all methods have (success, failed, usercontext parameters) docComments.Append(DebugXmlComments); } argsDict.Append("}"); if (args.Length > 0) { args.Append(','); } args.Append("succeededCallback, failedCallback, userContext"); } private void GenerateWebMethodProxy(WebServiceMethodData methodData) { string methodName = methodData.MethodName; string typeName = GetProxyTypeName(methodData.Owner); string useGet = methodData.UseGet ? "true" : "false"; _builder.Append(methodName).Append(':'); // e.g. MyMethod : function(param1, param2, ..., OnSuccess, OnFailure) StringBuilder args = new StringBuilder(); StringBuilder argsDict = new StringBuilder(); StringBuilder docComments = null; string docCommentsString = null; if (_debugMode) { docComments = new StringBuilder(); } BuildArgsDictionary(methodData, args, argsDict, docComments); if (_debugMode) { // Remember the doc comments for the static instance case docCommentsString = docComments.ToString(); _docCommentCache[methodName] = docCommentsString; } // Method calls look like this.invoke(FooNS.Sub.Method.get_path(), 'MethodName', true[useGet], {'arg1':'val1', 'arg2':'val2' }, onComplete, onError, userContext, 'FooNS.Sub.Method') _builder.Append("function(").Append(args.ToString()).Append(") {\r\n"); if (_debugMode) { // docCommentsString always end in \r\n _builder.Append(docCommentsString); } _builder.Append("return this._invoke(this._get_path(), "); _builder.Append("'").Append(methodName).Append("',"); _builder.Append(useGet).Append(','); _builder.Append(argsDict.ToString()).Append(",succeededCallback,failedCallback,userContext); }"); } /* e.g var Qqq = function() { this.__type = "Qqq"; } */ private void GenerateClientTypeProxies(WebServiceData data) { bool first = true; foreach (WebServiceTypeData t in data.ClientTypes) { if (first) { _builder.Append("var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;\r\n"); first = false; } string typeID = data.GetTypeStringRepresentation(t); string typeNameWithClientNamespace = GetClientTypeNamespace(t.TypeName); string typeName = ServicesUtilities.GetClientTypeName(typeNameWithClientNamespace); string clientTypeNamespace = GetClientTypeNamespace(t.TypeNamespace); EnsureNamespace(t.TypeNamespace); EnsureObjectGraph(clientTypeNamespace, typeName); _builder.Append("if (typeof(").Append(typeName).Append(") === 'undefined') {\r\n"); AppendClientTypeDeclaration(clientTypeNamespace, typeNameWithClientNamespace, false, false); // Need to use the _type id, which isn't necessarly the real name _builder.Append("gtc(\""); _builder.Append(typeID); _builder.Append("\");\r\n"); _builder.Append(typeName).Append(".registerClass('").Append(typeName).Append("');\r\n}\r\n"); } } // Create client stubs for all the enums private void GenerateEnumTypeProxies(IEnumerable<WebServiceEnumData> enumTypes) { foreach (WebServiceEnumData t in enumTypes) { EnsureNamespace(t.TypeNamespace); string typeNameWithClientNamespace = GetClientTypeNamespace(t.TypeName); string typeName = ServicesUtilities.GetClientTypeName(typeNameWithClientNamespace); string[] enumNames = t.Names; long[] enumValues = t.Values; Debug.Assert(enumNames.Length == enumValues.Length); EnsureObjectGraph(GetClientTypeNamespace(t.TypeNamespace), typeName); _builder.Append("if (typeof(").Append(typeName).Append(") === 'undefined') {\r\n"); if (typeName.IndexOf('.') == -1) { _builder.Append("var "); } _builder.Append(typeName).Append(" = function() { throw Error.invalidOperation(); }\r\n"); _builder.Append(typeName).Append(".prototype = {"); for (int i = 0; i < enumNames.Length; i++) { if (i > 0) _builder.Append(','); _builder.Append(enumNames[i]); _builder.Append(": "); if (t.IsULong) { _builder.Append((ulong)enumValues[i]); } else { _builder.Append(enumValues[i]); } } _builder.Append("}\r\n"); _builder.Append(typeName).Append(".registerEnum('").Append(typeName).Append('\''); _builder.Append(", true);\r\n}\r\n"); } } protected virtual string GetClientTypeNamespace(string ns) { return ns; } private void AppendClientTypeDeclaration(string ns, string typeName, bool genClass, bool ensureNS) { // Register the namespace if any // e.g. registerNamespace('MyNS.MySubNS'); string name = GetClientTypeNamespace(ServicesUtilities.GetClientTypeName(typeName)); if (!String.IsNullOrEmpty(ns)) { if (ensureNS) EnsureNamespace(ns); } else if (!genClass) { // If there is no namespace, we need a var to declare the variable if (!name.Contains(".")) { // if name contains '.', an object graph was already ensured and we dont need 'var'. _builder.Append("var "); } } _builder.Append(name); if (genClass) { _builder.Append(".prototype"); } _builder.Append('='); _ensuredObjectParts[name] = null; } // Normally returns MyNS.MySubNS.MyWebService OR var MyWebService, PageMethods will return PageMethods protected virtual string GetProxyTypeName(WebServiceData data) { return ServicesUtilities.GetClientTypeName(data.TypeData.TypeName); } private void EnsureNamespace(string ns) { //Give derived proxy generator a chance to transform namespace ( used by WCF) ns = GetClientTypeNamespace(ns); if (String.IsNullOrEmpty(ns)) return; // Don't register a given namespace more than once if (!_registeredNamespaces.Contains(ns)) { _builder.Append("Type.registerNamespace('").Append(ns).Append("');\r\n"); _registeredNamespaces[ns] = null; } } private void EnsureObjectGraph(string namespacePart, string typeName) { // When a type name includes dots, such as 'MyNamespace.MyClass.MyNestedClass', // this method writes code that ensures all the parts leading up to the actual class name // are either already namespaces or are at least Objects. // namespacePart is here so we dont unnecessarily ensure the first part that contains the // namespace is checked for. For example, if we have NS1.NS2.NS3.TYPE, the check for // _registeredNamespaces will find NS1.NS2.NS3 but not NS1 and NS1.NS2, so we'd insert // checks that NS1 and NS1.NS2 are objects, unnecessarily. int startFrom = 0; bool first = true; if (!String.IsNullOrEmpty(namespacePart)) { int nsIndex = typeName.IndexOf(namespacePart + ".", StringComparison.Ordinal); // in wcf services, the typeName starts with the namespace, // in asmx services, it doesnt. if (nsIndex > -1) { startFrom = nsIndex + namespacePart.Length + 1; first = false; } } int dotIndex = typeName.IndexOf('.', startFrom); while (dotIndex > -1) { string fullPath = typeName.Substring(0, dotIndex); if (!_registeredNamespaces.Contains(fullPath) && !_ensuredObjectParts.Contains(fullPath)) { _ensuredObjectParts[fullPath] = null; _builder.Append("if (typeof(" + fullPath + ") === \"undefined\") {\r\n "); if (first) { // var foo = {}; _builder.Append("var "); first = false; } // foo.bar = {}; _builder.Append(fullPath + " = {};\r\n}\r\n"); } dotIndex = typeName.IndexOf('.', dotIndex + 1); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Buffers; using System.Buffers.Text; using System.Diagnostics; namespace System.Text.Formatting { // This whole API is very speculative, i.e. I am not sure I am happy with the design // This API is trying to do composite formatting without boxing (or any other allocations). // And because not all types in the platfrom implement IBufferFormattable (in particular built-in primitives don't), // it needs to play some tricks with generic type parameters. But as you can see at the end of AppendUntyped, I am not sure how to tick the type system // not never box. public static class CompositeFormattingExtensions { public static void Format<TFormatter, T0>(this TFormatter formatter, string compositeFormat, T0 arg0) where TFormatter : ITextOutput { var reader = new CompositeFormatReader(compositeFormat); while (true) { var segment = reader.Next(); if (segment == null) return; if (segment.Value.Count == 0) // insertion point { if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format); else throw new Exception("invalid insertion point"); } else // literal { formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count); } } } public static void Format<TFormatter, T0, T1>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1) where TFormatter : ITextOutput { var reader = new CompositeFormatReader(compositeFormat); while (true) { var segment = reader.Next(); if (segment == null) return; if (segment.Value.Count == 0) // insertion point { if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format); else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format); else throw new Exception("invalid insertion point"); } else // literal { formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count); } } } public static void Format<TFormatter, T0, T1, T2>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2) where TFormatter : ITextOutput { var reader = new CompositeFormatReader(compositeFormat); while (true) { var segment = reader.Next(); if (segment == null) return; if (segment.Value.Count == 0) // insertion point { if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format); else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format); else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format); else throw new Exception("invalid insertion point"); } else // literal { formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count); } } } public static void Format<TFormatter, T0, T1, T2, T3>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2, T3 arg3) where TFormatter : ITextOutput { var reader = new CompositeFormatReader(compositeFormat); while (true) { var segment = reader.Next(); if (segment == null) return; if (segment.Value.Count == 0) // insertion point { if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format); else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format); else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format); else if (segment.Value.Index == 3) formatter.AppendUntyped(arg3, segment.Value.Format); else throw new Exception("invalid insertion point"); } else // literal { formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count); } } } public static void Format<TFormatter, T0, T1, T2, T3, T4>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) where TFormatter : ITextOutput { var reader = new CompositeFormatReader(compositeFormat); while (true) { var segment = reader.Next(); if (segment == null) return; if (segment.Value.Count == 0) // insertion point { if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format); else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format); else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format); else if (segment.Value.Index == 3) formatter.AppendUntyped(arg3, segment.Value.Format); else if (segment.Value.Index == 4) formatter.AppendUntyped(arg4, segment.Value.Format); else throw new Exception("invalid insertion point"); } else // literal { formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count); } } } // TODO: this should be removed and an ability to append substrings should be added static void Append<TFormatter>(this TFormatter formatter, string whole, int index, int count) where TFormatter : ITextOutput { var buffer = formatter.Buffer; var maxBytes = count << 4; // this is the worst case, i.e. 4 bytes per char while(buffer.Length < maxBytes) { formatter.Enlarge(maxBytes); buffer = formatter.Buffer; } // this should be optimized using fixed pointer to substring, but I will wait with this till we design proper substring var characters = whole.Slice(index, count); if (!formatter.TryAppend(characters, formatter.SymbolTable)) { Debug.Assert(false, "this should never happen"); // because I pre-resized the buffer to 4 bytes per char at the top of this method. } } static void AppendUntyped<TFormatter, T>(this TFormatter formatter, T value, ParsedFormat format) where TFormatter : ITextOutput { #region Built in types var i32 = value as int?; if (i32 != null) { formatter.Append(i32.Value, format); return; } var i64 = value as long?; if (i64 != null) { formatter.Append(i64.Value, format); return; } var i16 = value as short?; if (i16 != null) { formatter.Append(i16.Value, format); return; } var b = value as byte?; if (b != null) { formatter.Append(b.Value, format); return; } var c = value as char?; if (c != null) { formatter.Append(c.Value); return; } var u32 = value as uint?; if (u32 != null) { formatter.Append(u32.Value, format); return; } var u64 = value as ulong?; if (u64 != null) { formatter.Append(u64.Value, format); return; } var u16 = value as ushort?; if (u16 != null) { formatter.Append(u16.Value, format); return; } var sb = value as sbyte?; if (sb != null) { formatter.Append(sb.Value, format); return; } var str = value as string; if (str != null) { formatter.Append(str); return; } var dt = value as DateTime?; if (dt != null) { formatter.Append(dt.Value, format); return; } var dto = value as DateTimeOffset?; if (dto != null) { formatter.Append(dto.Value, format); return; } var ts = value as TimeSpan?; if (ts != null) { formatter.Append(ts.Value, format); return; } var guid = value as Guid?; if (guid != null) { formatter.Append(guid.Value, format); return; } #endregion if (value is IBufferFormattable) { formatter.Append((IBufferFormattable)value, format); // this is boxing. not sure how to avoid it. return; } throw new NotSupportedException("value is not formattable."); } // this is just a state machine walking the composite format and instructing CompositeFormattingExtensions.Format overloads on what to do. // this whole type is not just a hacky prototype. // I will clean it up later if I decide that I like this whole composite format model. struct CompositeFormatReader { string _compositeFormatString; int _currentIndex; int _spanStart; State _state; public CompositeFormatReader(string format) { _compositeFormatString = format; _currentIndex = 0; _spanStart = 0; _state = State.New; } public CompositeSegment? Next() { while (_currentIndex < _compositeFormatString.Length) { char c = _compositeFormatString[_currentIndex]; if (c == '{') { if (_state == State.Literal) { _state = State.New; return CompositeSegment.Literal(_spanStart, _currentIndex); } if ((_currentIndex + 1 < _compositeFormatString.Length) && (_compositeFormatString[_currentIndex + 1] == c)) { _state = State.Literal; _currentIndex++; _spanStart = _currentIndex; } else { _currentIndex++; return ParseInsertionPoint(); } } else if (c == '}') { if ((_currentIndex + 1 < _compositeFormatString.Length) && (_compositeFormatString[_currentIndex + 1] == c)) { if (_state == State.Literal) { _state = State.New; return CompositeSegment.Literal(_spanStart, _currentIndex); } _state = State.Literal; _currentIndex++; _spanStart = _currentIndex; } else { throw new Exception("missing start bracket"); } } else { if (_state != State.Literal) { _state = State.Literal; _spanStart = _currentIndex; } } _currentIndex++; } if (_state == State.Literal) { _state = State.New; return CompositeSegment.Literal(_spanStart, _currentIndex); } return null; } // this should be replaced with InvariantFormatter.Parse static bool TryParse(string compositeFormat, int start, int count, out uint value, out int consumed) { consumed = 0; value = 0; for (int i = start; i < start + count; i++) { var digit = (byte)(compositeFormat[i] - '0'); if (digit >= 0 && digit <= 9) { value *= 10; value += digit; consumed++; } else { if (i == start) return false; else return true; } } return true; } CompositeSegment ParseInsertionPoint() { uint arg; int consumed; char? formatSpecifier = null; if (!TryParse(_compositeFormatString, _currentIndex, 5, out arg, out consumed)) { throw new Exception("invalid insertion point"); } _currentIndex += consumed; if (_currentIndex >= _compositeFormatString.Length) { throw new Exception("missing end bracket"); } if(_compositeFormatString[_currentIndex] == ':') { _currentIndex++; formatSpecifier = _compositeFormatString[_currentIndex]; _currentIndex++; } if (_compositeFormatString[_currentIndex] != '}') { throw new Exception("missing end bracket"); } _currentIndex++; var parsedFormat = (formatSpecifier.HasValue && formatSpecifier.Value != 0) ? new ParsedFormat(formatSpecifier.Value) : default; return CompositeSegment.InsertionPoint(arg, parsedFormat); } public enum State : byte { New, Literal, InsertionPoint } public struct CompositeSegment { public ParsedFormat Format { get; private set; } public int Index { get; private set; } public int Count { get; private set; } public static CompositeSegment InsertionPoint(uint argIndex, ParsedFormat format) { return new CompositeSegment() { Index = (int)argIndex, Format = format }; } public static CompositeSegment Literal(int startIndex, int endIndex) { return new CompositeSegment() { Index = startIndex, Count = endIndex - startIndex }; } } } } }
using System.Web; using System.Web.Mvc; using System.Web.Routing; using MbUnit.Framework; using Moq; using STRouting = Subtext.Framework.Routing; namespace UnitTests.Subtext.Framework.Routing { [TestFixture] public class RootRouteTests { [Test] public void GetRouteDataWithRequestForAppRoot_WhenAggregationEnabled_MatchesAndReturnsAggDefault() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/", string.Empty /* subfolder */, "~/"); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/AggDefault.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); Assert.IsFalse(routeData.DataTokens.ContainsKey(STRouting.PageRoute.ControlNamesKey)); } [Test] public void GetRouteDataWithRequestForAppRoot_WhenAggregationDisabled_MatchesAndReturnsDtp() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/", string.Empty /* subfolder */, "~/"); var route = new STRouting.RootRoute(false, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); Assert.IsTrue(routeData.DataTokens.ContainsKey(STRouting.PageRoute.ControlNamesKey)); } [Test] public void GetRouteDataWithRequestForSubfolder_WhenAggregationEnabled_MatchesRequestAndReturnsDtp() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/subfolder", "subfolder" /* subfolder */, "~/"); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); } [Test] public void GetRouteDataWithRequestForSubfolder_WhenAggregationDisabled_MatchesRequestAndReturnsDtp() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/subfolder", "subfolder" /* subfolder */, "~/"); var route = new STRouting.RootRoute(false, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); } [Test] public void GetRouteDataWithRequestWithSubfolder_WhenAggregationEnabledAndBlogDoesNotHaveSubfolder_DoesNotMatch() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/foo", string.Empty /* subfolder */, "~/"); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert Assert.IsNull(routeData); } [Test] public void GetRouteDataWithRequestWithSubfolder_WhenAggregationDisabledAndBlogDoesNotHaveSubfolder_DoesNotMatch () { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/foo", string.Empty /* subfolder */, "~/"); var route = new STRouting.RootRoute(false, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert Assert.IsNull(routeData); } [Test] public void GetRouteDataWithRequestWithSubfolder_WhenAggregationEnabledAndSubfolderDoesNotMatchBlogSubfolder_DoesNotMatch () { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/foo", "bar" /* subfolder */, "~/"); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert Assert.IsNull(routeData); } [Test] public void GetRouteDataWithRequestWithSubfolder_WhenAggregationDisabledAndSubfolderDoesNotMatchBlogSubfolder_DoesNotMatch () { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/foo", "bar" /* subfolder */, "~/"); var route = new STRouting.RootRoute(false, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert Assert.IsNull(routeData); } [Test] public void GetRouteDataWithRequestForDefault_WhenAggregationEnabled_MatchesAndReturnsAggDefault() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/Default.aspx", string.Empty /* subfolder */, "~/"); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/AggDefault.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); } [Test] public void GetRouteDataWithRequestForDefault_WhenAggregationDisabled_MatchesAndReturnsDtp() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/Default.aspx", string.Empty /* subfolder */, "~/"); var route = new STRouting.RootRoute(false, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); } [Test] public void GetRouteDataWithRequestForDefaultInSubfolder_WhenAggregationEnabled_MatchesRequestAndReturnsDtp() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/"); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); } [Test] public void GetRouteDataWithRequestForDefaultInSubfolder_WhenAggregationDisabled_MatchesRequestAndReturnsDtp() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/"); var route = new STRouting.RootRoute(false, new Mock<IDependencyResolver>().Object); //act RouteData routeData = route.GetRouteData(httpContext.Object); //assert var routeHandler = routeData.RouteHandler as STRouting.PageRouteHandler; Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath); Assert.AreSame(route, routeData.Route); } [Test] public void GetVirtualPath_WhenAggregationEnabledAndNoSubfolderInRouteData_ReturnsRoot() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/default.aspx", string.Empty /* subfolder */, "~/"); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext.Object, routeData); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); var routeValues = new RouteValueDictionary(); //act VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues); //assert Assert.AreEqual(string.Empty, virtualPathInfo.VirtualPath); } [Test] public void GetVirtualPath_WhenAggregationEnabledWithSubfolderInRouteData_ReturnsSubfolder() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/"); var routeData = new RouteData(); routeData.Values.Add("subfolder", "subfolder"); var requestContext = new RequestContext(httpContext.Object, routeData); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); var routeValues = new RouteValueDictionary(); //act VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues); //assert Assert.AreEqual("subfolder", virtualPathInfo.VirtualPath); } [Test] public void GetVirtualPath_WhenAggregationEnabledWithSubfolderInRouteValues_ReturnsSubfolder() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/"); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext.Object, routeData); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); var routeValues = new RouteValueDictionary(new { subfolder = "subfolder" }); //act VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues); //assert Assert.AreEqual("subfolder", virtualPathInfo.VirtualPath); } [Test] public void GetVirtualPath_WhenSupplyingRouteValues_AppendsValuesToQueryString() { //arrange var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/subfolder/default.aspx", string.Empty /* subfolder */, "~/"); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext.Object, routeData); var route = new STRouting.RootRoute(true, new Mock<IDependencyResolver>().Object); var routeValues = new RouteValueDictionary(new { foo = "bar" }); //act VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues); //assert Assert.AreEqual(virtualPathInfo.VirtualPath, "?foo=bar"); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Workflow.Activities { using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Drawing.Design; using System.Diagnostics.CodeAnalysis; using System.Net.Security; using System.Reflection; using System.ServiceModel; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; [Browsable(true)] [DesignerSerializer(typeof(DependencyObjectCodeDomSerializer), typeof(CodeDomSerializer))] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class OperationParameterInfo : DependencyObject { [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly DependencyProperty AttributesProperty = DependencyProperty.Register("Attributes", typeof(ParameterAttributes), typeof(OperationParameterInfo), new PropertyMetadata(DependencyPropertyOptions.Metadata)); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(OperationParameterInfo), new PropertyMetadata(null, DependencyPropertyOptions.Metadata)); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly DependencyProperty ParameterTypeProperty = DependencyProperty.Register("ParameterType", typeof(Type), typeof(OperationParameterInfo), new PropertyMetadata(typeof(void), DependencyPropertyOptions.Metadata)); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly DependencyProperty PositionProperty = DependencyProperty.Register("Position", typeof(int), typeof(OperationParameterInfo), new PropertyMetadata(-1, DependencyPropertyOptions.Metadata)); public OperationParameterInfo() { } public OperationParameterInfo(string parameterName) { SetValue(NameProperty, parameterName); } internal OperationParameterInfo(ParameterInfo parameter) { if (parameter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameter"); } SetValue(OperationParameterInfo.NameProperty, parameter.Name); SetValue(OperationParameterInfo.PositionProperty, parameter.Position); SetValue(OperationParameterInfo.AttributesProperty, parameter.Attributes); SetValue(OperationParameterInfo.ParameterTypeProperty, parameter.ParameterType); } public ParameterAttributes Attributes { get { return (ParameterAttributes) GetValue(AttributesProperty); } set { SetValue(AttributesProperty, value); } } public bool IsIn { get { return ((this.Attributes & ParameterAttributes.In) != 0); } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public bool IsLcid { get { return ((this.Attributes & ParameterAttributes.Lcid) != 0); } } public bool IsOptional { get { return ((this.Attributes & ParameterAttributes.Optional) != 0); } } public bool IsOut { get { return ((this.Attributes & ParameterAttributes.Out) != 0); } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public bool IsRetval { get { return ((this.Attributes & ParameterAttributes.Retval) != 0); } } public string Name { get { return (string) GetValue(NameProperty); } set { SetValue(NameProperty, value); } } public Type ParameterType { get { return (Type) GetValue(ParameterTypeProperty); } set { SetValue(ParameterTypeProperty, value); } } public int Position { get { return (int) GetValue(PositionProperty); } set { SetValue(PositionProperty, value); } } public OperationParameterInfo Clone() { OperationParameterInfo clonedParameter = new OperationParameterInfo(); clonedParameter.Name = this.Name; clonedParameter.Attributes = this.Attributes; clonedParameter.Position = this.Position; clonedParameter.ParameterType = this.ParameterType; return clonedParameter; } public override bool Equals(object obj) { OperationParameterInfo parameter = obj as OperationParameterInfo; if (parameter == null) { return false; } if (String.Compare(parameter.Name, this.Name, StringComparison.Ordinal) != 0) { return false; } if (parameter.Attributes != this.Attributes) { return false; } if (parameter.Position != this.Position) { return false; } if (parameter.ParameterType != this.ParameterType) { return false; } return true; } public override int GetHashCode() { return base.GetHashCode(); } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers.ProtoGen { internal class RepeatedEnumFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator { internal RepeatedEnumFieldGenerator(FieldDescriptor descriptor, int fieldOrdinal) : base(descriptor, fieldOrdinal) { } public void GenerateMembers(TextGenerator writer) { if (Descriptor.IsPacked && OptimizeSpeed) { writer.WriteLine("private int {0}MemoizedSerializedSize;", Name); } writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name); AddDeprecatedFlag(writer); writer.WriteLine("public scg::IList<{0}> {1}List {{", TypeName, PropertyName); writer.WriteLine(" get {{ return pbc::Lists.AsReadOnly({0}_); }}", Name); writer.WriteLine("}"); // TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option. AddDeprecatedFlag(writer); writer.WriteLine("public int {0}Count {{", PropertyName); writer.WriteLine(" get {{ return {0}_.Count; }}", Name); writer.WriteLine("}"); AddDeprecatedFlag(writer); writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName); writer.WriteLine(" return {0}_[index];", Name); writer.WriteLine("}"); } public void GenerateBuilderMembers(TextGenerator writer) { // Note: We can return the original list here, because we make it unmodifiable when we build // We return it via IPopsicleList so that collection initializers work more pleasantly. AddDeprecatedFlag(writer); writer.WriteLine("public pbc::IPopsicleList<{0}> {1}List {{", TypeName, PropertyName); writer.WriteLine(" get {{ return PrepareBuilder().{0}_; }}", Name); writer.WriteLine("}"); AddDeprecatedFlag(writer); writer.WriteLine("public int {0}Count {{", PropertyName); writer.WriteLine(" get {{ return result.{0}Count; }}", PropertyName); writer.WriteLine("}"); AddDeprecatedFlag(writer); writer.WriteLine("public {0} Get{1}(int index) {{", TypeName, PropertyName); writer.WriteLine(" return result.Get{0}(index);", PropertyName); writer.WriteLine("}"); AddDeprecatedFlag(writer); writer.WriteLine("public Builder Set{0}(int index, {1} value) {{", PropertyName, TypeName); writer.WriteLine(" PrepareBuilder();"); writer.WriteLine(" result.{0}_[index] = value;", Name); writer.WriteLine(" return this;"); writer.WriteLine("}"); AddDeprecatedFlag(writer); writer.WriteLine("public Builder Add{0}({1} value) {{", PropertyName, TypeName); writer.WriteLine(" PrepareBuilder();"); writer.WriteLine(" result.{0}_.Add(value);", Name, TypeName); writer.WriteLine(" return this;"); writer.WriteLine("}"); AddDeprecatedFlag(writer); writer.WriteLine("public Builder AddRange{0}(scg::IEnumerable<{1}> values) {{", PropertyName, TypeName); writer.WriteLine(" PrepareBuilder();"); writer.WriteLine(" result.{0}_.Add(values);", Name); writer.WriteLine(" return this;"); writer.WriteLine("}"); AddDeprecatedFlag(writer); writer.WriteLine("public Builder Clear{0}() {{", PropertyName); writer.WriteLine(" PrepareBuilder();"); writer.WriteLine(" result.{0}_.Clear();", Name); writer.WriteLine(" return this;"); writer.WriteLine("}"); } public void GenerateMergingCode(TextGenerator writer) { writer.WriteLine("if (other.{0}_.Count != 0) {{", Name); writer.WriteLine(" result.{0}_.Add(other.{0}_);", Name); writer.WriteLine("}"); } public void GenerateBuildingCode(TextGenerator writer) { writer.WriteLine("{0}_.MakeReadOnly();", Name); } public void GenerateParsingCode(TextGenerator writer) { writer.WriteLine("scg::ICollection<object> unknownItems;"); writer.WriteLine("input.ReadEnumArray<{0}>(tag, field_name, result.{1}_, out unknownItems);", TypeName, Name); if (!UseLiteRuntime) { writer.WriteLine("if (unknownItems != null) {"); writer.WriteLine(" if (unknownFields == null) {"); writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);"); writer.WriteLine(" }"); writer.WriteLine(" foreach (object rawValue in unknownItems)"); writer.WriteLine(" if (rawValue is int)"); writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong)(int)rawValue);", Number); writer.WriteLine("}"); } } public void GenerateSerializationCode(TextGenerator writer) { writer.WriteLine("if ({0}_.Count > 0) {{", Name); writer.Indent(); if (Descriptor.IsPacked) { writer.WriteLine( "output.WritePackedEnumArray({0}, field_names[{2}], {1}MemoizedSerializedSize, {1}_);", Number, Name, FieldOrdinal, Descriptor.FieldType); } else { writer.WriteLine("output.WriteEnumArray({0}, field_names[{2}], {1}_);", Number, Name, FieldOrdinal, Descriptor.FieldType); } writer.Outdent(); writer.WriteLine("}"); } public void GenerateSerializedSizeCode(TextGenerator writer) { writer.WriteLine("{"); writer.Indent(); writer.WriteLine("int dataSize = 0;"); writer.WriteLine("if ({0}_.Count > 0) {{", Name); writer.Indent(); writer.WriteLine("foreach ({0} element in {1}_) {{", TypeName, Name); writer.WriteLine(" dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element);"); writer.WriteLine("}"); writer.WriteLine("size += dataSize;"); int tagSize = CodedOutputStream.ComputeTagSize(Descriptor.FieldNumber); if (Descriptor.IsPacked) { writer.WriteLine("size += {0};", tagSize); writer.WriteLine("size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize);"); } else { writer.WriteLine("size += {0} * {1}_.Count;", tagSize, Name); } writer.Outdent(); writer.WriteLine("}"); // cache the data size for packed fields. if (Descriptor.IsPacked) { writer.WriteLine("{0}MemoizedSerializedSize = dataSize;", Name); } writer.Outdent(); writer.WriteLine("}"); } public override void WriteHash(TextGenerator writer) { writer.WriteLine("foreach({0} i in {1}_)", TypeName, Name); writer.WriteLine(" hash ^= i.GetHashCode();"); } public override void WriteEquals(TextGenerator writer) { writer.WriteLine("if({0}_.Count != other.{0}_.Count) return false;", Name); writer.WriteLine("for(int ix=0; ix < {0}_.Count; ix++)", Name); writer.WriteLine(" if(!{0}_[ix].Equals(other.{0}_[ix])) return false;", Name); } public override void WriteToString(TextGenerator writer) { writer.WriteLine("PrintField(\"{0}\", {1}_, writer);", Descriptor.Name, Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class GeneralBinaryTests { private static readonly ExpressionType[] BinaryTypes = { ExpressionType.Add, ExpressionType.AddChecked, ExpressionType.Subtract, ExpressionType.SubtractChecked, ExpressionType.Multiply, ExpressionType.MultiplyChecked, ExpressionType.Divide, ExpressionType.Modulo, ExpressionType.Power, ExpressionType.And, ExpressionType.AndAlso, ExpressionType.Or, ExpressionType.OrElse, ExpressionType.LessThan, ExpressionType.LessThanOrEqual, ExpressionType.GreaterThan, ExpressionType.GreaterThanOrEqual, ExpressionType.Equal, ExpressionType.NotEqual, ExpressionType.ExclusiveOr, ExpressionType.Coalesce, ExpressionType.ArrayIndex, ExpressionType.RightShift, ExpressionType.LeftShift, ExpressionType.Assign, ExpressionType.AddAssign, ExpressionType.AndAssign, ExpressionType.DivideAssign, ExpressionType.ExclusiveOrAssign, ExpressionType.LeftShiftAssign, ExpressionType.ModuloAssign, ExpressionType.MultiplyAssign, ExpressionType.OrAssign, ExpressionType.PowerAssign, ExpressionType.RightShiftAssign, ExpressionType.SubtractAssign, ExpressionType.AddAssignChecked, ExpressionType.SubtractAssignChecked, ExpressionType.MultiplyAssignChecked }; public static IEnumerable<object[]> NonConversionBinaryTypesAndValues { get { yield return new object[] {ExpressionType.Add, 0, 0}; yield return new object[] {ExpressionType.AddChecked, 0, 0}; yield return new object[] {ExpressionType.Subtract, 0, 0}; yield return new object[] {ExpressionType.SubtractChecked, 0, 0}; yield return new object[] {ExpressionType.Multiply, 0, 0}; yield return new object[] {ExpressionType.MultiplyChecked, 0, 0}; yield return new object[] {ExpressionType.Divide, 0, 1}; yield return new object[] {ExpressionType.Modulo, 0, 2}; yield return new object[] {ExpressionType.Power, 1.0, 1.0}; yield return new object[] {ExpressionType.And, 0, 0}; yield return new object[] {ExpressionType.AndAlso, false, false}; yield return new object[] {ExpressionType.Or, 0, 0}; yield return new object[] {ExpressionType.OrElse, false, false}; yield return new object[] {ExpressionType.LessThan, 0, 0}; yield return new object[] {ExpressionType.LessThanOrEqual, 0, 0}; yield return new object[] {ExpressionType.GreaterThan, 0, 0}; yield return new object[] {ExpressionType.GreaterThanOrEqual, 0, 0}; yield return new object[] {ExpressionType.Equal, 0, 0}; yield return new object[] {ExpressionType.NotEqual, 0, 0}; yield return new object[] {ExpressionType.ExclusiveOr, false, false}; yield return new object[] {ExpressionType.ArrayIndex, new int[1], 0}; yield return new object[] {ExpressionType.RightShift, 0, 0}; yield return new object[] {ExpressionType.LeftShift, 0, 0}; } } public static IEnumerable<object[]> NumericMethodAllowedBinaryTypesAndValues { get { yield return new object[] {ExpressionType.Add}; yield return new object[] {ExpressionType.AddChecked}; yield return new object[] {ExpressionType.AddAssign}; yield return new object[] {ExpressionType.AddAssignChecked}; yield return new object[] {ExpressionType.Subtract}; yield return new object[] {ExpressionType.SubtractChecked}; yield return new object[] {ExpressionType.SubtractAssign}; yield return new object[] {ExpressionType.SubtractAssignChecked}; yield return new object[] {ExpressionType.Multiply}; yield return new object[] {ExpressionType.MultiplyChecked}; yield return new object[] {ExpressionType.MultiplyAssign}; yield return new object[] {ExpressionType.MultiplyAssignChecked}; yield return new object[] {ExpressionType.Divide}; yield return new object[] {ExpressionType.DivideAssign}; yield return new object[] {ExpressionType.Modulo}; yield return new object[] {ExpressionType.ModuloAssign}; yield return new object[] {ExpressionType.Power}; yield return new object[] {ExpressionType.PowerAssign}; yield return new object[] {ExpressionType.And}; yield return new object[] {ExpressionType.AndAssign}; yield return new object[] {ExpressionType.Or}; yield return new object[] {ExpressionType.OrAssign}; yield return new object[] {ExpressionType.LessThan}; yield return new object[] {ExpressionType.LessThanOrEqual}; yield return new object[] {ExpressionType.GreaterThan}; yield return new object[] {ExpressionType.GreaterThanOrEqual}; yield return new object[] {ExpressionType.Equal}; yield return new object[] {ExpressionType.NotEqual}; yield return new object[] {ExpressionType.ExclusiveOr}; yield return new object[] {ExpressionType.ExclusiveOrAssign}; yield return new object[] {ExpressionType.RightShift}; yield return new object[] {ExpressionType.RightShiftAssign}; yield return new object[] {ExpressionType.LeftShift}; yield return new object[] {ExpressionType.LeftShiftAssign}; } } public static IEnumerable<object[]> BooleanMethodAllowedBinaryTypesAndValues { get { yield return new object[] {ExpressionType.AndAlso}; yield return new object[] {ExpressionType.OrElse}; } } public static IEnumerable<object[]> BinaryTypesData() { return BinaryTypes.Select(i => new object[] { i }); } private static ExpressionType[] NonBinaryTypes = ((ExpressionType[])Enum.GetValues(typeof(ExpressionType))) .Except(BinaryTypes) .ToArray(); public static IEnumerable<ExpressionType> NonBinaryTypesIncludingInvalid = NonBinaryTypes.Concat(Enumerable.Repeat((ExpressionType)(-1), 1)); public static IEnumerable<object[]> NonBinaryTypesIncludingInvalidData() { return NonBinaryTypesIncludingInvalid.Select(i => new object[] { i }); } [Theory] [MemberData(nameof(NonBinaryTypesIncludingInvalidData))] public void MakeBinaryInvalidType(ExpressionType type) { AssertExtensions.Throws<ArgumentException>("binaryType", () => Expression.MakeBinary(type, Expression.Constant(0), Expression.Constant(0))); AssertExtensions.Throws<ArgumentException>("binaryType", () => Expression.MakeBinary(type, Expression.Constant(0), Expression.Constant(0), false, null)); AssertExtensions.Throws<ArgumentException>("binaryType", () => Expression.MakeBinary(type, Expression.Constant(0), Expression.Constant(0), false, null, null)); } [Theory] [MemberData(nameof(BinaryTypesData))] public void MakeBinaryLeftNull(ExpressionType type) { Assert.Throws<ArgumentNullException>(() => Expression.MakeBinary(type, null, Expression.Constant(0))); Assert.Throws<ArgumentNullException>(() => Expression.MakeBinary(type, null, Expression.Constant(0), false, null)); Assert.Throws<ArgumentNullException>(() => Expression.MakeBinary(type, null, Expression.Constant(0), false, null, null)); } [Theory] [MemberData(nameof(BinaryTypesData))] public void MakeBinaryRightNull(ExpressionType type) { Assert.Throws<ArgumentNullException>(() => Expression.MakeBinary(type, Expression.Variable(typeof(object)), null)); Assert.Throws<ArgumentNullException>(() => Expression.MakeBinary(type, Expression.Variable(typeof(object)), null, false, null)); Assert.Throws<ArgumentNullException>(() => Expression.MakeBinary(type, Expression.Variable(typeof(object)), null, false, null, null)); } public static void CompileBinaryExpression(BinaryExpression expression, bool useInterpreter, bool expected) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>(expression, Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(expected, f()); } public static bool CustomEquals(object a, object b) { // Allow for NaN if (a is double && b is double) { return (double)a == (double)b; } else if (a is float && b is float) { return (float)a == (float)b; } return a == null ? b == null : a.Equals(b); } public static bool CustomGreaterThan(object a, object b) { if (a is byte && b is byte) { return (byte)a > (byte)b; } else if (a is char && b is char) { return (char)a > (char)b; } else if (a is decimal && b is decimal) { return (decimal)a > (decimal)b; } else if (a is double && b is double) { return (double)a > (double)b; } else if (a is float && b is float) { return (float)a > (float)b; } else if (a is int && b is int) { return (int)a > (int)b; } else if (a is long && b is long) { return (long)a > (long)b; } else if (a is sbyte && b is sbyte) { return (sbyte)a > (sbyte)b; } else if (a is short && b is short) { return (short)a > (short)b; } else if (a is uint && b is uint) { return (uint)a > (uint)b; } else if (a is ulong && b is ulong) { return (ulong)a > (ulong)b; } else if (a is ushort && b is ushort) { return (ushort)a > (ushort)b; } return false; } public static bool CustomLessThan(object a, object b) => BothNotNull(a, b) && !IsNaN(a) && !IsNaN(b) && !CustomGreaterThanOrEqual(a, b); public static bool CustomGreaterThanOrEqual(object a, object b) => BothNotNull(a, b) && CustomEquals(a, b) || CustomGreaterThan(a, b); public static bool CustomLessThanOrEqual(object a, object b) => BothNotNull(a, b) && CustomEquals(a, b) || CustomLessThan(a, b); public static bool IsNaN(object obj) { if (obj is double) { return double.IsNaN((double)obj); } else if (obj is float) { return float.IsNaN((float)obj); } return false; } public static bool BothNotNull(object a, object b) => a != null && b != null; [Theory, PerCompilationType(nameof(NonConversionBinaryTypesAndValues))] public static void ConversionIgnoredWhenIrrelevant( ExpressionType type, object lhs, object rhs, bool useInterpreter) { // The types of binary expression that can't have a converter just ignore any lambda // passed in. This probably shouldn't be the case (an ArgumentException would be // appropriate, but it would be a breaking change to stop this now. Expression<Action> sillyLambda = Expression.Lambda<Action>(Expression.Throw(Expression.Constant(new Exception()))); BinaryExpression op = Expression.MakeBinary( type, Expression.Constant(lhs), Expression.Constant(rhs), false, null, sillyLambda); Expression.Lambda(op).Compile(useInterpreter).DynamicInvoke(); } private class GenericClassWithNonGenericMethod<TClassType> { public static int DoIntStuff(int x, int y) => unchecked(x + y); public static GenericClassWithNonGenericMethod<TClassType> DoBooleanStuff(GenericClassWithNonGenericMethod<TClassType> x, GenericClassWithNonGenericMethod<TClassType> y) => x; public static bool operator true(GenericClassWithNonGenericMethod<TClassType> obj) => true; public static bool operator false(GenericClassWithNonGenericMethod<TClassType> obj) => false; } [Theory, PerCompilationType(nameof(NumericMethodAllowedBinaryTypesAndValues))] public static void MethodOfOpenGeneric(ExpressionType type, bool useInterpreter) { ParameterExpression left = Expression.Parameter(typeof(int)); ConstantExpression right = Expression.Constant(2); var genType = typeof(GenericClassWithNonGenericMethod<>); MethodInfo method = genType.GetMethod(nameof(GenericClassWithNonGenericMethod<int>.DoIntStuff)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.MakeBinary(type, left, right, false, method)); method = genType.MakeGenericType(genType).GetMethod(nameof(GenericClassWithNonGenericMethod<int>.DoIntStuff)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.MakeBinary(type, left, right, false, method)); // Confirm does work when closed. var validType = typeof(GenericClassWithNonGenericMethod<int>); method = validType.GetMethod(nameof(GenericClassWithNonGenericMethod<int>.DoIntStuff)); Expression exp = Expression.MakeBinary(type, left, right, false, method); Func<int, int> f = Expression.Lambda<Func<int, int>>(exp, left).Compile(useInterpreter); Assert.Equal(5, f(3)); } [Theory, PerCompilationType(nameof(BooleanMethodAllowedBinaryTypesAndValues))] public static void MethodOfOpenGenericBoolean(ExpressionType type, bool useInterpreter) { GenericClassWithNonGenericMethod<bool> value = new GenericClassWithNonGenericMethod<bool>(); ConstantExpression left = Expression.Constant(value); ConstantExpression right = Expression.Constant(new GenericClassWithNonGenericMethod<bool>()); var genType = typeof(GenericClassWithNonGenericMethod<>); MethodInfo method = genType.GetMethod(nameof(GenericClassWithNonGenericMethod<bool>.DoBooleanStuff)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.MakeBinary(type, left, right, false, method)); method = genType.MakeGenericType(genType).GetMethod(nameof(GenericClassWithNonGenericMethod<int>.DoIntStuff)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.MakeBinary(type, left, right, false, method)); // Confirm does work when closed. var validType = typeof(GenericClassWithNonGenericMethod<bool>); method = validType.GetMethod(nameof(GenericClassWithNonGenericMethod<bool>.DoBooleanStuff)); Expression exp = Expression.MakeBinary(type, left, right, false, method); Func<GenericClassWithNonGenericMethod<bool>> f = Expression.Lambda<Func<GenericClassWithNonGenericMethod<bool>>>(exp).Compile(useInterpreter); Assert.Same(value, f()); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDocumentsClientTest { [xunit::FactAttribute] public void GetDocumentRequestObject() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), State = Document.Types.State.Unspecified, }; mockGrpcClient.Setup(x => x.GetDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document response = client.GetDocument(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDocumentRequestObjectAsync() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), State = Document.Types.State.Unspecified, }; mockGrpcClient.Setup(x => x.GetDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Document>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document responseCallSettings = await client.GetDocumentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Document responseCancellationToken = await client.GetDocumentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDocument() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), State = Document.Types.State.Unspecified, }; mockGrpcClient.Setup(x => x.GetDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document response = client.GetDocument(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDocumentAsync() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), State = Document.Types.State.Unspecified, }; mockGrpcClient.Setup(x => x.GetDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Document>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document responseCallSettings = await client.GetDocumentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Document responseCancellationToken = await client.GetDocumentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDocumentResourceNames() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), State = Document.Types.State.Unspecified, }; mockGrpcClient.Setup(x => x.GetDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document response = client.GetDocument(request.DocumentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDocumentResourceNamesAsync() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), State = Document.Types.State.Unspecified, }; mockGrpcClient.Setup(x => x.GetDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Document>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document responseCallSettings = await client.GetDocumentAsync(request.DocumentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Document responseCancellationToken = await client.GetDocumentAsync(request.DocumentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
namespace KabMan.Client { partial class RackList { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RackList)); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar1 = new DevExpress.XtraBars.Bar(); this.BBtnNew = new DevExpress.XtraBars.BarButtonItem(); this.BBtnDetail = new DevExpress.XtraBars.BarButtonItem(); this.BBtnDelete = new DevExpress.XtraBars.BarButtonItem(); this.BBtnClose = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.ServerId = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.Room = new DevExpress.XtraGrid.Columns.GridColumn(); this.OPSys = new DevExpress.XtraGrid.Columns.GridColumn(); this.ConnValue = new DevExpress.XtraGrid.Columns.GridColumn(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); this.SuspendLayout(); // // barManager1 // this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar1}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.BBtnNew, this.BBtnDetail, this.BBtnDelete, this.BBtnClose}); this.barManager1.MaxItemId = 6; // // bar1 // this.bar1.Appearance.BackColor = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BackColor2 = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BorderColor = System.Drawing.Color.Gainsboro; this.bar1.Appearance.Options.UseBackColor = true; this.bar1.Appearance.Options.UseBorderColor = true; this.bar1.BarName = "Tools"; this.bar1.DockCol = 0; this.bar1.DockRow = 0; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.BBtnNew), new DevExpress.XtraBars.LinkPersistInfo(this.BBtnDetail), new DevExpress.XtraBars.LinkPersistInfo(this.BBtnDelete), new DevExpress.XtraBars.LinkPersistInfo(this.BBtnClose, true)}); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; this.bar1.Text = "Tools"; // // BBtnNew // this.BBtnNew.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnNew.Glyph"))); this.BBtnNew.Id = 0; this.BBtnNew.Name = "BBtnNew"; this.BBtnNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.BBtnNew_ItemClick); // // BBtnDetail // this.BBtnDetail.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnDetail.Glyph"))); this.BBtnDetail.Id = 1; this.BBtnDetail.Name = "BBtnDetail"; this.BBtnDetail.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.BBtnDetail_ItemClick); // // BBtnDelete // this.BBtnDelete.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnDelete.Glyph"))); this.BBtnDelete.Id = 2; this.BBtnDelete.Name = "BBtnDelete"; this.BBtnDelete.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.BBtnDelete_ItemClick); // // BBtnClose // this.BBtnClose.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnClose.Glyph"))); this.BBtnClose.Id = 4; this.BBtnClose.Name = "BBtnClose"; this.BBtnClose.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.BBtnClose_ItemClick); // // layoutControl1 // this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.gridControl1); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 26); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(590, 383); this.layoutControl1.TabIndex = 4; this.layoutControl1.Text = "layoutControl1"; // // gridControl1 // this.gridControl1.Location = new System.Drawing.Point(7, 7); this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.Size = new System.Drawing.Size(577, 370); this.gridControl1.TabIndex = 5; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); // // gridView1 // this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.Empty.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.EvenRow.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.Options.UseForeColor = true; this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true; this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true; this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.gridView1.Appearance.FixedLine.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true; this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true; this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true; this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true; this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupButton.Options.UseBackColor = true; this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true; this.gridView1.Appearance.GroupButton.Options.UseForeColor = true; this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true; this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true; this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true; this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true; this.gridView1.Appearance.GroupPanel.Options.UseFont = true; this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupRow.Options.UseBackColor = true; this.gridView1.Appearance.GroupRow.Options.UseForeColor = true; this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseFont = true; this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true; this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true; this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true; this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HorzLine.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.gridView1.Appearance.OddRow.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.Options.UseForeColor = true; this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.gridView1.Appearance.Preview.Options.UseBackColor = true; this.gridView1.Appearance.Preview.Options.UseForeColor = true; this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.Row.Options.UseBackColor = true; this.gridView1.Appearance.Row.Options.UseForeColor = true; this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true; this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.VertLine.Options.UseBackColor = true; this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.ServerId, this.gridColumn2, this.gridColumn1, this.Room, this.OPSys, this.ConnValue}); this.gridView1.GridControl = this.gridControl1; this.gridView1.Name = "gridView1"; this.gridView1.OptionsBehavior.AllowIncrementalSearch = true; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsCustomization.AllowFilter = false; this.gridView1.OptionsMenu.EnableColumnMenu = false; this.gridView1.OptionsMenu.EnableFooterMenu = false; this.gridView1.OptionsMenu.EnableGroupPanelMenu = false; this.gridView1.OptionsView.EnableAppearanceEvenRow = true; this.gridView1.OptionsView.EnableAppearanceOddRow = true; this.gridView1.OptionsView.ShowAutoFilterRow = true; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.OptionsView.ShowIndicator = false; // // ServerId // this.ServerId.Caption = "Id"; this.ServerId.FieldName = "Id"; this.ServerId.Name = "ServerId"; // // gridColumn2 // this.gridColumn2.Caption = "Rack Name"; this.gridColumn2.FieldName = "Name1"; this.gridColumn2.Name = "gridColumn2"; this.gridColumn2.Visible = true; this.gridColumn2.VisibleIndex = 0; // // gridColumn1 // this.gridColumn1.Caption = "Location"; this.gridColumn1.FieldName = "Location"; this.gridColumn1.Name = "gridColumn1"; this.gridColumn1.Visible = true; this.gridColumn1.VisibleIndex = 1; // // Room // this.Room.Caption = "Data Center"; this.Room.FieldName = "Room"; this.Room.Name = "Room"; this.Room.Visible = true; this.Room.VisibleIndex = 2; this.Room.Width = 108; // // OPSys // this.OPSys.Caption = "Operation System"; this.OPSys.FieldName = "OPSys"; this.OPSys.Name = "OPSys"; this.OPSys.Visible = true; this.OPSys.VisibleIndex = 3; this.OPSys.Width = 84; // // ConnValue // this.ConnValue.Caption = "Count Connection"; this.ConnValue.FieldName = "ConnValue"; this.ConnValue.Name = "ConnValue"; this.ConnValue.Visible = true; this.ConnValue.VisibleIndex = 4; this.ConnValue.Width = 115; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(590, 383); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.gridControl1; this.layoutControlItem1.CustomizationFormText = "layoutControlItem1"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(588, 381); this.layoutControlItem1.Text = "layoutControlItem1"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // RackList // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(590, 409); this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "RackList"; this.Text = "Rack List"; this.Load += new System.EventHandler(this.ServerList_Load); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar1; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraBars.BarButtonItem BBtnNew; private DevExpress.XtraBars.BarButtonItem BBtnDetail; private DevExpress.XtraBars.BarButtonItem BBtnDelete; private DevExpress.XtraBars.BarButtonItem BBtnClose; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private DevExpress.XtraGrid.Columns.GridColumn ServerId; private DevExpress.XtraGrid.Columns.GridColumn Room; private DevExpress.XtraGrid.Columns.GridColumn OPSys; private DevExpress.XtraGrid.Columns.GridColumn ConnValue; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn2; } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Display; namespace RSSWeatherLayer { /// <summary> /// Add a new weather item given a zipCode. /// </summary> /// <remarks>Should the weather item exist, it will be updated</remarks> [ClassInterface(ClassInterfaceType.None)] [Guid("C9260965-D3AA-4c28-B55A-023C41F1CA39")] [ProgId("RSSWeatherLayer.AddRSSWeatherLayer")] [ComVisible(true)] public sealed class AddRSSWeatherLayer: BaseCommand { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Register(regKey); MxCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Unregister(regKey); MxCommands.Unregister(regKey); } #endregion #endregion private sealed class InvokeHelper : Control { //delegate used to pass the invoked method to the main thread public delegate void RefreshHelper(WKSEnvelope invalidateExtent); public delegate void RefreshWeatherItemHelper(WeatherItemEventArgs weatherItemInfo); private IActiveView m_activeView = null; private RSSWeatherLayerClass m_weatherLayer = null; private IEnvelope m_invalidateExtent = null; private IPoint m_point; public InvokeHelper (IActiveView activeView, RSSWeatherLayerClass weatherLayer) { m_activeView = activeView; m_weatherLayer = weatherLayer; CreateHandle(); CreateControl(); m_invalidateExtent = new EnvelopeClass(); m_invalidateExtent.SpatialReference = activeView.ScreenDisplay.DisplayTransformation.SpatialReference; m_point = new PointClass(); m_point.SpatialReference = activeView.ScreenDisplay.DisplayTransformation.SpatialReference; } public void RefreshWeatherItem(WeatherItemEventArgs weatherItemInfo) { try { // Invoke the RefreshInternal through its delegate if (!this.IsDisposed && this.IsHandleCreated) Invoke(new RefreshWeatherItemHelper(RefreshWeatherItemInvoked), new object[] { weatherItemInfo }); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } public void Refresh (WKSEnvelope invalidateExtent) { try { // Invoke the RefreshInternal through its delegate if (!this.IsDisposed && this.IsHandleCreated) Invoke(new RefreshHelper(RefreshInvoked), new object[] { invalidateExtent }); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } private void RefreshWeatherItemInvoked(WeatherItemEventArgs weatherItemInfo) { ITransformation transform = m_activeView.ScreenDisplay.DisplayTransformation as ITransformation; if (transform == null) return; double[] iconDimensions = new double[2]; iconDimensions[0] = (double)weatherItemInfo.IconWidth; iconDimensions[1] = (double)weatherItemInfo.IconHeight; double[] iconDimensionsMap = new double[2]; transform.TransformMeasuresFF(esriTransformDirection.esriTransformReverse, 1, ref iconDimensionsMap[0], ref iconDimensions[0]); m_invalidateExtent.PutCoords(0, 0, iconDimensionsMap[0], iconDimensionsMap[0]); m_point.PutCoords(weatherItemInfo.mapX, weatherItemInfo.mapY); m_invalidateExtent.CenterAt(m_point); m_activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, m_weatherLayer, m_invalidateExtent); m_activeView.ScreenDisplay.UpdateWindow(); } private void RefreshInvoked(WKSEnvelope invalidateExtent) { m_invalidateExtent.PutWKSCoords(ref invalidateExtent); if (!m_invalidateExtent.IsEmpty) m_activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, m_weatherLayer, m_invalidateExtent); else m_activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, m_weatherLayer, null); m_activeView.ScreenDisplay.UpdateWindow(); } } private InvokeHelper m_invokeHelper = null; //class members private IHookHelper m_pHookHelper = null; private RSSWeatherLayerClass m_weatherLayer = null; private bool m_bOnce = true; private bool m_bConnected = false; public AddRSSWeatherLayer() { base.m_category = "Weather"; base.m_caption = "Add RSS Weather Layer"; base.m_message = "Add RSS Weather Layer"; base.m_toolTip = "Add RSS Weather Layer"; base.m_name = base.m_category + "_" + base.m_caption; try { string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } #region Overriden Class Methods /// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { //Instantiate the hook helper if (m_pHookHelper == null) m_pHookHelper = new HookHelperClass (); //set the hook m_pHookHelper.Hook = hook; //set verbose events in order to listen to ItemDeleted event ((IViewManager)m_pHookHelper.FocusMap).VerboseEvents = true; //hook the ItemDeleted event in order to track removal of the layer from the TOC ((IActiveViewEvents_Event)m_pHookHelper.FocusMap).ItemDeleted += new IActiveViewEvents_ItemDeletedEventHandler(OnItemDeleted); } /// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { try { if(!m_bConnected) { //check first that the layer was added to the globe if(m_bOnce == true) { //instantiate the layer m_weatherLayer = new RSSWeatherLayerClass(); m_invokeHelper = new InvokeHelper(m_pHookHelper.ActiveView, m_weatherLayer); m_bOnce = false; } //test whether the layer has been added to the map bool bLayerHasBeenAdded = false; ILayer layer = null; if(m_pHookHelper.FocusMap.LayerCount != 0) { IEnumLayer layers = m_pHookHelper.FocusMap.get_Layers(null, false); layers.Reset(); layer = layers.Next(); while(layer != null) { if(layer is RSSWeatherLayerClass) { bLayerHasBeenAdded = true; break; } layer = layers.Next(); } } //add the layer to the map if(!bLayerHasBeenAdded) { layer = (ILayer)m_weatherLayer; layer.Name = "RSS Weather Layer"; try { m_pHookHelper.FocusMap.AddLayer(layer); //wires layer's events m_weatherLayer.OnWeatherItemAdded += new WeatherItemAdded(OnWeatherItemAdded); m_weatherLayer.OnWeatherItemsUpdated += new WeatherItemsUpdated(OnWeatherItemsUpdated); } catch(Exception ex) { System.Diagnostics.Trace.WriteLine("Failed" + ex.Message); } } //connect to the service m_weatherLayer.Connect(); } else { //disconnect from the service m_weatherLayer.Disconnect(); //un-wires layer's events m_weatherLayer.OnWeatherItemAdded -= new WeatherItemAdded(OnWeatherItemAdded); m_weatherLayer.OnWeatherItemsUpdated -= new WeatherItemsUpdated(OnWeatherItemsUpdated); //delete the layer m_pHookHelper.FocusMap.DeleteLayer(m_weatherLayer); //dispose the layer m_weatherLayer = null; m_bOnce = true; } m_bConnected = !m_bConnected; } catch(Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } /// <summary> /// Indicates whether or not this command is checked. /// </summary> public override bool Checked { get { m_bConnected = false; return m_bConnected; } } #endregion /// <summary> /// weather layer ItemAdded event handler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <remarks>gets fired when an item is added to the table</remarks> private void OnWeatherItemAdded(object sender, WeatherItemEventArgs args) { // use the invoke helper since this event gets fired on a different thread m_invokeHelper.RefreshWeatherItem(args); } /// <summary> /// Weather layer ItemsUpdated event handler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <remarks>gets fired when the update thread finish updating all the items in the table</remarks> private void OnWeatherItemsUpdated(object sender, EventArgs args) { //refresh the display WKSEnvelope emptyEnv; emptyEnv.XMax = emptyEnv.XMin = emptyEnv.YMax = emptyEnv.YMin = 0; m_invokeHelper.Refresh(emptyEnv); } /// <summary> /// Listen to ActiveViewEvents.ItemDeleted in order to track whether the layer has been /// removed from the TOC /// </summary> /// <param name="Item"></param> void OnItemDeleted(object Item) { //test that the deleted layer is RSSWeatherLayerClass if (Item is RSSWeatherLayerClass) { if (m_bConnected && null != m_weatherLayer) { m_bConnected = false; //disconnect from the service m_weatherLayer.Disconnect(); //dispose the layer m_weatherLayer = null; m_bOnce = true; } } } } }
using System.Collections.Generic; using Orleans.Configuration; using Orleans.Runtime; namespace Orleans.TestingHost { /// <summary> /// Configuration options for test clusters. /// </summary> public class TestClusterOptions { /// <summary> /// Gets or sets the cluster identifier. /// </summary> /// <seealso cref="ClusterOptions.ClusterId"/> /// <value>The cluster identifier.</value> public string ClusterId { get; set; } /// <summary> /// Gets or sets the service identifier. /// </summary> /// <seealso cref="ClusterOptions.ServiceId"/> /// <value>The service identifier.</value> public string ServiceId { get; set; } /// <summary> /// Gets or sets the base silo port, which is the port for the first silo. Other silos will use subsequent ports. /// </summary> /// <value>The base silo port.</value> public int BaseSiloPort{ get; set; } /// <summary> /// Gets or sets the base gateway port, which is the gateway port for the first silo. Other silos will use subsequent ports. /// </summary> /// <value>The base gateway port.</value> public int BaseGatewayPort { get; set; } /// <summary> /// Gets or sets a value indicating whether to use test cluster membership. /// </summary> /// <value><see langword="true" /> if test cluster membership should be used; otherwise, <see langword="false" />.</value> public bool UseTestClusterMembership { get; set; } /// <summary> /// Gets or sets a value indicating whether to initialize the client immediately on deployment. /// </summary> /// <value><see langword="true" /> if the client should be initialized immediately on deployment; otherwise, <see langword="false" />.</value> public bool InitializeClientOnDeploy { get; set; } /// <summary> /// Gets or sets the initial silos count. /// </summary> /// <value>The initial silos count.</value> public short InitialSilosCount { get; set; } /// <summary> /// Gets or sets the application base directory. /// </summary> /// <value>The application base directory.</value> public string ApplicationBaseDirectory { get; set; } /// <summary> /// Gets or sets a value indicating whether to configure file logging. /// </summary> /// <value><see langword="true" /> if file logging should be configured; otherwise, <see langword="false" />.</value> public bool ConfigureFileLogging { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to assume homogeneous silos for testing purposes. /// </summary> /// <value><see langword="true" /> if the cluster should assume homogeneous silos; otherwise, <see langword="false" />.</value> public bool AssumeHomogenousSilosForTesting { get; set; } /// <summary> /// Gets or sets a value indicating whether each silo should host a gateway. /// </summary> /// <value><see langword="true" /> if each silo should host a gateway; otherwise, <see langword="false" />.</value> public bool GatewayPerSilo { get; set; } = true; /// <summary> /// Gets the silo builder configurator types. /// </summary> /// <value>The silo builder configurator types.</value> public List<string> SiloBuilderConfiguratorTypes { get; } = new List<string>(); /// <summary> /// Gets the client builder configurator types. /// </summary> /// <value>The client builder configurator types.</value> public List<string> ClientBuilderConfiguratorTypes { get; } = new List<string>(); /// <summary> /// Gets or sets a value indicating whether to use an in-memory transport for connecting silos and clients, instead of TCP. /// </summary> /// <remarks> /// Defaults to <see langword="true"/> /// </remarks> public bool UseInMemoryTransport { get; set; } = true; /// <summary> /// Converts these options into a dictionary. /// </summary> /// <returns>The options dictionary.</returns> public Dictionary<string, string> ToDictionary() { var result = new Dictionary<string, string> { [nameof(ClusterId)] = this.ClusterId, [nameof(ServiceId)] = this.ServiceId, [nameof(BaseSiloPort)] = this.BaseSiloPort.ToString(), [nameof(BaseGatewayPort)] = this.BaseGatewayPort.ToString(), [nameof(UseTestClusterMembership)] = this.UseTestClusterMembership.ToString(), [nameof(InitializeClientOnDeploy)] = this.InitializeClientOnDeploy.ToString(), [nameof(InitialSilosCount)] = this.InitialSilosCount.ToString(), [nameof(ApplicationBaseDirectory)] = this.ApplicationBaseDirectory, [nameof(ConfigureFileLogging)] = this.ConfigureFileLogging.ToString(), [nameof(AssumeHomogenousSilosForTesting)] = this.AssumeHomogenousSilosForTesting.ToString(), [nameof(GatewayPerSilo)] = this.GatewayPerSilo.ToString(), [nameof(UseInMemoryTransport)] = this.UseInMemoryTransport.ToString(), }; if (this.SiloBuilderConfiguratorTypes != null) { for (int i = 0; i < this.SiloBuilderConfiguratorTypes.Count; i++) { result[$"{nameof(SiloBuilderConfiguratorTypes)}:{i}"] = this.SiloBuilderConfiguratorTypes[i]; } } if (this.ClientBuilderConfiguratorTypes != null) { for (int i = 0; i < this.ClientBuilderConfiguratorTypes.Count; i++) { result[$"{nameof(ClientBuilderConfiguratorTypes)}:{i}"] = this.ClientBuilderConfiguratorTypes[i]; } } return result; } } /// <summary> /// Configuration overrides for individual silos. /// </summary> public class TestSiloSpecificOptions { /// <summary> /// Gets or sets the silo port. /// </summary> /// <value>The silo port.</value> public int SiloPort { get; set; } /// <summary> /// Gets or sets the gateway port. /// </summary> /// <value>The gateway port.</value> public int GatewayPort { get; set; } /// <summary> /// Gets or sets the name of the silo. /// </summary> /// <value>The name of the silo.</value> public string SiloName { get; set; } /// <summary> /// Gets or sets the primary silo port. /// </summary> /// <value>The primary silo port.</value> public int PrimarySiloPort { get; set; } /// <summary> /// Creates an instance of the <see cref="TestSiloSpecificOptions"/> class. /// </summary> /// <param name="testCluster">The test cluster.</param> /// <param name="testClusterOptions">The test cluster options.</param> /// <param name="instanceNumber">The instance number.</param> /// <param name="assignNewPort">if set to <see langword="true" />, assign a new port for the silo.</param> /// <returns>The options.</returns> public static TestSiloSpecificOptions Create(TestCluster testCluster, TestClusterOptions testClusterOptions, int instanceNumber, bool assignNewPort = false) { var siloName = testClusterOptions.UseTestClusterMembership && instanceNumber == 0 ? Silo.PrimarySiloName : $"Secondary_{instanceNumber}"; if (assignNewPort) { (int siloPort, int gatewayPort) = testCluster.PortAllocator.AllocateConsecutivePortPairs(1); var result = new TestSiloSpecificOptions { SiloPort = siloPort, GatewayPort = (instanceNumber == 0 || testClusterOptions.GatewayPerSilo) ? gatewayPort : 0, SiloName = siloName, PrimarySiloPort = testClusterOptions.UseTestClusterMembership ? testClusterOptions.BaseSiloPort : 0, }; return result; } else { var result = new TestSiloSpecificOptions { SiloPort = testClusterOptions.BaseSiloPort + instanceNumber, GatewayPort = (instanceNumber == 0 || testClusterOptions.GatewayPerSilo) ? testClusterOptions.BaseGatewayPort + instanceNumber : 0, SiloName = siloName, PrimarySiloPort = testClusterOptions.UseTestClusterMembership ? testClusterOptions.BaseSiloPort : 0, }; return result; } } /// <summary> /// Converts these options into a dictionary. /// </summary> /// <returns>The options dictionary.</returns> public Dictionary<string, string> ToDictionary() => new Dictionary<string, string> { [nameof(SiloPort)] = this.SiloPort.ToString(), [nameof(GatewayPort)] = this.GatewayPort.ToString(), [nameof(SiloName)] = this.SiloName, [nameof(PrimarySiloPort)] = this.PrimarySiloPort.ToString() }; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private SyntaxToken _methodName; public static async Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult); return await codeGenerator.GenerateAsync(cancellationToken).ConfigureAwait(false); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult); } return Contract.FailWithReturn<CSharpCodeGenerator>("Unknown selection"); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { Contract.ThrowIfFalse(this.SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(this.MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)this.SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = this.InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: SpecializedCollections.EmptyList<AttributeData>(), accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: this.AnalyzerResult.ReturnType, explicitInterfaceSymbol: null, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(cancellationToken), parameters: CreateMethodParameters(), statements: result.Data); return result.With( this.MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = this.GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<IEnumerable<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = this.GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(this.CallSiteAnnotation, cancellationToken).ConfigureAwait(false); return SpecializedCollections.SingletonEnumerable(statement); } // regular case var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = SpecializedCollections.EmptyEnumerable<StatementSyntax>(); statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(statements, cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements, cancellationToken); return statements; } private bool IsExpressionBodiedMember(SyntaxNode node) { return node is MemberDeclarationSyntax && ((MemberDeclarationSyntax)node).GetExpressionBody() != null; } private SimpleNameSyntax CreateMethodNameForInvocation() { return this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in this.AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(this.SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = this.CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = this.CSharpSelectionResult.ShouldPutAsyncModifier(); return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: !this.AnalyzerResult.UseInstanceMember); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<List<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToList<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = this.CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } var block = statements.Single() as BlockSyntax; if (block != null) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private IEnumerable<StatementSyntax> CleanupCode(IEnumerable<StatementSyntax> statements) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); statements = postProcessor.RemoveRedundantBlock(statements); statements = postProcessor.RemoveDeclarationAssignmentPattern(statements); statements = postProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { var returnStatement = statements.Single() as ReturnStatementSyntax; if (returnStatement != null && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { var declStatement = statement as LocalDeclarationStatementSyntax; if (declStatement == null) { // found one return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private IEnumerable<StatementSyntax> MoveDeclarationOutFromMethodDefinition( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); foreach (var statement in statements) { var declarationStatement = statement as LocalDeclarationStatementSyntax; if (declarationStatement == null) { // if given statement is not decl statement. yield return statement; continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { SyntaxToken identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token yield return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { yield return SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, declarationStatement.RefKeyword, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); } // return any expression statement if there was any foreach (var expressionStatement in expressionStatements) { yield return expressionStatement; } } } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax) { if (typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); var identifierTrailingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } if (typeSyntax.HasTrailingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia) .WithTrailingTrivia(identifierTrailingTrivia); } return identifier; } private IEnumerable<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = this.GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) { return SyntaxFactory.Identifier(name); } protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); foreach (var argument in this.AnalyzerResult.MethodParameters) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default(SyntaxToken) : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = this.CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); } protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, CancellationToken cancellationToken, ExpressionSyntax initialValue = null) { var type = variable.GetVariableType(this.SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<MethodDeclarationSyntax>(this.MethodDefinitionAnnotation).First(); var newMethodDefinition = methodDefinition.ReplaceToken( methodDefinition.Body.OpenBraceToken, methodDefinition.Body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed))); newDocument = await newDocument.WithSyntaxRootAsync(root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (this.AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(this.AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } } } }
using System.Collections.Generic; using System.Text; using UnityEditor; using UnityEngine; namespace LuviKunG.LocaleCore.Editor { public class LocaleSheetData { public string LocaleName; public LocaleKey[] List; } public class EditorWindowLocaleCore : EditorWindow { private static string exportPath = ""; private static Object sourceCSV; private static LocaleSettings cachedLocaleSettings = null; private static bool isPreload; public static LocaleSettings GetLocaleSettings() { if (cachedLocaleSettings == null) { cachedLocaleSettings = Resources.Load<LocaleSettings>(Locale.defaultResourcePath + "/" + Locale.localeSettingsName); if (cachedLocaleSettings == null) { LocaleSettings _settings = CreateAsset<LocaleSettings>("Resources/" + Locale.defaultResourcePath, Locale.localeSettingsName); _settings.availableLocale = new LocaleCode[0]; _settings.sheetTitles = new string[0]; _settings.defaultLocale = LocaleCode.EN; _settings.isUseSystemLanguage = true; EditorUtility.SetDirty(_settings); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } return cachedLocaleSettings; } [MenuItem("LuviKunG/LocaleCore/Import CSV Wizard")] public static void WindowOpen() { GetWindow<EditorWindowLocaleCore>(false, "Locale Core", true); string editorCachePath = EditorPrefs.GetString("LocaleExportPath"); if (string.IsNullOrEmpty(editorCachePath)) { EditorPrefs.SetString("Locale Export Path", "Resources/" + Locale.defaultResourcePath); } else { exportPath = editorCachePath; } cachedLocaleSettings = GetLocaleSettings(); isPreload = true; } void OnGUI() { exportPath = EditorGUILayout.TextField("Export path", exportPath); if (GUILayout.Button("Select Export Location")) BatchSelectLocation(); sourceCSV = EditorGUILayout.ObjectField("CSV", sourceCSV, typeof(TextAsset), false); GUI.enabled = sourceCSV != null; if (GUILayout.Button("Export CSV Localization")) BatchExport(); GUI.enabled = true; isPreload = GUILayout.Toggle(isPreload, "Make this import as pre-load"); } public static void BatchSelectLocation() { exportPath = EditorUtility.OpenFolderPanel("Select localization for export XML file.", Application.dataPath, ""); exportPath = exportPath.Replace(Application.dataPath + "/", ""); if (string.IsNullOrEmpty(exportPath)) return; EditorPrefs.SetString("LocaleExportPath", exportPath); } public static void BatchExport() { LocaleSettings _settings = GetLocaleSettings(); if (_settings == null) { EditorUtility.DisplayDialog("Error", "Cannot perform this action because the editor cannot find any \'LocalizationSettings\' in resource path.", "Okay"); Debug.LogError("Cannot find LocalizationSettings.asset"); return; } if (sourceCSV == null) { EditorUtility.DisplayDialog("Error", "Cannot perform this action because CSV source are null.", "Okay"); Debug.LogError("Source are null."); return; } if (string.IsNullOrEmpty(exportPath)) { string exportPath = EditorUtility.OpenFolderPanel("Select localization for export XML file.", Application.dataPath, ""); if (string.IsNullOrEmpty(exportPath)) { exportPath = ""; return; } else { EditorPrefs.SetString("LocaleExportPath", exportPath); } } TextAsset textAssetCSV = sourceCSV as TextAsset; string fileName = textAssetCSV.name; string[][] table = CSVTextAsset(textAssetCSV); if (table == null) return; List<LocaleSheetData> sheets = new List<LocaleSheetData>(); for (int c = 1; c < table[0].Length; c++) { LocaleSheetData sheet = new LocaleSheetData(); sheet.LocaleName = table[0][c]; sheet.List = new LocaleKey[table.Length - 1]; for (int r = 1; r < table.GetLength(0); r++) sheet.List[r - 1] = new LocaleKey(table[r][0], table[r][c]); sheets.Add(sheet); } List<LocaleCode> availableLocale; if (_settings.availableLocale != null) availableLocale = new List<LocaleCode>(_settings.availableLocale); else availableLocale = new List<LocaleCode>(); foreach (LocaleSheetData sheet in sheets) { try { LocaleCode code = LocaleCode.Null; LocaleData localeData = null; code = (LocaleCode)System.Enum.Parse(typeof(LocaleCode), sheet.LocaleName); #if LOCALE_DATATH if (code == LocaleCode.TH) localeData = CreateAsset<LocaleDataTH>(exportPath + "/" + sheet.LocaleName, fileName); else localeData = CreateAsset<LocaleData>(exportPath + "/" + sheet.LocaleName, fileName); #else localeData = CreateAsset<LocaleData>(exportPath + "/" + sheet.LocaleName, fileName); #endif localeData.list = sheet.List; if (code != LocaleCode.Null && !availableLocale.Contains(code)) { availableLocale.Add(code); } EditorUtility.SetDirty(localeData); } catch { EditorUtility.DisplayDialog("Error", "Cannot parse \'" + sheet.LocaleName + "\' into \'LocaleCode\' enum. Please check your LocaleCode in CSV.", "Okay"); } } _settings.availableLocale = availableLocale.ToArray(); if (isPreload) { List<string> sheetTitle; if (_settings.availableLocale != null) sheetTitle = new List<string>(_settings.sheetTitles); else sheetTitle = new List<string>(); if (!sheetTitle.Contains(fileName)) { sheetTitle.Add(fileName); } _settings.sheetTitles = sheetTitle.ToArray(); EditorUtility.SetDirty(_settings); } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } public static string[][] CSVTextAsset(TextAsset text, char seperate = ',', char quote = '"') { StringBuilder reader = new StringBuilder(text.text); StringBuilder line = new StringBuilder(); List<string> row = new List<string>(); List<List<string>> lines = new List<List<string>>(); bool inQuotes = false; for (int i = 0; i < reader.Length; i++) { if (inQuotes) { // csv will create double quote in quote for telling character are single quote if (i < reader.Length - 1 && reader[i] == quote && reader[i + 1] == quote) { line.Append(quote); i++; continue; } else if (reader[i] == quote) { inQuotes = false; continue; } else { line.Append(reader[i]); continue; } } else { if (reader[i] == quote) { inQuotes = true; continue; } else if (reader[i] == '\r' || reader[i] == '\n') { if (line.Length > 0) { row.Add(line.ToString()); line.Length = 0; lines.Add(new List<string>(row.ToArray())); row.Clear(); } continue; } else if (reader[i] == seperate) { row.Add(line.ToString()); line.Length = 0; continue; } else if (i < reader.Length - 1 && reader[i] == '\\') { if (reader[i + 1] == 'n') { line.Append("\n"); i++; continue; } else if (reader[i + 1] == 'r') { line.Append("\r"); i++; continue; } } else { line.Append(reader[i]); continue; } } } // add final line row.Add(line.ToString()); line.Length = 0; lines.Add(new List<string>(row.ToArray())); row.Clear(); string[][] table = new string[lines.Count][]; for(int i = 0; i < lines.Count; i++) { table[i] = new string[lines[i].Count]; for (int j = 0; j < lines[i].Count; j++) { table[i][j] = lines[i][j]; } } return table; } public static T CreateAsset<T>(string _assetPath, string _name) where T : ScriptableObject { T asset = CreateInstance<T>(); string path = "Assets/" + _assetPath + "/" + _name + ".asset"; System.IO.Directory.CreateDirectory("Assets/" + _assetPath); AssetDatabase.CreateAsset(asset, path); EditorUtility.SetDirty(asset); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return asset; } } }
using System; using System.Reflection; using System.Reflection.Emit; using System.Threading; using BLToolkit.Properties; using BLToolkit.Reflection.Emit; using BLToolkit.TypeBuilder; using BLToolkit.TypeBuilder.Builders; namespace BLToolkit.Aspects.Builders { /// <summary> /// This aspect simplifies asynchronous operations. /// </summary> public class AsyncAspectBuilder : AbstractTypeBuilderBase { private readonly string _targetMethodName; private readonly Type[] _parameterTypes; public AsyncAspectBuilder(string targetMethodName, Type[] parameterTypes) { _targetMethodName = targetMethodName; _parameterTypes = parameterTypes; } public override int GetPriority(BuildContext context) { return TypeBuilderConsts.Priority.AsyncAspect; } public override bool IsCompatible(BuildContext context, IAbstractTypeBuilder typeBuilder) { if (context.IsBuildStep) return false; AbstractTypeBuilderList list = new AbstractTypeBuilderList(2); list.Add(this); list.Add(typeBuilder); BuildStep step = context.Step; try { context.Step = BuildStep.Build; return typeBuilder.IsApplied(context, list); } finally { context.Step = step; } } public override bool IsApplied(BuildContext context, AbstractTypeBuilderList builders) { if (context == null) throw new ArgumentNullException("context"); return context.IsBuildStep && context.BuildElement == BuildElement.AbstractMethod; } protected override void BuildAbstractMethod() { MethodInfo mi = Context.CurrentMethod; if (mi.ReturnType == typeof(IAsyncResult)) BuildBeginMethod(); else { ParameterInfo[] parameters = mi.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(IAsyncResult)) BuildEndMethod(); else throw new TypeBuilderException(string.Format("Method '{0}.{1}' is not a 'Begin' nor an 'End' method.", mi.DeclaringType.FullName, mi.Name)); } } private void BuildBeginMethod() { MethodInfo mi = Context.CurrentMethod; MethodInfo method = GetTargetMethod(Context, "Begin"); Type delegateType = EnsureDelegateType(Context, method); EmitHelper emit = Context.MethodBuilder.Emitter; Type type = typeof(InternalAsyncResult); LocalBuilder arLocal = emit.DeclareLocal(type); LocalBuilder dLocal = emit.DeclareLocal(delegateType); emit .newobj (type) .dup .dup .dup .stloc (arLocal) .ldarg_0 .ldftn (method) .newobj (delegateType, typeof(object), typeof(IntPtr)) .stloc (dLocal) .ldloc (dLocal) .stfld (type.GetField("Delegate")) .ldloc (dLocal) ; int callbackIndex = -1; ParameterInfo[] parameters = mi.GetParameters(); for (int i = 0; i < parameters.Length; ++i) { if (parameters[i].ParameterType == typeof(AsyncCallback)) { callbackIndex = i; emit .ldloc (arLocal) .dup .ldarg (parameters[i]) .stfld (type.GetField("AsyncCallback")) .ldftn (type.GetMethod("CallBack")) .newobj (typeof(AsyncCallback), typeof(object), typeof(IntPtr)) ; } else emit.ldarg(parameters[i]); } if (callbackIndex < 0) { // Callback omitted // emit .ldnull .ldnull .end(); } else if (callbackIndex == parameters.Length - 1) { // State omitted // emit .ldnull .end(); } emit .callvirt (delegateType.GetMethod("BeginInvoke")) .stfld (type.GetField("InnerResult")) .stloc (Context.ReturnValue) ; } private void BuildEndMethod() { MethodInfo method = GetTargetMethod(Context, "End"); Type delegateType = EnsureDelegateType(Context, method); EmitHelper emit = Context.MethodBuilder.Emitter; Type type = typeof(InternalAsyncResult); LocalBuilder arLocal = emit.DeclareLocal(type); emit .ldarg_1 .castclass (type) .dup .stloc (arLocal) .ldfld (type.GetField("Delegate")) .castclass (delegateType) .ldloc (arLocal) .ldfld (type.GetField("InnerResult")) .callvirt (delegateType, "EndInvoke", typeof(IAsyncResult)); if (Context.ReturnValue != null) emit.stloc(Context.ReturnValue); } private MethodInfo GetTargetMethod(BuildContext context, string prefix) { string targetMethodName = _targetMethodName; if (targetMethodName == null) { MethodInfo mi = context.CurrentMethod; string name = mi.Name; if (name.StartsWith(prefix)) targetMethodName = name.Substring(prefix.Length); else throw new TypeBuilderException(string.Format( Resources.AsyncAspectBuilder_NoTargetMethod, mi.DeclaringType.FullName, mi.Name)); } return _parameterTypes == null? context.Type.GetMethod(targetMethodName): context.Type.GetMethod(targetMethodName, _parameterTypes); } private static Type EnsureDelegateType(BuildContext context, MethodInfo method) { // The delegate should be defined as inner type of context.TypeBuilder. // It's possible, but we can not define and use newly defined type as Emit target in its owner type. // To solve this problem, we should create a top level delegate and make sure its name is unique. // string delegateName = context.TypeBuilder.TypeBuilder.FullName + "$" + method.Name + "$Delegate"; Type delegateType = (Type) context.Items[delegateName]; if (delegateType == null) { ParameterInfo[] pi = method.GetParameters(); Type[] parameters = new Type[pi.Length]; for (int i = 0; i < pi.Length; i++) parameters[i] = pi[i].ParameterType; const MethodImplAttributes mia = MethodImplAttributes.Runtime | MethodImplAttributes.Managed; const MethodAttributes ma = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual; TypeBuilderHelper delegateBuilder = context.AssemblyBuilder.DefineType(delegateName, TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate)); // Create constructor // ConstructorBuilderHelper ctorBuilder = delegateBuilder.DefineConstructor( MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard, typeof(object), typeof(IntPtr)); ctorBuilder.ConstructorBuilder.SetImplementationFlags(mia); // Define the BeginInvoke method for the delegate // Type[] beginParameters = new Type[parameters.Length + 2]; Array.Copy(parameters, 0, beginParameters, 0, parameters.Length); beginParameters[parameters.Length] = typeof(AsyncCallback); beginParameters[parameters.Length+1] = typeof(object); MethodBuilderHelper methodBuilder = delegateBuilder.DefineMethod("BeginInvoke", ma, typeof(IAsyncResult), beginParameters); methodBuilder.MethodBuilder.SetImplementationFlags(mia); // Define the EndInvoke method for the delegate // methodBuilder = delegateBuilder.DefineMethod("EndInvoke", ma, method.ReturnType, typeof(IAsyncResult)); methodBuilder.MethodBuilder.SetImplementationFlags(mia); // Define the Invoke method for the delegate // methodBuilder = delegateBuilder.DefineMethod("Invoke", ma, method.ReturnType, parameters); methodBuilder.MethodBuilder.SetImplementationFlags(mia); context.Items[delegateName] = delegateType = delegateBuilder.Create(); } return delegateType; } #region Helper /// <summary> /// Reserved for internal BLToolkit use. /// </summary> public class InternalAsyncResult : IAsyncResult { public IAsyncResult InnerResult; public Delegate Delegate; public AsyncCallback AsyncCallback; public void CallBack(IAsyncResult ar) { if (AsyncCallback != null) AsyncCallback(this); } public bool IsCompleted { get { return InnerResult.IsCompleted; } } public WaitHandle AsyncWaitHandle { get { return InnerResult.AsyncWaitHandle; } } public object AsyncState { get { return InnerResult.AsyncState; } } public bool CompletedSynchronously { get { return InnerResult.CompletedSynchronously; } } } #endregion } }
using System; using NUnit.Framework; using Whois.Parsers; namespace Whois.Parsing.Whois.Educause.Edu.Edu { [TestFixture] public class EduParsingTests : ParsingTests { private WhoisParser parser; [SetUp] public void SetUp() { SerilogConfig.Init(); parser = new WhoisParser(); } [Test] public void Test_found() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("nic.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2010, 06, 29, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1996, 12, 20, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("North Idaho College", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("1000 W. Garden Avenue", response.Registrant.Address[0]); Assert.AreEqual("Coeur d'Alene, ID 83814", response.Registrant.Address[1]); Assert.AreEqual("UNITED STATES", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("NetAdmin", response.AdminContact.Name); Assert.AreEqual("(208) 769-7860", response.AdminContact.TelephoneNumber); Assert.AreEqual("netsys@nic.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("North Idaho College", response.AdminContact.Address[0]); Assert.AreEqual("1000 W. Garden Avenue", response.AdminContact.Address[1]); Assert.AreEqual("Coeur d Alene, ID 83814", response.AdminContact.Address[2]); Assert.AreEqual("UNITED STATES", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Dennis L Noordam", response.TechnicalContact.Name); Assert.AreEqual("(208) 769-7860", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("dlnoordam@nic.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("Windows System Administrator", response.TechnicalContact.Address[0]); Assert.AreEqual("North Idaho College", response.TechnicalContact.Address[1]); Assert.AreEqual("1000 W. Garden Avenue", response.TechnicalContact.Address[2]); Assert.AreEqual("Coeur d Alene, ID 83814", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("nicns1.nic.edu", response.NameServers[0]); Assert.AreEqual("nicns2.nic.edu", response.NameServers[1]); Assert.AreEqual(26, response.FieldsParsed); } [Test] public void Test_found_fixture2() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_fixture2.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("harvard.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2012, 03, 19, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1985, 06, 27, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Harvard University", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("HUIT Network Services", response.Registrant.Address[0]); Assert.AreEqual("60 Oxford Street", response.Registrant.Address[1]); Assert.AreEqual("Cambridge, MA 02138", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Jacques N Laflamme", response.AdminContact.Name); Assert.AreEqual("(617) 384-6663", response.AdminContact.TelephoneNumber); Assert.AreEqual("jacques_laflamme@harvard.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Director, Network Services", response.AdminContact.Address[0]); Assert.AreEqual("Harvard University", response.AdminContact.Address[1]); Assert.AreEqual("60 Oxford Street", response.AdminContact.Address[2]); Assert.AreEqual("Cambridge, MA 02138", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Network Operations", response.TechnicalContact.Name); Assert.AreEqual("(617) 495-7777", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("netmanager@harvard.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("Harvard University", response.TechnicalContact.Address[0]); Assert.AreEqual("HUIT Network Services", response.TechnicalContact.Address[1]); Assert.AreEqual("60 Oxford Street", response.TechnicalContact.Address[2]); Assert.AreEqual("Cambridge, MA 02138", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("externaldns-c1.harvard.edu", response.NameServers[0]); Assert.AreEqual("externaldns-c2.harvard.edu", response.NameServers[1]); Assert.AreEqual("externaldns-c3.br.harvard.edu", response.NameServers[2]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_fixture3() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_fixture3.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found02", response.TemplateName); Assert.AreEqual("stanford.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2009, 05, 07, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1985, 10, 04, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Stanford University", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("The Board of Trustees of the Leland Stanford Junior University", response.Registrant.Address[0]); Assert.AreEqual("241 Panama Street, Pine Hall, Room 115", response.Registrant.Address[1]); Assert.AreEqual("Stanford, CA 94305-4122", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Domain Admin", response.AdminContact.Name); Assert.AreEqual("(650) 723-4328", response.AdminContact.TelephoneNumber); Assert.AreEqual("sunet-admin@stanford.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Stanford University", response.AdminContact.Address[0]); Assert.AreEqual("241 Panama Street Pine Hall, Room 115", response.AdminContact.Address[1]); Assert.AreEqual("Stanford, CA 94305-4122", response.AdminContact.Address[2]); Assert.AreEqual("UNITED STATES", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Domain Admin", response.TechnicalContact.Name); Assert.AreEqual("(650) 723-4328", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("sunet-admin@stanford.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Stanford University", response.TechnicalContact.Address[0]); Assert.AreEqual("241 Panama Street Pine Hall, Room 115", response.TechnicalContact.Address[1]); Assert.AreEqual("Stanford, CA 94305-4122", response.TechnicalContact.Address[2]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(4, response.NameServers.Count); Assert.AreEqual("argus.stanford.edu", response.NameServers[0]); Assert.AreEqual("avallone.stanford.edu", response.NameServers[1]); Assert.AreEqual("atalante.stanford.edu", response.NameServers[2]); Assert.AreEqual("aerathea.stanford.edu", response.NameServers[3]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_fixture4() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_fixture4.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found02", response.TemplateName); Assert.AreEqual("nyu.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2007, 10, 12, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1986, 10, 08, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("New York University", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("ITS Communications Operations Services", response.Registrant.Address[0]); Assert.AreEqual("7 East 12th Street, 5th Floor", response.Registrant.Address[1]); Assert.AreEqual("New York, NY 10003", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("NYU Network Operations Admin Role Account", response.AdminContact.Name); Assert.AreEqual("(212) 998-3431", response.AdminContact.TelephoneNumber); Assert.AreEqual("domreg.admin@nyu.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("New York University, ITS C&CS", response.AdminContact.Address[0]); Assert.AreEqual("7 East 12th Street", response.AdminContact.Address[1]); Assert.AreEqual("5th Floor", response.AdminContact.Address[2]); Assert.AreEqual("New York, NY 10003", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Network Operations Center Role Account", response.TechnicalContact.Name); Assert.AreEqual("(212) 998-3444", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("noc@nyu.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("New York University, ITS COS", response.TechnicalContact.Address[0]); Assert.AreEqual("7 East 12th Street", response.TechnicalContact.Address[1]); Assert.AreEqual("Room 501", response.TechnicalContact.Address[2]); Assert.AreEqual("New York, NY 10003", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns1.nyu.edu", response.NameServers[0]); Assert.AreEqual("ns2.nyu.edu", response.NameServers[1]); Assert.AreEqual("nyu-ns.berkeley.edu", response.NameServers[2]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_fixture5() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_fixture5.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("uiuc.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2011, 03, 22, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1985, 07, 18, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("University of Illinois at Urbana Champaign", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("CITES 1120 Digital Computer Laboratory", response.Registrant.Address[0]); Assert.AreEqual("1304 West Springfield Avenue", response.Registrant.Address[1]); Assert.AreEqual("Urbana, IL 61801-2910", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Tracy L. Smith", response.AdminContact.Name); Assert.AreEqual("(217) 244-2032", response.AdminContact.TelephoneNumber); Assert.AreEqual("edu-admin@listserv.illinois.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("University of Illinois at Urbana-Champaign", response.AdminContact.Address[0]); Assert.AreEqual("CITES 2105 Digital Computer Laboratory", response.AdminContact.Address[1]); Assert.AreEqual("1304 West Springfield Avenue", response.AdminContact.Address[2]); Assert.AreEqual("Urbana, IL 61801-4399", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Charles Kline", response.TechnicalContact.Name); Assert.AreEqual("(217) 333-3339", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("edu-tech@listserv.illinois.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("University of Illinois at Urbana Champaign", response.TechnicalContact.Address[0]); Assert.AreEqual("CITES 1120 Digital Computer Laboratory", response.TechnicalContact.Address[1]); Assert.AreEqual("1304 West Springfield Avenue", response.TechnicalContact.Address[2]); Assert.AreEqual("Urbana, IL 61801", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("dns1.illinois.edu", response.NameServers[0]); Assert.AreEqual("dns2.illinois.edu", response.NameServers[1]); Assert.AreEqual("dns1.iu.edu", response.NameServers[2]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_fixture6() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_fixture6.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); AssertWriter.Write(response); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found03", response.TemplateName); Assert.AreEqual("brown.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2011, 01, 05, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1986, 08, 27, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Brown University", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("Computing & Information", response.Registrant.Address[0]); Assert.AreEqual("Services Box 1885", response.Registrant.Address[1]); Assert.AreEqual("Providence, RI 02912-1885", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Kenise Harris", response.AdminContact.Name); Assert.AreEqual("(401) 863-7223", response.AdminContact.TelephoneNumber); Assert.AreEqual("kenise_harris@brown.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("CIS Manager", response.AdminContact.Address[0]); Assert.AreEqual("Brown University", response.AdminContact.Address[1]); Assert.AreEqual("115 Waterman St., Box 1885", response.AdminContact.Address[2]); Assert.AreEqual("Providence, RI 02912-1885", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("NOC", response.TechnicalContact.Name); Assert.AreEqual("(401) 863-7247", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("noc@brown.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Brown University", response.TechnicalContact.Address[0]); Assert.AreEqual("115 Waterman St., Box 1885", response.TechnicalContact.Address[1]); Assert.AreEqual("Providence, RI 02912-1885", response.TechnicalContact.Address[2]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("bru-ns1.brown.edu", response.NameServers[0]); Assert.AreEqual("bru-ns2.brown.edu", response.NameServers[1]); Assert.AreEqual("ns1.ucsb.edu", response.NameServers[2]); Assert.AreEqual(26, response.FieldsParsed); } [Test] public void Test_found_contacts() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contacts.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("nic.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2010, 06, 29, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1996, 12, 20, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("North Idaho College", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("1000 W. Garden Avenue", response.Registrant.Address[0]); Assert.AreEqual("Coeur d'Alene, ID 83814", response.Registrant.Address[1]); Assert.AreEqual("UNITED STATES", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("NetAdmin", response.AdminContact.Name); Assert.AreEqual("(208) 769-7860", response.AdminContact.TelephoneNumber); Assert.AreEqual("netsys@nic.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("North Idaho College", response.AdminContact.Address[0]); Assert.AreEqual("1000 W. Garden Avenue", response.AdminContact.Address[1]); Assert.AreEqual("Coeur d Alene, ID 83814", response.AdminContact.Address[2]); Assert.AreEqual("UNITED STATES", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Dennis L Noordam", response.TechnicalContact.Name); Assert.AreEqual("(208) 769-7860", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("dlnoordam@nic.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("Windows System Administrator", response.TechnicalContact.Address[0]); Assert.AreEqual("North Idaho College", response.TechnicalContact.Address[1]); Assert.AreEqual("1000 W. Garden Avenue", response.TechnicalContact.Address[2]); Assert.AreEqual("Coeur d Alene, ID 83814", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("nicns1.nic.edu", response.NameServers[0]); Assert.AreEqual("nicns2.nic.edu", response.NameServers[1]); Assert.AreEqual(26, response.FieldsParsed); } [Test] public void Test_found_contacts_case1() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contacts_case1.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("educause.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2009, 10, 02, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1998, 03, 11, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2010, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("EDUCAUSE", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("4772 Walnut Street", response.Registrant.Address[0]); Assert.AreEqual("Suite 206", response.Registrant.Address[1]); Assert.AreEqual("Boulder, CO 80301", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Information Technology", response.AdminContact.Name); Assert.AreEqual("(303) 449-4430", response.AdminContact.TelephoneNumber); Assert.AreEqual("netadmin@educause.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("EDUCAUSE", response.AdminContact.Address[0]); Assert.AreEqual("4772 Walnut Street", response.AdminContact.Address[1]); Assert.AreEqual("Ste 206", response.AdminContact.Address[2]); Assert.AreEqual("Boulder, CO 80301", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Information Technology", response.TechnicalContact.Name); Assert.AreEqual("(303) 449-4430", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("netadmin@educause.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("EDUCAUSE", response.TechnicalContact.Address[0]); Assert.AreEqual("4772 Walnut Street", response.TechnicalContact.Address[1]); Assert.AreEqual("Ste 206", response.TechnicalContact.Address[2]); Assert.AreEqual("Boulder, CO 80301", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns3.educause.edu", response.NameServers[0]); Assert.AreEqual("ns4.educause.edu", response.NameServers[1]); Assert.AreEqual("ns5.educause.edu", response.NameServers[2]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_contacts_case2() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contacts_case2.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found02", response.TemplateName); Assert.AreEqual("stanford.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2009, 05, 07, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1985, 10, 04, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Stanford University", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("The Board of Trustees of the Leland Stanford Junior University", response.Registrant.Address[0]); Assert.AreEqual("241 Panama Street, Pine Hall, Room 115", response.Registrant.Address[1]); Assert.AreEqual("Stanford, CA 94305-4122", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Domain Admin", response.AdminContact.Name); Assert.AreEqual("(650) 723-4328", response.AdminContact.TelephoneNumber); Assert.AreEqual("sunet-admin@stanford.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Stanford University", response.AdminContact.Address[0]); Assert.AreEqual("241 Panama Street Pine Hall, Room 115", response.AdminContact.Address[1]); Assert.AreEqual("Stanford, CA 94305-4122", response.AdminContact.Address[2]); Assert.AreEqual("UNITED STATES", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Domain Admin", response.TechnicalContact.Name); Assert.AreEqual("(650) 723-4328", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("sunet-admin@stanford.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Stanford University", response.TechnicalContact.Address[0]); Assert.AreEqual("241 Panama Street Pine Hall, Room 115", response.TechnicalContact.Address[1]); Assert.AreEqual("Stanford, CA 94305-4122", response.TechnicalContact.Address[2]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(4, response.NameServers.Count); Assert.AreEqual("argus.stanford.edu", response.NameServers[0]); Assert.AreEqual("avallone.stanford.edu", response.NameServers[1]); Assert.AreEqual("atalante.stanford.edu", response.NameServers[2]); Assert.AreEqual("aerathea.stanford.edu", response.NameServers[3]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_contacts_case3() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contacts_case3.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("uiuc.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2011, 03, 22, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1985, 07, 18, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("University of Illinois at Urbana Champaign", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("CITES 1120 Digital Computer Laboratory", response.Registrant.Address[0]); Assert.AreEqual("1304 West Springfield Avenue", response.Registrant.Address[1]); Assert.AreEqual("Urbana, IL 61801-2910", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Tracy L. Smith", response.AdminContact.Name); Assert.AreEqual("(217) 244-2032", response.AdminContact.TelephoneNumber); Assert.AreEqual("edu-admin@listserv.illinois.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("University of Illinois at Urbana-Champaign", response.AdminContact.Address[0]); Assert.AreEqual("CITES 2105 Digital Computer Laboratory", response.AdminContact.Address[1]); Assert.AreEqual("1304 West Springfield Avenue", response.AdminContact.Address[2]); Assert.AreEqual("Urbana, IL 61801-4399", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Charles Kline", response.TechnicalContact.Name); Assert.AreEqual("(217) 333-3339", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("edu-tech@listserv.illinois.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("University of Illinois at Urbana Champaign", response.TechnicalContact.Address[0]); Assert.AreEqual("CITES 1120 Digital Computer Laboratory", response.TechnicalContact.Address[1]); Assert.AreEqual("1304 West Springfield Avenue", response.TechnicalContact.Address[2]); Assert.AreEqual("Urbana, IL 61801", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("dns1.illinois.edu", response.NameServers[0]); Assert.AreEqual("dns2.illinois.edu", response.NameServers[1]); Assert.AreEqual("dns1.iu.edu", response.NameServers[2]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_contacts_case4() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contacts_case4.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found02", response.TemplateName); Assert.AreEqual("syr.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2010, 07, 07, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1986, 09, 02, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Syracuse University", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("Room 200 Machinery Hall", response.Registrant.Address[0]); Assert.AreEqual("Syracuse, NY 13244", response.Registrant.Address[1]); Assert.AreEqual("UNITED STATES", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("ITS Business Office", response.AdminContact.Name); Assert.AreEqual("(315) 443-6189", response.AdminContact.TelephoneNumber); Assert.AreEqual("itsoffice@syr.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Syracuse University", response.AdminContact.Address[0]); Assert.AreEqual("Information Technology and Services", response.AdminContact.Address[1]); Assert.AreEqual("Center for Science and Technology", response.AdminContact.Address[2]); Assert.AreEqual("Syracuse, NY 13244", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Networking", response.TechnicalContact.Name); Assert.AreEqual("(315) 443-2677", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("ndd@listserv.syr.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Syracuse University", response.TechnicalContact.Address[0]); Assert.AreEqual("Room 200 Machinery Hall", response.TechnicalContact.Address[1]); Assert.AreEqual("Syracuse, NY 13244", response.TechnicalContact.Address[2]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(5, response.NameServers.Count); Assert.AreEqual("lurch.cns.syr.edu", response.NameServers[0]); Assert.AreEqual("icarus.syr.edu", response.NameServers[1]); Assert.AreEqual("suec1.syr.edu", response.NameServers[2]); Assert.AreEqual("ns1.twtelecom.net", response.NameServers[3]); Assert.AreEqual("ns2.twtelecom.net", response.NameServers[4]); Assert.AreEqual(28, response.FieldsParsed); } [Test] public void Test_found_contact_registrant() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contact_registrant.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("nic.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2010, 06, 29, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1996, 12, 20, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("North Idaho College", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("1000 W. Garden Avenue", response.Registrant.Address[0]); Assert.AreEqual("Coeur d'Alene, ID 83814", response.Registrant.Address[1]); Assert.AreEqual("UNITED STATES", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("NetAdmin", response.AdminContact.Name); Assert.AreEqual("(208) 769-7860", response.AdminContact.TelephoneNumber); Assert.AreEqual("netsys@nic.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("North Idaho College", response.AdminContact.Address[0]); Assert.AreEqual("1000 W. Garden Avenue", response.AdminContact.Address[1]); Assert.AreEqual("Coeur d Alene, ID 83814", response.AdminContact.Address[2]); Assert.AreEqual("UNITED STATES", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Dennis L Noordam", response.TechnicalContact.Name); Assert.AreEqual("(208) 769-7860", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("dlnoordam@nic.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("Windows System Administrator", response.TechnicalContact.Address[0]); Assert.AreEqual("North Idaho College", response.TechnicalContact.Address[1]); Assert.AreEqual("1000 W. Garden Avenue", response.TechnicalContact.Address[2]); Assert.AreEqual("Coeur d Alene, ID 83814", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("nicns1.nic.edu", response.NameServers[0]); Assert.AreEqual("nicns2.nic.edu", response.NameServers[1]); Assert.AreEqual(26, response.FieldsParsed); } [Test] public void Test_found_contact_registrant_without_address() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contact_registrant_without_address.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("mit.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2010, 06, 18, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1985, 05, 23, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Massachusetts Institute of Technology", response.Registrant.Organization); // Registrant Address Assert.AreEqual(2, response.Registrant.Address.Count); Assert.AreEqual("Cambridge, MA 02139", response.Registrant.Address[0]); Assert.AreEqual("UNITED STATES", response.Registrant.Address[1]); // AdminContact Details Assert.AreEqual("Mark Silis", response.AdminContact.Name); Assert.AreEqual("(617) 324-5900", response.AdminContact.TelephoneNumber); Assert.AreEqual("mark@mit.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Massachusetts Institute of Technology", response.AdminContact.Address[0]); Assert.AreEqual("MIT Room W92-167, 77 Massachusetts Avenue", response.AdminContact.Address[1]); Assert.AreEqual("Cambridge, MA 02139-4307", response.AdminContact.Address[2]); Assert.AreEqual("UNITED STATES", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("MIT Network Operations", response.TechnicalContact.Name); Assert.AreEqual("(617) 253-8400", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("network@mit.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Massachusetts Institute of Technology", response.TechnicalContact.Address[0]); Assert.AreEqual("MIT Room W92-167, 77 Massachusetts Avenue", response.TechnicalContact.Address[1]); Assert.AreEqual("Cambridge, MA 02139-4307", response.TechnicalContact.Address[2]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[3]); Assert.AreEqual(22, response.FieldsParsed); } [Test] public void Test_found_contact_registrant_without_zip() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contact_registrant_without_zip.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("aucmed.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2011, 08, 09, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1997, 07, 02, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("The American University of the Caribbean School of Medicine", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("c/o Campbell Corporate Services, Ltd.", response.Registrant.Address[0]); Assert.AreEqual("Scotiabank Building, P. O. Box 268", response.Registrant.Address[1]); Assert.AreEqual("Grand Cayman", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Ron Spaide", response.AdminContact.Name); Assert.AreEqual("(732) 509-4796", response.AdminContact.TelephoneNumber); Assert.AreEqual("rspaide@devrymedical.org", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("VP, CIO", response.AdminContact.Address[0]); Assert.AreEqual("Devry Medical International, Inc", response.AdminContact.Address[1]); Assert.AreEqual("630 US Highway 1", response.AdminContact.Address[2]); Assert.AreEqual("North Brunswick, NJ 08902", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Bill Huber", response.TechnicalContact.Name); Assert.AreEqual("(732) 509-4796", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("bhuber@devrymedical.org", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("Director, Network Operations", response.TechnicalContact.Address[0]); Assert.AreEqual("DeVry Medical International, Inc", response.TechnicalContact.Address[1]); Assert.AreEqual("630 US Highway 1", response.TechnicalContact.Address[2]); Assert.AreEqual("North Brunswick, NJ 08902", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns1.geodns.net", response.NameServers[0]); Assert.AreEqual("ns2.geodns.net", response.NameServers[1]); Assert.AreEqual(26, response.FieldsParsed); } [Test] public void Test_found_contact_registrant_with_additional_organization() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_contact_registrant_with_additional_organization.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("harvard.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2012, 03, 19, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1985, 06, 27, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Harvard University", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("HUIT Network Services", response.Registrant.Address[0]); Assert.AreEqual("60 Oxford Street", response.Registrant.Address[1]); Assert.AreEqual("Cambridge, MA 02138", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Jacques N Laflamme", response.AdminContact.Name); Assert.AreEqual("(617) 384-6663", response.AdminContact.TelephoneNumber); Assert.AreEqual("jacques_laflamme@harvard.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Director, Network Services", response.AdminContact.Address[0]); Assert.AreEqual("Harvard University", response.AdminContact.Address[1]); Assert.AreEqual("60 Oxford Street", response.AdminContact.Address[2]); Assert.AreEqual("Cambridge, MA 02138", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Network Operations", response.TechnicalContact.Name); Assert.AreEqual("(617) 495-7777", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("netmanager@harvard.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("Harvard University", response.TechnicalContact.Address[0]); Assert.AreEqual("HUIT Network Services", response.TechnicalContact.Address[1]); Assert.AreEqual("60 Oxford Street", response.TechnicalContact.Address[2]); Assert.AreEqual("Cambridge, MA 02138", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("externaldns-c1.harvard.edu", response.NameServers[0]); Assert.AreEqual("externaldns-c2.harvard.edu", response.NameServers[1]); Assert.AreEqual("externaldns-c3.br.harvard.edu", response.NameServers[2]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_found_updated_on_unknown() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_updated_on_unknown.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); AssertWriter.Write(response); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("pcihealth.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2004, 03, 12, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("PCI Health Training Center", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("8101 John Carpenter Freeway", response.Registrant.Address[0]); Assert.AreEqual("Dallas, TX 75247-4720", response.Registrant.Address[1]); Assert.AreEqual("UNITED STATES", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Kelly Drake", response.AdminContact.Name); Assert.AreEqual("(214) 630-0568", response.AdminContact.TelephoneNumber); Assert.AreEqual("kdrake@pcihealth.net", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("admissions", response.AdminContact.Address[0]); Assert.AreEqual("PCI Health Training Center", response.AdminContact.Address[1]); Assert.AreEqual("8101 John Carpenter Freeway", response.AdminContact.Address[2]); Assert.AreEqual("Dallas, TX 75247-4720", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("daniel Roy", response.TechnicalContact.Name); Assert.AreEqual("(214) 215-1764", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("dan@nativetechnology.net", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("InfoTech Services", response.TechnicalContact.Address[0]); Assert.AreEqual("PCI Health Training Center", response.TechnicalContact.Address[1]); Assert.AreEqual("8101 John Carpenter Freeway", response.TechnicalContact.Address[2]); Assert.AreEqual("Dallas, TX 75247-4720", response.TechnicalContact.Address[3]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns1.maximumasp.com", response.NameServers[0]); Assert.AreEqual("ns2.maximumasp.com", response.NameServers[1]); Assert.AreEqual(25, response.FieldsParsed); } [Test] public void Test_not_found() { var sample = SampleReader.Read("whois.educause.edu", "edu", "not_found.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.NotFound, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/NotFound", response.TemplateName); Assert.AreEqual(1, response.FieldsParsed); } [Test] public void Test_found_status_registered() { var sample = SampleReader.Read("whois.educause.edu", "edu", "found_status_registered.txt"); var response = parser.Parse("whois.educause.edu", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.educause.edu/edu/Found01", response.TemplateName); Assert.AreEqual("academia.edu", response.DomainName.ToString()); Assert.AreEqual(new DateTime(2012, 04, 04, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1999, 05, 10, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2014, 07, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Academia", response.Registrant.Organization); // Registrant Address Assert.AreEqual(3, response.Registrant.Address.Count); Assert.AreEqual("251 Kearny St", response.Registrant.Address[0]); Assert.AreEqual("suite 520", response.Registrant.Address[1]); Assert.AreEqual("San Francisco, CA 94108", response.Registrant.Address[2]); // AdminContact Details Assert.AreEqual("Academia, Inc.", response.AdminContact.Name); Assert.AreEqual("(415) 829-2341", response.AdminContact.TelephoneNumber); Assert.AreEqual("helpdesk@academia.edu", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("251 Kearny St", response.AdminContact.Address[0]); Assert.AreEqual("suite 520", response.AdminContact.Address[1]); Assert.AreEqual("San Francisco, CA 94108", response.AdminContact.Address[2]); Assert.AreEqual("UNITED STATES", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("Academia, Inc.", response.TechnicalContact.Name); Assert.AreEqual("(415) 829-2341", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("helpdesk@academia.edu", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("251 Kearny St", response.TechnicalContact.Address[0]); Assert.AreEqual("suite 520", response.TechnicalContact.Address[1]); Assert.AreEqual("San Francisco, CA 94108", response.TechnicalContact.Address[2]); Assert.AreEqual("UNITED STATES", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(4, response.NameServers.Count); Assert.AreEqual("ns-1484.awsdns-57.org", response.NameServers[0]); Assert.AreEqual("ns-225.awsdns-28.com", response.NameServers[1]); Assert.AreEqual("ns-1850.awsdns-39.co.uk", response.NameServers[2]); Assert.AreEqual("ns-629.awsdns-14.net", response.NameServers[3]); Assert.AreEqual(27, response.FieldsParsed); } } }
using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Runtime.InteropServices; namespace LibuvSharp { public class Udp : HandleBase, IMessageSender<UdpMessage>, IMessageReceiver<UdpReceiveMessage>, ITrySend<UdpMessage>, IBindable<Udp, IPEndPoint> { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void recv_start_callback_win(IntPtr handle, IntPtr nread, ref WindowsBufferStruct buf, IntPtr sockaddr, ushort flags); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void recv_start_callback_unix(IntPtr handle, IntPtr nread, ref UnixBufferStruct buf, IntPtr sockaddr, ushort flags); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_init(IntPtr loop, IntPtr handle); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_bind(IntPtr handle, ref sockaddr_in sockaddr, uint flags); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_bind(IntPtr handle, ref sockaddr_in6 sockaddr, uint flags); ByteBufferAllocatorBase allocator; public ByteBufferAllocatorBase ByteBufferAllocator { get { return allocator ?? Loop.ByteBufferAllocator; } set { allocator = value; } } public Udp() : this(Loop.Constructor) { } public Udp(Loop loop) : base(loop, HandleType.UV_UDP, uv_udp_init) { } void Bind(IPAddress ipAddress, int port, bool dualstack) { CheckDisposed(); UV.Bind(this, uv_udp_bind, uv_udp_bind, ipAddress, port, dualstack); } public void Bind(int port) { Bind(IPAddress.IPv6Any, port, true); } public void Bind(IPEndPoint endPoint) { Ensure.ArgumentNotNull(endPoint, "endPoint"); Bind(endPoint.Address, endPoint.Port, false); } [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_send(IntPtr req, IntPtr handle, WindowsBufferStruct[] bufs, int nbufs, ref sockaddr_in addr, callback callback); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_send(IntPtr req, IntPtr handle, UnixBufferStruct[] bufs, int nbufs, ref sockaddr_in addr, callback callback); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_send(IntPtr req, IntPtr handle, WindowsBufferStruct[] bufs, int nbufs, ref sockaddr_in6 addr, callback callback); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_send(IntPtr req, IntPtr handle, UnixBufferStruct[] bufs, int nbufs, ref sockaddr_in6 addr, callback callback); public void Send(UdpMessage message, Action<Exception> callback) { CheckDisposed(); Ensure.ArgumentNotNull(message.EndPoint, "message EndPoint"); Ensure.AddressFamily(message.EndPoint.Address); var ipEndPoint = message.EndPoint; var data = message.Payload; GCHandle datagchandle = GCHandle.Alloc(data.Array, GCHandleType.Pinned); CallbackPermaRequest cpr = new CallbackPermaRequest(RequestType.UV_UDP_SEND); cpr.Callback = (status, cpr2) => { datagchandle.Free(); Ensure.Success(status, callback); }; var ptr = (IntPtr)(datagchandle.AddrOfPinnedObject().ToInt64() + data.Offset); int r; if (UV.isUnix) { UnixBufferStruct[] buf = new UnixBufferStruct[1]; buf[0] = new UnixBufferStruct(ptr, data.Count); if (ipEndPoint.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { sockaddr_in address = UV.ToStruct(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_send(cpr.Handle, NativeHandle, buf, 1, ref address, CallbackPermaRequest.CallbackDelegate); } else { sockaddr_in6 address = UV.ToStruct6(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_send(cpr.Handle, NativeHandle, buf, 1, ref address, CallbackPermaRequest.CallbackDelegate); } } else { WindowsBufferStruct[] buf = new WindowsBufferStruct[1]; buf[0] = new WindowsBufferStruct(ptr, data.Count); if (ipEndPoint.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { sockaddr_in address = UV.ToStruct(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_send(cpr.Handle, NativeHandle, buf, 1, ref address, CallbackPermaRequest.CallbackDelegate); } else { sockaddr_in6 address = UV.ToStruct6(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_send(cpr.Handle, NativeHandle, buf, 1, ref address, CallbackPermaRequest.CallbackDelegate); } } Ensure.Success(r); } [DllImport("uv", EntryPoint = "uv_udp_recv_start", CallingConvention = CallingConvention.Cdecl)] extern static int uv_udp_recv_start_win(IntPtr handle, alloc_callback_win alloc_callback, recv_start_callback_win callback); [DllImport("uv", EntryPoint = "uv_udp_recv_start", CallingConvention = CallingConvention.Cdecl)] extern static int uv_udp_recv_start_unix(IntPtr handle, alloc_callback_unix alloc_callback, recv_start_callback_unix callback); static recv_start_callback_win recv_start_cb_win = recv_start_callback_w; static void recv_start_callback_w(IntPtr handlePointer, IntPtr nread, ref WindowsBufferStruct buf, IntPtr sockaddr, ushort flags) { var handle = FromIntPtr<Udp>(handlePointer); handle.recv_start_callback(handlePointer, nread, sockaddr, flags); } static recv_start_callback_unix recv_start_cb_unix = recv_start_callback_u; static void recv_start_callback_u(IntPtr handlePointer, IntPtr nread, ref UnixBufferStruct buf, IntPtr sockaddr, ushort flags) { var handle = FromIntPtr<Udp>(handlePointer); handle.recv_start_callback(handlePointer, nread, sockaddr, flags); } void recv_start_callback(IntPtr handle, IntPtr nread, IntPtr sockaddr, ushort flags) { int n = (int)nread; if (n == 0) { return; } if (Message != null) { var ep = UV.GetIPEndPoint(sockaddr, true); var msg = new UdpReceiveMessage( ep, ByteBufferAllocator.Retrieve(n), (flags & (short)uv_udp_flags.UV_UDP_PARTIAL) > 0 ); Message(msg); } } public void Resume() { CheckDisposed(); int r; if (UV.isUnix) { r = uv_udp_recv_start_unix(NativeHandle, ByteBufferAllocator.AllocCallbackUnix, recv_start_cb_unix); } else { r = uv_udp_recv_start_win(NativeHandle, ByteBufferAllocator.AllocCallbackWin, recv_start_cb_win); } Ensure.Success(r); } [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_recv_stop(IntPtr handle); public void Pause() { Invoke(uv_udp_recv_stop); } public event Action<UdpReceiveMessage> Message; [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_set_ttl(IntPtr handle, int ttl); public byte TTL { set { Invoke(uv_udp_set_ttl, (int)value); } } [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_set_broadcast(IntPtr handle, int on); public bool Broadcast { set { Invoke(uv_udp_set_broadcast, value ? 1 : 0); } } [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_set_multicast_ttl(IntPtr handle, int ttl); public byte MulticastTTL { set { Invoke(uv_udp_set_multicast_ttl, (int)value); } } [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_set_multicast_loop(IntPtr handle, int on); public bool MulticastLoop { set { Invoke(uv_udp_set_multicast_loop, value ? 1 : 0); } } [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] static extern int uv_udp_getsockname(IntPtr handle, IntPtr addr, ref int length); public IPEndPoint LocalAddress { get { CheckDisposed(); return UV.GetSockname(this, uv_udp_getsockname); } } [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_try_send(IntPtr handle, WindowsBufferStruct[] bufs, int nbufs, ref sockaddr_in addr); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_try_send(IntPtr handle, UnixBufferStruct[] bufs, int nbufs, ref sockaddr_in addr); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_try_send(IntPtr handle, WindowsBufferStruct[] bufs, int nbufs, ref sockaddr_in6 addr); [DllImport("uv", CallingConvention = CallingConvention.Cdecl)] internal extern static int uv_udp_try_send(IntPtr handle, UnixBufferStruct[] bufs, int nbufs, ref sockaddr_in6 addr); unsafe public int TrySend(UdpMessage message) { Ensure.ArgumentNotNull(message, "message"); var data = message.Payload; var ipEndPoint = message.EndPoint; fixed (byte* bytePtr = data.Array) { var ptr = (IntPtr)(bytePtr + message.Payload.Offset); int r; if (UV.isUnix) { UnixBufferStruct[] buf = new UnixBufferStruct[1]; buf[0] = new UnixBufferStruct(ptr, data.Count); if (ipEndPoint.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { sockaddr_in address = UV.ToStruct(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_try_send(NativeHandle, buf, 1, ref address); } else { sockaddr_in6 address = UV.ToStruct6(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_try_send(NativeHandle, buf, 1, ref address); } } else { WindowsBufferStruct[] buf = new WindowsBufferStruct[1]; buf[0] = new WindowsBufferStruct(ptr, data.Count); if (ipEndPoint.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { sockaddr_in address = UV.ToStruct(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_try_send(NativeHandle, buf, 1, ref address); } else { sockaddr_in6 address = UV.ToStruct6(ipEndPoint.Address.ToString(), ipEndPoint.Port); r = uv_udp_try_send(NativeHandle, buf, 1, ref address); } } return r; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace RealMocking.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)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections; using System.Collections.Specialized; using System.IO; using OpenADK.Library; using OpenADK.Util; /// <summary> A convenience class to parse the command-line of all Adk Example agents /// and to read a list of zones from a zones.properties file, if present in /// the current working directory.<p> /// * /// </summary> /// <version> Adk 1.0 /// /// </version> public class AdkExamples { /// <summary> False if the /noreg option was specified, indicating the agent should /// not send a SIF_Register message when connecting to zones /// </summary> public static bool Reg = true; /// <summary> True if the /unreg option was specified, indicating the agent should /// send a SIF_Unregister when shutting down and disconnecting from zones /// </summary> public static bool Unreg = false; /// <summary> The SIFVersion specified on the command-line /// </summary> public static SifVersion Version; /// <summary> Parsed command-line arguments /// </summary> public static string[] args = null; /// <summary> Parse the command-line. This method may be called repeatedly, usually /// once from the sample agent's <c>main</code> function prior to /// initializing the Adk and again from the <c>Agent.initialize</code> /// method after initializing the Agent superclass. When called without an /// Agent instance, only those options that do not rely on an AgentProperties /// object are processed (e.g. the /D option). /// <p> /// * /// If a file named 'agent.rsp' exists in the current directory, any command /// line options specified will be appended to the command-line arguments /// passed to this method. Each line of the agent.rsp text file may be /// comprised of one or more arguments separated by spaces, so that the /// entirely set of arguments can be on one line or broken up onto many /// lines.<p> /// * /// </summary> /// <param name="agent">An Agent instance that will be updated when certain /// command-line options are parsed /// </param> /// <param name="arguments">The string of arguments provided by the <c>main</code> /// function /// /// </param> public static NameValueCollection parseCL( Agent agent, string[] arguments ) { if ( args == null ) { args = arguments; if ( args.Length > 0 && args[0][0] != '/' ) { // Look for an agent.rsp response file FileInfo rsp = new FileInfo( args[0] ); if ( rsp.Exists ) { try { ArrayList v = new ArrayList(); using ( StreamReader reader = File.OpenText( rsp.FullName ) ) { string line = null; while ( (line = reader.ReadLine()) != null ) { // allow comment lines, starting with a ; if ( !line.StartsWith( ";" ) ) { foreach ( string token in line.Split( ' ' ) ) { v.Add( token ); } } } reader.Close(); } // Append any arguments found to the args array if ( v.Count > 0 ) { args = new string[args.Length + v.Count]; Array.Copy( arguments, 0, args, 0, arguments.Length ); v.CopyTo( args, arguments.Length ); Console.Out.Write ( "Reading command-line arguments from " + args[0] + ": " ); for ( int i = 0; i < args.Length; i++ ) { Console.Out.Write( args[i] + " " ); } Console.WriteLine(); Console.WriteLine(); } } catch ( Exception ex ) { Console.WriteLine ( "Error reading command-line arguments from agent.rsp file: " + ex ); } } } } if ( agent == null ) { // Look for options that do not affect the AgentProperties... for ( int i = 0; i < args.Length; i++ ) { if ( args[i].ToUpper().Equals( "/debug".ToUpper() ) ) { if ( i < args.Length - 1 ) { try { Adk.Debug = AdkDebugFlags.None; int k = Int32.Parse( args[++i] ); if ( k == 1 ) { Adk.Debug = AdkDebugFlags.Minimal; } else if ( k == 2 ) { Adk.Debug = AdkDebugFlags.Moderate; } else if ( k == 3 ) { Adk.Debug = AdkDebugFlags.Detailed; } else if ( k == 4 ) { Adk.Debug = AdkDebugFlags.Very_Detailed; } else if ( k == 5 ) { Adk.Debug = AdkDebugFlags.All; } } catch ( Exception ) { Adk.Debug = AdkDebugFlags.All; } } else { Adk.Debug = AdkDebugFlags.All; } } else if ( args[i].StartsWith( "/D" ) ) { string prop = args[i].Substring( 2 ); if ( i != args.Length - 1 ) { Properties.SetProperty( prop, args[++i] ); } else { Console.WriteLine( "Usage: /Dproperty value" ); } } else if ( args[i].ToUpper().Equals( "/log".ToUpper() ) && i != args.Length - 1 ) { try { Adk.SetLogFile( args[++i] ); } catch ( IOException ioe ) { Console.WriteLine( "Could not redirect debug output to log file: " + ioe ); } } else if ( args[i].ToUpper().Equals( "/ver".ToUpper() ) && i != args.Length - 1 ) { Version = SifVersion.Parse( args[++i] ); } else if ( args[i].Equals( "/?" ) ) { Console.WriteLine(); Console.WriteLine ( "These options are common to all Adk Example agents. For help on the usage" ); Console.WriteLine ( "of this agent in particular, run the agent without any parameters. Note that" ); Console.WriteLine ( "most agents support multiple zones if a zones.properties file is found in" ); Console.WriteLine( "the current directory." ); Console.WriteLine(); printHelp(); Environment.Exit( 0 ); } } return null; } // Parse all other options... AgentProperties props = agent.Properties; NameValueCollection misc = new NameValueCollection(); int port = -1; string host = null; bool useHttps = false; string sslCert = null; string clientCert = null; int clientAuth = 0; for ( int i = 0; i < args.Length; i++ ) { if ( args[i].ToUpper().Equals( "/sourceId".ToUpper() ) && i != args.Length - 1 ) { agent.Id = args[++i]; } else if ( args[i].ToUpper().Equals( "/noreg".ToUpper() ) ) { Reg = false; } else if ( args[i].ToUpper().Equals( "/unreg".ToUpper() ) ) { Unreg = true; } else if ( args[i].ToUpper().Equals( "/pull".ToUpper() ) ) { props.MessagingMode = AgentMessagingMode.Pull; } else if ( args[i].ToUpper().Equals( "/push".ToUpper() ) ) { props.MessagingMode = AgentMessagingMode.Push; } else if ( args[i].ToUpper().Equals( "/port".ToUpper() ) && i != args.Length - 1 ) { try { port = Int32.Parse( args[++i] ); } catch ( FormatException ) { Console.WriteLine( "Invalid port: " + args[i - 1] ); } } else if ( args[i].ToUpper().Equals( "/https".ToUpper() ) ) { useHttps = true; } else if ( args[i].ToUpper().Equals( "/sslCert".ToUpper() ) ) { sslCert = args[++i]; } else if ( args[i].ToUpper().Equals( "/clientCert".ToUpper() ) ) { clientCert = args[++i]; } else if ( args[i].ToUpper().Equals( "/clientAuth".ToUpper() ) ) { try { clientAuth = int.Parse( args[++i] ); } catch ( FormatException ) { clientAuth = 0; } } else if ( args[i].ToUpper().Equals( "/host".ToUpper() ) && i != args.Length - 1 ) { host = args[++i]; } else if ( args[i].ToUpper().Equals( "/timeout".ToUpper() ) && i != args.Length - 1 ) { try { props.DefaultTimeout = TimeSpan.FromMilliseconds( Int32.Parse( args[++i] ) ); } catch ( FormatException ) { Console.WriteLine( "Invalid timeout: " + args[i - 1] ); } } else if ( args[i].ToUpper().Equals( "/freq".ToUpper() ) && i != args.Length - 1 ) { try { props.PullFrequency = TimeSpan.FromMilliseconds( int.Parse( args[++i] ) ); } catch ( FormatException ) { Console.WriteLine( "Invalid pull frequency: " + args[i - 1] ); } } else if ( args[i].ToUpper().Equals( "/opensif".ToUpper() ) ) { // OpenSIF reports attempts to re-subscribe to objects as an // error instead of a success status code. The Adk would therefore // throw an exception if it encountered the error, so we can // disable that behavior here. props.IgnoreProvisioningErrors = true; } else if ( args[i][0] == '/' ) { if ( i == args.Length - 1 || args[i + 1].StartsWith( "/" ) ) { misc[args[i].Substring( 1 )] = null; } else { misc[args[i].Substring( 1 )] = args[++i]; } } } if ( useHttps ) { // Set transport properties (HTTPS) HttpsProperties https = agent.DefaultHttpsProperties; if ( sslCert != null ) { https.SSLCertName = sslCert; } if ( clientCert != null ) { https.ClientCertName = clientCert; } https.ClientAuthLevel = clientAuth; if ( port != -1 ) { https.Port = port; } https.Host = host; props.TransportProtocol = "https"; } else { // Set transport properties (HTTP) HttpProperties http = agent.DefaultHttpProperties; if ( port != -1 ) { http.Port = port; } http.Host = host; props.TransportProtocol = "http"; } return misc; } /// <summary> Display help to System.out /// </summary> public static void printHelp() { Console.WriteLine( " /sourceId name The name of the agent" ); Console.WriteLine ( " /ver version Default SIF Version to use (e.g. 10r1, 10r2, etc.)" ); Console.WriteLine( " /debug level Enable debugging to the console" ); Console.WriteLine( " 1 - Minimal" ); Console.WriteLine( " 2 - Moderate" ); Console.WriteLine( " 3 - Detailed" ); Console.WriteLine( " 4 - Very Detailed" ); Console.WriteLine( " 5 - All" ); Console.WriteLine( " /log file Redirects logging to the specified file" ); Console.WriteLine( " /pull Use Pull mode" ); Console.WriteLine ( " /freq Sets the Pull frequency (defaults to 15 seconds)" ); Console.WriteLine( " /push Use Push mode" ); Console.WriteLine ( " /port n The local port for Push mode (defaults to 12000)" ); Console.WriteLine ( " /host addr The local IP address for push mode (defaults to any)" ); Console.WriteLine ( " /noreg Do not send a SIF_Register on startup (sent by default)" ); Console.WriteLine ( " /unreg Send a SIF_Unregister on exit (not sent by default)" ); Console.WriteLine( " /timeout ms Sets the Adk timeout period (defaults to 30000)" ); Console.WriteLine( " /opensif Ignores provisioning errors from OpenSIF" ); Console.WriteLine( " /Dproperty val Sets a Java System property" ); Console.WriteLine(); Console.WriteLine( " HTTPS Transport Options:" ); Console.WriteLine ( " Certificates will be retrieved from the Current User's Personal Store" ); Console.WriteLine( " /https Use HTTPS instead of HTTP." ); Console.WriteLine( " /clientAuth [1|2|3] Require Client Authentication level" ); Console.WriteLine( " /sslCert cert The subject of the certificate to use for SSL" ); Console.WriteLine ( " /clientCert The subject of the certificate to use for Client Authentication" ); Console.WriteLine(); Console.WriteLine(); Console.WriteLine( " Response Files:" ); Console.WriteLine ( " To use a response file instead of typing arguments on the command-line," ); Console.WriteLine ( " pass the name of the response file as the first argument. This text" ); Console.WriteLine ( " file may contain any combination of arguments on one or more lines," ); Console.WriteLine ( " which are appended to any arguments specified on the command-line." ); } /// <summary> Looks for a file named zones.properties and if found reads its contents /// into a HashMap where the key of each entry is the Zone ID and the value /// is the Zone URL. A valid HashMap is always returned by this method; the /// called typically assigns the value of the /zone and /url command-line /// options to that map (when applicable). /// </summary> public static NameValueCollection ReadZonesList() { NameValueCollection list = new NameValueCollection(); return list; } static AdkExamples() { Version = SifVersion.LATEST; } }
using System.Collections.Generic; using System.Threading.Tasks; using EmsApi.Dto.V2; namespace EmsApi.Client.V2.Access { /// <summary> /// Provides access to EMS API "profiles" routes. /// </summary> public class ProfilesAccess : RouteAccess { /// <summary> /// Returns APM profile results for the given flight and profile id. /// </summary> /// <param name="flightId"> /// The flight id to return APM results for. /// </param> /// <param name="profileId"> /// The APM profile guid to return results for, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0" /// for the library flight safety events profile. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<ProfileResults> GetResultsAsync( int flightId, string profileId, CallContext context = null ) { return CallApiTask( api => api.GetProfileResults( flightId, profileId, context ) ); } /// <summary> /// Returns APM profile results for the given flight and profile id. /// </summary> /// <param name="flightId"> /// The flight id to return APM results for. /// </param> /// <param name="profileId"> /// The APM profile guid to return results for, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0" /// for the library flight safety events profile. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual ProfileResults GetResults( int flightId, string profileId, CallContext context = null ) { return AccessTaskResult( GetResultsAsync( flightId, profileId, context ) ); } /// <summary> /// Returns information about the set of APM profiles on the given EMS system. /// </summary> /// <param name="parentGroupId"> /// The optional parent profile group ID whose contents to search. /// </param> /// <param name="search"> /// An optional profile name search string used to match profiles to return. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<IEnumerable<Profile>> GetDefinitionsAsync( string parentGroupId = null, string search = null, CallContext context = null ) { return CallApiTask( api => api.GetProfiles( parentGroupId, search, context ) ); } /// <summary> /// Returns information about the set of APM profiles on the given EMS system. /// </summary> /// <param name="parentGroupId"> /// The optional parent profile group ID whose contents to search. /// </param> /// <param name="search"> /// An optional profile name search string used to match profiles to return. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual IEnumerable<Profile> GetDefinitions( string parentGroupId = null, string search = null, CallContext context = null ) { return AccessTaskResult( GetDefinitionsAsync( parentGroupId, search, context ) ); } /// <summary> /// Returns a profile group with a matching ID containing only its immediate /// children in a hierarchical tree used to organize profiles. /// </summary> /// <param name="groupId"> /// The unique identifier of the profile group whose contents to return. If /// not specified, the contents of the root group are returned. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<ProfileGroup> GetGroupAsync( string groupId = null, CallContext context = null ) { return CallApiTask( api => api.GetProfileGroup( groupId, context ) ); } /// <summary> /// Returns a profile group with a matching ID containing only its immediate /// children in a hierarchical tree used to organize profiles. /// </summary> /// <param name="groupId"> /// The unique identifier of the profile group whose contents to return. If /// not specified, the contents of the root group are returned. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual ProfileGroup GetGroup( string groupId = null, CallContext context = null ) { return AccessTaskResult( GetGroupAsync( groupId, context ) ); } /// <summary> /// Returns a "glossary" for a specific profile and version, which helps define the /// results that can be returned in a profile. /// </summary> /// <param name="profileId"> /// The unique identifier of the profile whose glossary to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0". /// </param> /// <param name="profileVersionNumber"> /// Integer version of the profile to return. If not specified the current version of the profile is used by default. /// </param> /// <param name="format"> /// The format of the returned glossary. Options are "json" or "csv". Defaults to JSON. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<ProfileGlossary> GetGlossaryAsync( string profileId, int? profileVersionNumber = null, string format = null, CallContext context = null ) { return CallApiTask( api => api.GetProfileGlossary( profileId, profileVersionNumber, format, context ) ); } /// <summary> /// Returns a "glossary" for a specific profile and version, which helps define the /// results that can be returned in a profile. /// </summary> /// <param name="profileId"> /// The unique identifier of the profile whose glossary to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0". /// </param> /// <param name="profileVersionNumber"> /// Integer version of the profile to return. If not specified the current version of the profile is used by default. /// </param> /// <param name="format"> /// The format of the returned glossary. Options are "json" or "csv". Defaults to JSON. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual ProfileGlossary GetGlossary( string profileId, int? profileVersionNumber = null, string format = null, CallContext context = null ) { return AccessTaskResult( GetGlossaryAsync( profileId, profileVersionNumber, format, context ) ); } /// <summary> /// Returns the events for a specific profile. /// </summary> /// <param name="profileId"> /// The unique identifier of the profile whose events to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0". /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<IEnumerable<Event>> GetEventsAsync( string profileId, CallContext context = null ) { return CallApiTask( api => api.GetProfileEvents( profileId, context ) ); } /// <summary> /// Returns the events for a specific profile. /// </summary> /// <param name="profileId"> /// The unique identifier of the profile whose events to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0". /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual IEnumerable<Event> GetEvents( string profileId, CallContext context = null ) { return AccessTaskResult( GetEventsAsync( profileId, context ) ); } /// <summary> /// Returns an event for a specific profile. /// </summary> /// <param name="profileId"> /// The unique identifier of the profile whose events to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0". /// </param> /// <param name="eventId"> /// The integer ID for the event. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<Event> GetEventAsync( string profileId, int eventId, CallContext context = null ) { return CallApiTask( api => api.GetProfileEvent( profileId, eventId, context ) ); } /// <summary> /// Returns an event for a specific profile. /// </summary> /// <param name="profileId"> /// The unique identifier of the profile whose events to return, e.g. "A7483C44-9DB9-4A44-9EB5-F67681EE52B0". /// </param> /// <param name="eventId"> /// The integer ID for the event. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Event GetEvent( string profileId, int eventId, CallContext context = null ) { return AccessTaskResult( GetEventAsync( profileId, eventId, context ) ); } } }
/* * 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; using BitCoinSharp.Common; using BitCoinSharp.Store; using NUnit.Framework; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities.Encoders; namespace BitCoinSharp.Test { [TestFixture] public class BlockChainTest { private static readonly NetworkParameters _testNet = NetworkParameters.TestNet(); private IBlockStore _testNetChainBlockStore; private BlockChain _testNetChain; private Wallet _wallet; private BlockChain _chain; private IBlockStore _blockStore; private Address _coinbaseTo; private NetworkParameters _unitTestParams; private void ResetBlockStore() { _blockStore = new MemoryBlockStore(_unitTestParams); } [SetUp] public void SetUp() { _testNetChainBlockStore = new MemoryBlockStore(_testNet); _testNetChain = new BlockChain(_testNet, new Wallet(_testNet), _testNetChainBlockStore); _unitTestParams = NetworkParameters.UnitTests(); _wallet = new Wallet(_unitTestParams); _wallet.AddKey(new EcKey()); ResetBlockStore(); _chain = new BlockChain(_unitTestParams, _wallet, _blockStore); _coinbaseTo = _wallet.Keychain[0].ToAddress(_unitTestParams); } [TearDown] public void TearDown() { _testNetChainBlockStore.Dispose(); _blockStore.Dispose(); } [Test] public void TestBasicChaining() { // Check that we can plug a few blocks together. // Block 1 from the testnet. var b1 = GetBlock1(); Assert.IsTrue(_testNetChain.Add(b1)); // Block 2 from the testnet. var b2 = GetBlock2(); // Let's try adding an invalid block. var n = b2.Nonce; try { b2.Nonce = 12345; _testNetChain.Add(b2); Assert.Fail(); } catch (VerificationException) { b2.Nonce = n; } // Now it works because we reset the nonce. Assert.IsTrue(_testNetChain.Add(b2)); } [Test] public void ReceiveCoins() { // Quick check that we can actually receive coins. var tx1 = TestUtils.CreateFakeTx(_unitTestParams, Utils.ToNanoCoins(1, 0), _wallet.Keychain[0].ToAddress(_unitTestParams)); var b1 = TestUtils.CreateFakeBlock(_unitTestParams, _blockStore, tx1).Block; _chain.Add(b1); Assert.IsTrue(_wallet.GetBalance().CompareTo(0UL) > 0); } [Test] public void MerkleRoots() { // Test that merkle root verification takes place when a relevant transaction is present and doesn't when // there isn't any such tx present (as an optimization). var tx1 = TestUtils.CreateFakeTx(_unitTestParams, Utils.ToNanoCoins(1, 0), _wallet.Keychain[0].ToAddress(_unitTestParams)); var b1 = TestUtils.CreateFakeBlock(_unitTestParams, _blockStore, tx1).Block; _chain.Add(b1); ResetBlockStore(); var hash = b1.MerkleRoot; b1.MerkleRoot = Sha256Hash.ZeroHash; try { _chain.Add(b1); Assert.Fail(); } catch (VerificationException) { // Expected. b1.MerkleRoot = hash; } // Now add a second block with no relevant transactions and then break it. var tx2 = TestUtils.CreateFakeTx(_unitTestParams, Utils.ToNanoCoins(1, 0), new EcKey().ToAddress(_unitTestParams)); var b2 = TestUtils.CreateFakeBlock(_unitTestParams, _blockStore, tx2).Block; b2.MerkleRoot = Sha256Hash.ZeroHash; b2.Solve(); _chain.Add(b2); // Broken block is accepted because its contents don't matter to us. } [Test] public void TestUnconnectedBlocks() { var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_coinbaseTo); var b2 = b1.CreateNextBlock(_coinbaseTo); var b3 = b2.CreateNextBlock(_coinbaseTo); // Connected. Assert.IsTrue(_chain.Add(b1)); // Unconnected but stored. The head of the chain is still b1. Assert.IsFalse(_chain.Add(b3)); Assert.AreEqual(_chain.ChainHead.Header, b1.CloneAsHeader()); // Add in the middle block. Assert.IsTrue(_chain.Add(b2)); Assert.AreEqual(_chain.ChainHead.Header, b3.CloneAsHeader()); } [Test] public void TestDifficultyTransitions() { // Add a bunch of blocks in a loop until we reach a difficulty transition point. The unit test params have an // artificially shortened period. var prev = _unitTestParams.GenesisBlock; Block.FakeClock = UnixTime.ToUnixTime(DateTime.UtcNow); for (var i = 0; i < _unitTestParams.Interval - 1; i++) { var newBlock = prev.CreateNextBlock(_coinbaseTo, (uint) Block.FakeClock); Assert.IsTrue(_chain.Add(newBlock)); prev = newBlock; // The fake chain should seem to be "fast" for the purposes of difficulty calculations. Block.FakeClock += 2; } // Now add another block that has no difficulty adjustment, it should be rejected. try { _chain.Add(prev.CreateNextBlock(_coinbaseTo)); Assert.Fail(); } catch (VerificationException) { } // Create a new block with the right difficulty target given our blistering speed relative to the huge amount // of time it's supposed to take (set in the unit test network parameters). var b = prev.CreateNextBlock(_coinbaseTo, (uint) Block.FakeClock); b.DifficultyTarget = 0x201FFFFF; b.Solve(); Assert.IsTrue(_chain.Add(b)); } // Successfully traversed a difficulty transition period. [Test] public void TestBadDifficulty() { Assert.IsTrue(_testNetChain.Add(GetBlock1())); var b2 = GetBlock2(); Assert.IsTrue(_testNetChain.Add(b2)); var params2 = NetworkParameters.TestNet(); var bad = new Block(params2); // Merkle root can be anything here, doesn't matter. bad.MerkleRoot = new Sha256Hash(Hex.Decode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); // Nonce was just some number that made the hash < difficulty limit set below, it can be anything. bad.Nonce = 140548933; bad.TimeSeconds = 1279242649; bad.PrevBlockHash = b2.Hash; // We're going to make this block so easy 50% of solutions will pass, and check it gets rejected for having a // bad difficulty target. Unfortunately the encoding mechanism means we cannot make one that accepts all // solutions. bad.DifficultyTarget = Block.EasiestDifficultyTarget; try { _testNetChain.Add(bad); // The difficulty target above should be rejected on the grounds of being easier than the networks // allowable difficulty. Assert.Fail(); } catch (VerificationException e) { Assert.IsTrue(e.Message.IndexOf("Difficulty target is bad") >= 0, e.Message); } // Accept any level of difficulty now. params2.ProofOfWorkLimit = new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16); try { _testNetChain.Add(bad); // We should not get here as the difficulty target should not be changing at this point. Assert.Fail(); } catch (VerificationException e) { Assert.IsTrue(e.Message.IndexOf("Unexpected change in difficulty") >= 0, e.Message); } // TODO: Test difficulty change is not out of range when a transition period becomes valid. } // Some blocks from the test net. private static Block GetBlock2() { var b2 = new Block(_testNet); b2.MerkleRoot = new Sha256Hash(Hex.Decode("addc858a17e21e68350f968ccd384d6439b64aafa6c193c8b9dd66320470838b")); b2.Nonce = 2642058077; b2.TimeSeconds = 1296734343; b2.PrevBlockHash = new Sha256Hash(Hex.Decode("000000033cc282bc1fa9dcae7a533263fd7fe66490f550d80076433340831604")); Assert.AreEqual("000000037b21cac5d30fc6fda2581cf7b2612908aed2abbcc429c45b0557a15f", b2.HashAsString); b2.VerifyHeader(); return b2; } private static Block GetBlock1() { var b1 = new Block(_testNet); b1.MerkleRoot = new Sha256Hash(Hex.Decode("0e8e58ecdacaa7b3c6304a35ae4ffff964816d2b80b62b58558866ce4e648c10")); b1.Nonce = 236038445; b1.TimeSeconds = 1296734340; b1.PrevBlockHash = new Sha256Hash(Hex.Decode("00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008")); Assert.AreEqual("000000033cc282bc1fa9dcae7a533263fd7fe66490f550d80076433340831604", b1.HashAsString); b1.VerifyHeader(); return b1; } } }
using System; using System.Web.UI; using Vevo; using Vevo.DataAccessLib.Cart; using Vevo.Domain; using Vevo.Domain.Products; using Vevo.Domain.Stores; using Vevo.Domain.Users; using Vevo.WebUI; public partial class AdminAdvanced_Components_ProductReviewDetails : AdminAdvancedBaseUserControl { private enum Mode { Add, Edit }; private Mode _mode = Mode.Add; public bool IsEditMode() { return (_mode == Mode.Edit); } public bool SetVisibleLanguageControl { set { uxLanguageControl.Visible = value; } } public void SetEditMode() { _mode = Mode.Edit; } private string CurrentID { get { return MainContext.QueryString["ReviewID"]; } } private string CurrentProductID { get { if (MainContext.QueryString["ProductID"] != null) { return MainContext.QueryString["ProductID"]; } else { if (ViewState["CurrentProductID"] == null) ViewState["CurrentProductID"] = CustomerReviewAccess.GetProductIDByReviewID( CurrentID ); return (string) ViewState["CurrentProductID"]; } } } private void SetProductName() { Product product = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentProductID, new StoreRetriever().GetCurrentStoreID() ); uxProductNameLabel.Text = product.Name; } private void Details_RefreshHandler( object sender, EventArgs e ) { PopulateControls(); } protected void uxLanguageControl_BubbleEvent( object sender, EventArgs e ) { SetProductName(); } protected void Page_Load( object sender, EventArgs e ) { if (!MainContext.IsPostBack) { uxReviewCheck.Checked = true; if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxDateText.Visible = false; } else { uxDateText.Visible = true; } SetProductName(); } uxLanguageControl.BubbleEvent += new EventHandler( uxLanguageControl_BubbleEvent ); } private void ClearTextFeilds() { uxLongDescriptionText.Text = ""; uxCustomerID.Text = string.Empty; uxReviewRating.Text = string.Empty; uxSubject.Text = string.Empty; uxReviewCheck.Checked = true; uxCalendar.SelectedDate = DateTime.Now; } private void ClearTextFieldsCrossCulture() { uxLongDescriptionText.Text = ""; uxSubject.Text = string.Empty; } private void PopulateControls() { if (CurrentID != null && int.Parse( CurrentID ) >= 0) { CustomerReviewDetails details = CustomerReviewAccess.GetDetails( CurrentID, uxLanguageControl.CurrentCultureID ); if (details != null) { Customer customer = DataAccessContext.CustomerRepository.GetOne( details.CustomerID ); uxCustomerID.Text = customer.UserName; uxReviewRating.Text = Convert.ToString( Convert.ToDouble( details.ReviewRating ) * Convert.ToDouble( DataAccessContext.Configurations.GetValue( "StarRatingAmount" ) ) ); uxSubject.Text = details.Subject; uxLongDescriptionText.Text = details.Body; uxReviewCheck.Checked = details.IsEnabled; uxCalendar.SelectedDate = details.ReviewDate; } else { ClearTextFieldsCrossCulture(); } } } protected void Page_PreRender( object sender, EventArgs e ) { if (IsEditMode()) { if (!MainContext.IsPostBack) { PopulateControls(); } uxAddButton.Visible = false; if (IsAdminModifiable()) { uxEditButton.Visible = true; } else { uxEditButton.Visible = false; } } else { if (IsAdminModifiable()) { uxAddButton.Visible = true; uxEditButton.Visible = false; uxCalendar.SelectedDate = DateTime.Now; } else { MainContext.RedirectMainControl( "ProductReviewList.ascx", "" ); } } } protected void uxAddButton_Click( object sender, EventArgs e ) { try { if (Page.IsValid) { double reviewRating = Convert.ToDouble( uxReviewRating.Text.Trim() ) / Convert.ToDouble( DataAccessContext.Configurations.GetValue( "StarRatingAmount" ) ); string customerID = DataAccessContext.CustomerRepository.GetIDFromUserName( uxCustomerID.Text.Trim() ); if (customerID == "") customerID = "0"; string ReviewID = CustomerReviewAccess.Create( CurrentProductID, uxLanguageControl.CurrentCultureID, customerID, reviewRating, bool.Parse( uxReviewCheck.Checked.ToString() ), uxSubject.Text.Trim(), uxLongDescriptionText.Text ); uxMessage.DisplayMessage( Resources.ProductReviewMessage.AddSuccess ); ClearTextFeilds(); } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } protected void uxEditButton_Click( object sender, EventArgs e ) { try { if (Page.IsValid) { DateTime date; double reviewRating = Convert.ToDouble( uxReviewRating.Text.Trim() ) / Convert.ToDouble( DataAccessContext.Configurations.GetValue( "StarRatingAmount" ) ); string customerID = DataAccessContext.CustomerRepository.GetIDFromUserName( uxCustomerID.Text.Trim() ); if (customerID == "") customerID = "0"; if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { date = Convert.ToDateTime( uxCalendar.SelectedDate ); } else { date = Convert.ToDateTime( uxDateText.Text ); } CustomerReviewAccess.Update( CurrentID, CustomerReviewAccess.GetProductIDByReviewID( CurrentID ), uxLanguageControl.CurrentCultureID, customerID, reviewRating, date, uxReviewCheck.Checked, uxSubject.Text.Trim(), uxLongDescriptionText.Text ); uxMessage.DisplayMessage( Resources.ProductReviewMessage.UpdateSuccess ); PopulateControls(); } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } }